From a2854790afddbb298f7cce12ed08e1a6f1913722 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Torbj=C3=B6rn=20SVENSSON?= Date: Sun, 1 Oct 2023 23:07:37 +0200 Subject: [PATCH] Format java files in o.e.osgi MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This was achieved by running: eclipse -consolelog -nosplash -application org.eclipse.jdt.core.JavaCodeFormatter \ -config .settings/org.eclipse.jdt.core.prefs . -data `mktemp -d` && \ git checkout src/org/osgi felix Signed-off-by: Torbjörn SVENSSON --- .../core/runtime/adaptor/EclipseStarter.java | 384 +++++++---- .../internal/adaptor/ConsoleManager.java | 11 +- .../adaptor/DefaultStartupMonitor.java | 16 +- .../internal/adaptor/EclipseAppLauncher.java | 44 +- .../org/eclipse/osgi/container/Module.java | 198 +++--- .../osgi/container/ModuleCapability.java | 8 +- .../osgi/container/ModuleCollisionHook.java | 41 +- .../osgi/container/ModuleContainer.java | 430 +++++++----- .../container/ModuleContainerAdaptor.java | 188 +++-- .../osgi/container/ModuleDatabase.java | 475 +++++++------ .../eclipse/osgi/container/ModuleLoader.java | 37 +- .../osgi/container/ModuleRequirement.java | 18 +- .../container/ModuleResolutionReport.java | 100 +-- .../osgi/container/ModuleResolver.java | 311 +++++---- .../osgi/container/ModuleRevision.java | 33 +- .../osgi/container/ModuleRevisionBuilder.java | 103 ++- .../osgi/container/ModuleRevisions.java | 24 +- .../eclipse/osgi/container/ModuleWire.java | 7 +- .../eclipse/osgi/container/ModuleWiring.java | 28 +- .../eclipse/osgi/container/SystemModule.java | 35 +- .../builders/OSGiManifestBuilderFactory.java | 310 ++++++--- .../namespaces/EclipsePlatformNamespace.java | 10 +- .../namespaces/EquinoxFragmentNamespace.java | 7 +- .../EquinoxModuleDataNamespace.java | 94 +-- .../eclipse/osgi/framework/util/ArrayMap.java | 15 +- .../util/CaseInsensitiveDictionaryMap.java | 251 +++---- .../eclipse/osgi/framework/util/FilePath.java | 30 +- .../eclipse/osgi/framework/util/Headers.java | 61 +- .../osgi/framework/util/KeyedElement.java | 19 +- .../osgi/framework/util/ObjectPool.java | 9 +- .../osgi/framework/util/SecureAction.java | 126 ++-- .../osgi/framework/util/ThreadInfoReport.java | 3 +- .../osgi/internal/cds/CDSBundleEntry.java | 31 +- .../osgi/internal/cds/CDSBundleFile.java | 36 +- .../internal/cds/CDSHookConfigurator.java | 4 +- .../osgi/internal/cds/CDSHookImpls.java | 38 +- .../internal/connect/ConnectBundleFile.java | 3 +- .../connect/ConnectHookConfigurator.java | 12 +- .../internal/connect/ConnectInputStream.java | 3 +- .../connect/DelegatingConnectClassLoader.java | 3 +- .../container/AtomicLazyInitializer.java | 19 +- .../osgi/internal/container/Capabilities.java | 26 +- .../internal/container/ComputeNodeOrder.java | 351 +++++----- .../internal/container/InternalUtils.java | 6 +- .../osgi/internal/container/LockSet.java | 6 +- .../internal/container/NamespaceList.java | 6 +- .../eclipse/osgi/internal/debug/Debug.java | 36 +- .../internal/debug/EclipseDebugTrace.java | 201 ++++-- .../internal/debug/FrameworkDebugOptions.java | 86 ++- .../debug/FrameworkDebugTraceEntry.java | 66 +- .../osgi/internal/framework/AliasMapper.java | 6 +- .../internal/framework/BundleContextImpl.java | 642 +++++++++--------- .../internal/framework/ContextFinder.java | 29 +- .../osgi/internal/framework/DTOBuilder.java | 8 +- .../internal/framework/EquinoxBundle.java | 103 +-- .../framework/EquinoxConfiguration.java | 156 +++-- .../internal/framework/EquinoxContainer.java | 8 +- .../framework/EquinoxContainerAdaptor.java | 145 ++-- .../framework/EquinoxEventPublisher.java | 107 +-- .../osgi/internal/framework/FilterImpl.java | 363 +++++----- .../framework/OSGiFrameworkHooks.java | 82 ++- .../osgi/internal/framework/StorageSaver.java | 3 +- .../framework/SystemBundleActivator.java | 25 +- .../framework/XMLParsingServiceFactory.java | 14 +- .../framework/legacy/PackageAdminImpl.java | 44 +- .../hookregistry/ActivatorHookFactory.java | 8 +- .../BundleFileWrapperFactoryHook.java | 12 +- .../hookregistry/ClassLoaderHook.java | 331 +++++---- .../hookregistry/HookConfigurator.java | 2 + .../internal/hookregistry/HookRegistry.java | 110 ++- .../hookregistry/StorageHookFactory.java | 176 +++-- .../internal/hooks/DevClassLoadingHook.java | 37 +- .../internal/hooks/EclipseLazyStarter.java | 52 +- .../osgi/internal/loader/BundleLoader.java | 277 +++++--- .../internal/loader/BundleLoaderSources.java | 21 +- .../internal/loader/EquinoxClassLoader.java | 16 +- .../internal/loader/ModuleClassLoader.java | 105 +-- .../internal/loader/SystemBundleLoader.java | 33 +- .../loader/buddy/DependentPolicy.java | 25 +- .../internal/loader/buddy/GlobalPolicy.java | 8 +- .../internal/loader/buddy/PolicyHandler.java | 60 +- .../loader/buddy/RegisteredPolicy.java | 20 +- .../internal/loader/buddy/SystemPolicy.java | 25 +- .../loader/classpath/ClasspathEntry.java | 53 +- .../loader/classpath/ClasspathManager.java | 260 ++++--- .../loader/classpath/FragmentClasspath.java | 12 +- .../classpath/ManifestPackageAttributes.java | 53 +- .../loader/classpath/TitleVersionVendor.java | 14 +- .../loader/sources/NullPackageSource.java | 8 +- .../loader/sources/PackageSource.java | 30 +- .../loader/sources/SingleSourcePackage.java | 5 +- .../osgi/internal/location/BasicLocation.java | 13 +- .../internal/location/EquinoxLocations.java | 81 ++- .../eclipse/osgi/internal/log/Arguments.java | 3 +- .../internal/log/ConfigAdminListener.java | 20 +- .../osgi/internal/log/EquinoxLogFactory.java | 47 +- .../osgi/internal/log/EquinoxLogServices.java | 11 +- .../osgi/internal/log/EquinoxLogWriter.java | 104 ++- .../osgi/internal/log/EventAdminAdapter.java | 5 +- .../internal/log/EventAdminLogListener.java | 31 +- .../internal/log/ExtendedLogEntryImpl.java | 4 +- .../log/ExtendedLogReaderServiceFactory.java | 48 +- .../log/ExtendedLogServiceFactory.java | 15 +- .../osgi/internal/log/LogServiceManager.java | 117 ++-- .../eclipse/osgi/internal/log/LoggerImpl.java | 69 +- .../internal/permadmin/BundlePermissions.java | 13 +- .../permadmin/EquinoxSecurityManager.java | 24 +- .../permadmin/PermissionInfoCollection.java | 34 +- .../internal/permadmin/PermissionsHash.java | 39 +- .../osgi/internal/permadmin/SecurityRow.java | 86 +-- .../permadmin/SecurityRowSnapShot.java | 3 +- .../internal/permadmin/SecurityTable.java | 27 +- .../permadmin/SecurityTableUpdate.java | 6 +- .../service/security/AuthorizationEngine.java | 33 +- .../service/security/AuthorizationEvent.java | 16 +- .../security/AuthorizationListener.java | 5 +- .../service/security/AuthorizationStatus.java | 8 +- .../verifier/CertificateChain.java | 24 +- .../verifier/CertificateTrustAuthority.java | 9 +- .../verifier/CertificateVerifier.java | 26 +- .../verifier/CertificateVerifierFactory.java | 13 +- .../service/security/KeyStoreTrustEngine.java | 37 +- .../FilteredServiceListener.java | 65 +- .../internal/serviceregistry/HookContext.java | 13 +- .../serviceregistry/ModifiedServiceEvent.java | 16 +- .../PrototypeServiceFactoryUse.java | 27 +- .../serviceregistry/ServiceConsumer.java | 6 +- .../serviceregistry/ServiceFactoryUse.java | 98 +-- .../serviceregistry/ServiceObjectsImpl.java | 85 +-- .../serviceregistry/ServiceProperties.java | 17 +- .../serviceregistry/ServiceReferenceImpl.java | 123 ++-- .../ServiceRegistrationImpl.java | 198 +++--- .../serviceregistry/ServiceRegistry.java | 602 ++++++++-------- .../internal/serviceregistry/ServiceUse.java | 16 +- .../serviceregistry/ShrinkableCollection.java | 22 +- .../ShrinkableValueCollectionMap.java | 7 +- .../signedcontent/SignedBundleHook.java | 58 +- .../signedcontent/SignedContentConstants.java | 30 +- .../SignedContentFromBundleFile.java | 1 + .../url/ContentHandlerFactoryImpl.java | 55 +- .../internal/url/ContentHandlerProxy.java | 48 +- .../internal/url/EquinoxFactoryManager.java | 22 +- .../internal/url/MultiplexingFactory.java | 55 +- .../url/MultiplexingURLStreamHandler.java | 91 ++- .../url/NullURLStreamHandlerService.java | 16 +- .../url/URLStreamHandlerFactoryImpl.java | 36 +- .../internal/url/URLStreamHandlerProxy.java | 3 +- .../internal/url/URLStreamHandlerSetter.java | 9 +- .../weaving/WeavingHookConfigurator.java | 15 +- .../osgi/internal/weaving/WovenClassImpl.java | 15 +- .../eclipse/osgi/launch/EquinoxFactory.java | 1 + .../PluginConversionException.java | 6 +- .../pluginconversion/PluginConverter.java | 116 ++-- .../service/resolver/BaseDescription.java | 46 +- .../osgi/service/resolver/BundleDelta.java | 89 +-- .../service/resolver/BundleDescription.java | 172 +++-- .../service/resolver/BundleSpecification.java | 7 +- .../osgi/service/resolver/DisabledInfo.java | 28 +- .../resolver/ExportPackageDescription.java | 21 +- .../service/resolver/GenericDescription.java | 35 +- .../resolver/GenericSpecification.java | 16 +- .../service/resolver/HostSpecification.java | 15 +- .../resolver/ImportPackageSpecification.java | 25 +- .../resolver/NativeCodeDescription.java | 42 +- .../resolver/NativeCodeSpecification.java | 21 +- .../osgi/service/resolver/PlatformAdmin.java | 64 +- .../osgi/service/resolver/Resolver.java | 124 ++-- .../osgi/service/resolver/ResolverError.java | 138 ++-- .../resolver/ResolverHookException.java | 8 +- .../eclipse/osgi/service/resolver/State.java | 507 ++++++++------ .../osgi/service/resolver/StateDelta.java | 19 +- .../osgi/service/resolver/StateHelper.java | 162 +++-- .../service/resolver/StateObjectFactory.java | 560 +++++++++------ .../osgi/service/resolver/StateWire.java | 45 +- .../service/resolver/VersionConstraint.java | 43 +- .../osgi/service/resolver/VersionRange.java | 48 +- .../osgi/service/security/TrustEngine.java | 90 ++- .../InvalidContentException.java | 18 +- .../osgi/signedcontent/SignedContent.java | 64 +- .../signedcontent/SignedContentEntry.java | 22 +- .../signedcontent/SignedContentFactory.java | 58 +- .../osgi/signedcontent/SignerInfo.java | 13 +- .../org/eclipse/osgi/storage/BundleInfo.java | 75 +- .../osgi/storage/BundleLocalizationImpl.java | 15 +- .../eclipse/osgi/storage/ContentProvider.java | 14 +- .../storage/FrameworkExtensionInstaller.java | 54 +- .../osgi/storage/ManifestLocalization.java | 26 +- .../osgi/storage/NativeCodeFinder.java | 40 +- .../eclipse/osgi/storage/PermissionData.java | 53 +- .../src/org/eclipse/osgi/storage/Storage.java | 401 +++++++---- .../org/eclipse/osgi/storage/StorageUtil.java | 12 +- .../osgi/storage/SystemBundleFile.java | 9 +- .../osgi/storage/bundlefile/BundleEntry.java | 21 +- .../osgi/storage/bundlefile/BundleFile.java | 92 +-- .../storage/bundlefile/BundleFileWrapper.java | 12 +- .../bundlefile/BundleFileWrapperChain.java | 18 +- .../bundlefile/CloseableBundleFile.java | 66 +- .../storage/bundlefile/DirBundleFile.java | 4 +- .../storage/bundlefile/DirZipBundleEntry.java | 4 +- .../storage/bundlefile/FileBundleEntry.java | 10 +- .../storage/bundlefile/MRUBundleFileList.java | 33 +- .../bundlefile/NestedDirBundleFile.java | 18 +- .../storage/bundlefile/ZipBundleEntry.java | 14 +- .../storage/bundlefile/ZipBundleFile.java | 13 +- .../storage/url/BundleResourceHandler.java | 44 +- .../osgi/storage/url/BundleURLConnection.java | 11 +- .../osgi/storage/url/BundleURLConverter.java | 29 +- .../osgi/storage/url/reference/Handler.java | 14 +- .../url/reference/ReferenceInputStream.java | 7 +- .../org/eclipse/osgi/util/TextProcessor.java | 117 ++-- 210 files changed, 8510 insertions(+), 5906 deletions(-) diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/core/runtime/adaptor/EclipseStarter.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/core/runtime/adaptor/EclipseStarter.java index cf593b6d5f1..144b0a27705 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/core/runtime/adaptor/EclipseStarter.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/core/runtime/adaptor/EclipseStarter.java @@ -57,14 +57,17 @@ * instantiated; all functionality is provided by static methods. *

* The Eclipse Platform makes heavy use of Java class loaders for loading - * plug-ins. Even the Eclipse Runtime itself and the OSGi framework need - * to be loaded by special class loaders. The upshot is that a - * client program (such as a Java main program, a servlet) cannot - * reference any part of Eclipse directly. Instead, a client must use this - * loader class to start the platform, invoking functionality defined - * in plug-ins, and shutting down the platform when done. + * plug-ins. Even the Eclipse Runtime itself and the OSGi framework need to be + * loaded by special class loaders. The upshot is that a client program (such as + * a Java main program, a servlet) cannot reference any part of Eclipse + * directly. Instead, a client must use this loader class to start the platform, + * invoking functionality defined in plug-ins, and shutting down the platform + * when done. *

- *

Note that the fields on this class are not API.

+ *

+ * Note that the fields on this class are not API. + *

+ * * @since 3.0 * @noextend This class is not intended to be subclassed by clients. */ @@ -100,9 +103,12 @@ public class EclipseStarter { // System properties public static final String PROP_BUNDLES = "osgi.bundles"; //$NON-NLS-1$ - public static final String PROP_BUNDLES_STARTLEVEL = "osgi.bundles.defaultStartLevel"; //$NON-NLS-1$ //The start level used to install the bundles + public static final String PROP_BUNDLES_STARTLEVEL = "osgi.bundles.defaultStartLevel"; //$NON-NLS-1$ //The start + // level used to install the + // bundles public static final String PROP_EXTENSIONS = "osgi.framework.extensions"; //$NON-NLS-1$ - public static final String PROP_INITIAL_STARTLEVEL = "osgi.startLevel"; //$NON-NLS-1$ //The start level when the fwl start + public static final String PROP_INITIAL_STARTLEVEL = "osgi.startLevel"; //$NON-NLS-1$ //The start level when the + // fwl start public static final String PROP_DEBUG = "osgi.debug"; //$NON-NLS-1$ public static final String PROP_DEV = "osgi.dev"; //$NON-NLS-1$ public static final String PROP_CLEAN = "osgi.clean"; //$NON-NLS-1$ @@ -119,7 +125,8 @@ public class EclipseStarter { public static final String PROP_LOGFILE = "osgi.logfile"; //$NON-NLS-1$ public static final String PROP_FRAMEWORK = "osgi.framework"; //$NON-NLS-1$ public static final String PROP_INSTALL_AREA = "osgi.install.area"; //$NON-NLS-1$ - public static final String PROP_FRAMEWORK_SHAPE = "osgi.framework.shape"; //$NON-NLS-1$ //the shape of the fwk (jar, or folder) + public static final String PROP_FRAMEWORK_SHAPE = "osgi.framework.shape"; //$NON-NLS-1$ //the shape of the fwk + // (jar, or folder) public static final String PROP_NOSHUTDOWN = "osgi.noShutdown"; //$NON-NLS-1$ public static final String PROP_EXITCODE = "eclipse.exitcode"; //$NON-NLS-1$ @@ -139,7 +146,8 @@ public class EclipseStarter { private static final String DEFAULT_BUNDLES_STARTLEVEL = "4"; //$NON-NLS-1$ private static FrameworkLog log; - // directory of serch candidates keyed by directory abs path -> directory listing (bug 122024) + // directory of serch candidates keyed by directory abs path -> directory + // listing (bug 122024) private static Map searchCandidates = new HashMap<>(4); private static EclipseAppLauncher appLauncher; private static List shutdownHandlers; @@ -189,8 +197,10 @@ private synchronized static Map getConfiguration() { if (configuration == null) { configuration = new HashMap<>(); // TODO hack to set these to defaults for EclipseStarter - // Note that this hack does not allow this property to be specified in config.ini - configuration.put(EquinoxConfiguration.PROP_USE_SYSTEM_PROPERTIES, System.getProperty(EquinoxConfiguration.PROP_USE_SYSTEM_PROPERTIES, "true")); //$NON-NLS-1$ + // Note that this hack does not allow this property to be specified in + // config.ini + configuration.put(EquinoxConfiguration.PROP_USE_SYSTEM_PROPERTIES, + System.getProperty(EquinoxConfiguration.PROP_USE_SYSTEM_PROPERTIES, "true")); //$NON-NLS-1$ // we handle this compatibility setting special for EclipseStarter String systemCompatibilityBoot = System.getProperty(EquinoxConfiguration.PROP_COMPATIBILITY_BOOTDELEGATION); if (systemCompatibilityBoot != null) { @@ -198,7 +208,8 @@ private synchronized static Map getConfiguration() { configuration.put(EquinoxConfiguration.PROP_COMPATIBILITY_BOOTDELEGATION, systemCompatibilityBoot); } else { // set a default value; but this value can be overriden by the config.ini - configuration.put(EquinoxConfiguration.PROP_COMPATIBILITY_BOOTDELEGATION + EquinoxConfiguration.PROP_DEFAULT_SUFFIX, "true"); //$NON-NLS-1$ + configuration.put(EquinoxConfiguration.PROP_COMPATIBILITY_BOOTDELEGATION + + EquinoxConfiguration.PROP_DEFAULT_SUFFIX, "true"); //$NON-NLS-1$ } String dsDelayedKeepInstances = System.getProperty(EquinoxConfiguration.PROP_DS_DELAYED_KEEPINSTANCES); @@ -207,22 +218,25 @@ private synchronized static Map getConfiguration() { configuration.put(EquinoxConfiguration.PROP_DS_DELAYED_KEEPINSTANCES, dsDelayedKeepInstances); } else { // set a default value; but this value can be overriden by the config.ini - configuration.put(EquinoxConfiguration.PROP_DS_DELAYED_KEEPINSTANCES + EquinoxConfiguration.PROP_DEFAULT_SUFFIX, "true"); //$NON-NLS-1$ + configuration.put( + EquinoxConfiguration.PROP_DS_DELAYED_KEEPINSTANCES + EquinoxConfiguration.PROP_DEFAULT_SUFFIX, + "true"); //$NON-NLS-1$ } } return configuration; } /** - * This is the main to start osgi. - * It only works when the framework is being jared as a single jar + * This is the main to start osgi. It only works when the framework is being + * jared as a single jar */ public static void main(String[] args) throws Exception { if (getProperty("eclipse.startTime") == null) //$NON-NLS-1$ setProperty("eclipse.startTime", Long.toString(System.currentTimeMillis())); //$NON-NLS-1$ if (getProperty(PROP_NOSHUTDOWN) == null) setProperty(PROP_NOSHUTDOWN, "true"); //$NON-NLS-1$ - // set the compatibility boot delegation flag to false to get "standard" OSGi behavior WRT boot delegation (bug 178477) + // set the compatibility boot delegation flag to false to get "standard" OSGi + // behavior WRT boot delegation (bug 178477) if (getProperty(EquinoxConfiguration.PROP_COMPATIBILITY_BOOTDELEGATION) == null) setProperty(EquinoxConfiguration.PROP_COMPATIBILITY_BOOTDELEGATION, "false"); //$NON-NLS-1$ Object result = run(args, null); @@ -231,15 +245,17 @@ public static void main(String[] args) throws Exception { } /** - * Launches the platform and runs a single application. The application is either identified - * in the given arguments (e.g., -application <app id>) or in the eclipse.application - * System property. This convenience method starts - * up the platform, runs the indicated application, and then shuts down the - * platform. The platform must not be running already. + * Launches the platform and runs a single application. The application is + * either identified in the given arguments (e.g., -application <app id>) + * or in the eclipse.application System property. This convenience + * method starts up the platform, runs the indicated application, and then shuts + * down the platform. The platform must not be running already. * - * @param args the command line-style arguments used to configure the platform + * @param args the command line-style arguments used to configure + * the platform * @param endSplashHandler the block of code to run to tear down the splash - * screen or null if no tear down is required + * screen or null if no tear down is + * required * @return the result of running the application * @throws Exception if anything goes wrong */ @@ -258,39 +274,47 @@ public static Object run(String[] args, Runnable endSplashHandler) throws Except if (endSplashHandler != null) endSplashHandler.run(); // may use startupFailed to understand where the error happened - FrameworkLogEntry logEntry = new FrameworkLogEntry(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, 0, startupFailed ? Msg.ECLIPSE_STARTUP_STARTUP_ERROR : Msg.ECLIPSE_STARTUP_APP_ERROR, 1, e, null); + FrameworkLogEntry logEntry = new FrameworkLogEntry(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, 0, + startupFailed ? Msg.ECLIPSE_STARTUP_STARTUP_ERROR : Msg.ECLIPSE_STARTUP_APP_ERROR, 1, e, null); if (log != null) log.log(logEntry); else - // TODO desperate measure - ideally, we should write this to disk (a la Main.log) + // TODO desperate measure - ideally, we should write this to disk (a la + // Main.log) e.printStackTrace(); } finally { try { - // The application typically sets the exit code however the framework can request that - // it be re-started. We need to check for this and potentially override the exit code. + // The application typically sets the exit code however the framework can + // request that + // it be re-started. We need to check for this and potentially override the exit + // code. if (isForcedRestart()) setProperty(PROP_EXITCODE, "23"); //$NON-NLS-1$ if (!Boolean.valueOf(getProperty(PROP_NOSHUTDOWN)).booleanValue()) shutdown(); } catch (Throwable e) { - FrameworkLogEntry logEntry = new FrameworkLogEntry(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, 0, Msg.ECLIPSE_STARTUP_SHUTDOWN_ERROR, 1, e, null); + FrameworkLogEntry logEntry = new FrameworkLogEntry(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, 0, + Msg.ECLIPSE_STARTUP_SHUTDOWN_ERROR, 1, e, null); if (log != null) log.log(logEntry); else - // TODO desperate measure - ideally, we should write this to disk (a la Main.log) + // TODO desperate measure - ideally, we should write this to disk (a la + // Main.log) e.printStackTrace(); } } // we only get here if an error happened if (getProperty(PROP_EXITCODE) == null) { setProperty(PROP_EXITCODE, "13"); //$NON-NLS-1$ - setProperty(PROP_EXITDATA, NLS.bind(Msg.ECLIPSE_STARTUP_ERROR_CHECK_LOG, log == null ? null : log.getFile().getPath())); + setProperty(PROP_EXITDATA, + NLS.bind(Msg.ECLIPSE_STARTUP_ERROR_CHECK_LOG, log == null ? null : log.getFile().getPath())); } return null; } /** * Returns true if the platform is already running, false otherwise. + * * @return whether or not the platform is already running */ public static boolean isRunning() { @@ -298,12 +322,15 @@ public static boolean isRunning() { } /** - * Starts the platform and sets it up to run a single application. The application is either identified - * in the given arguments (e.g., -application <app id>) or in the eclipse.application - * System property. The platform must not be running already. + * Starts the platform and sets it up to run a single application. The + * application is either identified in the given arguments (e.g., -application + * <app id>) or in the eclipse.application System property. + * The platform must not be running already. *

- * The given runnable (if not null) is used to tear down the splash screen if required. + * The given runnable (if not null) is used to tear down the splash + * screen if required. *

+ * * @param args the arguments passed to the application * @return BundleContext the context of the system bundle * @throws Exception if anything goes wrong @@ -330,9 +357,11 @@ public static BundleContext startup(String[] args, Runnable endSplashHandler) th Bundle[] startBundles = loadBasicBundles(); - if (startBundles == null || ("true".equals(getProperty(PROP_REFRESH_BUNDLES)) && refreshPackages(getCurrentBundles(false)))) { //$NON-NLS-1$ + if (startBundles == null + || ("true".equals(getProperty(PROP_REFRESH_BUNDLES)) && refreshPackages(getCurrentBundles(false)))) { //$NON-NLS-1$ waitForShutdown(); - return context; // cannot continue; loadBasicBundles caused refreshPackages to shutdown the framework + return context; // cannot continue; loadBasicBundles caused refreshPackages to shutdown the + // framework } framework.start(); @@ -341,17 +370,20 @@ public static BundleContext startup(String[] args, Runnable endSplashHandler) th waitForShutdown(); return context; } - // set the framework start level to the ultimate value. This will actually start things + // set the framework start level to the ultimate value. This will actually start + // things // running if they are persistently active. setStartLevel(getStartLevel()); // they should all be active by this time ensureBundlesActive(startBundles); - // in the case where the built-in console is disabled we should try to start the console bundle + // in the case where the built-in console is disabled we should try to start the + // console bundle try { consoleMgr.checkForConsoleBundle(); } catch (BundleException e) { - FrameworkLogEntry entry = new FrameworkLogEntry(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, 0, e.getMessage(), 0, e, null); + FrameworkLogEntry entry = new FrameworkLogEntry(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, 0, + e.getMessage(), 0, e, null); log.log(entry); } // TODO should log unresolved bundles if in debug or dev mode @@ -372,14 +404,17 @@ private static int getStartLevel() { } /** - * Runs the application for which the platform was started. The platform - * must be running. + * Runs the application for which the platform was started. The platform must be + * running. *

- * The given argument is passed to the application being run. If it is null - * then the command line arguments used in starting the platform, and not consumed - * by the platform code, are passed to the application as a String[]. + * The given argument is passed to the application being run. If it is + * null then the command line arguments used in starting the + * platform, and not consumed by the platform code, are passed to the + * application as a String[]. *

- * @param argument the argument passed to the application. May be null + * + * @param argument the argument passed to the application. May be + * null * @return the result of running the application * @throws Exception if anything goes wrong */ @@ -394,10 +429,12 @@ public static Object run(Object argument) throws Exception { boolean launchDefault = Boolean.parseBoolean(getProperty(PROP_APPLICATION_LAUNCHDEFAULT, "true")); //$NON-NLS-1$ // create the ApplicationLauncher and register it as a service - appLauncher = new EclipseAppLauncher(context, Boolean.parseBoolean(getProperty(PROP_ALLOW_APPRELAUNCH)), launchDefault, log, equinoxConfig); - appLauncherRegistration = context.registerService(ApplicationLauncher.class.getName(), appLauncher, null); + appLauncher = new EclipseAppLauncher(context, Boolean.parseBoolean(getProperty(PROP_ALLOW_APPRELAUNCH)), + launchDefault, log, equinoxConfig); + appLauncherRegistration = context.registerService(ApplicationLauncher.class.getName(), appLauncher, + null); // must start the launcher AFTER service restration because this method - // blocks and runs the application on the current thread. This method + // blocks and runs the application on the current thread. This method // will return only after the application has stopped. return appLauncher.start(argument); } @@ -407,7 +444,9 @@ public static Object run(Object argument) throws Exception { ResolutionReport report = context.getBundle().adapt(Module.class).getContainer().resolve(null, false); for (Resource unresolved : report.getEntries().keySet()) { String bsn = ((ModuleRevision) unresolved).getSymbolicName(); - FrameworkLogEntry logEntry = new FrameworkLogEntry(bsn != null ? bsn : EquinoxContainer.NAME, FrameworkLogEntry.WARNING, 0, Msg.Module_ResolveError + report.getResolutionReportMessage(unresolved), 1, null, null); + FrameworkLogEntry logEntry = new FrameworkLogEntry(bsn != null ? bsn : EquinoxContainer.NAME, + FrameworkLogEntry.WARNING, 0, + Msg.Module_ResolveError + report.getResolutionReportMessage(unresolved), 1, null, null); log.log(logEntry); } } @@ -416,20 +455,21 @@ public static Object run(Object argument) throws Exception { } /** - * Shuts down the Platform. The state of the Platform is not automatically - * saved before shutting down. + * Shuts down the Platform. The state of the Platform is not automatically saved + * before shutting down. *

* On return, the Platform will no longer be running (but could be re-launched - * with another call to startup). If relaunching, care must be taken to reinitialize - * any System properties which the platform uses (e.g., osgi.instance.area) as - * some policies in the platform do not allow resetting of such properties on - * subsequent runs. - *

- * Any objects handed out by running Platform, - * including Platform runnables obtained via getRunnable, will be - * permanently invalid. The effects of attempting to invoke methods - * on invalid objects is undefined. + * with another call to startup). If relaunching, care must be taken to + * reinitialize any System properties which the platform uses (e.g., + * osgi.instance.area) as some policies in the platform do not allow resetting + * of such properties on subsequent runs. *

+ *

+ * Any objects handed out by running Platform, including Platform runnables + * obtained via getRunnable, will be permanently invalid. The effects of + * attempting to invoke methods on invalid objects is undefined. + *

+ * * @throws Exception if anything goes wrong */ public static void shutdown() throws Exception { @@ -469,14 +509,17 @@ private static void ensureBundlesActive(Bundle[] bundles) { if (bundle.getState() != Bundle.ACTIVE) { if (bundle.getState() == Bundle.INSTALLED) { // Log that the bundle is not resolved - log.log(new FrameworkLogEntry(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, 0, NLS.bind(Msg.ECLIPSE_STARTUP_ERROR_BUNDLE_NOT_RESOLVED, bundle.getLocation()), 0, null, null)); + log.log(new FrameworkLogEntry(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, 0, + NLS.bind(Msg.ECLIPSE_STARTUP_ERROR_BUNDLE_NOT_RESOLVED, bundle.getLocation()), 0, null, + null)); continue; } // check that the startlevel allows the bundle to be active (111550) FrameworkStartLevel fwStartLevel = context.getBundle().adapt(FrameworkStartLevel.class); BundleStartLevel bundleStartLevel = bundle.adapt(BundleStartLevel.class); if (fwStartLevel != null && (bundleStartLevel.getStartLevel() <= fwStartLevel.getStartLevel())) { - log.log(new FrameworkLogEntry(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, 0, NLS.bind(Msg.ECLIPSE_STARTUP_ERROR_BUNDLE_NOT_ACTIVE, bundle), 0, null, null)); + log.log(new FrameworkLogEntry(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, 0, + NLS.bind(Msg.ECLIPSE_STARTUP_ERROR_BUNDLE_NOT_ACTIVE, bundle), 0, null, null)); } } } @@ -492,7 +535,8 @@ private static void publishSplashScreen(final Runnable endSplashHandler) { if (outputStream instanceof OutputStream) { Dictionary osProperties = new Hashtable<>(); osProperties.put("name", "splashstream"); //$NON-NLS-1$//$NON-NLS-2$ - splashStreamRegistration = context.registerService(OutputStream.class.getName(), outputStream, osProperties); + splashStreamRegistration = context.registerService(OutputStream.class.getName(), outputStream, + osProperties); } } catch (Exception ex) { // ignore @@ -501,9 +545,10 @@ private static void publishSplashScreen(final Runnable endSplashHandler) { try { Dictionary monitorProps = new Hashtable<>(); monitorProps.put(Constants.SERVICE_RANKING, Integer.valueOf(Integer.MIN_VALUE)); - defaultMonitorRegistration = context.registerService(StartupMonitor.class.getName(), new DefaultStartupMonitor(endSplashHandler, equinoxConfig), monitorProps); + defaultMonitorRegistration = context.registerService(StartupMonitor.class.getName(), + new DefaultStartupMonitor(endSplashHandler, equinoxConfig), monitorProps); } catch (IllegalStateException e) { - //splash handler did not provide the necessary methods, ignore it + // splash handler did not provide the necessary methods, ignore it } } @@ -516,19 +561,22 @@ private static URL searchForBundle(String name, String parent) throws MalformedU createURL(name); // quick check to see if the name is a valid URL url = createURL(new File(parent).toURL(), name); } catch (MalformedURLException e) { - // TODO this is legacy support for non-URL names. It should be removed eventually. + // TODO this is legacy support for non-URL names. It should be removed + // eventually. // if name was not a URL then construct one. - // Assume it should be a reference and that it is relative. This support need not + // Assume it should be a reference and that it is relative. This support need + // not // be robust as it is temporary.. File child = new File(name); fileLocation = child.isAbsolute() ? child : new File(parent, name); url = createURL(REFERENCE_PROTOCOL, null, fileLocation.toURL().toExternalForm()); reference = true; } - // if the name was a URL then see if it is relative. If so, insert syspath. + // if the name was a URL then see if it is relative. If so, insert syspath. if (!reference) { URL baseURL = url; - // if it is a reference URL then strip off the reference: and set base to the file:... + // if it is a reference URL then strip off the reference: and set base to the + // file:... if (url.getProtocol().equals(REFERENCE_PROTOCOL)) { reference = true; String baseSpec = url.getPath(); @@ -560,16 +608,17 @@ private static URL searchForBundle(String name, String parent) throws MalformedU result.connect(); return url; } catch (IOException e) { - // int i = location.lastIndexOf('_'); - // return i == -1? location : location.substring(0, i); + // int i = location.lastIndexOf('_'); + // return i == -1? location : location.substring(0, i); return null; } } /* - * Ensure all basic bundles are installed, resolved and scheduled to start. Returns an array containing - * all basic bundles that are marked to start. - * Returns null if the framework has been shutdown as a result of refreshPackages + * Ensure all basic bundles are installed, resolved and scheduled to start. + * Returns an array containing all basic bundles that are marked to start. + * Returns null if the framework has been shutdown as a result of + * refreshPackages */ private static Bundle[] loadBasicBundles() throws InterruptedException { long startTime = System.currentTimeMillis(); @@ -596,7 +645,8 @@ private static Bundle[] loadBasicBundles() throws InterruptedException { List lazyActivationBundles = new ArrayList<>(installEntries.length); installBundles(initialBundles, curInitBundles, startBundles, lazyActivationBundles, toRefresh); - // If we installed/uninstalled something, force a refresh of all installed/uninstalled bundles + // If we installed/uninstalled something, force a refresh of all + // installed/uninstalled bundles if (!toRefresh.isEmpty() && refreshPackages(toRefresh.toArray(new Bundle[toRefresh.size()]))) return null; // cannot continue; refreshPackages shutdown the framework @@ -654,7 +704,8 @@ private static InitialBundle[] getInitialBundles(String[] installEntries) { try { URL location = searchForBundle(name, syspath); if (location == null) { - FrameworkLogEntry entry = new FrameworkLogEntry(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, 0, NLS.bind(Msg.ECLIPSE_STARTUP_BUNDLE_NOT_FOUND, name), 0, null, null); + FrameworkLogEntry entry = new FrameworkLogEntry(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, 0, + NLS.bind(Msg.ECLIPSE_STARTUP_BUNDLE_NOT_FOUND, name), 0, null, null); log.log(entry); // skip this entry continue; @@ -662,14 +713,16 @@ private static InitialBundle[] getInitialBundles(String[] installEntries) { location = makeRelative(installLocation.getURL(), location); String locationString = INITIAL_LOCATION + location.toExternalForm(); result.add(new InitialBundle(locationString, location, level, start)); - }catch (IOException e) { - log.log(new FrameworkLogEntry(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, 0, e.getMessage(), 0, e, null)); + } catch (IOException e) { + log.log(new FrameworkLogEntry(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, 0, e.getMessage(), 0, e, + null)); } } return result.toArray(new InitialBundle[result.size()]); } - // returns true if the refreshPackages operation caused the framework to shutdown + // returns true if the refreshPackages operation caused the framework to + // shutdown private static boolean refreshPackages(Bundle[] bundles) throws InterruptedException { FrameworkWiring frameworkWiring = context.getBundle().adapt(FrameworkWiring.class); if (frameworkWiring == null) @@ -706,20 +759,26 @@ private static void processCommandLine(String[] args) throws Exception { // check for args without parameters (i.e., a flag arg) // check if debug should be enabled for the entire platform - // If this is the last arg or there is a following arg (i.e., arg+1 has a leading -), - // simply enable debug. Otherwise, assume that that the following arg is - // actually the filename of an options file. This will be processed below. - if (args[i].equalsIgnoreCase(DEBUG) && ((i + 1 == args.length) || ((i + 1 < args.length) && (args[i + 1].startsWith("-"))))) { //$NON-NLS-1$ + // If this is the last arg or there is a following arg (i.e., arg+1 has a + // leading -), + // simply enable debug. Otherwise, assume that that the following arg is + // actually the filename of an options file. This will be processed below. + if (args[i].equalsIgnoreCase(DEBUG) + && ((i + 1 == args.length) || ((i + 1 < args.length) && (args[i + 1].startsWith("-"))))) { //$NON-NLS-1$ setProperty(PROP_DEBUG, ""); //$NON-NLS-1$ debug = true; found = true; } // check if development mode should be enabled for the entire platform - // If this is the last arg or there is a following arg (i.e., arg+1 has a leading -), - // simply enable development mode. Otherwise, assume that that the following arg is - // actually some additional development time class path entries. This will be processed below. - if (args[i].equalsIgnoreCase(DEV) && ((i + 1 == args.length) || ((i + 1 < args.length) && (args[i + 1].startsWith("-"))))) { //$NON-NLS-1$ + // If this is the last arg or there is a following arg (i.e., arg+1 has a + // leading -), + // simply enable development mode. Otherwise, assume that that the following arg + // is + // actually some additional development time class path entries. This will be + // processed below. + if (args[i].equalsIgnoreCase(DEV) + && ((i + 1 == args.length) || ((i + 1 < args.length) && (args[i + 1].startsWith("-"))))) { //$NON-NLS-1$ setProperty(PROP_DEV, ""); //$NON-NLS-1$ found = true; } @@ -743,7 +802,8 @@ private static void processCommandLine(String[] args) throws Exception { } // look for the console with no port. - if (args[i].equalsIgnoreCase(CONSOLE) && ((i + 1 == args.length) || ((i + 1 < args.length) && (args[i + 1].startsWith("-"))))) { //$NON-NLS-1$ + if (args[i].equalsIgnoreCase(CONSOLE) + && ((i + 1 == args.length) || ((i + 1 < args.length) && (args[i + 1].startsWith("-"))))) { //$NON-NLS-1$ setProperty(PROP_CONSOLE, ""); //$NON-NLS-1$ found = true; } @@ -757,8 +817,10 @@ private static void processCommandLine(String[] args) throws Exception { configArgs[configArgIndex++] = i; continue; } - // 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 parm so continue. + // 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 parm so + // continue. if (i == args.length - 1 || args[i + 1].startsWith("-")) { //$NON-NLS-1$ continue; } @@ -836,7 +898,7 @@ private static void processCommandLine(String[] args) throws Exception { found = true; } - // done checking for args. Remember where an arg was found + // done checking for args. Remember where an arg was found if (found) { configArgs[configArgIndex++] = i - 1; configArgs[configArgIndex++] = i; @@ -865,7 +927,8 @@ private static void processCommandLine(String[] args) throws Exception { } /** - * Returns the result of converting a list of comma-separated tokens into an array + * Returns the result of converting a list of comma-separated tokens into an + * array * * @return the array of string tokens * @param prop the initial comma-separated string @@ -953,7 +1016,8 @@ private static Bundle getBundleByLocation(String location, Bundle[] bundles) { return null; } - private static void uninstallBundles(Bundle[] curInitBundles, InitialBundle[] newInitBundles, List toRefresh) { + private static void uninstallBundles(Bundle[] curInitBundles, InitialBundle[] newInitBundles, + List toRefresh) { for (Bundle curInitBundle : curInitBundles) { boolean found = false; for (InitialBundle newInitBundle : newInitBundles) { @@ -967,14 +1031,16 @@ private static void uninstallBundles(Bundle[] curInitBundles, InitialBundle[] ne curInitBundle.uninstall(); toRefresh.add(curInitBundle); } catch (BundleException e) { - FrameworkLogEntry entry = new FrameworkLogEntry(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, 0, NLS.bind(Msg.ECLIPSE_STARTUP_FAILED_UNINSTALL, curInitBundle.getLocation()), 0, e, null); + FrameworkLogEntry entry = new FrameworkLogEntry(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, 0, + NLS.bind(Msg.ECLIPSE_STARTUP_FAILED_UNINSTALL, curInitBundle.getLocation()), 0, e, null); log.log(entry); } } } } - private static void installBundles(InitialBundle[] initialBundles, Bundle[] curInitBundles, List startBundles, List lazyActivationBundles, List toRefresh) { + private static void installBundles(InitialBundle[] initialBundles, Bundle[] curInitBundles, + List startBundles, List lazyActivationBundles, List toRefresh) { for (InitialBundle initialBundle : initialBundles) { Bundle osgiBundle = getBundleByLocation(initialBundle.locationString, curInitBundles); try { @@ -983,14 +1049,15 @@ private static void installBundles(InitialBundle[] initialBundles, Bundle[] curI InputStream in = LocationHelper.getStream(initialBundle.location); try { osgiBundle = context.installBundle(initialBundle.locationString, in); - }catch (BundleException e) { + } catch (BundleException e) { if (e.getType() == BundleException.DUPLICATE_BUNDLE_ERROR) { continue; // TODO should attempt to lookup the existing bundle } throw e; } - // only check for lazy activation header if this is a newly installed bundle and is not marked for persistent start + // only check for lazy activation header if this is a newly installed bundle and + // is not marked for persistent start if (!initialBundle.start && hasLazyActivationPolicy(osgiBundle)) { lazyActivationBundles.add(osgiBundle); } @@ -1008,7 +1075,8 @@ private static void installBundles(InitialBundle[] initialBundles, Bundle[] curI if ((osgiBundle.getState() & Bundle.INSTALLED) != 0) toRefresh.add(osgiBundle); } catch (BundleException | IOException e) { - FrameworkLogEntry entry = new FrameworkLogEntry(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, 0, NLS.bind(Msg.ECLIPSE_STARTUP_FAILED_INSTALL, initialBundle.location), 0, e, null); + FrameworkLogEntry entry = new FrameworkLogEntry(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, 0, + NLS.bind(Msg.ECLIPSE_STARTUP_FAILED_INSTALL, initialBundle.location), 0, e, null); log.log(entry); } } @@ -1026,18 +1094,21 @@ private static boolean hasLazyActivationPolicy(Bundle target) { String activationPolicy = headers.get(Constants.BUNDLE_ACTIVATIONPOLICY); try { if (activationPolicy != null) { - ManifestElement[] elements = ManifestElement.parseHeader(Constants.BUNDLE_ACTIVATIONPOLICY, activationPolicy); + ManifestElement[] elements = ManifestElement.parseHeader(Constants.BUNDLE_ACTIVATIONPOLICY, + activationPolicy); if (elements != null && elements.length > 0) { // if the value is "lazy" then it has a lazy activation poliyc if (Constants.ACTIVATION_LAZY.equals(elements[0].getValue())) return true; } } else { - // check for Eclipse specific lazy start headers "Eclipse-LazyStart" and "Eclipse-AutoStart" + // check for Eclipse specific lazy start headers "Eclipse-LazyStart" and + // "Eclipse-AutoStart" String eclipseLazyStart = headers.get(EquinoxModuleDataNamespace.LAZYSTART_HEADER); if (eclipseLazyStart == null) eclipseLazyStart = headers.get(EquinoxModuleDataNamespace.AUTOSTART_HEADER); - ManifestElement[] elements = ManifestElement.parseHeader(EquinoxModuleDataNamespace.AUTOSTART_HEADER, eclipseLazyStart); + ManifestElement[] elements = ManifestElement.parseHeader(EquinoxModuleDataNamespace.AUTOSTART_HEADER, + eclipseLazyStart); if (elements != null && elements.length > 0) { // if the value is true then it is lazy activated if ("true".equals(elements[0].getValue())) //$NON-NLS-1$ @@ -1068,15 +1139,17 @@ private static void startBundle(Bundle bundle, int options) { } catch (BundleException e) { if ((bundle.getState() & Bundle.RESOLVED) != 0) { // only log errors if the bundle is resolved - FrameworkLogEntry entry = new FrameworkLogEntry(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, 0, NLS.bind(Msg.ECLIPSE_STARTUP_FAILED_START, bundle.getLocation()), 0, e, null); + FrameworkLogEntry entry = new FrameworkLogEntry(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, 0, + NLS.bind(Msg.ECLIPSE_STARTUP_FAILED_START, bundle.getLocation()), 0, e, null); log.log(entry); } } } /** - * Returns a URL which is equivalent to the given URL relative to the - * specified base URL. Works only for file: URLs + * Returns a URL which is equivalent to the given URL relative to the specified + * base URL. Works only for file: URLs + * * @throws MalformedURLException */ private static URL makeRelative(URL base, URL location) throws MalformedURLException { @@ -1101,7 +1174,8 @@ private static URL makeRelative(URL base, URL location) throws MalformedURLExcep if (nonReferenceLocation.getPath().endsWith("/")) //$NON-NLS-1$ // restore original trailing slash urlPath += '/'; - // couldn't use File to create URL here because it prepends the path with user.dir + // couldn't use File to create URL here because it prepends the path with + // user.dir URL relativeURL = createURL(base.getProtocol(), base.getHost(), base.getPort(), urlPath); // now make it back to a reference URL relativeURL = createURL(REFERENCE_SCHEME + relativeURL.toExternalForm()); @@ -1125,7 +1199,8 @@ private static URL createURL(String protocol, String host, String file) throws M private static URL createURL(String protocol, String host, int port, String file) throws MalformedURLException { if (context != null && REFERENCE_PROTOCOL.equalsIgnoreCase(protocol)) { - return new URL(protocol, host, port, file, new Handler(context.getProperty(EquinoxLocations.PROP_INSTALL_AREA))); + return new URL(protocol, host, port, file, + new Handler(context.getProperty(EquinoxLocations.PROP_INSTALL_AREA))); } return new URL(protocol, host, port, file); } @@ -1170,7 +1245,8 @@ public void frameworkEvent(FrameworkEvent event) { } private static void updateSplash(Semaphore semaphore, StartupEventListener listener) throws InterruptedException { - ServiceTracker monitorTracker = new ServiceTracker<>(context, StartupMonitor.class.getName(), null); + ServiceTracker monitorTracker = new ServiceTracker<>(context, + StartupMonitor.class.getName(), null); try { monitorTracker.open(); } catch (IllegalStateException e) { @@ -1189,8 +1265,8 @@ private static void updateSplash(Semaphore semaphore, StartupEventListener liste } // can we acquire the semaphore yet? if (semaphore.tryAcquire(50, TimeUnit.MILLISECONDS)) - break; //done - //else still working, spin another update + break; // done + // else still working, spin another update } } finally { if (listener != null) { @@ -1205,9 +1281,9 @@ private static void updateSplash(Semaphore semaphore, StartupEventListener liste } /** - * Searches for the given target directory immediately under - * the given start location. If one is found then this location is returned; - * otherwise an exception is thrown. + * Searches for the given target directory immediately under the given start + * location. If one is found then this location is returned; otherwise an + * exception is thrown. * * @return the location where target directory was found * @param start the location to begin searching @@ -1230,7 +1306,8 @@ private static String searchFor(final String target, String start) { if (!candidateName.startsWith(target)) continue; boolean simpleJar = false; - final char versionSep = candidateName.length() > target.length() ? candidateName.charAt(target.length()) : 0; + final char versionSep = candidateName.length() > target.length() ? candidateName.charAt(target.length()) + : 0; if (candidateName.length() > target.length() && versionSep != '_' && versionSep != '-') { // make sure this is not just a jar with no (_|-)version tacked on the end if (candidateName.length() == 4 + target.length() && candidateName.endsWith(".jar")) //$NON-NLS-1$ @@ -1239,8 +1316,11 @@ private static String searchFor(final String target, String start) { // name does not match the target properly with an (_|-) version at the end continue; } - // Note: directory with version suffix is always > than directory without version suffix - String version = candidateName.length() > target.length() + 1 && (versionSep == '_' || versionSep == '-') ? candidateName.substring(target.length() + 1) : ""; //$NON-NLS-1$ + // Note: directory with version suffix is always > than directory without + // version suffix + String version = candidateName.length() > target.length() + 1 && (versionSep == '_' || versionSep == '-') + ? candidateName.substring(target.length() + 1) + : ""; //$NON-NLS-1$ Object[] currentVersion = getVersionElements(version); if (currentVersion != null && compareVersion(maxVersion, currentVersion) < 0) { File candidate = new File(start, candidateName); @@ -1259,16 +1339,18 @@ private static String searchFor(final String target, String start) { } /** - * Do a quick parse of version identifier so its elements can be correctly compared. - * If we are unable to parse the full version, remaining elements are initialized - * with suitable defaults. - * @return an array of size 4; first three elements are of type Integer (representing - * major, minor and service) and the fourth element is of type String (representing - * qualifier). A value of null is returned if there are no valid Integers. Note, that - * returning anything else will cause exceptions in the caller. + * Do a quick parse of version identifier so its elements can be correctly + * compared. If we are unable to parse the full version, remaining elements are + * initialized with suitable defaults. + * + * @return an array of size 4; first three elements are of type Integer + * (representing major, minor and service) and the fourth element is of + * type String (representing qualifier). A value of null is returned if + * there are no valid Integers. Note, that returning anything else will + * cause exceptions in the caller. */ private static Object[] getVersionElements(String version) { - Object[] result = {Integer.valueOf(-1), Integer.valueOf(-1), Integer.valueOf(-1), ""}; //$NON-NLS-1$ + Object[] result = { Integer.valueOf(-1), Integer.valueOf(-1), Integer.valueOf(-1), "" }; //$NON-NLS-1$ StringTokenizer t = new StringTokenizer(version, "."); //$NON-NLS-1$ String token; for (int i = 0; t.hasMoreTokens() && i < 4; i++) { @@ -1293,10 +1375,9 @@ private static Object[] getVersionElements(String version) { /** * Compares version strings. - * @return result of comparison, as integer; - * <0 if left < right; - * 0 if left == right; - * >0 if left > right; + * + * @return result of comparison, as integer; <0 if left < right; + * 0 if left == right; >0 if left > right; */ private static int compareVersion(Object[] left, Object[] right) { if (left == null) @@ -1331,14 +1412,15 @@ private static class InitialBundle { } /** - * Sets the initial properties for the platform. - * This method must be called before calling the {@link #run(String[], Runnable)} or + * Sets the initial properties for the platform. This method must be called + * before calling the {@link #run(String[], Runnable)} or * {@link #startup(String[], Runnable)} methods for the properties to be used in * a launched instance of the platform. *

* If the specified properties contains a null value then the key for that value * will be cleared from the properties of the platform. *

+ * * @param initialProperties the initial properties to set for the platform. * @since 3.2 */ @@ -1354,12 +1436,15 @@ public static void setInitialProperties(Map initialProperties) { } /** - * Returns the context of the system bundle. A value of - * null is returned if the platform is not running. + * Returns the context of the system bundle. A value of null is + * returned if the platform is not running. + * * @return the context of the system bundle * @throws java.lang.SecurityException If the caller does not have the - * appropriate AdminPermission[system.bundle,CONTEXT], and - * the Java Runtime Environment supports permissions. + * appropriate + * AdminPermission[system.bundle,CONTEXT], + * and the Java Runtime Environment supports + * permissions. */ public static BundleContext getSystemBundleContext() { if (context == null || !running) @@ -1372,19 +1457,20 @@ private static boolean isForcedRestart() { } /* - * NOTE: This is an internal/experimental method used by launchers that need to react when the framework - * is shutdown internally. + * NOTE: This is an internal/experimental method used by launchers that need to + * react when the framework is shutdown internally. * - * Adds a framework shutdown handler.

- * A handler implements the {@link Runnable} interface. When the framework is shutdown - * the {@link Runnable#run()} method is called for each registered handler. Handlers should - * make no assumptions on the thread it is being called from. If a handler object is - * registered multiple times it will be called once for each registration. - *

- * At the time a handler is called the framework is shutdown. Handlers must not depend on - * a running framework to execute or attempt to load additional classes from bundles - * installed in the framework. + * Adds a framework shutdown handler.

A handler implements the {@link + * Runnable} interface. When the framework is shutdown the {@link + * Runnable#run()} method is called for each registered handler. Handlers should + * make no assumptions on the thread it is being called from. If a handler + * object is registered multiple times it will be called once for each + * registration.

At the time a handler is called the framework is shutdown. + * Handlers must not depend on a running framework to execute or attempt to load + * additional classes from bundles installed in the framework. + * * @param handler the framework shutdown handler + * * @throws IllegalStateException if the platform is already running */ static void internalAddFrameworkShutdownHandler(Runnable handler) { @@ -1398,11 +1484,13 @@ static void internalAddFrameworkShutdownHandler(Runnable handler) { } /* - * NOTE: This is an internal/experimental method used by launchers that need to react when the framework - * is shutdown internally. + * NOTE: This is an internal/experimental method used by launchers that need to + * react when the framework is shutdown internally. * * Removes a framework shutdown handler.

+ * * @param handler the framework shutdown handler + * * @throws IllegalStateException if the platform is already running */ static void internalRemoveFrameworkShutdownHandler(Runnable handler) { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/core/runtime/internal/adaptor/ConsoleManager.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/core/runtime/internal/adaptor/ConsoleManager.java index d5de745907d..8e34f880923 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/core/runtime/internal/adaptor/ConsoleManager.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/core/runtime/internal/adaptor/ConsoleManager.java @@ -61,23 +61,26 @@ public void checkForConsoleBundle() throws BundleException { if ("none".equals(consolePort)) //$NON-NLS-1$ return; // otherwise we need to check for the equinox console bundle and start it - ServiceReference paRef = context.getServiceReference(org.osgi.service.packageadmin.PackageAdmin.class); + ServiceReference paRef = context + .getServiceReference(org.osgi.service.packageadmin.PackageAdmin.class); org.osgi.service.packageadmin.PackageAdmin pa = paRef == null ? null : context.getService(paRef); Bundle[] consoles = pa.getBundles(consoleBundle, null); if (consoles == null || consoles.length == 0) { if (consolePort != null) - throw new BundleException("Could not find bundle: " + consoleBundle, BundleException.UNSUPPORTED_OPERATION); //$NON-NLS-1$ + throw new BundleException("Could not find bundle: " + consoleBundle, //$NON-NLS-1$ + BundleException.UNSUPPORTED_OPERATION); return; } try { consoles[0].start(Bundle.START_TRANSIENT); } catch (BundleException e) { - throw new BundleException("Could not start bundle: " + consoleBundle, BundleException.UNSUPPORTED_OPERATION, e); //$NON-NLS-1$ + throw new BundleException("Could not start bundle: " + consoleBundle, BundleException.UNSUPPORTED_OPERATION, //$NON-NLS-1$ + e); } } /** - * Stops the OSGi Command console + * Stops the OSGi Command console * */ public void stopConsole() { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/core/runtime/internal/adaptor/DefaultStartupMonitor.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/core/runtime/internal/adaptor/DefaultStartupMonitor.java index bad1d89e4f7..500471110a1 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/core/runtime/internal/adaptor/DefaultStartupMonitor.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/core/runtime/internal/adaptor/DefaultStartupMonitor.java @@ -26,26 +26,30 @@ public class DefaultStartupMonitor implements StartupMonitor { private final EquinoxConfiguration equinoxConfig; /** - * Create a new startup monitor using the given splash handler. The splash handle must - * have an updateSplash method. + * Create a new startup monitor using the given splash handler. The splash + * handle must have an updateSplash method. * * @param splashHandler * @throws IllegalStateException */ - public DefaultStartupMonitor(Runnable splashHandler, EquinoxConfiguration equinoxConfig) throws IllegalStateException { + public DefaultStartupMonitor(Runnable splashHandler, EquinoxConfiguration equinoxConfig) + throws IllegalStateException { this.splashHandler = splashHandler; this.equinoxConfig = equinoxConfig; try { updateMethod = splashHandler.getClass().getMethod("updateSplash", (Class[]) null); //$NON-NLS-1$ } catch (SecurityException | NoSuchMethodException e) { - //TODO maybe we could do something else in the update method in this case, like print something to the console? + // TODO maybe we could do something else in the update method in this case, like + // print something to the console? throw new IllegalStateException(e.getMessage(), e); } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.eclipse.core.runtime.adaptor.StartupMonitor#update() */ @Override @@ -57,7 +61,7 @@ public void update() { // ignore, this is best effort } } else { - //TODO maybe we could print something interesting to the console? + // TODO maybe we could print something interesting to the console? } } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/core/runtime/internal/adaptor/EclipseAppLauncher.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/core/runtime/internal/adaptor/EclipseAppLauncher.java index 8d65643e400..ae29006c449 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/core/runtime/internal/adaptor/EclipseAppLauncher.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/core/runtime/internal/adaptor/EclipseAppLauncher.java @@ -39,7 +39,8 @@ public class EclipseAppLauncher implements ApplicationLauncher { private final FrameworkLog log; private final EquinoxConfiguration equinoxConfig; - public EclipseAppLauncher(BundleContext context, boolean relaunch, boolean failOnNoDefault, FrameworkLog log, EquinoxConfiguration equinoxConfig) { + public EclipseAppLauncher(BundleContext context, boolean relaunch, boolean failOnNoDefault, FrameworkLog log, + EquinoxConfiguration equinoxConfig) { this.context = context; this.relaunch = relaunch; this.failOnNoDefault = failOnNoDefault; @@ -52,13 +53,15 @@ public EclipseAppLauncher(BundleContext context, boolean relaunch, boolean failO * Used for backwards compatibility with < 3.2 runtime */ private void findRunnableService() { - // look for a ParameterizedRunnable registered as a service by runtimes (3.0, 3.1) + // look for a ParameterizedRunnable registered as a service by runtimes (3.0, + // 3.1) String appClass = ParameterizedRunnable.class.getName(); ServiceReference[] runRefs = null; try { - runRefs = context.getServiceReferences(ParameterizedRunnable.class.getName(), "(&(objectClass=" + appClass + ")(eclipse.application=*))"); //$NON-NLS-1$//$NON-NLS-2$ + runRefs = context.getServiceReferences(ParameterizedRunnable.class.getName(), + "(&(objectClass=" + appClass + ")(eclipse.application=*))"); //$NON-NLS-1$//$NON-NLS-2$ } catch (InvalidSyntaxException e) { - // ignore this. It should never happen as we have tested the above format. + // ignore this. It should never happen as we have tested the above format. } if (runRefs != null && runRefs.length > 0) { // found the service use it as the application. @@ -70,13 +73,15 @@ private void findRunnableService() { } /* - * Starts this application launcher on the current thread. This method - * should be called by the main thread to ensure that applications are - * launched in the main thread. + * Starts this application launcher on the current thread. This method should be + * called by the main thread to ensure that applications are launched in the + * main thread. */ public Object start(Object defaultContext) throws Exception { // here we assume that launch has been called by runtime before we started - // TODO this may be a bad assumption but it works for now because we register the app launcher as a service and runtime synchronously calls launch on the service + // TODO this may be a bad assumption but it works for now because we register + // the app launcher as a service and runtime synchronously calls launch on the + // service if (failOnNoDefault && runnable == null) throw new IllegalStateException(Msg.ECLIPSE_STARTUP_ERROR_NO_APPLICATION); Object result = null; @@ -108,7 +113,8 @@ public Object start(Object defaultContext) throws Exception { if (!relaunch || (b.getState() & Bundle.ACTIVE) == 0) throw e; if (log != null) - log.log(new FrameworkLogEntry(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, 0, Msg.ECLIPSE_STARTUP_APP_ERROR, 1, e, null)); + log.log(new FrameworkLogEntry(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, 0, + Msg.ECLIPSE_STARTUP_APP_ERROR, 1, e, null)); } doRelaunch = (relaunch && (b.getState() & Bundle.ACTIVE) != 0); } while (doRelaunch); @@ -124,7 +130,8 @@ private Object runApplication(Object defaultContext) throws Exception { // wait for an application to be launched. waitForAppLock.acquire(); // an application is ready; acquire the running lock. - // this must happen after we have acquired an application (by acquiring waitForAppLock above). + // this must happen after we have acquired an application (by acquiring + // waitForAppLock above). runningLock.acquire(); if (EclipseStarter.debug) { String timeString = equinoxConfig.getConfiguration("eclipse.startTime"); //$NON-NLS-1$ @@ -135,7 +142,8 @@ private Object runApplication(Object defaultContext) throws Exception { // run the actual application on the current thread (main). return runnable.run(appContext != null ? appContext : defaultContext); } finally { - // free the runnable application and release the lock to allow another app to be launched. + // free the runnable application and release the lock to allow another app to be + // launched. runnable = null; appContext = null; runningLock.release(); @@ -177,17 +185,19 @@ public void shutdown() { } /* - * Similar to the start method this method will restart the default method on current thread. - * This method assumes that the default application was launched at least once and that an ApplicationDescriptor - * exists that can be used to relaunch the default application. + * Similar to the start method this method will restart the default method on + * current thread. This method assumes that the default application was launched + * at least once and that an ApplicationDescriptor exists that can be used to + * relaunch the default application. */ public Object reStart(Object argument) throws Exception { ServiceReference ref[] = null; - ref = context.getServiceReferences("org.osgi.service.application.ApplicationDescriptor", "(eclipse.application.default=true)"); //$NON-NLS-1$//$NON-NLS-2$ + ref = context.getServiceReferences("org.osgi.service.application.ApplicationDescriptor", //$NON-NLS-1$ + "(eclipse.application.default=true)"); //$NON-NLS-1$ if (ref != null && ref.length > 0) { Object defaultApp = context.getService(ref[0]); - Method launch = defaultApp.getClass().getMethod("launch", new Class[] {Map.class}); //$NON-NLS-1$ - launch.invoke(defaultApp, new Object[] {null}); + Method launch = defaultApp.getClass().getMethod("launch", new Class[] { Map.class }); //$NON-NLS-1$ + launch.invoke(defaultApp, new Object[] { null }); return start(argument); } throw new IllegalStateException(Msg.ECLIPSE_STARTUP_ERROR_NO_APPLICATION); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/Module.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/Module.java index 64cda188b05..362bbcb17e1 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/Module.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/Module.java @@ -34,8 +34,9 @@ import org.osgi.service.resolver.ResolutionException; /** - * A module represents a set of revisions installed in a - * module {@link ModuleContainer container}. + * A module represents a set of revisions installed in a module + * {@link ModuleContainer container}. + * * @since 3.10 */ public abstract class Module implements BundleReference, BundleStartLevel, Comparable { @@ -44,13 +45,13 @@ public abstract class Module implements BundleReference, BundleStartLevel, Compa */ public static enum StartOptions { /** - * The module start operation is transient and the persistent - * autostart or activation policy setting of the module is not modified. + * The module start operation is transient and the persistent autostart or + * activation policy setting of the module is not modified. */ TRANSIENT, /** - * The module start operation must activate the module according to the module's declared - * activation policy. + * The module start operation must activate the module according to the module's + * declared activation policy. */ USE_ACTIVATION_POLICY, /** @@ -59,13 +60,13 @@ public static enum StartOptions { */ TRANSIENT_RESUME, /** - * The module start operation is transient and will only happen if {@link Settings#AUTO_START auto start} - * setting is persistent. + * The module start operation is transient and will only happen if + * {@link Settings#AUTO_START auto start} setting is persistent. */ TRANSIENT_IF_AUTO_START, /** - * The module start operation that indicates the module is being started because of a - * lazy start trigger class load. + * The module start operation that indicates the module is being started because + * of a lazy start trigger class load. */ LAZY_TRIGGER; @@ -87,8 +88,8 @@ public boolean isContained(StartOptions... options) { */ public static enum StopOptions { /** - * The module stop operation is transient and the persistent - * autostart setting of the module is not modified. + * The module stop operation is transient and the persistent autostart setting + * of the module is not modified. */ TRANSIENT; @@ -106,7 +107,8 @@ public boolean isContained(StopOptions... options) { } /** - * An enumeration of the possible {@link Module#getState() states} a module may be in. + * An enumeration of the possible {@link Module#getState() states} a module may + * be in. */ public static enum State { /** @@ -118,8 +120,8 @@ public static enum State { */ RESOLVED, /** - * The module is waiting for a {@link StartOptions#LAZY_TRIGGER trigger} - * class load to proceed with starting. + * The module is waiting for a {@link StartOptions#LAZY_TRIGGER trigger} class + * load to proceed with starting. */ LAZY_STARTING, /** @@ -154,6 +156,7 @@ public static enum Settings { USE_ACTIVATION_POLICY, /** * The module has been set for parallel activation from start-level + * * @since 3.15 */ PARALLEL_ACTIVATION @@ -162,11 +165,13 @@ public static enum Settings { /** * A set of {@link State states} that indicate a module is active. */ - public static final EnumSet ACTIVE_SET = EnumSet.of(State.STARTING, State.LAZY_STARTING, State.ACTIVE, State.STOPPING); + public static final EnumSet ACTIVE_SET = EnumSet.of(State.STARTING, State.LAZY_STARTING, State.ACTIVE, + State.STOPPING); /** * A set of {@link State states} that indicate a module is resolved. */ - public static final EnumSet RESOLVED_SET = EnumSet.of(State.RESOLVED, State.STARTING, State.LAZY_STARTING, State.ACTIVE, State.STOPPING); + public static final EnumSet RESOLVED_SET = EnumSet.of(State.RESOLVED, State.STARTING, State.LAZY_STARTING, + State.ACTIVE, State.STOPPING); private final Long id; private final String location; @@ -180,12 +185,13 @@ public static enum Settings { private volatile long lastModified; /** - * Constructs a new module with the specified id, location and - * container. - * @param id the new module id - * @param location the new module location - * @param container the container for the new module - * @param settings the persisted settings. May be {@code null} if there are no settings. + * Constructs a new module with the specified id, location and container. + * + * @param id the new module id + * @param location the new module location + * @param container the container for the new module + * @param settings the persisted settings. May be {@code null} if there are no + * settings. * @param startlevel the persisted start level or initial start level. */ public Module(Long id, String location, ModuleContainer container, EnumSet settings, int startlevel) { @@ -198,13 +204,16 @@ public Module(Long id, String location, ModuleContainer container, EnumSet - * The time value is a the number of milliseconds since January 1, 1970, 00:00:00 UTC. + * The time value is a the number of milliseconds since January 1, 1970, + * 00:00:00 UTC. + * * @return the time when this bundle was last modified. */ public final long getLastModified() { @@ -291,14 +308,17 @@ final void setlastModified(long lastModified) { } private static final EnumSet VALID_RESOLVED_TRANSITION = EnumSet.of(ModuleEvent.STARTED); - private static final EnumSet VALID_STOPPED_TRANSITION = EnumSet.of(ModuleEvent.UPDATED, ModuleEvent.UNRESOLVED, ModuleEvent.UNINSTALLED); + private static final EnumSet VALID_STOPPED_TRANSITION = EnumSet.of(ModuleEvent.UPDATED, + ModuleEvent.UNRESOLVED, ModuleEvent.UNINSTALLED); /** - * Acquires the module lock for state changes by the current thread for the specified - * transition event. Certain transition events locks may be nested within other - * transition event locks. For example, a resolved transition event lock may be - * nested within a started transition event lock. A stopped transition lock - * may be nested within an updated, unresolved or uninstalled transition lock. + * Acquires the module lock for state changes by the current thread for the + * specified transition event. Certain transition events locks may be nested + * within other transition event locks. For example, a resolved transition event + * lock may be nested within a started transition event lock. A stopped + * transition lock may be nested within an updated, unresolved or uninstalled + * transition lock. + * * @param transitionEvent the transition event to acquire the lock for. * @throws BundleException */ @@ -306,28 +326,29 @@ protected final void lockStateChange(ModuleEvent transitionEvent) throws BundleE boolean previousInterruption = Thread.interrupted(); boolean invalid = false; try { - boolean acquired = stateChangeLock.tryLock(revisions.getContainer().getModuleLockTimeout(), TimeUnit.SECONDS); + boolean acquired = stateChangeLock.tryLock(revisions.getContainer().getModuleLockTimeout(), + TimeUnit.SECONDS); Set currentTransition = Collections.emptySet(); if (acquired) { boolean isValidTransition = true; switch (transitionEvent) { - case STARTED : - case UPDATED : - case UNINSTALLED : - case UNRESOLVED : - // These states must be initiating transition states - // no other transition state is allowed when these are kicked off - isValidTransition = stateTransitionEvents.isEmpty(); - break; - case RESOLVED : - isValidTransition = VALID_RESOLVED_TRANSITION.containsAll(stateTransitionEvents); - break; - case STOPPED : - isValidTransition = VALID_STOPPED_TRANSITION.containsAll(stateTransitionEvents); - break; - default : - isValidTransition = false; - break; + case STARTED: + case UPDATED: + case UNINSTALLED: + case UNRESOLVED: + // These states must be initiating transition states + // no other transition state is allowed when these are kicked off + isValidTransition = stateTransitionEvents.isEmpty(); + break; + case RESOLVED: + isValidTransition = VALID_RESOLVED_TRANSITION.containsAll(stateTransitionEvents); + break; + case STOPPED: + isValidTransition = VALID_STOPPED_TRANSITION.containsAll(stateTransitionEvents); + break; + default: + isValidTransition = false; + break; } if (!isValidTransition) { currentTransition = EnumSet.copyOf(stateTransitionEvents); @@ -342,15 +363,19 @@ protected final void lockStateChange(ModuleEvent transitionEvent) throws BundleE } Throwable cause; if (invalid) { - cause = new IllegalStateException(NLS.bind(Msg.Module_LockStateError, transitionEvent, currentTransition)); + cause = new IllegalStateException( + NLS.bind(Msg.Module_LockStateError, transitionEvent, currentTransition)); } else { - cause = new TimeoutException(NLS.bind(Msg.Module_LockTimeout, revisions.getContainer().getModuleLockTimeout())).initCause(new ThreadInfoReport(stateChangeLock.toString())); + cause = new TimeoutException( + NLS.bind(Msg.Module_LockTimeout, revisions.getContainer().getModuleLockTimeout())) + .initCause(new ThreadInfoReport(stateChangeLock.toString())); } String exceptonInfo = toString() + ' ' + transitionEvent + ' ' + currentTransition; throw new BundleException(Msg.Module_LockError + exceptonInfo, BundleException.STATECHANGE_ERROR, cause); } catch (InterruptedException e) { Thread.currentThread().interrupt(); - throw new BundleException(Msg.Module_LockError + toString() + ' ' + transitionEvent, BundleException.STATECHANGE_ERROR, e); + throw new BundleException(Msg.Module_LockError + toString() + ' ' + transitionEvent, + BundleException.STATECHANGE_ERROR, e); } finally { if (previousInterruption) { Thread.currentThread().interrupt(); @@ -360,27 +385,33 @@ protected final void lockStateChange(ModuleEvent transitionEvent) throws BundleE /** * Releases the lock for state changes for the specified transition event. + * * @param transitionEvent */ protected final void unlockStateChange(ModuleEvent transitionEvent) { if (stateChangeLock.getHoldCount() == 0 || !stateTransitionEvents.contains(transitionEvent)) - throw new IllegalMonitorStateException("Current thread does not hold the state change lock for: " + transitionEvent); //$NON-NLS-1$ + throw new IllegalMonitorStateException( + "Current thread does not hold the state change lock for: " + transitionEvent); //$NON-NLS-1$ stateTransitionEvents.remove(transitionEvent); stateChangeLock.unlock(); } /** - * Returns true if the current thread holds the state change lock for the specified transition event. + * Returns true if the current thread holds the state change lock for the + * specified transition event. + * * @param transitionEvent - * @return true if the current thread holds the state change lock for the specified transition event. + * @return true if the current thread holds the state change lock for the + * specified transition event. */ public final boolean holdsTransitionEventLock(ModuleEvent transitionEvent) { return stateChangeLock.getHoldCount() > 0 && stateTransitionEvents.contains(transitionEvent); } /** - * Returns the thread that currently owns the state change lock for this module, or - * null if not owned. + * Returns the thread that currently owns the state change lock for this module, + * or null if not owned. + * * @return the owner, or null if not owned. */ public final Thread getStateChangeOwner() { @@ -389,6 +420,7 @@ public final Thread getStateChangeOwner() { /** * Starts this module + * * @param options the options for starting * @throws BundleException if an errors occurs while starting */ @@ -420,14 +452,16 @@ public void start(StartOptions... options) throws BundleException { lockedStarted = true; checkValid(); if (StartOptions.TRANSIENT_IF_AUTO_START.isContained(options) && !settings.contains(Settings.AUTO_START)) { - // Do nothing; this is a request to start only if the module is set for auto start + // Do nothing; this is a request to start only if the module is set for auto + // start return; } checkFragment(); persistStartOptions(options); if (getStartLevel() > container.getStartLevel()) { if (StartOptions.TRANSIENT.isContained(options)) { - // it is an error to attempt to transient start a bundle without its start level met + // it is an error to attempt to transient start a bundle without its start level + // met throw new BundleException(Msg.Module_Transient_StartError + ' ' + this, BundleException.START_TRANSIENT_ERROR); } @@ -484,9 +518,11 @@ public void start(StartOptions... options) throws BundleException { if (!EnumSet.of(ModuleEvent.STARTED, ModuleEvent.LAZY_ACTIVATION, ModuleEvent.STOPPED).contains(event)) throw new IllegalStateException("Wrong event type: " + event); //$NON-NLS-1$ publishEvent(event); - // only print bundleTime information if we actually fired an event for this bundle + // only print bundleTime information if we actually fired an event for this + // bundle if (container.DEBUG_BUNDLE_START_TIME) { - Debug.println(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime) + " ms for total start time event " + event + " - " + this); //$NON-NLS-1$ //$NON-NLS-2$ + Debug.println(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime) + + " ms for total start time event " + event + " - " + this); //$NON-NLS-1$ //$NON-NLS-2$ } } @@ -501,6 +537,7 @@ final void publishEvent(ModuleEvent type) { /** * Stops this module. + * * @param options options for stopping * @throws BundleException if an error occurs while stopping */ @@ -585,7 +622,8 @@ private ModuleEvent doStart(StartOptions... options) throws BundleException { } else { if (isLazyActivate(options) && !isTriggerSet()) { if (State.LAZY_STARTING.equals(getState())) { - // a sync listener must have tried to start this module again with the lazy option + // a sync listener must have tried to start this module again with the lazy + // option return null; // no event to publish; nothing to do } // set the lazy starting state and return lazy activation event for firing @@ -645,8 +683,9 @@ private ModuleLoader getCurrentLoader() { } /** - * Performs any work associated with starting a module. For example, - * loading and calling start on an activator. + * Performs any work associated with starting a module. For example, loading and + * calling start on an activator. + * * @throws BundleException if there was an exception starting the module */ protected void startWorker() throws BundleException { @@ -670,8 +709,9 @@ private ModuleEvent doStop() throws BundleException { } /** - * Performs any work associated with stopping a module. For example, - * calling stop on an activator. + * Performs any work associated with stopping a module. For example, calling + * stop on an activator. + * * @throws BundleException if there was an exception stopping the module */ protected void stopWorker() throws BundleException { @@ -684,7 +724,8 @@ public String toString() { } private void persistStartOptions(StartOptions... options) { - if (StartOptions.TRANSIENT.isContained(options) || StartOptions.TRANSIENT_RESUME.isContained(options) || StartOptions.LAZY_TRIGGER.isContained(options)) { + if (StartOptions.TRANSIENT.isContained(options) || StartOptions.TRANSIENT_RESUME.isContained(options) + || StartOptions.LAZY_TRIGGER.isContained(options)) { return; } @@ -706,9 +747,11 @@ private void persistStopOptions(StopOptions... options) { } /** - * Set if this module should be activated in parallel with other modules that have - * the same {@link #getStartLevel() start level}. - * @param parallelActivation true if the module should be started in parallel; false otherwise + * Set if this module should be activated in parallel with other modules that + * have the same {@link #getStartLevel() start level}. + * + * @param parallelActivation true if the module should be started in parallel; + * false otherwise * @since 3.15 */ public void setParallelActivation(boolean parallelActivation) { @@ -721,8 +764,9 @@ public void setParallelActivation(boolean parallelActivation) { } /** - * Returns if this module should be activated in parallel with other modules that have - * the same {@link #getStartLevel() start level}. + * Returns if this module should be activated in parallel with other modules + * that have the same {@link #getStartLevel() start level}. + * * @return true if the module should be started in parallel; false otherwise * @since 3.15 */ @@ -733,6 +777,7 @@ public boolean isParallelActivated() { /** * The container is done with the revision and it has been completely removed. * This method allows the resources behind the revision to be cleaned up. + * * @param revision the revision to clean up */ abstract protected void cleanup(ModuleRevision revision); @@ -756,6 +801,7 @@ final boolean hasLazyActivatePolicy() { /** * Used internally by the container to determine if any thread is in the middle * of a start operation on this module. + * * @return */ final boolean inStart() { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleCapability.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleCapability.java index 7cda53fd070..3547910b1ee 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleCapability.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleCapability.java @@ -21,6 +21,7 @@ /** * An implementation of {@link BundleCapability}. + * * @since 3.10 */ public final class ModuleCapability implements BundleCapability { @@ -30,7 +31,8 @@ public final class ModuleCapability implements BundleCapability { private final Map transientAttrs; private final ModuleRevision revision; - ModuleCapability(String namespace, Map directives, Map attributes, ModuleRevision revision) { + ModuleCapability(String namespace, Map directives, Map attributes, + ModuleRevision revision) { this.namespace = namespace; this.directives = directives; this.attributes = attributes; @@ -69,6 +71,7 @@ Map getPersistentAttributes() { /** * Only used by the system module for setting transient attributes associated * with the {@link NativeNamespace osgi.native} namespace. + * * @param transientAttrs */ public void setTransientAttrs(Map transientAttrs) { @@ -76,7 +79,8 @@ public void setTransientAttrs(Map transientAttrs) { throw new UnsupportedOperationException(namespace + ": namespace does not support transient attributes."); //$NON-NLS-1$ } if (!(getResource().getRevisions().getModule() instanceof SystemModule)) { - throw new UnsupportedOperationException("Only allowed to set transient attributes for the system module: " + getResource()); //$NON-NLS-1$ + throw new UnsupportedOperationException( + "Only allowed to set transient attributes for the system module: " + getResource()); //$NON-NLS-1$ } this.transientAttrs.clear(); this.transientAttrs.putAll(transientAttrs); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleCollisionHook.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleCollisionHook.java index 7f2193dccb5..9b77353270e 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleCollisionHook.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleCollisionHook.java @@ -16,7 +16,9 @@ import java.util.Collection; /** - * Hook used to determine if a module revision being installed or updated will cause a collision + * Hook used to determine if a module revision being installed or updated will + * cause a collision + * * @since 3.10 */ public interface ModuleCollisionHook { @@ -33,29 +35,28 @@ public interface ModuleCollisionHook { /** * Filter bundle collisions hook method. This method is called during the - * install or update operation. The operation type will be - * {@link #INSTALLING installing} or {@link #UPDATING updating}. Depending - * on the operation type the target module and the collision candidate - * collection are the following: + * install or update operation. The operation type will be {@link #INSTALLING + * installing} or {@link #UPDATING updating}. Depending on the operation type + * the target module and the collision candidate collection are the following: *

    - *
  • {@link #INSTALLING installing} - The target is the module associated - * which is performing the install operation. The - * collision candidate collection contains the existing modules installed - * which have a current revision with the same symbolic name and version as the - * module being installed. - *
  • {@link #UPDATING updating} - The target is the module being updated. - * The collision candidate collection contains the existing modules installed which have - * a current revision with the same symbolic name and version as the content the target - * module is being updated to. + *
  • {@link #INSTALLING installing} - The target is the module associated + * which is performing the install operation. The collision candidate collection + * contains the existing modules installed which have a current revision with + * the same symbolic name and version as the module being installed. + *
  • {@link #UPDATING updating} - The target is the module being updated. The + * collision candidate collection contains the existing modules installed which + * have a current revision with the same symbolic name and version as the + * content the target module is being updated to. *
* This method can filter the collection of collision candidates by removing - * potential collisions. For the specified operation to succeed, the - * collection of collision candidates must be empty when this method returns. + * potential collisions. For the specified operation to succeed, the collection + * of collision candidates must be empty when this method returns. * - * @param operationType The operation type. Must be the value of - * {@link #INSTALLING installing} or {@link #UPDATING updating}. - * @param target The target module used to determine what collision - * candidates to filter. + * @param operationType The operation type. Must be the value of + * {@link #INSTALLING installing} or {@link #UPDATING + * updating}. + * @param target The target module used to determine what collision + * candidates to filter. * @param collisionCandidates The collection of collision candidates. */ void filterCollisions(int operationType, Module target, Collection collisionCandidates); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleContainer.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleContainer.java index 0ce498543a0..a6a3e5d64f4 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleContainer.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleContainer.java @@ -82,6 +82,7 @@ /** * A container for installing, updating, uninstalling and resolve modules. + * * @since 3.10 */ public final class ModuleContainer implements DebugOptionsListener { @@ -118,8 +119,8 @@ public final class ModuleContainer implements DebugOptionsListener { final ModuleContainerAdaptor adaptor; /** - * The module resolver which implements the ResolverContext and handles calling the - * resolver service. + * The module resolver which implements the ResolverContext and handles calling + * the resolver service. */ private final ModuleResolver moduleResolver; @@ -139,7 +140,8 @@ public final class ModuleContainer implements DebugOptionsListener { /** * Constructs a new container with the specified adaptor, module database. - * @param adaptor the adaptor for the container + * + * @param adaptor the adaptor for the container * @param moduledataBase the module database */ public ModuleContainer(ModuleContainerAdaptor adaptor, ModuleDatabase moduledataBase) { @@ -172,11 +174,13 @@ public ModuleContainer(ModuleContainerAdaptor adaptor, ModuleDatabase moduledata autoStartOnResolveProp = Boolean.toString(true); } this.autoStartOnResolve = Boolean.parseBoolean(autoStartOnResolveProp); - this.restrictParallelStart = Boolean.parseBoolean(adaptor.getProperty(EquinoxConfiguration.PROP_EQUINOX_START_LEVEL_RESTRICT_PARALLEL)); + this.restrictParallelStart = Boolean + .parseBoolean(adaptor.getProperty(EquinoxConfiguration.PROP_EQUINOX_START_LEVEL_RESTRICT_PARALLEL)); } /** * Returns the adaptor for this container + * * @return the adaptor for this container */ public ModuleContainerAdaptor getAdaptor() { @@ -185,6 +189,7 @@ public ModuleContainerAdaptor getAdaptor() { /** * Returns the list of currently installed modules sorted by module id. + * * @return the list of currently installed modules sorted by module id. */ public List getModules() { @@ -192,56 +197,66 @@ public List getModules() { } /** - * Returns the module installed with the specified id, or null if no - * such module is installed. + * Returns the module installed with the specified id, or null if no such module + * is installed. + * * @param id the id of the module - * @return the module with the specified id, or null of no such module is installed. + * @return the module with the specified id, or null of no such module is + * installed. */ public Module getModule(long id) { return moduleDatabase.getModule(id); } /** - * Returns the module installed with the specified location, or null if no - * such module is installed. + * Returns the module installed with the specified location, or null if no such + * module is installed. + * * @param location the location of the module - * @return the module with the specified location, or null of no such module is installed. + * @return the module with the specified location, or null of no such module is + * installed. */ public Module getModule(String location) { return moduleDatabase.getModule(location); } /** - * Creates a synthetic requirement that is not associated with any module revision. - * This is useful for calling {@link FrameworkWiring#findProviders(Requirement)}. - * @param namespace the requirement namespace + * Creates a synthetic requirement that is not associated with any module + * revision. This is useful for calling + * {@link FrameworkWiring#findProviders(Requirement)}. + * + * @param namespace the requirement namespace * @param directives the requirement directives * @param attributes the requirement attributes * @return a synthetic requirement */ - public static Requirement createRequirement(String namespace, Map directives, Map attributes) { + public static Requirement createRequirement(String namespace, Map directives, + Map attributes) { return new ModuleRequirement(namespace, directives, attributes, null); } /** - * Installs a new module using the specified location. The specified - * builder is used to create a new {@link ModuleRevision revision} - * which will become the {@link Module#getCurrentRevision() current} - * revision of the new module. + * Installs a new module using the specified location. The specified builder is + * used to create a new {@link ModuleRevision revision} which will become the + * {@link Module#getCurrentRevision() current} revision of the new module. *

- * If a module already exists with the specified location then the - * existing module is returned and the builder is not used. - * @param origin the module performing the install, may be {@code null}. - * @param location The location identifier of the module to install. - * @param builder the builder used to create the revision to install. - * @param revisionInfo the revision info for the new revision, may be {@code null}. - * @return a new module or a existing module if one exists at the - * specified location. + * If a module already exists with the specified location then the existing + * module is returned and the builder is not used. + * + * @param origin the module performing the install, may be {@code null}. + * @param location The location identifier of the module to install. + * @param builder the builder used to create the revision to install. + * @param revisionInfo the revision info for the new revision, may be + * {@code null}. + * @return a new module or a existing module if one exists at the specified + * location. * @throws BundleException if some error occurs installing the module */ - public Module install(Module origin, String location, ModuleRevisionBuilder builder, Object revisionInfo) throws BundleException { + public Module install(Module origin, String location, ModuleRevisionBuilder builder, Object revisionInfo) + throws BundleException { long id = builder.getId(); - ModuleRevisionBuilder adaptBuilder = getAdaptor().adaptModuleRevisionBuilder(ModuleEvent.INSTALLED, origin, builder, revisionInfo); + ModuleRevisionBuilder adaptBuilder = getAdaptor().adaptModuleRevisionBuilder(ModuleEvent.INSTALLED, origin, + builder, revisionInfo); if (adaptBuilder != null) { // be sure to restore the id from the original builder adaptBuilder.setInternalId(id); @@ -256,14 +271,18 @@ public Module install(Module origin, String location, ModuleRevisionBuilder buil locationLocked = locationLocks.tryLock(location, 5, TimeUnit.SECONDS); nameLocked = name != null && nameLocks.tryLock(name, 5, TimeUnit.SECONDS); if (!locationLocked) { - throw new BundleException("Failed to obtain location lock for installation: " + location, BundleException.STATECHANGE_ERROR, new ThreadInfoReport(locationLocks.getLockInfo(location))); //$NON-NLS-1$ + throw new BundleException("Failed to obtain location lock for installation: " + location, //$NON-NLS-1$ + BundleException.STATECHANGE_ERROR, + new ThreadInfoReport(locationLocks.getLockInfo(location))); } if (name != null && !nameLocked) { - throw new BundleException("Failed to obtain symbolic name lock for installation: " + name, BundleException.STATECHANGE_ERROR, new ThreadInfoReport(nameLocks.getLockInfo(name))); //$NON-NLS-1$ + throw new BundleException("Failed to obtain symbolic name lock for installation: " + name, //$NON-NLS-1$ + BundleException.STATECHANGE_ERROR, new ThreadInfoReport(nameLocks.getLockInfo(name))); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); - throw new BundleException("Failed to obtain id locks for installation.", BundleException.STATECHANGE_ERROR, e); //$NON-NLS-1$ + throw new BundleException("Failed to obtain id locks for installation.", //$NON-NLS-1$ + BundleException.STATECHANGE_ERROR, e); } Module existingLocation = null; @@ -272,16 +291,19 @@ public Module install(Module origin, String location, ModuleRevisionBuilder buil try { existingLocation = moduleDatabase.getModule(location); if (existingLocation == null) { - // Collect existing current revisions with the same name and version as the revision we want to install + // Collect existing current revisions with the same name and version as the + // revision we want to install // This is to perform the collision check below - List sameIdentity = moduleDatabase.findCapabilities(getIdentityRequirement(name, builder.getVersion())); + List sameIdentity = moduleDatabase + .findCapabilities(getIdentityRequirement(name, builder.getVersion())); if (!sameIdentity.isEmpty()) { collisionCandidates = new ArrayList<>(1); for (ModuleCapability identity : sameIdentity) { ModuleRevision equinoxRevision = identity.getRevision(); if (!equinoxRevision.isCurrent()) continue; // only pay attention to current revisions - // need to prevent duplicates here; this is in case a revisions object contains multiple revision objects. + // need to prevent duplicates here; this is in case a revisions object contains + // multiple revision objects. if (!collisionCandidates.contains(equinoxRevision.getRevisions().getModule())) collisionCandidates.add(equinoxRevision.getRevisions().getModule()); } @@ -297,18 +319,24 @@ public Module install(Module origin, String location, ModuleRevisionBuilder buil BundleContext context = bundle == null ? null : bundle.getBundleContext(); if (context != null && context.getBundle(existingLocation.getId()) == null) { Bundle b = existingLocation.getBundle(); - throw new BundleException(NLS.bind(Msg.ModuleContainer_NameCollisionWithLocation, new Object[] {b.getSymbolicName(), b.getVersion(), location}), BundleException.REJECTED_BY_HOOK); + throw new BundleException( + NLS.bind(Msg.ModuleContainer_NameCollisionWithLocation, + new Object[] { b.getSymbolicName(), b.getVersion(), location }), + BundleException.REJECTED_BY_HOOK); } } return existingLocation; } - // Check that the bundle does not collide with other bundles with the same name and version + // Check that the bundle does not collide with other bundles with the same name + // and version // This is from the perspective of the origin bundle if (origin != null && !collisionCandidates.isEmpty()) { - adaptor.getModuleCollisionHook().filterCollisions(ModuleCollisionHook.INSTALLING, origin, collisionCandidates); + adaptor.getModuleCollisionHook().filterCollisions(ModuleCollisionHook.INSTALLING, origin, + collisionCandidates); } if (!collisionCandidates.isEmpty()) { - throw new BundleException(NLS.bind(Msg.ModuleContainer_NameCollision, name, builder.getVersion()), BundleException.DUPLICATE_BUNDLE_ERROR); + throw new BundleException(NLS.bind(Msg.ModuleContainer_NameCollision, name, builder.getVersion()), + BundleException.DUPLICATE_BUNDLE_ERROR); } Module result = moduleDatabase.install(location, builder, revisionInfo); @@ -325,18 +353,20 @@ public Module install(Module origin, String location, ModuleRevisionBuilder buil } /** - * Updates the specified module with a new revision. The specified - * builder is used to create a new {@link ModuleRevision revision} - * which will become the {@link Module#getCurrentRevision() current} - * revision of the new module. - * @param module the module to update - * @param builder the builder used to create the revision for the update. - * @param revisionInfo the revision info for the new revision, may be {@code null}. + * Updates the specified module with a new revision. The specified builder is + * used to create a new {@link ModuleRevision revision} which will become the + * {@link Module#getCurrentRevision() current} revision of the new module. + * + * @param module the module to update + * @param builder the builder used to create the revision for the update. + * @param revisionInfo the revision info for the new revision, may be + * {@code null}. * @throws BundleException if some error occurs updating the module */ public void update(Module module, ModuleRevisionBuilder builder, Object revisionInfo) throws BundleException { long id = builder.getId(); - ModuleRevisionBuilder adaptBuilder = getAdaptor().adaptModuleRevisionBuilder(ModuleEvent.UPDATED, module, builder, revisionInfo); + ModuleRevisionBuilder adaptBuilder = getAdaptor().adaptModuleRevisionBuilder(ModuleEvent.UPDATED, module, + builder, revisionInfo); if (adaptBuilder != null) { // be sure to restore the id from the original builder adaptBuilder.setInternalId(id); @@ -354,15 +384,18 @@ public void update(Module module, ModuleRevisionBuilder builder, Object revision } } catch (InterruptedException e) { Thread.currentThread().interrupt(); - throw new BundleException("Failed to obtain id locks for installation.", BundleException.STATECHANGE_ERROR, e); //$NON-NLS-1$ + throw new BundleException("Failed to obtain id locks for installation.", //$NON-NLS-1$ + BundleException.STATECHANGE_ERROR, e); } Collection collisionCandidates = Collections.emptyList(); moduleDatabase.readLock(); try { - // Collect existing bundles with the same name and version as the bundle we want to install + // Collect existing bundles with the same name and version as the bundle we want + // to install // This is to perform the collision check below - List sameIdentity = moduleDatabase.findCapabilities(getIdentityRequirement(name, builder.getVersion())); + List sameIdentity = moduleDatabase + .findCapabilities(getIdentityRequirement(name, builder.getVersion())); if (!sameIdentity.isEmpty()) { collisionCandidates = new ArrayList<>(1); for (ModuleCapability identity : sameIdentity) { @@ -372,7 +405,8 @@ public void update(Module module, ModuleRevisionBuilder builder, Object revision Module m = equinoxRevision.getRevisions().getModule(); if (m.equals(module)) continue; // don't worry about the updating modules revisions - // need to prevent duplicates here; this is in case a revisions object contains multiple revision objects. + // need to prevent duplicates here; this is in case a revisions object contains + // multiple revision objects. if (!collisionCandidates.contains(m)) collisionCandidates.add(m); } @@ -382,14 +416,17 @@ public void update(Module module, ModuleRevisionBuilder builder, Object revision moduleDatabase.readUnlock(); } - // Check that the module does not collide with other modules with the same name and version + // Check that the module does not collide with other modules with the same name + // and version // This is from the perspective of the module being updated if (module != null && !collisionCandidates.isEmpty()) { - adaptor.getModuleCollisionHook().filterCollisions(ModuleCollisionHook.UPDATING, module, collisionCandidates); + adaptor.getModuleCollisionHook().filterCollisions(ModuleCollisionHook.UPDATING, module, + collisionCandidates); } if (!collisionCandidates.isEmpty()) { - throw new BundleException(NLS.bind(Msg.ModuleContainer_NameCollision, name, builder.getVersion()), BundleException.DUPLICATE_BUNDLE_ERROR); + throw new BundleException(NLS.bind(Msg.ModuleContainer_NameCollision, name, builder.getVersion()), + BundleException.DUPLICATE_BUNDLE_ERROR); } module.lockStateChange(ModuleEvent.UPDATED); @@ -429,6 +466,7 @@ public void update(Module module, ModuleRevisionBuilder builder, Object revision /** * Uninstalls the specified module. + * * @param module the module to uninstall * @throws BundleException if some error occurs uninstalling the module */ @@ -465,6 +503,7 @@ ModuleWiring getWiring(ModuleRevision revision) { /** * Returns the {@link FrameworkWiring} for this container + * * @return the framework wiring for this container. */ public FrameworkWiring getFrameworkWiring() { @@ -473,6 +512,7 @@ public FrameworkWiring getFrameworkWiring() { /** * Returns the {@link FrameworkStartLevel} for this container + * * @return the framework start level for this container */ public FrameworkStartLevel getFrameworkStartLevel() { @@ -481,10 +521,12 @@ public FrameworkStartLevel getFrameworkStartLevel() { /** * Attempts to resolve the current revisions of the specified modules. - * @param triggers the modules to resolve or {@code null} to resolve all unresolved - * current revisions. - * @param triggersMandatory true if the triggers must be resolved. This will result in - * a {@link ResolutionException} if set to true and one of the triggers could not be resolved. + * + * @param triggers the modules to resolve or {@code null} to resolve + * all unresolved current revisions. + * @param triggersMandatory true if the triggers must be resolved. This will + * result in a {@link ResolutionException} if set to + * true and one of the triggers could not be resolved. * @see FrameworkWiring#resolveBundles(Collection) * @return A resolution report for the resolve operation */ @@ -494,7 +536,8 @@ public ResolutionReport resolve(Collection triggers, boolean triggersMan private ResolutionReport resolve(Collection triggers, boolean triggersMandatory, boolean restartTriggers) { if (isRefreshingSystemModule()) { - return new ModuleResolutionReport(null, Collections.emptyMap(), new ResolutionException("Unable to resolve while shutting down the framework.")); //$NON-NLS-1$ + return new ModuleResolutionReport(null, Collections.emptyMap(), + new ResolutionException("Unable to resolve while shutting down the framework.")); //$NON-NLS-1$ } ResolutionReport report = null; try (ResolutionLock.Permits resolutionPermits = _resolutionLock.acquire(1)) { @@ -504,20 +547,24 @@ private ResolutionReport resolve(Collection triggers, boolean triggersMa } catch (RuntimeException e) { if (e.getCause() instanceof BundleException) { BundleException be = (BundleException) e.getCause(); - if (be.getType() == BundleException.REJECTED_BY_HOOK || be.getType() == BundleException.STATECHANGE_ERROR) { - return new ModuleResolutionReport(null, Collections.emptyMap(), new ResolutionException(be)); + if (be.getType() == BundleException.REJECTED_BY_HOOK + || be.getType() == BundleException.STATECHANGE_ERROR) { + return new ModuleResolutionReport(null, Collections.emptyMap(), + new ResolutionException(be)); } } throw e; } } while (report == null); } catch (ResolutionLockException e) { - return new ModuleResolutionReport(null, Collections.emptyMap(), new ResolutionException("Timeout acquiring lock for resolution", e, Collections.emptyList())); //$NON-NLS-1$ + return new ModuleResolutionReport(null, Collections.emptyMap(), + new ResolutionException("Timeout acquiring lock for resolution", e, Collections.emptyList())); //$NON-NLS-1$ } return report; } - private ResolutionReport resolveAndApply(Collection triggers, boolean triggersMandatory, boolean restartTriggers, ResolutionLock.Permits resolutionPermits) { + private ResolutionReport resolveAndApply(Collection triggers, boolean triggersMandatory, + boolean restartTriggers, ResolutionLock.Permits resolutionPermits) { if (triggers == null) { triggers = new ArrayList<>(0); } @@ -550,9 +597,11 @@ private ResolutionReport resolveAndApply(Collection triggers, boolean tr moduleDatabase.readUnlock(); } - ModuleResolutionReport report = moduleResolver.resolveDelta(triggerRevisions, triggersMandatory, unresolved, wiringClone, moduleDatabase); + ModuleResolutionReport report = moduleResolver.resolveDelta(triggerRevisions, triggersMandatory, unresolved, + wiringClone, moduleDatabase); Map> resolutionResult = report.getResolutionResult(); - Map deltaWiring = resolutionResult == null ? Collections.emptyMap() : moduleResolver.generateDelta(resolutionResult, wiringClone); + Map deltaWiring = resolutionResult == null ? Collections.emptyMap() + : moduleResolver.generateDelta(resolutionResult, wiringClone); if (deltaWiring.isEmpty()) return report; // nothing to do @@ -562,15 +611,20 @@ private ResolutionReport resolveAndApply(Collection triggers, boolean tr modulesResolved.add(deltaRevision.getRevisions().getModule()); } - return applyDelta(deltaWiring, modulesResolved, triggers, timestamp, restartTriggers, resolutionPermits) ? report : null; + return applyDelta(deltaWiring, modulesResolved, triggers, timestamp, restartTriggers, resolutionPermits) + ? report + : null; } /** - * Attempts to resolve the specified dynamic package name request for the specified revision. + * Attempts to resolve the specified dynamic package name request for the + * specified revision. + * * @param dynamicPkgName the package name to attempt a dynamic resolution for - * @param revision the module revision the dynamic resolution request is for - * @return the new resolution wire establishing a dynamic package resolution or null if - * a dynamic wire could not be established. + * @param revision the module revision the dynamic resolution request is + * for + * @return the new resolution wire establishing a dynamic package resolution or + * null if a dynamic wire could not be established. */ public ModuleWire resolveDynamic(String dynamicPkgName, ModuleRevision revision) { ModuleWire result; @@ -620,9 +674,11 @@ public ModuleWire resolveDynamic(String dynamicPkgName, ModuleRevision revision) deltaWiring = null; boolean foundCandidates = false; for (DynamicModuleRequirement dynamicReq : dynamicReqs) { - ModuleResolutionReport report = moduleResolver.resolveDynamicDelta(dynamicReq, unresolved, wiringClone, moduleDatabase); + ModuleResolutionReport report = moduleResolver.resolveDynamicDelta(dynamicReq, unresolved, + wiringClone, moduleDatabase); Map> resolutionResult = report.getResolutionResult(); - deltaWiring = resolutionResult == null ? Collections.emptyMap() : moduleResolver.generateDelta(resolutionResult, wiringClone); + deltaWiring = resolutionResult == null ? Collections.emptyMap() + : moduleResolver.generateDelta(resolutionResult, wiringClone); if (deltaWiring.get(revision) != null) { break; } @@ -661,7 +717,8 @@ public ModuleWire resolveDynamic(String dynamicPkgName, ModuleRevision revision) // Save the result ModuleWiring wiring = deltaWiring.get(revision); result = findExistingDynamicWire(wiring, dynamicPkgName); - } while (!applyDelta(deltaWiring, modulesResolved, Collections.emptyList(), timestamp, false, resolutionPermits)); + } while (!applyDelta(deltaWiring, modulesResolved, Collections.emptyList(), timestamp, false, + resolutionPermits)); } catch (ResolutionLockException e) { return null; } @@ -675,13 +732,15 @@ private ModuleWire findExistingDynamicWire(ModuleWiring wiring, String dynamicPk } List wires = wiring.getRequiredModuleWires(PackageNamespace.PACKAGE_NAMESPACE); // No null check; we are holding the database lock here. - // Work backwards to find the first wire with the dynamic requirement that matches package name + // Work backwards to find the first wire with the dynamic requirement that + // matches package name for (int i = wires.size() - 1; i >= 0; i--) { ModuleWire wire = wires.get(i); if (dynamicPkgName.equals(wire.getCapability().getAttributes().get(PackageNamespace.PACKAGE_NAMESPACE))) { return wire; } - if (!PackageNamespace.RESOLUTION_DYNAMIC.equals(wire.getRequirement().getDirectives().get(Namespace.REQUIREMENT_RESOLUTION_DIRECTIVE))) { + if (!PackageNamespace.RESOLUTION_DYNAMIC + .equals(wire.getRequirement().getDirectives().get(Namespace.REQUIREMENT_RESOLUTION_DIRECTIVE))) { return null; } } @@ -691,12 +750,12 @@ private ModuleWire findExistingDynamicWire(ModuleWiring wiring, String dynamicPk // The resolution algorithm uses optimistic locking approach; // This involves taking a snapshot of the state and performing an // operation on the snapshot while holding no locks and then - // obtaining the write lock to apply the results. If we + // obtaining the write lock to apply the results. If we // detect the state has changed since the snapshot taken then - // the process is started over. If we allow too many threads + // the process is started over. If we allow too many threads // to try to do this at the same time it causes thrashing // between taking the snapshot and successfully applying the - // results. Instead of resorting to single threaded operations + // results. Instead of resorting to single threaded operations // we choose to limit the number of concurrent resolves final ResolutionLock _resolutionLock = new ResolutionLock(); final ReentrantLock _bundleStateLock = new ReentrantLock(); @@ -715,11 +774,11 @@ public ResolutionLockException(Throwable cause) { /** * A resolution hook allows for a max of 10 threads to do resolution operations - * at the same time. The implementation uses a semaphore to grant the max number - * of permits (threads) but a reentrant read lock is also used to detect reentry. - * If a thread reenters then no extra permits are required by the thread. - * This lock returns a Permits object that implements closeable for use in - * try->with. If permits is closed multiple times then the additional close + * at the same time. The implementation uses a semaphore to grant the max number + * of permits (threads) but a reentrant read lock is also used to detect + * reentry. If a thread reenters then no extra permits are required by the + * thread. This lock returns a Permits object that implements closeable for use + * in try->with. If permits is closed multiple times then the additional close * operations are a no-op. */ static class ResolutionLock { @@ -767,15 +826,21 @@ Permits acquire(int requestedPermits) throws ResolutionLockException { } } - private boolean applyDelta(Map deltaWiring, Collection modulesResolved, Collection triggers, long timestamp, boolean restartTriggers, ResolutionLock.Permits resolutionPermits) { + private boolean applyDelta(Map deltaWiring, Collection modulesResolved, + Collection triggers, long timestamp, boolean restartTriggers, + ResolutionLock.Permits resolutionPermits) { List modulesLocked = new ArrayList<>(modulesResolved.size()); // now attempt to apply the delta try { // Acquire the necessary RESOLVED state change lock. - // Note this is done while holding a global lock to avoid multiple threads trying to compete over - // locking multiple modules; otherwise out of order locks between modules can happen - // NOTE this MUST be done outside of holding the moduleDatabase lock also to avoid - // introducing out of order locks between the bundle state change lock and the moduleDatabase + // Note this is done while holding a global lock to avoid multiple threads + // trying to compete over + // locking multiple modules; otherwise out of order locks between modules can + // happen + // NOTE this MUST be done outside of holding the moduleDatabase lock also to + // avoid + // introducing out of order locks between the bundle state change lock and the + // moduleDatabase // lock. _bundleStateLock.lock(); try { @@ -810,7 +875,8 @@ private boolean applyDelta(Map deltaWiring, Collec for (Map.Entry deltaEntry : deltaWiring.entrySet()) { ModuleWiring current = wiringCopy.get(deltaEntry.getKey()); if (current != null) { - // need to update the provided capabilities, provided and required wires for currently resolved + // need to update the provided capabilities, provided and required wires for + // currently resolved current.setCapabilities(deltaEntry.getValue().getCapabilities()); current.setProvidedWires(deltaEntry.getValue().getProvidedWires()); current.setRequirements(deltaEntry.getValue().getRequirements()); @@ -820,7 +886,8 @@ private boolean applyDelta(Map deltaWiring, Collec ModuleRevision revision = deltaEntry.getValue().getRevision(); modulesResolved.add(revision.getRevisions().getModule()); if ((revision.getTypes() & BundleRevision.TYPE_FRAGMENT) != 0) { - for (ModuleWire hostWire : deltaEntry.getValue().getRequiredModuleWires(HostNamespace.HOST_NAMESPACE)) { + for (ModuleWire hostWire : deltaEntry.getValue() + .getRequiredModuleWires(HostNamespace.HOST_NAMESPACE)) { // check to see if the host revision has a wiring ModuleWiring hostWiring = hostWire.getProvider().getWiring(); if (hostWiring != null) { @@ -846,7 +913,8 @@ private boolean applyDelta(Map deltaWiring, Collec } // attach fragments to already resolved hosts that have // dynamically attached fragments - for (Map.Entry> dynamicFragments : hostsWithDynamicFrags.entrySet()) { + for (Map.Entry> dynamicFragments : hostsWithDynamicFrags + .entrySet()) { dynamicFragments.getKey().loadFragments(dynamicFragments.getValue()); } } finally { @@ -872,13 +940,18 @@ private boolean applyDelta(Map deltaWiring, Collec } } if (autoStartOnResolve) { - // This is questionable behavior according to the spec but this was the way equinox previously behaved + // This is questionable behavior according to the spec but this was the way + // equinox previously behaved // Need to auto-start any persistently started bundles that got resolved for (Module module : modulesLocked) { - // Note that we check inStart here. There is still a timing issue that is impossible to avoid. - // Another thread could attempt to start the module but we could check inStart() before that thread - // increments inStart. One thread will win the race to grab the module STARTED lock. That thread - // will end up actually starting the module and the other thread will block. If a timeout occurs + // Note that we check inStart here. There is still a timing issue that is + // impossible to avoid. + // Another thread could attempt to start the module but we could check inStart() + // before that thread + // increments inStart. One thread will win the race to grab the module STARTED + // lock. That thread + // will end up actually starting the module and the other thread will block. If + // a timeout occurs // the blocking thread will get an exception. if (!module.inStart() && module.getId() != 0 && !triggerSet.contains(module)) { start(module, StartOptions.TRANSIENT_IF_AUTO_START, StartOptions.TRANSIENT_RESUME); @@ -1003,15 +1076,20 @@ private Collection unresolve0(Collection initial) { Collection modulesUnresolved = new ArrayList<>(); try { // Acquire the module state change locks. - // Note this is done while holding a global lock to avoid multiple threads trying to compete over - // locking multiple modules; otherwise out of order locks between modules can happen - // NOTE this MUST be done outside of holding the moduleDatabase lock also to avoid - // introducing out of order locks between the bundle state change lock and the moduleDatabase + // Note this is done while holding a global lock to avoid multiple threads + // trying to compete over + // locking multiple modules; otherwise out of order locks between modules can + // happen + // NOTE this MUST be done outside of holding the moduleDatabase lock also to + // avoid + // introducing out of order locks between the bundle state change lock and the + // moduleDatabase // lock. _bundleStateLock.lock(); try { // go in reverse order - for (ListIterator iTriggers = refreshTriggers.listIterator(refreshTriggers.size()); iTriggers.hasPrevious();) { + for (ListIterator iTriggers = refreshTriggers.listIterator(refreshTriggers.size()); iTriggers + .hasPrevious();) { Module refreshModule = iTriggers.previous(); refreshModule.lockStateChange(ModuleEvent.UNRESOLVED); modulesLocked.add(refreshModule); @@ -1023,8 +1101,10 @@ private Collection unresolve0(Collection initial) { _bundleStateLock.unlock(); } // Must not hold the module database lock while stopping bundles - // Stop any active bundles and remove non-active modules from the refreshTriggers - for (ListIterator iTriggers = refreshTriggers.listIterator(refreshTriggers.size()); iTriggers.hasPrevious();) { + // Stop any active bundles and remove non-active modules from the + // refreshTriggers + for (ListIterator iTriggers = refreshTriggers.listIterator(refreshTriggers.size()); iTriggers + .hasPrevious();) { Module refreshModule = iTriggers.previous(); State previousState = refreshModule.getState(); if (Module.ACTIVE_SET.contains(previousState)) { @@ -1038,10 +1118,12 @@ private Collection unresolve0(Collection initial) { } } - // do a sanity check on states of the modules, they must be INSTALLED, RESOLVED or UNINSTALLED + // do a sanity check on states of the modules, they must be INSTALLED, RESOLVED + // or UNINSTALLED for (Module module : modulesLocked) { if (Module.ACTIVE_SET.contains(module.getState())) { - throw new IllegalStateException("Module is in the wrong state: " + module + ": " + module.getState()); //$NON-NLS-1$ //$NON-NLS-2$ + throw new IllegalStateException( + "Module is in the wrong state: " + module + ": " + module.getState()); //$NON-NLS-1$ //$NON-NLS-2$ } } @@ -1103,7 +1185,8 @@ private void checkSystemExtensionRefresh(Collection initial) { for (Iterator iModules = initial.iterator(); iModules.hasNext();) { Module m = iModules.next(); if (m.getId().equals(zero)) { - // never allow system bundle to be unresolved directly if the system module is active + // never allow system bundle to be unresolved directly if the system module is + // active if (Module.ACTIVE_SET.contains(m.getState())) { iModules.remove(); } @@ -1131,10 +1214,11 @@ private void checkSystemExtensionRefresh(Collection initial) { /** * Refreshes the specified collection of modules. - * @param initial the modules to refresh or {@code null} to refresh the - * removal pending. - * @return a resolution report for the resolve operation that may have - * occurred during the refresh operation. + * + * @param initial the modules to refresh or {@code null} to refresh the removal + * pending. + * @return a resolution report for the resolve operation that may have occurred + * during the refresh operation. * @see FrameworkWiring#refreshBundles(Collection, FrameworkListener...) */ public ResolutionReport refresh(Collection initial) { @@ -1148,9 +1232,12 @@ public ResolutionReport refresh(Collection initial) { /** * Returns the dependency closure of for the specified modules. - * @param initial The initial modules for which to generate the dependency closure - * @return A collection containing a snapshot of the dependency closure of the specified - * modules, or an empty collection if there were no specified modules. + * + * @param initial The initial modules for which to generate the dependency + * closure + * @return A collection containing a snapshot of the dependency closure of the + * specified modules, or an empty collection if there were no specified + * modules. */ public Collection getDependencyClosure(Collection initial) { moduleDatabase.readLock(); @@ -1162,9 +1249,12 @@ public Collection getDependencyClosure(Collection initial) { } /** - * Returns the revisions that have {@link ModuleWiring#isCurrent() non-current}, {@link ModuleWiring#isInUse() in use} module wirings. - * @return A collection containing a snapshot of the revisions which have non-current, in use ModuleWirings, - * or an empty collection if there are no such revisions. + * Returns the revisions that have {@link ModuleWiring#isCurrent() non-current}, + * {@link ModuleWiring#isInUse() in use} module wirings. + * + * @return A collection containing a snapshot of the revisions which have + * non-current, in use ModuleWirings, or an empty collection if there + * are no such revisions. */ public Collection getRemovalPending() { return moduleDatabase.getRemovalPending(); @@ -1173,9 +1263,9 @@ public Collection getRemovalPending() { /** * Return the active start level value of this container. * - * If the container is in the process of changing the start level this - * method must return the active start level if this differs from the - * requested start level. + * If the container is in the process of changing the start level this method + * must return the active start level if this differs from the requested start + * level. * * @return The active start level value of the Framework. */ @@ -1277,6 +1367,7 @@ private void unloadModules() { /** * Sets all the module states uninstalled except for the system module. + * * @throws BundleException */ public void setInitialModuleStates() throws BundleException { @@ -1323,7 +1414,8 @@ Set getRefreshClosure(Collection initial, Map wiringCopy, Set refreshClosure) { + private static void addDependents(Module module, Map wiringCopy, + Set refreshClosure) { if (refreshClosure.contains(module)) return; refreshClosure.add(module); @@ -1348,13 +1440,15 @@ private static void addDependents(Module module, Map getDependencyClosure(ModuleRevision initial, Map wiringCopy) { + static Collection getDependencyClosure(ModuleRevision initial, + Map wiringCopy) { Set dependencyClosure = new HashSet<>(); addDependents(initial, wiringCopy, dependencyClosure); return dependencyClosure; } - private static void addDependents(ModuleRevision revision, Map wiringCopy, Set dependencyClosure) { + private static void addDependents(ModuleRevision revision, Map wiringCopy, + Set dependencyClosure) { if (dependencyClosure.contains(revision)) return; dependencyClosure.add(revision); @@ -1419,12 +1513,14 @@ boolean isRefreshingSystemModule() { static Requirement getIdentityRequirement(String name, Version version) { version = version == null ? Version.emptyVersion : version; - String filter = "(&(" + IdentityNamespace.IDENTITY_NAMESPACE + "=" + name + ")(" + IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE + "=" + version.toString() + "))"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$//$NON-NLS-4$//$NON-NLS-5$ + String filter = "(&(" + IdentityNamespace.IDENTITY_NAMESPACE + "=" + name + ")(" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + + IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE + "=" + version.toString() + "))"; //$NON-NLS-1$//$NON-NLS-2$ Map directives = Collections.singletonMap(Namespace.REQUIREMENT_FILTER_DIRECTIVE, filter); return new ModuleRequirement(IdentityNamespace.IDENTITY_NAMESPACE, directives, Collections.emptyMap(), null); } - class ContainerWiring implements FrameworkWiring, EventDispatcher> { + class ContainerWiring + implements FrameworkWiring, EventDispatcher> { private final Object monitor = new Object(); private EventManager refreshThread = null; @@ -1442,7 +1538,8 @@ public void refreshBundles(Collection bundles, FrameworkListener... list // notice that we only do one refresh operation at a time CopyOnWriteIdentityMap dispatchListeners = new CopyOnWriteIdentityMap<>(); dispatchListeners.put(this, listeners); - ListenerQueue> queue = new ListenerQueue<>(getManager()); + ListenerQueue> queue = new ListenerQueue<>( + getManager()); queue.queueListeners(dispatchListeners.entrySet(), this); // dispatch the refresh job @@ -1520,11 +1617,13 @@ public Collection run() { } @Override - public void dispatchEvent(ContainerWiring eventListener, FrameworkListener[] frameworkListeners, int eventAction, Collection eventObject) { + public void dispatchEvent(ContainerWiring eventListener, FrameworkListener[] frameworkListeners, + int eventAction, Collection eventObject) { try { refresh(eventObject); } finally { - adaptor.publishContainerEvent(ContainerEvent.REFRESH, moduleDatabase.getModule(0), null, frameworkListeners); + adaptor.publishContainerEvent(ContainerEvent.REFRESH, moduleDatabase.getModule(0), null, + frameworkListeners); } } @@ -1668,37 +1767,40 @@ public void setInitialBundleStartLevel(int startlevel) { @Override public void dispatchEvent(Module module, FrameworkListener[] listeners, int eventAction, Integer startlevel) { switch (eventAction) { - case FRAMEWORK_STARTLEVEL : - doContainerStartLevel(module, startlevel, listeners); - break; - case MODULE_STARTLEVEL : - if (debugStartLevel) { - Debug.println("StartLevel: changing bundle startlevel; " + toString(module) + "; newSL=" + startlevel + "; activeSL=" + getStartLevel()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - try { - if (getStartLevel() < startlevel) { - if (Module.ACTIVE_SET.contains(module.getState())) { - if (debugStartLevel) { - Debug.println("StartLevel: stopping bundle; " + toString(module) + "; with startLevel=" + startlevel); //$NON-NLS-1$ //$NON-NLS-2$ - } - // Note that we don't need to hold the state change lock - // here when checking the active status because no other - // thread will successfully be able to start this bundle - // since the start-level is no longer met. - module.stop(StopOptions.TRANSIENT); - } - } else { + case FRAMEWORK_STARTLEVEL: + doContainerStartLevel(module, startlevel, listeners); + break; + case MODULE_STARTLEVEL: + if (debugStartLevel) { + Debug.println("StartLevel: changing bundle startlevel; " + toString(module) + "; newSL=" //$NON-NLS-1$ //$NON-NLS-2$ + + startlevel + "; activeSL=" + getStartLevel()); //$NON-NLS-1$ + } + try { + if (getStartLevel() < startlevel) { + if (Module.ACTIVE_SET.contains(module.getState())) { if (debugStartLevel) { - Debug.println("StartLevel: resuming bundle; " + toString(module) + "; with startLevel=" + startlevel); //$NON-NLS-1$ //$NON-NLS-2$ + Debug.println("StartLevel: stopping bundle; " + toString(module) + "; with startLevel=" //$NON-NLS-1$ //$NON-NLS-2$ + + startlevel); } - module.start(StartOptions.TRANSIENT_IF_AUTO_START, StartOptions.TRANSIENT_RESUME); + // Note that we don't need to hold the state change lock + // here when checking the active status because no other + // thread will successfully be able to start this bundle + // since the start-level is no longer met. + module.stop(StopOptions.TRANSIENT); } - } catch (BundleException e) { - adaptor.publishContainerEvent(ContainerEvent.ERROR, module, e); + } else { + if (debugStartLevel) { + Debug.println("StartLevel: resuming bundle; " + toString(module) + "; with startLevel=" //$NON-NLS-1$ //$NON-NLS-2$ + + startlevel); + } + module.start(StartOptions.TRANSIENT_IF_AUTO_START, StartOptions.TRANSIENT_RESUME); } - break; - default : - break; + } catch (BundleException e) { + adaptor.publishContainerEvent(ContainerEvent.ERROR, module, e); + } + break; + default: + break; } } @@ -1711,14 +1813,16 @@ void doContainerStartLevel(Module module, int newStartLevel, FrameworkListener.. try { int currentSL = getStartLevel(); if (currentSL == 0) { - // check for an active framework; this is only valid when the system bundle is starting + // check for an active framework; this is only valid when the system bundle is + // starting Module systemModule = moduleDatabase.getModule(0); if (systemModule != null && !State.STARTING.equals(systemModule.getState())) { return; } } // Note that we must get a new list of modules each time; - // this is because additional modules could have been installed from the previous start-level + // this is because additional modules could have been installed from the + // previous start-level // but only do this if the module database has changed!! List sorted = null; long currentTimestamp = Long.MIN_VALUE; @@ -1741,7 +1845,8 @@ void doContainerStartLevel(Module module, int newStartLevel, FrameworkListener.. lazyStartParallel = new ArrayList<>(sorted.size()); eagerStart = new ArrayList<>(sorted.size()); eagerStartParallel = new ArrayList<>(sorted.size()); - separateModulesByActivationPolicy(sorted, lazyStart, lazyStartParallel, eagerStart, eagerStartParallel); + separateModulesByActivationPolicy(sorted, lazyStart, lazyStartParallel, eagerStart, + eagerStartParallel); currentTimestamp = moduleDatabase.getTimestamp(); } finally { moduleDatabase.readUnlock(); @@ -1780,7 +1885,8 @@ void doContainerStartLevel(Module module, int newStartLevel, FrameworkListener.. } } - private void incStartLevel(int toStartLevel, List lazyStart, List lazyStartParallel, List eagerStart, List eagerStartParallel) { + private void incStartLevel(int toStartLevel, List lazyStart, List lazyStartParallel, + List eagerStart, List eagerStartParallel) { // start lazy activated first // start parallel bundles first incStartLevel(toStartLevel, lazyStartParallel, true); @@ -1789,7 +1895,8 @@ private void incStartLevel(int toStartLevel, List lazyStart, List sortedModules, List lazyStart, List lazyStartParallel, List eagerStart, List eagerStartParallel) { + private void separateModulesByActivationPolicy(List sortedModules, List lazyStart, + List lazyStartParallel, List eagerStart, List eagerStartParallel) { for (Module module : sortedModules) { if (!restrictParallelStart || module.isParallelActivated()) { if (module.isLazyActivate()) { @@ -1847,7 +1954,9 @@ public void execute(Runnable command) { public void run() { try { if (debugStartLevel) { - Debug.println("StartLevel: resuming bundle; " + ContainerStartLevel.this.toString(module) + "; with startLevel=" + toStartLevel); //$NON-NLS-1$ //$NON-NLS-2$ + Debug.println( + "StartLevel: resuming bundle; " + ContainerStartLevel.this.toString(module) //$NON-NLS-1$ + + "; with startLevel=" + toStartLevel); //$NON-NLS-1$ } module.start(StartOptions.TRANSIENT_IF_AUTO_START, StartOptions.TRANSIENT_RESUME); } catch (BundleException e) { @@ -1884,7 +1993,8 @@ private void decStartLevel(int toStartLevel, List sortedModules) { try { if (Module.ACTIVE_SET.contains(module.getState())) { if (debugStartLevel) { - Debug.println("StartLevel: stopping bundle; " + toString(module) + "; with startLevel=" + moduleStartLevel); //$NON-NLS-1$ //$NON-NLS-2$ + Debug.println("StartLevel: stopping bundle; " + toString(module) + "; with startLevel=" //$NON-NLS-1$ //$NON-NLS-2$ + + moduleStartLevel); } // Note that we don't need to hold the state change lock // here when checking the active status because no other diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleContainerAdaptor.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleContainerAdaptor.java index 2a536092b73..f8ffabcc7a9 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleContainerAdaptor.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleContainerAdaptor.java @@ -26,6 +26,7 @@ /** * Adapts the behavior of a container. + * * @since 3.10 */ public abstract class ModuleContainerAdaptor { @@ -37,18 +38,21 @@ public void execute(Runnable command) { }; /** - * Event types that may be {@link #publishContainerEvent(ContainerEvent, Module, Throwable, FrameworkListener...) published} - * for a container. + * Event types that may be + * {@link #publishContainerEvent(ContainerEvent, Module, Throwable, FrameworkListener...) + * published} for a container. * */ public enum ContainerEvent { /** - * A container {@link ModuleContainer#refresh(java.util.Collection) refresh} operation has completed + * A container {@link ModuleContainer#refresh(java.util.Collection) refresh} + * operation has completed */ REFRESH, /** - * A container {@link ModuleContainer#getFrameworkStartLevel() start level} change has completed. + * A container {@link ModuleContainer#getFrameworkStartLevel() start level} + * change has completed. */ START_LEVEL, @@ -58,28 +62,26 @@ public enum ContainerEvent { STARTED, /** - * This event is returned by {@link SystemModule#waitForStop(long)} - * to indicate that the container has stopped. + * This event is returned by {@link SystemModule#waitForStop(long)} to indicate + * that the container has stopped. */ STOPPED, /** - * This event is returned by {@link SystemModule#waitForStop(long)} - * to indicate that the container has stopped because of an update - * operation. + * This event is returned by {@link SystemModule#waitForStop(long)} to indicate + * that the container has stopped because of an update operation. */ STOPPED_UPDATE, /** - * This event is returned by {@link SystemModule#waitForStop(long)} - * to indicate that the container has stopped because of an refresh - * operation. + * This event is returned by {@link SystemModule#waitForStop(long)} to indicate + * that the container has stopped because of an refresh operation. */ STOPPED_REFRESH, /** - * This event is returned by {@link SystemModule#waitForStop(long)} - * to indicate that the wait operation has timed out.. + * This event is returned by {@link SystemModule#waitForStop(long)} to indicate + * that the wait operation has timed out.. */ STOPPED_TIMEOUT, @@ -100,8 +102,10 @@ public enum ContainerEvent { } /** - * Event types that may be {@link #publishModuleEvent(ModuleEvent, Module, Module) published} for a module - * indicating a {@link Module#getState() state} change has occurred for a module. + * Event types that may be + * {@link #publishModuleEvent(ModuleEvent, Module, Module) published} for a + * module indicating a {@link Module#getState() state} change has occurred for a + * module. */ public static enum ModuleEvent { /** @@ -109,8 +113,8 @@ public static enum ModuleEvent { */ INSTALLED, /** - * The module has been activated with the lazy activation policy and - * is waiting a {@link Module.StartOptions#LAZY_TRIGGER trigger} class load. + * The module has been activated with the lazy activation policy and is waiting + * a {@link Module.StartOptions#LAZY_TRIGGER trigger} class load. */ LAZY_ACTIVATION, /** @@ -149,40 +153,47 @@ public static enum ModuleEvent { /** * Returns the collision hook the container will use. + * * @return the collision hook the container will use. */ public abstract ModuleCollisionHook getModuleCollisionHook(); /** * Returns the resolver hook factory the container will use. + * * @return the resolver hook factory the container will use. */ public abstract ResolverHookFactory getResolverHookFactory(); /** - * Publishes the specified container event. - * No locks are held by the container when this method is called - * @param type the type of event - * @param module the module associated with the event - * @param error the error associated with the event, may be {@code null} + * Publishes the specified container event. No locks are held by the container + * when this method is called + * + * @param type the type of event + * @param module the module associated with the event + * @param error the error associated with the event, may be {@code null} * @param listeners additional listeners to publish the event to synchronously */ - public abstract void publishContainerEvent(ContainerEvent type, Module module, Throwable error, FrameworkListener... listeners); + public abstract void publishContainerEvent(ContainerEvent type, Module module, Throwable error, + FrameworkListener... listeners); /** - * Publishes the specified module event type for the specified module. - * No locks are held by the container when this method is called - * @param type the event type to publish + * Publishes the specified module event type for the specified module. No locks + * are held by the container when this method is called + * + * @param type the event type to publish * @param module the module the event is associated with - * @param origin the module which is the origin of the event. For the event - * type {@link ModuleEvent#INSTALLED}, this is the module whose context was used - * to install the module. Otherwise it is the module itself. May be null only - * when the event is not of type {@link ModuleEvent#INSTALLED}. + * @param origin the module which is the origin of the event. For the event type + * {@link ModuleEvent#INSTALLED}, this is the module whose context + * was used to install the module. Otherwise it is the module + * itself. May be null only when the event is not of type + * {@link ModuleEvent#INSTALLED}. */ public abstract void publishModuleEvent(ModuleEvent type, Module module, Module origin); /** * Returns the specified configuration property value + * * @param key the key of the configuration property * @return the configuration property value */ @@ -192,6 +203,7 @@ public String getProperty(String key) { /** * Creates a new {@link ModuleLoader} for the specified wiring. + * * @param wiring the module wiring to create a module loader for * @return a new {@link ModuleLoader} for the specified wiring. */ @@ -200,32 +212,37 @@ public ModuleLoader createModuleLoader(ModuleWiring wiring) { } /** - * Creates a new module. This gets called when a new module is installed - * or when {@link ModuleDatabase#load(DataInputStream) loading} persistent data into this - * database. - * @param location the location for the module - * @param id the id for the module - * @param settings the settings for the module. May be {@code null} if there are no settings. + * Creates a new module. This gets called when a new module is installed or when + * {@link ModuleDatabase#load(DataInputStream) loading} persistent data into + * this database. + * + * @param location the location for the module + * @param id the id for the module + * @param settings the settings for the module. May be {@code null} if there + * are no settings. * @param startlevel the start level for the module * @return the Module */ public abstract Module createModule(String location, long id, EnumSet settings, int startlevel); /** - * Creates the system module. This gets called when the system module is installed - * or when {@link ModuleDatabase#load(DataInputStream) loading} persistent data into this - * database. + * Creates the system module. This gets called when the system module is + * installed or when {@link ModuleDatabase#load(DataInputStream) loading} + * persistent data into this database. *

- * The returned system module must have an {@link Module#getId() id} of zero and a location - * of {@link Constants#SYSTEM_BUNDLE_LOCATION System Bundle}. + * The returned system module must have an {@link Module#getId() id} of zero and + * a location of {@link Constants#SYSTEM_BUNDLE_LOCATION System Bundle}. + * * @return the system module */ public abstract SystemModule createSystemModule(); /** - * Returns the current revision info for a module with the specified location and id + * Returns the current revision info for a module with the specified location + * and id + * * @param location the location of the module - * @param id the id of the module + * @param id the id of the module * @return the revision info, may be {@code null} */ public Object getRevisionInfo(String location, long id) { @@ -233,8 +250,10 @@ public Object getRevisionInfo(String location, long id) { } /** - * After a revision is created this method is called with the specified revision info. - * @param revision the newly created revision + * After a revision is created this method is called with the specified revision + * info. + * + * @param revision the newly created revision * @param revisionInfo the revision info that got associated with the revision */ public void associateRevision(ModuleRevision revision, Object revisionInfo) { @@ -243,21 +262,23 @@ public void associateRevision(ModuleRevision revision, Object revisionInfo) { /** * This is called when a wiring is made invalid and allows the adaptor to react - * to this. This method is called while holding state change lock for the - * module as well as for the module database. Care must be taken not to introduce + * to this. This method is called while holding state change lock for the module + * as well as for the module database. Care must be taken not to introduce * deadlock. + * * @param moduleWiring the module wiring being invalidated - * @param current the current module loader associated with the wiring, may be null. + * @param current the current module loader associated with the wiring, may + * be null. */ public void invalidateWiring(ModuleWiring moduleWiring, ModuleLoader current) { // do nothing by default } /** - * This is called if a request to refresh modules causes the system module - * to be refreshed. This causes the system module to be stopped in a back - * ground thread. This method is called before the background thread is - * started to stop the system module. + * This is called if a request to refresh modules causes the system module to be + * refreshed. This causes the system module to be stopped in a back ground + * thread. This method is called before the background thread is started to stop + * the system module. */ public void refreshedSystemModule() { // do nothing by default @@ -286,7 +307,9 @@ public void initEnd() { /** * Returns the debug options for the module container. - * @return the debug options for the module container, or null if there are no debug options. + * + * @return the debug options for the module container, or null if there are no + * debug options. */ public DebugOptions getDebugOptions() { // be default there are no debug options @@ -295,6 +318,7 @@ public DebugOptions getDebugOptions() { /** * Returns the executor used to perform resolve operations + * * @return the executor used to perform resolve operations * @since 3.11 */ @@ -304,9 +328,10 @@ public Executor getResolverExecutor() { /** * Returns the executor used to by the - * {@link ModuleContainer#getFrameworkStartLevel() FrameworkStartLevel} implementation to - * start bundles that have the same start level. This allows bundles to be - * started in parallel. + * {@link ModuleContainer#getFrameworkStartLevel() FrameworkStartLevel} + * implementation to start bundles that have the same start level. This allows + * bundles to be started in parallel. + * * @return the executor used by the {@link FrameworkStartLevel} implementation. * @since 3.14 */ @@ -316,30 +341,45 @@ public Executor getStartLevelExecutor() { /** * Allows a builder to be modified before it is used by the container. This gets - * call when a new module is {@link ModuleContainer#install(Module, String, ModuleRevisionBuilder, Object) installed} - * into the container or when an existing module is {@link ModuleContainer#update(Module, ModuleRevisionBuilder, Object) updated} - * with a new revision. The container does not call any methods on the builder before calling this method. - * @param operation The lifecycle operation event that is in progress using the supplied builder. - * This will be either {@link ModuleEvent#INSTALLED installed} or {@link ModuleEvent#UPDATED updated}. - * @param origin The module which originated the lifecycle operation. The origin may be {@code null} for - * {@link ModuleEvent#INSTALLED installed} operations. This is the module - * passed to the {@link ModuleContainer#install(Module, String, ModuleRevisionBuilder, Object) install} or - * {@link ModuleContainer#update(Module, ModuleRevisionBuilder, Object) update} method. - * @param builder the builder that will be used to create a new {@link ModuleRevision}. - * @param revisionInfo the revision info that will be used for the new revision, may be {@code null}. - * @return The modified builder or a completely new builder to be used by the bundle. A {@code null} value - * indicates the original builder should be used, which may have been modified by adding requirements or - * capabilities. + * call when a new module is + * {@link ModuleContainer#install(Module, String, ModuleRevisionBuilder, Object) + * installed} into the container or when an existing module is + * {@link ModuleContainer#update(Module, ModuleRevisionBuilder, Object) updated} + * with a new revision. The container does not call any methods on the builder + * before calling this method. + * + * @param operation The lifecycle operation event that is in progress using + * the supplied builder. This will be either + * {@link ModuleEvent#INSTALLED installed} or + * {@link ModuleEvent#UPDATED updated}. + * @param origin The module which originated the lifecycle operation. The + * origin may be {@code null} for + * {@link ModuleEvent#INSTALLED installed} operations. This + * is the module passed to the + * {@link ModuleContainer#install(Module, String, ModuleRevisionBuilder, Object) + * install} or + * {@link ModuleContainer#update(Module, ModuleRevisionBuilder, Object) + * update} method. + * @param builder the builder that will be used to create a new + * {@link ModuleRevision}. + * @param revisionInfo the revision info that will be used for the new revision, + * may be {@code null}. + * @return The modified builder or a completely new builder to be used by the + * bundle. A {@code null} value indicates the original builder should be + * used, which may have been modified by adding requirements or + * capabilities. * @since 3.12 */ - public ModuleRevisionBuilder adaptModuleRevisionBuilder(ModuleEvent operation, Module origin, ModuleRevisionBuilder builder, Object revisionInfo) { + public ModuleRevisionBuilder adaptModuleRevisionBuilder(ModuleEvent operation, Module origin, + ModuleRevisionBuilder builder, Object revisionInfo) { // do nothing by default return null; } /** - * Returns the scheduled executor that may be used by the - * container to schedule background tasks. + * Returns the scheduled executor that may be used by the container to schedule + * background tasks. + * * @return the scheduled executor, or null if background tasks are not supported * @since 3.13 */ diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleDatabase.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleDatabase.java index aaeda57d26f..385b07159d9 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleDatabase.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleDatabase.java @@ -55,30 +55,31 @@ import org.osgi.service.resolver.Resolver; /** - * A database for storing modules, their revisions and wiring states. The + * A database for storing modules, their revisions and wiring states. The * database is responsible for assigning ids and providing access to the - * capabilities provided by the revisions currently installed as well as - * the wiring states. + * capabilities provided by the revisions currently installed as well as the + * wiring states. *

* Concurrent Semantics
* - * Implementations must be thread safe. The database allows for concurrent - * read operations and all read operations are protected by the - * {@link #readLock() read} lock. All write operations are - * protected by the {@link #writeLock() write} lock. The read and write - * locks are reentrant and follow the semantics of the - * {@link ReentrantReadWriteLock}. Just like the {@code ReentrantReadWriteLock} - * the lock on a database can not be upgraded from a read to a write. Doing so will result in an - * {@link IllegalMonitorStateException} being thrown. This is behavior is different from - * the {@code ReentrantReadWriteLock} which results in a deadlock if an attempt is made - * to upgrade from a read to a write lock. + * Implementations must be thread safe. The database allows for concurrent read + * operations and all read operations are protected by the {@link #readLock() + * read} lock. All write operations are protected by the {@link #writeLock() + * write} lock. The read and write locks are reentrant and follow the semantics + * of the {@link ReentrantReadWriteLock}. Just like the + * {@code ReentrantReadWriteLock} the lock on a database can not be upgraded + * from a read to a write. Doing so will result in an + * {@link IllegalMonitorStateException} being thrown. This is behavior is + * different from the {@code ReentrantReadWriteLock} which results in a deadlock + * if an attempt is made to upgrade from a read to a write lock. *

- * A database is associated with a {@link ModuleContainer container}. The container - * associated with a database provides public API for manipulating the modules - * and their wiring states. For example, installing, updating, uninstalling, - * resolving and unresolving modules. Except for the {@link #load(DataInputStream)}, - * all other methods that perform write operations are intended to be used by - * the associated container. + * A database is associated with a {@link ModuleContainer container}. The + * container associated with a database provides public API for manipulating the + * modules and their wiring states. For example, installing, updating, + * uninstalling, resolving and unresolving modules. Except for the + * {@link #load(DataInputStream)}, all other methods that perform write + * operations are intended to be used by the associated container. + * * @since 3.10 */ public class ModuleDatabase { @@ -113,15 +114,15 @@ public class ModuleDatabase { final AtomicLong revisionsTimeStamp; /** - * Holds the current timestamp for all changes to this database. - * This includes changes to revisions and changes to module settings. + * Holds the current timestamp for all changes to this database. This includes + * changes to revisions and changes to module settings. */ final AtomicLong allTimeStamp; /** * Holds the construction time which is used to check for empty database on - * load. This is necessary to ensure the loaded database is consistent with - * what was persisted. + * load. This is necessary to ensure the loaded database is consistent with what + * was persisted. */ final long constructionTime; @@ -160,6 +161,7 @@ public boolean isContained(Sort... options) { /** * Constructs a new empty database. + * * @param adaptor the module container adaptor */ public ModuleDatabase(ModuleContainerAdaptor adaptor) { @@ -178,10 +180,11 @@ public ModuleDatabase(ModuleContainerAdaptor adaptor) { } /** - * Returns the module at the given location or null if no module exists - * at the given location. + * Returns the module at the given location or null if no module exists at the + * given location. *

* A read operation protected by the {@link #readLock() read} lock. + * * @param location the location of the module. * @return the module at the given location or null. */ @@ -195,10 +198,11 @@ final Module getModule(String location) { } /** - * Returns the module at the given id or null if no module exists - * at the given location. + * Returns the module at the given id or null if no module exists at the given + * location. *

* A read operation protected by the {@link #readLock() read} lock. + * * @param id the id of the module. * @return the module at the given id or null. */ @@ -215,9 +219,11 @@ final Module getModule(long id) { * Installs a new revision using the specified builder, location and module. *

* A write operation protected by the {@link #writeLock() write} lock. - * @param location the location to use for the installation - * @param builder the builder to use to create the new revision - * @param revisionInfo the revision info for the new revision, may be {@code null}. + * + * @param location the location to use for the installation + * @param builder the builder to use to create the new revision + * @param revisionInfo the revision info for the new revision, may be + * {@code null}. * @return the installed module */ final Module install(String location, ModuleRevisionBuilder builder, Object revisionInfo) { @@ -250,7 +256,8 @@ private EnumSet getActivationPolicySettings(ModuleRevisionBuilder buil return null; } for (GenericInfo info : builder.getCapabilities(EquinoxModuleDataNamespace.MODULE_DATA_NAMESPACE)) { - if (EquinoxModuleDataNamespace.CAPABILITY_ACTIVATION_POLICY_LAZY.equals(info.getAttributes().get(EquinoxModuleDataNamespace.CAPABILITY_ACTIVATION_POLICY))) { + if (EquinoxModuleDataNamespace.CAPABILITY_ACTIVATION_POLICY_LAZY + .equals(info.getAttributes().get(EquinoxModuleDataNamespace.CAPABILITY_ACTIVATION_POLICY))) { String compatibilityStartLazy = adaptor.getProperty(EquinoxConfiguration.PROP_COMPATIBILITY_START_LAZY); if (compatibilityStartLazy == null || Boolean.valueOf(compatibilityStartLazy)) { // TODO hack until p2 is fixed (bug 177641) @@ -265,7 +272,8 @@ private EnumSet getActivationPolicySettings(ModuleRevisionBuilder buil return null; } - final Module load(String location, ModuleRevisionBuilder builder, Object revisionInfo, long id, EnumSet settings, int startlevel) { + final Module load(String location, ModuleRevisionBuilder builder, Object revisionInfo, long id, + EnumSet settings, int startlevel) { // sanity check checkWrite(); if (modulesByLocations.containsKey(location)) @@ -289,11 +297,11 @@ final Module load(String location, ModuleRevisionBuilder builder, Object revisio } /** - * Uninstalls the specified module from this database. - * Uninstalling a module will attempt to clean up any removal pending - * revisions possible. + * Uninstalls the specified module from this database. Uninstalling a module + * will attempt to clean up any removal pending revisions possible. *

* A write operation protected by the {@link #writeLock() write} lock. + * * @param module the module to uninstall */ final void uninstall(Module module) { @@ -333,9 +341,11 @@ final void uninstall(Module module) { * Updates the specified module with anew revision using the specified builder. *

* A write operation protected by the {@link #writeLock() write} lock. - * @param module the module for which the revision provides an update for - * @param builder the builder to use to create the new revision - * @param revisionInfo the revision info for the new revision, may be {@code null}. + * + * @param module the module for which the revision provides an update for + * @param builder the builder to use to create the new revision + * @param revisionInfo the revision info for the new revision, may be + * {@code null}. */ final void update(Module module, ModuleRevisionBuilder builder, Object revisionInfo) { writeLock(); @@ -363,10 +373,9 @@ final void update(Module module, ModuleRevisionBuilder builder, Object revisionI } /** - * Examines the wirings to determine if there are any removal - * pending wiring objects that can be removed. We consider - * a removal pending wiring as removable if all dependent - * wiring are also removal pending. + * Examines the wirings to determine if there are any removal pending wiring + * objects that can be removed. We consider a removal pending wiring as + * removable if all dependent wiring are also removal pending. */ void cleanupRemovalPending() { // sanity check @@ -429,6 +438,7 @@ void cleanupRemovalPending() { * Gets all revisions with a removal pending wiring. *

* A read operation protected by the {@link #readLock() read} lock. + * * @return all revisions with a removal pending wiring. */ final Collection getRemovalPending() { @@ -446,10 +456,11 @@ final Collection getRemovalPending() { } /** - * Returns the current wiring for the specified revision or - * null of no wiring exists for the revision. + * Returns the current wiring for the specified revision or null of no wiring + * exists for the revision. *

* A read operation protected by the {@link #readLock() read} lock. + * * @param revision the revision to get the wiring for * @return the current wiring for the specified revision. */ @@ -463,10 +474,11 @@ final ModuleWiring getWiring(ModuleRevision revision) { } /** - * Returns a snapshot of the wirings for all revisions. This - * performs a shallow copy of each entry in the wirings map. + * Returns a snapshot of the wirings for all revisions. This performs a shallow + * copy of each entry in the wirings map. *

* A read operation protected by the {@link #readLock() read} lock. + * * @return a snapshot of the wirings for all revisions. */ final Map getWiringsCopy() { @@ -479,22 +491,22 @@ final Map getWiringsCopy() { } /** - * Returns a cloned snapshot of the wirings of all revisions. This - * performs a clone of each {@link ModuleWiring}. The - * {@link ModuleWiring#getRevision() revision}, - * {@link ModuleWiring#getModuleCapabilities(String) capabilities}, + * Returns a cloned snapshot of the wirings of all revisions. This performs a + * clone of each {@link ModuleWiring}. The {@link ModuleWiring#getRevision() + * revision}, {@link ModuleWiring#getModuleCapabilities(String) capabilities}, * {@link ModuleWiring#getModuleRequirements(String) requirements}, * {@link ModuleWiring#getProvidedModuleWires(String) provided wires}, * {@link ModuleWiring#getRequiredModuleWires(String) required wires}, and - * {@link ModuleWiring#getSubstitutedNames()} of - * each wiring are copied into a cloned copy of the wiring. + * {@link ModuleWiring#getSubstitutedNames()} of each wiring are copied into a + * cloned copy of the wiring. *

- * The returned map of wirings may be safely read from while not holding - * any read or write locks on this database. This is useful for doing + * The returned map of wirings may be safely read from while not holding any + * read or write locks on this database. This is useful for doing * {@link Resolver#resolve(org.osgi.service.resolver.ResolveContext) resolve} * operations without holding the read or write lock on this database. *

* A read operation protected by the {@link #readLock() read} lock. + * * @return a cloned snapshot of the wirings of all revisions. */ final Map getWiringsClone() { @@ -517,8 +529,9 @@ public ModuleWiring apply(ModuleRevision r, ModuleWiring w) { * Replaces the complete wiring map with the specified wiring *

* A write operation protected by the {@link #writeLock() write} lock. - * @param newWiring the new wiring to take effect. The values - * from the new wiring are copied. + * + * @param newWiring the new wiring to take effect. The values from the new + * wiring are copied. */ final void setWiring(Map newWiring) { writeLock(); @@ -532,12 +545,13 @@ final void setWiring(Map newWiring) { } /** - * Adds all the values from the specified delta wirings to the - * wirings current wirings + * Adds all the values from the specified delta wirings to the wirings current + * wirings *

* A write operation protected by the {@link #writeLock() write} lock. - * @param deltaWiring the new wiring values to take effect. - * The values from the delta wiring are copied. + * + * @param deltaWiring the new wiring values to take effect. The values from the + * delta wiring are copied. */ final void mergeWiring(Map deltaWiring) { writeLock(); @@ -549,15 +563,15 @@ final void mergeWiring(Map deltaWiring) { } } - /** - * Perform the specified operation while holding the write lock. - * This will also increment the timestamps and optionally the - * revisions timestamps. + * Perform the specified operation while holding the write lock. This will also + * increment the timestamps and optionally the revisions timestamps. *

* A write operation protected by the {@link #writeLock() write} lock. - * @param incrementRevision if true the revision timestamps will be incremented after successfully running the operation - * @param op the operation to run while holding the write lock. + * + * @param incrementRevision if true the revision timestamps will be incremented + * after successfully running the operation + * @param op the operation to run while holding the write lock. */ final void writeLockOperation(boolean incrementRevision, Runnable op) { writeLock(); @@ -573,6 +587,7 @@ final void writeLockOperation(boolean incrementRevision, Runnable op) { * Returns a snapshot of all modules ordered by module ID. *

* A read operation protected by the {@link #readLock() read} lock. + * * @return a snapshot of all modules. */ final List getModules() { @@ -581,6 +596,7 @@ final List getModules() { /** * Returns a snapshot of all modules ordered according to the sort options + * * @param sortOptions options for sorting * @return a snapshot of all modules ordered according to the sort options */ @@ -655,16 +671,21 @@ private Collection> sortByDependencies(List toSort) { ModuleRequirement req = wire.getRequirement(); // Add all requirements that are not package requirements. // Only add package requirements that are not dynamic - // TODO may want to consider only adding package, bundle and host requirements, other generic requirement are not that interesting - if (!PackageNamespace.PACKAGE_NAMESPACE.equals(req.getNamespace()) || !PackageNamespace.RESOLUTION_DYNAMIC.equals(req.getDirectives().get(Namespace.REQUIREMENT_RESOLUTION_DIRECTIVE))) { - references.add(new Module[] {wire.getRequirer().getRevisions().getModule(), wire.getProvider().getRevisions().getModule()}); + // TODO may want to consider only adding package, bundle and host requirements, + // other generic requirement are not that interesting + if (!PackageNamespace.PACKAGE_NAMESPACE.equals(req.getNamespace()) + || !PackageNamespace.RESOLUTION_DYNAMIC + .equals(req.getDirectives().get(Namespace.REQUIREMENT_RESOLUTION_DIRECTIVE))) { + references.add(new Module[] { wire.getRequirer().getRevisions().getModule(), + wire.getProvider().getRevisions().getModule() }); } } } // Sort an array using the references Module[] sorted = toSort.toArray(new Module[toSort.size()]); - Object[][] cycles = ComputeNodeOrder.computeNodeOrder(sorted, references.toArray(new Module[references.size()][])); + Object[][] cycles = ComputeNodeOrder.computeNodeOrder(sorted, + references.toArray(new Module[references.size()][])); // Apply the sorted array to the list toSort.clear(); @@ -693,6 +714,7 @@ private void checkWrite() { * returns the next module ID. *

* A read operation protected by the {@link #readLock() read} lock. + * * @return the next module ID */ public final long getNextId() { @@ -708,6 +730,7 @@ public final long getNextId() { * Atomically increments by one the next module ID. *

* A write operation protected by the {@link #writeLock()} lock. + * * @return the previous module ID * @since 3.13 */ @@ -721,17 +744,18 @@ public final long getAndIncrementNextId() { } /** - * Returns the current timestamp for the revisions of this database. - * The timestamp is incremented any time a modification - * is made to the revisions in this database. For example: + * Returns the current timestamp for the revisions of this database. The + * timestamp is incremented any time a modification is made to the revisions in + * this database. For example: *

    - *
  • installing a module - *
  • updating a module - *
  • uninstalling a module - *
  • modifying the wirings + *
  • installing a module + *
  • updating a module + *
  • uninstalling a module + *
  • modifying the wirings *
*

* A read operation protected by the {@link #readLock() read} lock. + * * @return the current timestamp of this database. */ final public long getRevisionsTimestamp() { @@ -744,18 +768,18 @@ final public long getRevisionsTimestamp() { } /** - * Returns the current timestamp for this database. - * The timestamp is incremented any time a modification - * is made to this database. This includes the modifications - * described in {@link #getRevisionsTimestamp() revisions timestamp} - * and the following modifications related to modules: + * Returns the current timestamp for this database. The timestamp is incremented + * any time a modification is made to this database. This includes the + * modifications described in {@link #getRevisionsTimestamp() revisions + * timestamp} and the following modifications related to modules: *

    - *
  • modifying the initial module start level - *
  • modifying a module start level - *
  • modifying a module settings + *
  • modifying the initial module start level + *
  • modifying a module start level + *
  • modifying a module settings *
*

* A read operation protected by the {@link #readLock() read} lock. + * * @return the current timestamp of this database. */ final public long getTimestamp() { @@ -769,6 +793,7 @@ final public long getTimestamp() { /** * Increments the timestamps of this database. + * * @param incrementRevision indicates if the revision timestamp should change */ private void incrementTimestamps(boolean incrementRevision) { @@ -792,6 +817,7 @@ private void setSystemLastModified(long currentTime) { /** * Acquires the read lock for this database. + * * @see ReadLock#lock() */ public final void readLock() { @@ -799,13 +825,13 @@ public final void readLock() { } /** - * Acquires the write lock for this database. - * Same as {@link WriteLock#lock()} except an illegal - * state exception is thrown if the current thread holds - * one or more read locks. + * Acquires the write lock for this database. Same as {@link WriteLock#lock()} + * except an illegal state exception is thrown if the current thread holds one + * or more read locks. + * * @see WriteLock#lock() - * @throws IllegalMonitorStateException if the current thread holds - * one or more read locks. + * @throws IllegalMonitorStateException if the current thread holds one or more + * read locks. */ public final void writeLock() { if (monitor.getReadHoldCount() > 0) { @@ -818,6 +844,7 @@ public final void writeLock() { /** * Attempts to release the read lock for this database. + * * @see ReadLock#unlock() */ public final void readUnlock() { @@ -826,6 +853,7 @@ public final void readUnlock() { /** * Attempts to release the write lock for this database. + * * @see WriteLock#unlock() */ public final void writeUnlock() { @@ -834,11 +862,12 @@ public final void writeUnlock() { /** * Adds the {@link ModuleRevision#getModuleCapabilities(String) capabilities} - * provided by the specified revision to this database. These capabilities must - * become available for lookup with the {@link ModuleDatabase#findCapabilities(Requirement)} - * method. + * provided by the specified revision to this database. These capabilities must + * become available for lookup with the + * {@link ModuleDatabase#findCapabilities(Requirement)} method. *

* This method must be called while holding the {@link #writeLock() write} lock. + * * @param revision the revision which has capabilities to add */ final void addCapabilities(ModuleRevision revision) { @@ -852,11 +881,12 @@ final void addCapabilities(ModuleRevision revision) { /** * Removes the {@link ModuleRevision#getModuleCapabilities(String) capabilities} - * provided by the specified revision from this database. These capabilities + * provided by the specified revision from this database. These capabilities * must no longer be available for lookup with the * {@link ModuleDatabase#findCapabilities(Requirement)} method. *

* This method must be called while holding the {@link #writeLock() write} lock. + * * @param revision */ protected void removeCapabilities(ModuleRevision revision) { @@ -865,12 +895,12 @@ protected void removeCapabilities(ModuleRevision revision) { } /** - * Returns a mutable snapshot of capabilities that are candidates for - * satisfying the specified requirement. + * Returns a mutable snapshot of capabilities that are candidates for satisfying + * the specified requirement. *

- * A read operation protected by the {@link #readLock() read} lock. - * Implementers of this method should acquire the read lock while - * finding capabilities. + * A read operation protected by the {@link #readLock() read} lock. Implementers + * of this method should acquire the read lock while finding capabilities. + * * @param requirement the requirement * @return the candidates for the requirement */ @@ -884,22 +914,26 @@ final List findCapabilities(Requirement requirement) { } /** - * Writes this database in a format suitable for using the {@link #load(DataInputStream)} - * method. All modules are stored which have a current {@link ModuleRevision revision}. - * Only the current revision of each module is stored (no removal pending revisions - * are stored). Optionally the {@link ModuleWiring wiring} of each current revision - * may be stored. Wiring can only be stored if there are no {@link #getRemovalPending() - * removal pending} revisions. + * Writes this database in a format suitable for using the + * {@link #load(DataInputStream)} method. All modules are stored which have a + * current {@link ModuleRevision revision}. Only the current revision of each + * module is stored (no removal pending revisions are stored). Optionally the + * {@link ModuleWiring wiring} of each current revision may be stored. Wiring + * can only be stored if there are no {@link #getRemovalPending() removal + * pending} revisions. *

* This method acquires the {@link #readLock() read} lock while writing this * database. *

- * After this database have been written, the output stream is flushed. - * The output stream remains open after this method returns. - * @param out the data output steam. - * @param persistWirings true if wirings should be persisted. This option will be ignored - * if there are {@link #getRemovalPending() removal pending} revisions. - * @throws IOException if writing this database to the specified output stream throws an IOException + * After this database have been written, the output stream is flushed. The + * output stream remains open after this method returns. + * + * @param out the data output steam. + * @param persistWirings true if wirings should be persisted. This option will + * be ignored if there are {@link #getRemovalPending() + * removal pending} revisions. + * @throws IOException if writing this database to the specified output stream + * throws an IOException */ public final void store(DataOutputStream out, boolean persistWirings) throws IOException { readLock(); @@ -911,18 +945,21 @@ public final void store(DataOutputStream out, boolean persistWirings) throws IOE } /** - * Loads information into this database from the input data stream. This data - * base must be empty and never been modified (the {@link #getRevisionsTimestamp() timestamp} is zero). - * All stored modules are loaded into this database. If the input stream contains - * wiring then it will also be loaded into this database. + * Loads information into this database from the input data stream. This data + * base must be empty and never been modified (the + * {@link #getRevisionsTimestamp() timestamp} is zero). All stored modules are + * loaded into this database. If the input stream contains wiring then it will + * also be loaded into this database. *

* Since this method modifies this database it is considered a write operation. - * This method acquires the {@link #writeLock() write} lock while loading - * the information into this database. + * This method acquires the {@link #writeLock() write} lock while loading the + * information into this database. *

* The specified stream remains open after this method returns. + * * @param in the data input stream. - * @throws IOException if an error occurred when reading from the input stream. + * @throws IOException if an error occurred when reading from the + * input stream. * @throws IllegalStateException if this database is not empty. */ public final void load(DataInputStream in) throws IOException { @@ -987,9 +1024,12 @@ private static class Persistence { private static final byte LONG_STRING = 3; private static final byte VALUE_STRING = 0; - // REMOVED treated as List - private static final byte VALUE_STRING_ARRAY = 1; - // REMOVED never was really supported by the OSGi builder - private static final byte VAlUE_BOOLEAN = 2; - // REMOVED never was really supported by the OSGi builder - private static final byte VALUE_INTEGER = 3; + // REMOVED treated as List - private static final byte + // VALUE_STRING_ARRAY = 1; + // REMOVED never was really supported by the OSGi builder - private static final + // byte VAlUE_BOOLEAN = 2; + // REMOVED never was really supported by the OSGi builder - private static final + // byte VALUE_INTEGER = 3; private static final byte VALUE_LONG = 4; private static final byte VALUE_DOUBLE = 5; private static final byte VALUE_VERSION = 6; @@ -1020,7 +1060,8 @@ private static void addToReadTable(Object object, int index, List object } } - public static void store(ModuleDatabase moduleDatabase, DataOutputStream out, boolean persistWirings) throws IOException { + public static void store(ModuleDatabase moduleDatabase, DataOutputStream out, boolean persistWirings) + throws IOException { out.writeInt(VERSION); out.writeLong(moduleDatabase.getRevisionsTimestamp()); out.writeLong(moduleDatabase.getTimestamp()); @@ -1079,7 +1120,8 @@ public static void store(ModuleDatabase moduleDatabase, DataOutputStream out, bo return; } - // prime the object table with all the required wires which reference the modules + // prime the object table with all the required wires which reference the + // modules out.writeInt(wirings.size()); for (ModuleWiring wiring : wirings.values()) { List requiredWires = wiring.getPersistentRequiredWires(); @@ -1089,7 +1131,8 @@ public static void store(ModuleDatabase moduleDatabase, DataOutputStream out, bo } } - // now write all the info about each wiring using only indexes from the objectTable + // now write all the info about each wiring using only indexes from the + // objectTable for (ModuleWiring wiring : wirings.values()) { writeWiring(wiring, out, objectTable); } @@ -1097,7 +1140,8 @@ public static void store(ModuleDatabase moduleDatabase, DataOutputStream out, bo out.flush(); } - private static void getStringsVersionsAndMaps(Module module, ModuleDatabase moduleDatabase, Set allStrings, Set allVersions, Set> allMaps) { + private static void getStringsVersionsAndMaps(Module module, ModuleDatabase moduleDatabase, + Set allStrings, Set allVersions, Set> allMaps) { ModuleRevision current = module.getCurrentRevision(); if (current == null) return; @@ -1128,7 +1172,8 @@ private static void getStringsVersionsAndMaps(Module module, ModuleDatabase modu } } - private static void addMap(Map map, Set allStrings, Set allVersions, Set> allMaps) { + private static void addMap(Map map, Set allStrings, Set allVersions, + Set> allMaps) { if (!allMaps.add(map)) { // map was already added return; @@ -1143,17 +1188,17 @@ private static void addMap(Map map, Set allStrings, Set) value)) { - case VALUE_STRING : - for (Object string : (List) value) { - allStrings.add((String) string); - } - break; - case VALUE_VERSION : - for (Object version : (List) value) { - allStrings.add(((Version) version).getQualifier()); - allVersions.add((Version) version); - } - break; + case VALUE_STRING: + for (Object string : (List) value) { + allStrings.add((String) string); + } + break; + case VALUE_VERSION: + for (Object version : (List) value) { + allStrings.add(((Version) version).getQualifier()); + allVersions.add((Version) version); + } + break; } } } @@ -1162,7 +1207,8 @@ private static void addMap(Map map, Set allStrings, Set VERSION || VERSION / 1000 != version / 1000) - throw new IllegalArgumentException("The version of the persistent framework data is not compatible: " + version + " expecting: " + VERSION); //$NON-NLS-1$ //$NON-NLS-2$ + throw new IllegalArgumentException("The version of the persistent framework data is not compatible: " //$NON-NLS-1$ + + version + " expecting: " + VERSION); //$NON-NLS-1$ long revisionsTimeStamp = in.readLong(); long allTimeStamp = in.readLong(); moduleDatabase.nextId.set(in.readLong()); @@ -1223,7 +1269,8 @@ public static void load(ModuleDatabase moduleDatabase, DataInputStream in) throw moduleDatabase.allTimeStamp.set(allTimeStamp); } - private static void writeModule(Module module, ModuleDatabase moduleDatabase, DataOutputStream out, Map objectTable) throws IOException { + private static void writeModule(Module module, ModuleDatabase moduleDatabase, DataOutputStream out, + Map objectTable) throws IOException { ModuleRevision current = module.getCurrentRevision(); if (current == null) return; @@ -1240,14 +1287,16 @@ private static void writeModule(Module module, ModuleDatabase moduleDatabase, Da out.writeInt(capabilities.size()); for (ModuleCapability capability : capabilities) { out.writeInt(addToWriteTable(capability, objectTable)); - writeGenericInfo(capability.getNamespace(), capability.getPersistentAttributes(), capability.getDirectives(), out, objectTable); + writeGenericInfo(capability.getNamespace(), capability.getPersistentAttributes(), + capability.getDirectives(), out, objectTable); } List requirements = current.getRequirements(null); out.writeInt(requirements.size()); for (Requirement requirement : requirements) { out.writeInt(addToWriteTable(requirement, objectTable)); - writeGenericInfo(requirement.getNamespace(), requirement.getAttributes(), requirement.getDirectives(), out, objectTable); + writeGenericInfo(requirement.getNamespace(), requirement.getAttributes(), requirement.getDirectives(), + out, objectTable); } // settings @@ -1266,7 +1315,8 @@ private static void writeModule(Module module, ModuleDatabase moduleDatabase, Da out.writeLong(module.getLastModified()); } - private static void readModule(ModuleRevisionBuilder builder, ModuleDatabase moduleDatabase, DataInputStream in, List objectTable, int version) throws IOException { + private static void readModule(ModuleRevisionBuilder builder, ModuleDatabase moduleDatabase, DataInputStream in, + List objectTable, int version) throws IOException { builder.clear(); int moduleIndex = in.readInt(); String location = readString(in, objectTable); @@ -1321,7 +1371,8 @@ private static void readModule(ModuleRevisionBuilder builder, ModuleDatabase mod } } - private static void writeWire(ModuleWire wire, DataOutputStream out, Map objectTable) throws IOException { + private static void writeWire(ModuleWire wire, DataOutputStream out, Map objectTable) + throws IOException { Wire w = wire; Integer capability = objectTable.get(w.getCapability()); Integer provider = objectTable.get(w.getProvider()); @@ -1355,7 +1406,8 @@ private static void readWire(DataInputStream in, List objectTable) throw addToReadTable(result, wireIndex, objectTable); } - private static void writeWiring(ModuleWiring wiring, DataOutputStream out, Map objectTable) throws IOException { + private static void writeWiring(ModuleWiring wiring, DataOutputStream out, Map objectTable) + throws IOException { Integer revisionIndex = objectTable.get(wiring.getRevision()); if (revisionIndex == null) throw new NullPointerException("Could not find revision for wiring."); //$NON-NLS-1$ @@ -1443,7 +1495,9 @@ private static ModuleWiring readWiring(DataInputStream in, List objectTa requiredWires.build(), substituted); } - private static void writeGenericInfo(String namespace, Map attributes, Map directives, DataOutputStream out, Map objectTable) throws IOException { + private static void writeGenericInfo(String namespace, Map attributes, + Map directives, DataOutputStream out, Map objectTable) + throws IOException { writeString(namespace, out, objectTable); Integer attributesIndex = objectTable.get(attributes); @@ -1455,10 +1509,13 @@ private static void writeGenericInfo(String namespace, Map attributes } @SuppressWarnings("unchecked") - private static void readGenericInfo(boolean isCapability, DataInputStream in, ModuleRevisionBuilder builder, List objectTable, int version) throws IOException { + private static void readGenericInfo(boolean isCapability, DataInputStream in, ModuleRevisionBuilder builder, + List objectTable, int version) throws IOException { String namespace = readString(in, objectTable); - Map attributes = version >= 2 ? (Map) objectTable.get(in.readInt()) : readMap(in, objectTable); - Map directives = version >= 2 ? (Map) objectTable.get(in.readInt()) : readMap(in, objectTable); + Map attributes = version >= 2 ? (Map) objectTable.get(in.readInt()) + : readMap(in, objectTable); + Map directives = version >= 2 ? (Map) objectTable.get(in.readInt()) + : readMap(in, objectTable); if (attributes == null || directives == null) throw new NullPointerException("Could not find the expected indexes"); //$NON-NLS-1$ if (isCapability) { @@ -1469,7 +1526,8 @@ private static void readGenericInfo(boolean isCapability, DataInputStream in, Mo } - private static void writeMap(Map source, DataOutputStream out, Map objectTable, ModuleDatabase moduleDatabase) throws IOException { + private static void writeMap(Map source, DataOutputStream out, Map objectTable, + ModuleDatabase moduleDatabase) throws IOException { if (source == null) { out.writeInt(0); } else { @@ -1494,8 +1552,11 @@ private static void writeMap(Map source, DataOutputStream out, Map) value, objectTable, moduleDatabase); } else { // do our best and write a string; post an error. - // This will be difficult to debug because we don't know which module it is coming from, but it is better than being silent - moduleDatabase.adaptor.publishContainerEvent(ContainerEvent.ERROR, moduleDatabase.getModule(0), new BundleException("Invalid map value: " + key + " = " + value.getClass().getName() + '[' + value + ']')); //$NON-NLS-1$ //$NON-NLS-2$ + // This will be difficult to debug because we don't know which module it is + // coming from, but it is better than being silent + moduleDatabase.adaptor.publishContainerEvent(ContainerEvent.ERROR, moduleDatabase.getModule(0), + new BundleException("Invalid map value: " + key + " = " + value.getClass().getName() //$NON-NLS-1$ //$NON-NLS-2$ + + '[' + value + ']')); out.writeByte(VALUE_STRING); writeString(String.valueOf(value), out, objectTable); } @@ -1533,22 +1594,23 @@ private static Map readMap(DataInputStream in, List obje private static Object readMapValue(DataInputStream in, int type, List objectTable) throws IOException { switch (type) { - case VALUE_STRING : - return readString(in, objectTable); - case VALUE_LONG : - return Long.valueOf(in.readLong()); - case VALUE_DOUBLE : - return Double.valueOf(in.readDouble()); - case VALUE_VERSION : - return readVersion(in, objectTable); - case VALUE_LIST : - return readList(in, objectTable); - default : - throw new IllegalArgumentException("Invalid type: " + type); //$NON-NLS-1$ - } - } - - private static void writeList(DataOutputStream out, String key, List list, Map objectTable, ModuleDatabase moduleDatabase) throws IOException { + case VALUE_STRING: + return readString(in, objectTable); + case VALUE_LONG: + return Long.valueOf(in.readLong()); + case VALUE_DOUBLE: + return Double.valueOf(in.readDouble()); + case VALUE_VERSION: + return readVersion(in, objectTable); + case VALUE_LIST: + return readList(in, objectTable); + default: + throw new IllegalArgumentException("Invalid type: " + type); //$NON-NLS-1$ + } + } + + private static void writeList(DataOutputStream out, String key, List list, Map objectTable, + ModuleDatabase moduleDatabase) throws IOException { if (list.isEmpty()) { out.writeInt(0); return; @@ -1562,24 +1624,27 @@ private static void writeList(DataOutputStream out, String key, List list, Ma out.writeByte(type == -2 ? VALUE_STRING : type); for (Object value : list) { switch (type) { - case VALUE_STRING : - writeString((String) value, out, objectTable); - break; - case VALUE_LONG : - out.writeLong(((Long) value).longValue()); - break; - case VALUE_DOUBLE : - out.writeDouble(((Double) value).doubleValue()); - break; - case VALUE_VERSION : - writeVersion((Version) value, out, objectTable); - break; - default : - // do our best and write a string; post an error. - // This will be difficult to debug because we don't know which module it is coming from, but it is better than being silent - moduleDatabase.adaptor.publishContainerEvent(ContainerEvent.ERROR, moduleDatabase.getModule(0), new BundleException("Invalid list element in map: " + key + " = " + value.getClass().getName() + '[' + value + ']')); //$NON-NLS-1$ //$NON-NLS-2$ - writeString(String.valueOf(value), out, objectTable); - break; + case VALUE_STRING: + writeString((String) value, out, objectTable); + break; + case VALUE_LONG: + out.writeLong(((Long) value).longValue()); + break; + case VALUE_DOUBLE: + out.writeDouble(((Double) value).doubleValue()); + break; + case VALUE_VERSION: + writeVersion((Version) value, out, objectTable); + break; + default: + // do our best and write a string; post an error. + // This will be difficult to debug because we don't know which module it is + // coming from, but it is better than being silent + moduleDatabase.adaptor.publishContainerEvent(ContainerEvent.ERROR, moduleDatabase.getModule(0), + new BundleException("Invalid list element in map: " + key + " = " //$NON-NLS-1$ //$NON-NLS-2$ + + value.getClass().getName() + '[' + value + ']')); + writeString(String.valueOf(value), out, objectTable); + break; } } } @@ -1614,22 +1679,24 @@ private static List readList(DataInputStream in, List objectTable) th return Collections.unmodifiableList(list); } - private static Object readListValue(byte listType, DataInputStream in, List objectTable) throws IOException { + private static Object readListValue(byte listType, DataInputStream in, List objectTable) + throws IOException { switch (listType) { - case VALUE_STRING : - return readString(in, objectTable); - case VALUE_LONG : - return Long.valueOf(in.readLong()); - case VALUE_DOUBLE : - return Double.valueOf(in.readDouble()); - case VALUE_VERSION : - return readVersion(in, objectTable); - default : - throw new IllegalArgumentException("Invalid type: " + listType); //$NON-NLS-1$ + case VALUE_STRING: + return readString(in, objectTable); + case VALUE_LONG: + return Long.valueOf(in.readLong()); + case VALUE_DOUBLE: + return Double.valueOf(in.readDouble()); + case VALUE_VERSION: + return readVersion(in, objectTable); + default: + throw new IllegalArgumentException("Invalid type: " + listType); //$NON-NLS-1$ } } - private static void writeVersion(Version version, DataOutputStream out, Map objectTable) throws IOException { + private static void writeVersion(Version version, DataOutputStream out, Map objectTable) + throws IOException { if (version == null || version.equals(Version.emptyVersion)) { out.writeByte(NULL); return; @@ -1647,7 +1714,8 @@ private static void writeVersion(Version version, DataOutputStream out, Map objectTable) throws IOException { + private static void writeQualifier(String string, DataOutputStream out, Map objectTable) + throws IOException { if (string != null && string.length() == 0) string = null; writeString(string, out, objectTable); @@ -1663,7 +1731,8 @@ private static Version readVersion(DataInputStream in, List objectTable) return readVersion0(in, objectTable, true); } - private static Version readVersion0(DataInputStream in, List objectTable, boolean intern) throws IOException { + private static Version readVersion0(DataInputStream in, List objectTable, boolean intern) + throws IOException { byte type = in.readByte(); if (type == INDEX) { int index = in.readInt(); @@ -1679,7 +1748,8 @@ private static Version readVersion0(DataInputStream in, List objectTable return intern ? ObjectPool.intern(version) : version; } - private static void writeString(String string, DataOutputStream out, Map objectTable) throws IOException { + private static void writeString(String string, DataOutputStream out, Map objectTable) + throws IOException { Integer index = string != null ? objectTable.get(string) : null; if (index != null) { out.writeByte(INDEX); @@ -1713,7 +1783,8 @@ static private String readString(DataInputStream in, List objectTable) t return readString0(in, objectTable, true); } - static private String readString0(DataInputStream in, List objectTable, boolean intern) throws IOException { + static private String readString0(DataInputStream in, List objectTable, boolean intern) + throws IOException { byte type = in.readByte(); if (type == INDEX) { int index = in.readInt(); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleLoader.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleLoader.java index 9e2c390c2b0..edc78ca5c8f 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleLoader.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleLoader.java @@ -19,19 +19,21 @@ import org.eclipse.osgi.container.Module.StartOptions; /** - * A module loader is what connects a {@link ModuleWiring} to a real classloader. + * A module loader is what connects a {@link ModuleWiring} to a real + * classloader. + * * @since 3.10 */ public abstract class ModuleLoader { /** - * Returns entries in wiring this module loader - * is associated with. - * @param path The path name in which to look. + * Returns entries in wiring this module loader is associated with. + * + * @param path The path name in which to look. * @param filePattern The file name pattern for selecting entries in the - * specified path - * @param options The options for listing resource names. - * @return An unmodifiable list of URL objects for each matching entry, or - * an empty list if no matching entry could be found + * specified path + * @param options The options for listing resource names. + * @return An unmodifiable list of URL objects for each matching entry, or an + * empty list if no matching entry could be found * @see ModuleWiring#findEntries(String, String, int) */ protected abstract List findEntries(String path, String filePattern, int options); @@ -47,30 +49,33 @@ public abstract class ModuleLoader { protected abstract Collection listResources(String path, String filePattern, int options); /** - * Returns the class loader for this module loader. A null - * value will be returned if this module loader is for a fragment. + * Returns the class loader for this module loader. A null value + * will be returned if this module loader is for a fragment. + * * @return The class loader for this module loader. * @see ModuleWiring#getClassLoader() */ protected abstract ClassLoader getClassLoader(); /** - * Is called by {@link Module#start(Module.StartOptions...)} when - * using the {@link StartOptions#LAZY_TRIGGER} option is used. - * @return false if the trigger was not previously set; otherwise - * true is returned + * Is called by {@link Module#start(Module.StartOptions...)} when using the + * {@link StartOptions#LAZY_TRIGGER} option is used. + * + * @return false if the trigger was not previously set; otherwise true is + * returned */ protected abstract boolean getAndSetTrigger(); /** * Returns true if the lazy trigger is set for this module loader + * * @return true if the lazy trigger is set for this module loader */ public abstract boolean isTriggerSet(); /** - * Dynamically loads fragment revisions to this already resolved - * module loader. + * Dynamically loads fragment revisions to this already resolved module loader. + * * @param fragments the fragments to load */ protected abstract void loadFragments(Collection fragments); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleRequirement.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleRequirement.java index 42f69c1c96c..ec4d7c9d0b4 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleRequirement.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleRequirement.java @@ -24,9 +24,10 @@ import org.osgi.resource.Namespace; /** - * An implementation of {@link BundleRequirement}. This requirement implements + * An implementation of {@link BundleRequirement}. This requirement implements * the matches method according to the OSGi specification which includes * implementing the mandatory directive for the osgi.wiring.* namespaces. + * * @since 3.10 * @noextend This class is not intended to be subclassed by clients. */ @@ -36,7 +37,8 @@ public class ModuleRequirement implements BundleRequirement { private final Map attributes; private final ModuleRevision revision; - ModuleRequirement(String namespace, Map directives, Map attributes, ModuleRevision revision) { + ModuleRequirement(String namespace, Map directives, Map attributes, + ModuleRevision revision) { this.namespace = namespace; this.directives = ModuleRevisionBuilder.unmodifiableMap(directives); this.attributes = ModuleRevisionBuilder.unmodifiableMap(attributes); @@ -61,7 +63,8 @@ public boolean matches(BundleCapability capability) { return false; } } - boolean matchMandatory = PackageNamespace.PACKAGE_NAMESPACE.equals(namespace) || BundleNamespace.BUNDLE_NAMESPACE.equals(namespace) || HostNamespace.HOST_NAMESPACE.equals(namespace); + boolean matchMandatory = PackageNamespace.PACKAGE_NAMESPACE.equals(namespace) + || BundleNamespace.BUNDLE_NAMESPACE.equals(namespace) || HostNamespace.HOST_NAMESPACE.equals(namespace); return Capabilities.matches(f, capability, matchMandatory); } @@ -96,7 +99,8 @@ DynamicModuleRequirement getDynamicPackageRequirement(ModuleRevision host, Strin if (!PackageNamespace.PACKAGE_NAMESPACE.equals(namespace)) { return null; } - if (!PackageNamespace.RESOLUTION_DYNAMIC.equals(directives.get(PackageNamespace.REQUIREMENT_RESOLUTION_DIRECTIVE))) { + if (!PackageNamespace.RESOLUTION_DYNAMIC + .equals(directives.get(PackageNamespace.REQUIREMENT_RESOLUTION_DIRECTIVE))) { // not dynamic return null; } @@ -117,10 +121,12 @@ DynamicModuleRequirement getDynamicPackageRequirement(ModuleRevision host, Strin String specificPackageFilter = null; if ("*".equals(filterPackageName)) { //$NON-NLS-1$ // matches all - specificPackageFilter = dynamicFilter.replace(PACKAGENAME_FILTER_COMPONENT + filterPackageName, PACKAGENAME_FILTER_COMPONENT + dynamicPkgName); + specificPackageFilter = dynamicFilter.replace(PACKAGENAME_FILTER_COMPONENT + filterPackageName, + PACKAGENAME_FILTER_COMPONENT + dynamicPkgName); } else if (filterPackageName.endsWith(".*")) { //$NON-NLS-1$ if (dynamicPkgName.startsWith(filterPackageName.substring(0, filterPackageName.length() - 1))) { - specificPackageFilter = dynamicFilter.replace(PACKAGENAME_FILTER_COMPONENT + filterPackageName, PACKAGENAME_FILTER_COMPONENT + dynamicPkgName); + specificPackageFilter = dynamicFilter.replace(PACKAGENAME_FILTER_COMPONENT + filterPackageName, + PACKAGENAME_FILTER_COMPONENT + dynamicPkgName); } } else if (dynamicPkgName.equals(filterPackageName)) { specificPackageFilter = dynamicFilter; diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleResolutionReport.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleResolutionReport.java index edd51c87eaa..cf8df979fd5 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleResolutionReport.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleResolutionReport.java @@ -37,7 +37,9 @@ import org.osgi.service.resolver.ResolutionException; /** - * A resolution report implementation used by the container for resolution operations. + * A resolution report implementation used by the container for resolution + * operations. + * * @since 3.10 */ class ModuleResolutionReport implements ResolutionReport { @@ -83,9 +85,11 @@ public Type getType() { private final ResolutionException resolutionException; private final Map> resolutionResult; - ModuleResolutionReport(Map> resolutionResult, Map> entries, ResolutionException cause) { + ModuleResolutionReport(Map> resolutionResult, Map> entries, + ResolutionException cause) { this.entries = entries == null ? Collections.emptyMap() : Collections.unmodifiableMap(new HashMap<>(entries)); - this.resolutionResult = resolutionResult == null ? Collections.emptyMap() : Collections.unmodifiableMap(resolutionResult); + this.resolutionResult = resolutionResult == null ? Collections.emptyMap() + : Collections.unmodifiableMap(resolutionResult); this.resolutionException = cause; } @@ -103,7 +107,8 @@ Map> getResolutionResult() { return resolutionResult; } - private static String getResolutionReport0(String prepend, ModuleRevision revision, Map> reportEntries, Set visited) { + private static String getResolutionReport0(String prepend, ModuleRevision revision, + Map> reportEntries, Set visited) { if (prepend == null) { prepend = ""; //$NON-NLS-1$ } @@ -129,41 +134,48 @@ private static String getResolutionReport0(String prepend, ModuleRevision revisi return result.toString(); } - private static void printResolutionEntry(StringBuilder result, String prepend, ResolutionReport.Entry entry, Map> reportEntries, Set visited) { + private static void printResolutionEntry(StringBuilder result, String prepend, ResolutionReport.Entry entry, + Map> reportEntries, Set visited) { switch (entry.getType()) { - case MISSING_CAPABILITY : - result.append(prepend).append(Msg.ModuleResolutionReport_UnresolvedReq).append(printRequirement(entry.getData())).append('\n'); - break; - case SINGLETON_SELECTION : - result.append(prepend).append(Msg.ModuleResolutionReport_AnotherSingleton).append(entry.getData()).append('\n'); - break; - case UNRESOLVED_PROVIDER : - @SuppressWarnings("unchecked") - Map> unresolvedProviders = (Map>) entry.getData(); - for (Map.Entry> unresolvedRequirement : unresolvedProviders.entrySet()) { - // for now only printing the first possible unresolved candidates - Set unresolvedCapabilities = unresolvedRequirement.getValue(); - if (!unresolvedCapabilities.isEmpty()) { - Capability unresolvedCapability = unresolvedCapabilities.iterator().next(); - // make sure this is not a case of importing and exporting the same package - if (!unresolvedRequirement.getKey().getResource().equals(unresolvedCapability.getResource())) { - result.append(prepend).append(Msg.ModuleResolutionReport_UnresolvedReq).append(printRequirement(unresolvedRequirement.getKey())).append('\n'); - result.append(prepend).append(" -> ").append(printCapability(unresolvedCapability)).append('\n'); //$NON-NLS-1$ - result.append(getResolutionReport0(prepend + " ", (ModuleRevision) unresolvedCapability.getResource(), reportEntries, visited)); //$NON-NLS-1$ - } + case MISSING_CAPABILITY: + result.append(prepend).append(Msg.ModuleResolutionReport_UnresolvedReq) + .append(printRequirement(entry.getData())).append('\n'); + break; + case SINGLETON_SELECTION: + result.append(prepend).append(Msg.ModuleResolutionReport_AnotherSingleton).append(entry.getData()) + .append('\n'); + break; + case UNRESOLVED_PROVIDER: + @SuppressWarnings("unchecked") + Map> unresolvedProviders = (Map>) entry.getData(); + for (Map.Entry> unresolvedRequirement : unresolvedProviders.entrySet()) { + // for now only printing the first possible unresolved candidates + Set unresolvedCapabilities = unresolvedRequirement.getValue(); + if (!unresolvedCapabilities.isEmpty()) { + Capability unresolvedCapability = unresolvedCapabilities.iterator().next(); + // make sure this is not a case of importing and exporting the same package + if (!unresolvedRequirement.getKey().getResource().equals(unresolvedCapability.getResource())) { + result.append(prepend).append(Msg.ModuleResolutionReport_UnresolvedReq) + .append(printRequirement(unresolvedRequirement.getKey())).append('\n'); + result.append(prepend).append(" -> ").append(printCapability(unresolvedCapability)) //$NON-NLS-1$ + .append('\n'); + result.append(getResolutionReport0(prepend + " ", //$NON-NLS-1$ + (ModuleRevision) unresolvedCapability.getResource(), reportEntries, visited)); } } - break; - case FILTERED_BY_RESOLVER_HOOK : - result.append(Msg.ModuleResolutionReport_FilteredByHook).append('\n'); - break; - case USES_CONSTRAINT_VIOLATION : - result.append(prepend).append(Msg.ModuleResolutionReport_UsesConstraintError).append('\n'); - result.append(" ").append(entry.getData()); //$NON-NLS-1$ - break; - default : - result.append(Msg.ModuleResolutionReport_Unknown).append("type=").append(entry.getType()).append(" data=").append(entry.getData()).append('\n'); //$NON-NLS-1$ //$NON-NLS-2$ - break; + } + break; + case FILTERED_BY_RESOLVER_HOOK: + result.append(Msg.ModuleResolutionReport_FilteredByHook).append('\n'); + break; + case USES_CONSTRAINT_VIOLATION: + result.append(prepend).append(Msg.ModuleResolutionReport_UsesConstraintError).append('\n'); + result.append(" ").append(entry.getData()); //$NON-NLS-1$ + break; + default: + result.append(Msg.ModuleResolutionReport_Unknown).append("type=").append(entry.getType()).append(" data=") //$NON-NLS-1$ //$NON-NLS-2$ + .append(entry.getData()).append('\n'); + break; } } @@ -182,7 +194,8 @@ private static String createOSGiCapability(Capability cap) { Map attributes = new HashMap<>(cap.getAttributes()); Map directives = cap.getDirectives(); String name = String.valueOf(attributes.remove(cap.getNamespace())); - return name + ModuleRevision.toString(attributes, false, true) + ModuleRevision.toString(directives, true, true); + return name + ModuleRevision.toString(attributes, false, true) + + ModuleRevision.toString(directives, true, true); } private static String printRequirement(Object data) { @@ -191,11 +204,15 @@ private static String printRequirement(Object data) { } Requirement req = (Requirement) data; if (PackageNamespace.PACKAGE_NAMESPACE.equals(req.getNamespace())) { - return Constants.IMPORT_PACKAGE + ": " + createOSGiRequirement(req, PackageNamespace.CAPABILITY_VERSION_ATTRIBUTE, PackageNamespace.CAPABILITY_BUNDLE_VERSION_ATTRIBUTE); //$NON-NLS-1$ + return Constants.IMPORT_PACKAGE + ": " //$NON-NLS-1$ + + createOSGiRequirement(req, PackageNamespace.CAPABILITY_VERSION_ATTRIBUTE, + PackageNamespace.CAPABILITY_BUNDLE_VERSION_ATTRIBUTE); } else if (BundleNamespace.BUNDLE_NAMESPACE.equals(req.getNamespace())) { - return Constants.REQUIRE_BUNDLE + ": " + createOSGiRequirement(req, BundleNamespace.CAPABILITY_BUNDLE_VERSION_ATTRIBUTE); //$NON-NLS-1$ + return Constants.REQUIRE_BUNDLE + ": " //$NON-NLS-1$ + + createOSGiRequirement(req, BundleNamespace.CAPABILITY_BUNDLE_VERSION_ATTRIBUTE); } else if (HostNamespace.HOST_NAMESPACE.equals(req.getNamespace())) { - return Constants.FRAGMENT_HOST + ": " + createOSGiRequirement(req, HostNamespace.CAPABILITY_BUNDLE_VERSION_ATTRIBUTE); //$NON-NLS-1$ + return Constants.FRAGMENT_HOST + ": " //$NON-NLS-1$ + + createOSGiRequirement(req, HostNamespace.CAPABILITY_BUNDLE_VERSION_ATTRIBUTE); } return Constants.REQUIRE_CAPABILITY + ": " + req.toString(); //$NON-NLS-1$ } @@ -215,7 +232,8 @@ private static String createOSGiRequirement(Requirement requirement, String... v String name = matchingAttributes.remove(requirement.getNamespace()); if (name == null) throw new IllegalArgumentException("Invalid requirement: " + requirement); //$NON-NLS-1$ - return name + ModuleRevision.toString(matchingAttributes, false, true) + ModuleRevision.toString(directives, true, true); + return name + ModuleRevision.toString(matchingAttributes, false, true) + + ModuleRevision.toString(directives, true, true); } @Override diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleResolver.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleResolver.java index 402c3f28d11..555ee250c78 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleResolver.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleResolver.java @@ -75,8 +75,8 @@ import org.osgi.service.resolver.Resolver; /** - * The module resolver handles calls to the {@link Resolver} service for resolving modules - * in a module {@link ModuleContainer container}. + * The module resolver handles calls to the {@link Resolver} service for + * resolving modules in a module {@link ModuleContainer container}. */ final class ModuleResolver { static final String SEPARATOR = System.lineSeparator(); @@ -118,15 +118,18 @@ void setDebugOptions() { } static final Collection NON_PAYLOAD_CAPABILITIES = Arrays.asList(IdentityNamespace.IDENTITY_NAMESPACE); - static final Collection NON_PAYLOAD_REQUIREMENTS = Arrays.asList(HostNamespace.HOST_NAMESPACE, ExecutionEnvironmentNamespace.EXECUTION_ENVIRONMENT_NAMESPACE); - static final Collection NON_SUBSTITUTED_REQUIREMENTS = Arrays.asList(PackageNamespace.PACKAGE_NAMESPACE, BundleNamespace.BUNDLE_NAMESPACE); + static final Collection NON_PAYLOAD_REQUIREMENTS = Arrays.asList(HostNamespace.HOST_NAMESPACE, + ExecutionEnvironmentNamespace.EXECUTION_ENVIRONMENT_NAMESPACE); + static final Collection NON_SUBSTITUTED_REQUIREMENTS = Arrays.asList(PackageNamespace.PACKAGE_NAMESPACE, + BundleNamespace.BUNDLE_NAMESPACE); final ThreadLocal threadResolving = new ThreadLocal<>(); final ModuleContainerAdaptor adaptor; /** - * Constructs the module resolver with the specified resolver hook factory - * and resolver. + * Constructs the module resolver with the specified resolver hook factory and + * resolver. + * * @param adaptor the container adaptor */ ModuleResolver(final ModuleContainerAdaptor adaptor) { @@ -151,46 +154,59 @@ private static int parseInteger(String sInteger, int defaultValue, int minValue) } /** - * Attempts to resolve all unresolved modules installed in the specified module database. - * returns a delta containing the new wirings or modified wirings that should be - * merged into the specified moduleDatabase. + * Attempts to resolve all unresolved modules installed in the specified module + * database. returns a delta containing the new wirings or modified wirings that + * should be merged into the specified moduleDatabase. *

* This method only does read operations on the database no wirings are modified - * directly by this method. The returned wirings need to be merged into - * the database. - * @param triggers the triggers that caused the resolver operation to occur - * @param triggersMandatory true if the triggers must be resolved by the resolve process - * @param unresolved a snapshot of unresolved revisions - * @param wiringCopy the wirings snapshot of the currently resolved revisions - * @param moduleDatabase the module database. + * directly by this method. The returned wirings need to be merged into the + * database. + * + * @param triggers the triggers that caused the resolver operation to + * occur + * @param triggersMandatory true if the triggers must be resolved by the resolve + * process + * @param unresolved a snapshot of unresolved revisions + * @param wiringCopy the wirings snapshot of the currently resolved + * revisions + * @param moduleDatabase the module database. * @return a delta container the new wirings or modified wirings that should be - * merged into the moduleDatabase + * merged into the moduleDatabase * @throws ResolutionException */ - ModuleResolutionReport resolveDelta(Collection triggers, boolean triggersMandatory, Collection unresolved, Map wiringCopy, ModuleDatabase moduleDatabase) { + ModuleResolutionReport resolveDelta(Collection triggers, boolean triggersMandatory, + Collection unresolved, Map wiringCopy, + ModuleDatabase moduleDatabase) { if (!triggersMandatory) { // we are just resolving all bundles optionally triggers = unresolved; } - ResolveProcess resolveProcess = new ResolveProcess(unresolved, triggers, triggersMandatory, wiringCopy, moduleDatabase); + ResolveProcess resolveProcess = new ResolveProcess(unresolved, triggers, triggersMandatory, wiringCopy, + moduleDatabase); return resolveProcess.resolve(); } - ModuleResolutionReport resolveDynamicDelta(DynamicModuleRequirement dynamicReq, Collection unresolved, Map wiringCopy, ModuleDatabase moduleDatabase) { + ModuleResolutionReport resolveDynamicDelta(DynamicModuleRequirement dynamicReq, + Collection unresolved, Map wiringCopy, + ModuleDatabase moduleDatabase) { ResolveProcess resolveProcess = new ResolveProcess(unresolved, dynamicReq, wiringCopy, moduleDatabase); return resolveProcess.resolve(); } - Map generateDelta(Map> result, Map wiringCopy) { + Map generateDelta(Map> result, + Map wiringCopy) { Map>> provided = new HashMap<>(); Map> required = new HashMap<>(result.size() * 4 / 3 + 1); // First populate the list of provided and required wires for revision - // This is done this way to share the wire object between both the provider and requirer + // This is done this way to share the wire object between both the provider and + // requirer for (Map.Entry> resultEntry : result.entrySet()) { ModuleRevision revision = (ModuleRevision) resultEntry.getKey(); NamespaceList.Builder requiredWires = NamespaceList.Builder.create(WIRE); for (Wire wire : resultEntry.getValue()) { - ModuleWire moduleWire = new ModuleWire((ModuleCapability) wire.getCapability(), (ModuleRevision) wire.getProvider(), (ModuleRequirement) wire.getRequirement(), (ModuleRevision) wire.getRequirer()); + ModuleWire moduleWire = new ModuleWire((ModuleCapability) wire.getCapability(), + (ModuleRevision) wire.getProvider(), (ModuleRequirement) wire.getRequirement(), + (ModuleRevision) wire.getRequirer()); requiredWires.add(moduleWire); Map> providedWiresMap = provided.get(moduleWire.getProvider()); if (providedWiresMap == null) { @@ -215,7 +231,8 @@ Map generateDelta(Map> result delta.put(revision, createNewWiring(revision, provided, required)); } else { // this is to handle dynamic imports - delta.put(revision, createWiringDelta(revision, existingWiring, provided.get(revision), required.get(revision))); + delta.put(revision, + createWiringDelta(revision, existingWiring, provided.get(revision), required.get(revision))); } } // Also need to create the wiring deltas for already resolved bundles @@ -224,15 +241,19 @@ Map generateDelta(Map> result for (ModuleRevision revision : provided.keySet()) { ModuleWiring existingWiring = wiringCopy.get(revision); if (existingWiring != null && !delta.containsKey(revision)) { - delta.put(revision, createWiringDelta(revision, existingWiring, provided.get(revision), required.get(revision))); + delta.put(revision, + createWiringDelta(revision, existingWiring, provided.get(revision), required.get(revision))); } } return delta; } - private ModuleWiring createNewWiring(ModuleRevision revision, Map>> provided, Map> required) { + private ModuleWiring createNewWiring(ModuleRevision revision, + Map>> provided, + Map> required) { - Map> providedWireMap = provided.getOrDefault(revision, Collections.emptyMap()); + Map> providedWireMap = provided.getOrDefault(revision, + Collections.emptyMap()); NamespaceList requiredWires = required.getOrDefault(revision, NamespaceList.empty(WIRE)); NamespaceList.Builder capabilities = revision.getCapabilities().createBuilder(); @@ -270,10 +291,12 @@ private static void removePayloadContent(NamespaceList.Builder requirements.removeNamespaceIf(namespace -> !NON_PAYLOAD_REQUIREMENTS.contains(namespace)); } - private static Collection removeSubstitutedCapabilities(NamespaceList.Builder capabilities, NamespaceList requiredWires) { + private static Collection removeSubstitutedCapabilities( + NamespaceList.Builder capabilities, NamespaceList requiredWires) { Collection substituted = new ArrayList<>(); for (ModuleWire moduleWire : requiredWires.getList(PackageNamespace.PACKAGE_NAMESPACE)) { - String packageName = (String) moduleWire.getCapability().getAttributes().get(PackageNamespace.PACKAGE_NAMESPACE); + String packageName = (String) moduleWire.getCapability().getAttributes() + .get(PackageNamespace.PACKAGE_NAMESPACE); capabilities.removeElementsOfNamespaceIf(PackageNamespace.PACKAGE_NAMESPACE, capability -> { if (packageName.equals(capability.getAttributes().get(PackageNamespace.PACKAGE_NAMESPACE))) { // found a package capability with the same name as a package that got imported @@ -289,7 +312,8 @@ private static Collection removeSubstitutedCapabilities(NamespaceList.Bu return substituted.isEmpty() ? Collections.emptyList() : substituted; } - private static void removeNonEffectiveRequirements(NamespaceList.Builder requirements, NamespaceList requiredWires) { + private static void removeNonEffectiveRequirements(NamespaceList.Builder requirements, + NamespaceList requiredWires) { Set wireRequirements = new HashSet<>(); for (ModuleWire mw : requiredWires.getList(null)) { @@ -334,7 +358,9 @@ void removeNonEffectiveCapabilities(Collection capabilities) { }); } - private static void addPayloadContent(List hostWires, NamespaceList.Builder capabilities, NamespaceList.Builder requirements) { + private static void addPayloadContent(List hostWires, + NamespaceList.Builder capabilities, + NamespaceList.Builder requirements) { if (hostWires == null) return; for (ModuleWire hostWire : hostWires) { @@ -367,7 +393,9 @@ private static void addPayloadContent(List hostWires, NamespaceList. } static boolean isDynamic(Requirement requirement) { - return PackageNamespace.PACKAGE_NAMESPACE.equals(requirement.getNamespace()) && PackageNamespace.RESOLUTION_DYNAMIC.equals(requirement.getDirectives().get(Namespace.REQUIREMENT_RESOLUTION_DIRECTIVE)); + return PackageNamespace.PACKAGE_NAMESPACE.equals(requirement.getNamespace()) + && PackageNamespace.RESOLUTION_DYNAMIC + .equals(requirement.getDirectives().get(Namespace.REQUIREMENT_RESOLUTION_DIRECTIVE)); } private static void addProvidedWires(Map> toAdd, @@ -382,12 +410,14 @@ private static void addProvidedWires(Map> toA } } - private static ModuleWiring createWiringDelta(ModuleRevision revision, ModuleWiring existingWiring, Map> providedWireMap, NamespaceList requiredWires) { + private static ModuleWiring createWiringDelta(ModuleRevision revision, ModuleWiring existingWiring, + Map> providedWireMap, NamespaceList requiredWires) { // No null checks are done here on the wires since this is a copy. NamespaceList.Builder existingProvidedWires = existingWiring.getProvidedWires().createBuilder(); NamespaceList.Builder existingCapabilities = existingWiring.getCapabilities().createBuilder(); NamespaceList.Builder existingRequiredWires = existingWiring.getRequiredWires().createBuilder(); - NamespaceList.Builder existingRequirements = existingWiring.getRequirements().createBuilder(); + NamespaceList.Builder existingRequirements = existingWiring.getRequirements() + .createBuilder(); // First, add newly resolved fragment capabilities and requirements if (providedWireMap != null) { @@ -399,10 +429,12 @@ private static ModuleWiring createWiringDelta(ModuleRevision revision, ModuleWir } } - // Create a ModuleWiring that only contains the new ordered list of provided wires + // Create a ModuleWiring that only contains the new ordered list of provided + // wires addProvidedWires(providedWireMap, existingProvidedWires, existingCapabilities); - // Also need to include any new required wires that may have be added for fragment hosts + // Also need to include any new required wires that may have be added for + // fragment hosts // Also will be needed for dynamic imports if (requiredWires != null) { existingRequiredWires.addAll(requiredWires); @@ -479,26 +511,26 @@ public boolean isDebugEnabled() { @Override protected void doLog(int level, String msg, Throwable throwable) { - Debug.println("RESOLVER: " + msg + SEPARATOR + (throwable != null ? (TAB + TAB + throwable.getMessage()) : "")); //$NON-NLS-1$ //$NON-NLS-2$ + Debug.println("RESOLVER: " + msg + SEPARATOR //$NON-NLS-1$ + + (throwable != null ? (TAB + TAB + throwable.getMessage()) : "")); //$NON-NLS-1$ } } private final ModuleResolutionReport.Builder reportBuilder = new ModuleResolutionReport.Builder(); /* - * Contains the revisions that were requested to be resolved and is not - * modified post instantiation. + * Contains the revisions that were requested to be resolved and is not modified + * post instantiation. */ private final Collection unresolved; /* - * Contains unresolved revisions that should not be resolved as part of - * this process. The reasons they should not be resolved will vary. For - * example, some might have been filtered out by the resolver hook while - * others represent singleton collisions. It is assumed that all - * unresolved revisions are disabled at the start of the resolve - * process (see initialization in constructors). Any not filtered out - * by ResolverHook.filterResolvable are then removed but may be added - * back later for other reasons. + * Contains unresolved revisions that should not be resolved as part of this + * process. The reasons they should not be resolved will vary. For example, some + * might have been filtered out by the resolver hook while others represent + * singleton collisions. It is assumed that all unresolved revisions are + * disabled at the start of the resolve process (see initialization in + * constructors). Any not filtered out by ResolverHook.filterResolvable are then + * removed but may be added back later for other reasons. */ private final Collection disabled; private final Collection triggers; @@ -519,14 +551,14 @@ protected void doLog(int level, String msg, Throwable throwable) { * Used to generate the UNRESOLVED_PROVIDER resolution report entries. * * The inner map associates a requirement to the set of all matching - * capabilities that were found. The outer map associates the requiring - * resource to the inner map so that its contents may easily be looked - * up from the set of unresolved resources, if any, after the resolution - * has occurred. + * capabilities that were found. The outer map associates the requiring resource + * to the inner map so that its contents may easily be looked up from the set of + * unresolved resources, if any, after the resolution has occurred. */ private final Map>> unresolvedProviders = new HashMap<>(); - ResolveProcess(Collection unresolved, Collection triggers, boolean triggersMandatory, Map wirings, ModuleDatabase moduleDatabase) { + ResolveProcess(Collection unresolved, Collection triggers, + boolean triggersMandatory, Map wirings, ModuleDatabase moduleDatabase) { this.unresolved = unresolved; this.disabled = new HashSet<>(unresolved); this.triggers = new ArrayList<>(triggers); @@ -537,7 +569,8 @@ protected void doLog(int level, String msg, Throwable throwable) { this.dynamicReq = null; } - ResolveProcess(Collection unresolved, DynamicModuleRequirement dynamicReq, Map wirings, ModuleDatabase moduleDatabase) { + ResolveProcess(Collection unresolved, DynamicModuleRequirement dynamicReq, + Map wirings, ModuleDatabase moduleDatabase) { this.unresolved = unresolved; this.disabled = new HashSet<>(unresolved); ModuleRevision revision = dynamicReq.getRevision(); @@ -553,7 +586,8 @@ protected void doLog(int level, String msg, Throwable throwable) { @Override public List findProviders(Requirement requirement) { Requirement origReq = requirement; - Requirement lookupReq = dynamicReq == null || dynamicReq.getOriginal() != requirement ? requirement : dynamicReq; + Requirement lookupReq = dynamicReq == null || dynamicReq.getOriginal() != requirement ? requirement + : dynamicReq; return findProviders0(origReq, lookupReq); } @@ -591,7 +625,8 @@ private List filterProviders(Requirement requirement, List filterProviders(Requirement requirement, List candidates, boolean filterResolvedHosts) { + List filterProviders(Requirement requirement, List candidates, + boolean filterResolvedHosts) { filterDisabled(candidates); removeNonEffectiveCapabilities(candidates); removeSubstituted(candidates); @@ -605,7 +640,8 @@ List filterProviders(Requirement requirement, List if (DEBUG_PROVIDERS || DEBUG_HOOKS) { filteredMatches.removeAll(candidates); if (!filteredMatches.isEmpty()) { - StringBuilder builder = new StringBuilder("RESOLVER: Capabilities filtered by ResolverHook.filterMatches"); //$NON-NLS-1$ + StringBuilder builder = new StringBuilder( + "RESOLVER: Capabilities filtered by ResolverHook.filterMatches"); //$NON-NLS-1$ int i = 0; for (Capability capability : filteredMatches) { builder.append(SEPARATOR).append(TAB) // @@ -620,7 +656,8 @@ List filterProviders(Requirement requirement, List } } - // filter resolved hosts after calling hooks to allow hooks to see the host capability + // filter resolved hosts after calling hooks to allow hooks to see the host + // capability filterResolvedHosts(requirement, candidates, filterResolvedHosts); if (candidates.isEmpty()) { @@ -647,20 +684,22 @@ private void filterFailedToResolve(List candidates) { if (failedToResolve.contains(capability.getRevision())) { iCandidates.remove(); if (DEBUG_PROVIDERS) { - Debug.println(new StringBuilder("RESOLVER: Capability filtered because its resource was not resolved") //$NON-NLS-1$ - .append(SEPARATOR).append(TAB) // - .append(capability) // - .append(SEPARATOR).append(TAB).append(TAB) // - .append("of resource") //$NON-NLS-1$ - .append(SEPARATOR).append(TAB).append(TAB).append(TAB) // - .append(capability.getResource()) // - .toString()); + Debug.println( + new StringBuilder("RESOLVER: Capability filtered because its resource was not resolved") //$NON-NLS-1$ + .append(SEPARATOR).append(TAB) // + .append(capability) // + .append(SEPARATOR).append(TAB).append(TAB) // + .append("of resource") //$NON-NLS-1$ + .append(SEPARATOR).append(TAB).append(TAB).append(TAB) // + .append(capability.getResource()) // + .toString()); } } } } - private void filterResolvedHosts(Requirement requirement, List candidates, boolean filterResolvedHosts) { + private void filterResolvedHosts(Requirement requirement, List candidates, + boolean filterResolvedHosts) { if (filterResolvedHosts && HostNamespace.HOST_NAMESPACE.equals(requirement.getNamespace())) { for (Iterator iCandidates = candidates.iterator(); iCandidates.hasNext();) { if (wirings.containsKey(iCandidates.next().getRevision())) { @@ -691,7 +730,8 @@ private void filterPermissions(BundleRequirement requirement, List getOptionalResources() { @Override public Collection findRelatedResources(Resource host) { // for the container we only care about fragments for related resources - List hostCaps = ((ModuleRevision) host).getModuleCapabilities(HostNamespace.HOST_NAMESPACE); + List hostCaps = ((ModuleRevision) host) + .getModuleCapabilities(HostNamespace.HOST_NAMESPACE); if (hostCaps.isEmpty()) { return Collections.emptyList(); } @@ -806,12 +848,16 @@ public Collection findRelatedResources(Resource host) { Collection relatedFragments = new ArrayList<>(); for (String hostBSN : getHostBSNs(hostCaps)) { String matchFilter = "(" + EquinoxFragmentNamespace.FRAGMENT_NAMESPACE + "=" + hostBSN + ")"; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ - Requirement fragmentRequirement = ModuleContainer.createRequirement(EquinoxFragmentNamespace.FRAGMENT_NAMESPACE, Collections.singletonMap(Namespace.REQUIREMENT_FILTER_DIRECTIVE, matchFilter), Collections.emptyMap()); + Requirement fragmentRequirement = ModuleContainer.createRequirement( + EquinoxFragmentNamespace.FRAGMENT_NAMESPACE, + Collections.singletonMap(Namespace.REQUIREMENT_FILTER_DIRECTIVE, matchFilter), + Collections.emptyMap()); List candidates = moduleDatabase.findCapabilities(fragmentRequirement); // filter out disabled fragments and singletons filterDisabled(candidates); for (ModuleCapability candidate : candidates) { - ModuleRequirement hostReq = candidate.getRevision().getModuleRequirements(HostNamespace.HOST_NAMESPACE).get(0); + ModuleRequirement hostReq = candidate.getRevision() + .getModuleRequirements(HostNamespace.HOST_NAMESPACE).get(0); for (ModuleCapability hostCap : hostCaps) { if (hostReq.matches(hostCap)) { relatedFragments.add(candidate.getResource()); @@ -826,7 +872,8 @@ public Collection findRelatedResources(Resource host) { private Collection getHostBSNs(List hostCaps) { if (hostCaps.size() == 1) { - // optimization and likely the only case since you are not supposed to have multiple host caps + // optimization and likely the only case since you are not supposed to have + // multiple host caps return getHostBSNs(hostCaps.get(0)); } Set result = new HashSet<>(); @@ -854,18 +901,21 @@ private Collection getHostBSNs(ModuleCapability moduleCapability) { ModuleResolutionReport resolve() { if (threadResolving()) { // throw up a runtime exception, if this is caused by a resolver hook - // then it will get caught at the call to the resolver hook and a proper exception is thrown + // then it will get caught at the call to the resolver hook and a proper + // exception is thrown throw new IllegalStateException(Msg.ModuleResolver_RecursiveError); } threadResolving.set(Boolean.TRUE); try { try { - hook = adaptor.getResolverHookFactory().begin(InternalUtils.asList((List) triggers)); + hook = adaptor.getResolverHookFactory() + .begin(InternalUtils.asList((List) triggers)); } catch (RuntimeException e) { if (e.getCause() instanceof BundleException) { BundleException be = (BundleException) e.getCause(); if (be.getType() == BundleException.REJECTED_BY_HOOK) { - return new ModuleResolutionReport(null, Collections.emptyMap(), new ResolutionException(be)); + return new ModuleResolutionReport(null, Collections.emptyMap(), + new ResolutionException(be)); } } throw e; @@ -956,7 +1006,8 @@ private void printWirings(Map> wires) { Debug.println(builder); } - private void resolveRevisionsInBatch(Collection revisions, boolean isMandatory, ResolveLogger logger, Map> result) throws ResolutionException { + private void resolveRevisionsInBatch(Collection revisions, boolean isMandatory, + ResolveLogger logger, Map> result) throws ResolutionException { long startTime = System.currentTimeMillis(); long initialFreeMemory = Runtime.getRuntime().freeMemory(); long maxUsedMemory = 0; @@ -1002,7 +1053,9 @@ private void resolveRevisionsInBatch(Collection revisions, boole } } - private void resolveRevisionsIndividually(boolean isMandatory, ResolveLogger logger, Map> result, Collection toResolve, Collection revisions) throws ResolutionException { + private void resolveRevisionsIndividually(boolean isMandatory, ResolveLogger logger, + Map> result, Collection toResolve, Collection revisions) + throws ResolutionException { scheduleTimeout.set(false); for (Resource resource : toResolve) { if (!wirings.containsKey(resource) && !failedToResolve.contains(resource)) { @@ -1016,7 +1069,8 @@ private void resolveRevisionsIndividually(boolean isMandatory, ResolveLogger log } } - private void resolveRevisions(List revisions, boolean isMandatory, ResolveLogger logger, Map> result) throws ResolutionException { + private void resolveRevisions(List revisions, boolean isMandatory, ResolveLogger logger, + Map> result) throws ResolutionException { boolean applyTransitiveFailures = true; currentlyResolving = revisions; currentlyResolvingMandatory = isMandatory; @@ -1076,16 +1130,17 @@ private void applyInterimResultToWiringCopy(Map> interimRes } private void computeUsesConstraintViolations(Map usesConstraintViolations) { - for (Map.Entry usesConstraintViolation : usesConstraintViolations.entrySet()) { - reportBuilder.addEntry(usesConstraintViolation.getKey(), Type.USES_CONSTRAINT_VIOLATION, usesConstraintViolation.getValue()); + for (Map.Entry usesConstraintViolation : usesConstraintViolations + .entrySet()) { + reportBuilder.addEntry(usesConstraintViolation.getKey(), Type.USES_CONSTRAINT_VIOLATION, + usesConstraintViolation.getValue()); } } /* - * Given the results of a resolution, compute which, if any, of the - * enabled, resolving resources are still unresolved. For those that are - * unresolved, generate resolution report entries for unresolved - * providers, if necessary. + * Given the results of a resolution, compute which, if any, of the enabled, + * resolving resources are still unresolved. For those that are unresolved, + * generate resolution report entries for unresolved providers, if necessary. */ private void computeUnresolvedProviderResolutionReportEntries(Map> resolution) { // Create a collection representing the resources asked to be @@ -1102,14 +1157,16 @@ private void computeUnresolvedProviderResolutionReportEntries(Map> requirementToCapabilities = unresolvedProviders.get(shouldHaveResolvedResource); + Map> requirementToCapabilities = unresolvedProviders + .get(shouldHaveResolvedResource); if (requirementToCapabilities == null) continue; // If nothing resolved then there are no resolved resources to // filter out. if (resolution != null) { // Filter out capability providers that resolved. - for (Iterator> values = requirementToCapabilities.values().iterator(); values.hasNext();) { + for (Iterator> values = requirementToCapabilities.values().iterator(); values + .hasNext();) { Set value = values.next(); for (Iterator capabilities = value.iterator(); capabilities.hasNext();) if (resolution.containsKey(capabilities.next().getResource())) @@ -1124,17 +1181,19 @@ private void computeUnresolvedProviderResolutionReportEntries(Map capabilities) { + private void computeUnresolvedProviders(Requirement requirement, + Collection capabilities) { Resource requirer = requirement.getResource(); Map> requirementToCapabilities = unresolvedProviders.get(requirer); if (requirementToCapabilities == null) { @@ -1184,18 +1243,22 @@ Map> getNewWires() { do { retry = false; result.clear(); - fragmentsLoop: for (Iterator> iFragments = fragments.entrySet().iterator(); iFragments.hasNext();) { + fragmentsLoop: for (Iterator> iFragments = fragments.entrySet() + .iterator(); iFragments.hasNext();) { Map.Entry fragmentEntry = iFragments.next(); if (wirings.get(fragmentEntry.getValue()) == null) { for (ModuleRequirement req : fragmentEntry.getValue().getModuleRequirements(null)) { - ModuleRevision requirer = NON_PAYLOAD_REQUIREMENTS.contains(req.getNamespace()) ? req.getRevision() : hostCapability.getRevision(); + ModuleRevision requirer = NON_PAYLOAD_REQUIREMENTS.contains(req.getNamespace()) + ? req.getRevision() + : hostCapability.getRevision(); List newWires = result.get(requirer); if (newWires == null) { newWires = new ArrayList<>(); result.put(requirer, newWires); } if (HostNamespace.HOST_NAMESPACE.equals(req.getNamespace())) { - newWires.add(new ModuleWire(hostCapability, hostCapability.getRevision(), req, requirer)); + newWires.add(new ModuleWire(hostCapability, hostCapability.getRevision(), req, + requirer)); } else { if (failToWire(req, requirer, newWires)) { iFragments.remove(); @@ -1219,24 +1282,32 @@ private boolean failToWire(ModuleRequirement requirement, ModuleRevision require List newWires = new ArrayList<>(0); filterProviders(requirement, matching, false); for (ModuleCapability candidate : matching) { - // If the requirer equals the requirement revision then this is a non-payload requirement. + // If the requirer equals the requirement revision then this is a non-payload + // requirement. // We let non-payload requirements come from anywhere. - // Payload requirements must come from the host or one of the fragments attached to the host - if (requirer.equals(requirement.getRevision()) || validProviders.contains(candidate.getRevision())) { - ModuleRevision provider = NON_PAYLOAD_CAPABILITIES.contains(candidate.getNamespace()) ? candidate.getRevision() : hostCapability.getRevision(); + // Payload requirements must come from the host or one of the fragments attached + // to the host + if (requirer.equals(requirement.getRevision()) + || validProviders.contains(candidate.getRevision())) { + ModuleRevision provider = NON_PAYLOAD_CAPABILITIES.contains(candidate.getNamespace()) + ? candidate.getRevision() + : hostCapability.getRevision(); // if there are multiple candidates; then check for cardinality - if (newWires.isEmpty() || Namespace.CARDINALITY_MULTIPLE.equals(requirement.getDirectives().get(Namespace.REQUIREMENT_CARDINALITY_DIRECTIVE))) { + if (newWires.isEmpty() || Namespace.CARDINALITY_MULTIPLE + .equals(requirement.getDirectives().get(Namespace.REQUIREMENT_CARDINALITY_DIRECTIVE))) { newWires.add(new ModuleWire(candidate, provider, requirement, requirer)); } } } if (newWires.isEmpty()) { - if (!Namespace.RESOLUTION_OPTIONAL.equals(requirement.getDirectives().get(Namespace.REQUIREMENT_RESOLUTION_DIRECTIVE))) { + if (!Namespace.RESOLUTION_OPTIONAL + .equals(requirement.getDirectives().get(Namespace.REQUIREMENT_RESOLUTION_DIRECTIVE))) { // could not resolve mandatory requirement; return true; } } - // only create the wire if the namespace is a non-substituted namespace (e.g. NOT package) + // only create the wire if the namespace is a non-substituted namespace (e.g. + // NOT package) if (!NON_SUBSTITUTED_REQUIREMENTS.contains(requirement.getNamespace())) { wires.addAll(newWires); } @@ -1277,9 +1348,12 @@ private Map> resolveNonPayLoadFragments() { filterProviders(requirement, matchingHosts, false); for (ModuleCapability hostCandidate : matchingHosts) { ModuleWiring hostWiring = wirings.get(hostCandidate.getRevision()); - String attachDirective = hostCandidate.getDirectives().get(HostNamespace.CAPABILITY_FRAGMENT_ATTACHMENT_DIRECTIVE); - boolean attachAlways = attachDirective == null || HostNamespace.FRAGMENT_ATTACHMENT_ALWAYS.equals(attachDirective); - // only do this if the candidate host is already resolved and it allows dynamic attachment + String attachDirective = hostCandidate.getDirectives() + .get(HostNamespace.CAPABILITY_FRAGMENT_ATTACHMENT_DIRECTIVE); + boolean attachAlways = attachDirective == null + || HostNamespace.FRAGMENT_ATTACHMENT_ALWAYS.equals(attachDirective); + // only do this if the candidate host is already resolved and it allows dynamic + // attachment if (!attachAlways || hostWiring == null) { continue; } @@ -1355,7 +1429,8 @@ private void selectSingletons() { Collection pickOneToResolve = new ArrayList<>(); for (ModuleRevision collision : collisions) { if (selected.contains(collision)) { - // Must fail since there is already a selected bundle which is a collision of the singleton bundle + // Must fail since there is already a selected bundle which is a collision of + // the singleton bundle disabled.add(singleton); reportBuilder.addEntry(singleton, Type.SINGLETON_SELECTION, collision); break; @@ -1365,12 +1440,15 @@ private void selectSingletons() { } if (!disabled.contains(singleton)) { // need to make sure the bundle does not collide from the POV of another entry - for (Map.Entry> collisionEntry : collisionMap.entrySet()) { + for (Map.Entry> collisionEntry : collisionMap + .entrySet()) { if (collisionEntry.getKey() != singleton && collisionEntry.getValue().contains(singleton)) { if (selected.contains(collisionEntry.getKey())) { - // Must fail since there is already a selected bundle for which the singleton bundle is a collision + // Must fail since there is already a selected bundle for which the singleton + // bundle is a collision disabled.add(singleton); - reportBuilder.addEntry(singleton, Type.SINGLETON_SELECTION, collisionEntry.getKey()); + reportBuilder.addEntry(singleton, Type.SINGLETON_SELECTION, + collisionEntry.getKey()); break; } if (!pickOneToResolve.contains(collisionEntry.getKey())) @@ -1452,7 +1530,8 @@ private Map> getCollisionMap(Collecti filteredSingletons.removeAll(collisionCandidates); filteredSingletons.remove(singleton); if (!filteredSingletons.isEmpty()) { - StringBuilder builder = new StringBuilder("RESOLVER: Resources filtered by ResolverHook.filterSingletonCollisions") //$NON-NLS-1$ + StringBuilder builder = new StringBuilder( + "RESOLVER: Resources filtered by ResolverHook.filterSingletonCollisions") //$NON-NLS-1$ .append(SEPARATOR).append(TAB) // .append("Singleton") //$NON-NLS-1$ .append(SEPARATOR).append(TAB).append(TAB) // @@ -1521,8 +1600,10 @@ public int compare(Capability c1, Capability c2) { } ModuleRevision getModuleRevision(Capability c) { - // We assume all capabilities here either come from us and have ModuleRevision resources or - // they are HostedCapabilities which have ModuleRevision resources as the host revision + // We assume all capabilities here either come from us and have ModuleRevision + // resources or + // they are HostedCapabilities which have ModuleRevision resources as the host + // revision if (c instanceof HostedCapability) { c = ((HostedCapability) c).getDeclaredCapability(); } @@ -1540,12 +1621,14 @@ public void execute(Runnable command) { @Override public void onCancel(Runnable callback) { - // Note that for each resolve Process we only want timeout the initial batch resolve + // Note that for each resolve Process we only want timeout the initial batch + // resolve if (scheduleTimeout.compareAndSet(true, false)) { ScheduledExecutorService scheduledExecutor = adaptor.getScheduledExecutor(); if (scheduledExecutor != null) { try { - timoutFuture.set(scheduledExecutor.schedule(callback, resolverBatchTimeout, TimeUnit.MILLISECONDS)); + timoutFuture + .set(scheduledExecutor.schedule(callback, resolverBatchTimeout, TimeUnit.MILLISECONDS)); } catch (RejectedExecutionException e) { // ignore may have been shutdown, it is ok we will not be able to timeout } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleRevision.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleRevision.java index 462075c3b03..ed5eada4e90 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleRevision.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleRevision.java @@ -35,6 +35,7 @@ /** * An implementation of {@link BundleRevision}. + * * @since 3.10 */ public final class ModuleRevision implements BundleRevision { @@ -47,7 +48,8 @@ public final class ModuleRevision implements BundleRevision { private final Object revisionInfo; private volatile Boolean lazyActivationPolicy = null; - ModuleRevision(String symbolicName, Version version, int types, NamespaceList.Builder capabilityInfos, NamespaceList.Builder requirementInfos, ModuleRevisions revisions, Object revisionInfo) { + ModuleRevision(String symbolicName, Version version, int types, NamespaceList.Builder capabilityInfos, + NamespaceList.Builder requirementInfos, ModuleRevisions revisions, Object revisionInfo) { this.symbolicName = symbolicName; this.version = version; this.types = types; @@ -58,7 +60,7 @@ public final class ModuleRevision implements BundleRevision { } private NamespaceList createCapabilities(NamespaceList.Builder capabilityInfos) { - return capabilityInfos.transformIntoCopy(new Function() { + return capabilityInfos.transformIntoCopy(new Function() { public ModuleCapability apply(GenericInfo i) { Map directives = i.mutable ? copyUnmodifiableMap(i.directives) : i.directives; Map attributes = i.mutable ? copyUnmodifiableMap(i.attributes) : i.attributes; @@ -80,7 +82,7 @@ private static Map copyUnmodifiableMap(Map map) { } private NamespaceList createRequirements(NamespaceList.Builder infos) { - return infos.transformIntoCopy(new Function() { + return infos.transformIntoCopy(new Function() { public ModuleRequirement apply(GenericInfo i) { return new ModuleRequirement(i.namespace, i.directives, i.attributes, ModuleRevision.this); } @@ -114,8 +116,10 @@ public List getDeclaredRequirements(String namespace) { /** * Returns the capabilities declared by this revision + * * @param namespace The namespace of the declared capabilities to return or - * {@code null} to return the declared capabilities from all namespaces. + * {@code null} to return the declared capabilities from all + * namespaces. * @return An unmodifiable list containing the declared capabilities. */ public List getModuleCapabilities(String namespace) { @@ -124,8 +128,10 @@ public List getModuleCapabilities(String namespace) { /** * Returns the requirements declared by this revision + * * @param namespace The namespace of the declared requirements to return or - * {@code null} to return the declared requirements from all namespaces. + * {@code null} to return the declared requirements from all + * namespaces. * @return An unmodifiable list containing the declared requirements. */ public List getModuleRequirements(String namespace) { @@ -154,6 +160,7 @@ public List getRequirements(String namespace) { /** * Returns the {@link ModuleRevisions revisions} for this revision. + * * @return the {@link ModuleRevisions revisions} for this revision. */ public ModuleRevisions getRevisions() { @@ -161,8 +168,9 @@ public ModuleRevisions getRevisions() { } /** - * Returns the revision info for this revision. The revision info is - * assigned when a revision is created to install a module or update module + * Returns the revision info for this revision. The revision info is assigned + * when a revision is created to install a module or update module + * * @return the revision info for this revision, may be {@code null}. */ public Object getRevisionInfo() { @@ -170,9 +178,11 @@ public Object getRevisionInfo() { } /** - * A convenience method to quickly determine if this revision - * has declared the lazy activation policy. - * @return true if the lazy activation policy has been declared by this module; otherwise false is returned. + * A convenience method to quickly determine if this revision has declared the + * lazy activation policy. + * + * @return true if the lazy activation policy has been declared by this module; + * otherwise false is returned. */ public boolean hasLazyActivatePolicy() { Boolean currentPolicy = lazyActivationPolicy; @@ -183,7 +193,8 @@ public boolean hasLazyActivatePolicy() { List data = getCapabilities(EquinoxModuleDataNamespace.MODULE_DATA_NAMESPACE); if (!data.isEmpty()) { Capability moduleData = data.get(0); - lazyPolicy = EquinoxModuleDataNamespace.CAPABILITY_ACTIVATION_POLICY_LAZY.equals(moduleData.getAttributes().get(EquinoxModuleDataNamespace.CAPABILITY_ACTIVATION_POLICY)); + lazyPolicy = EquinoxModuleDataNamespace.CAPABILITY_ACTIVATION_POLICY_LAZY + .equals(moduleData.getAttributes().get(EquinoxModuleDataNamespace.CAPABILITY_ACTIVATION_POLICY)); } lazyActivationPolicy = Boolean.valueOf(lazyPolicy); return lazyPolicy; diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleRevisionBuilder.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleRevisionBuilder.java index 2c549394670..7ce5bfd86c9 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleRevisionBuilder.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleRevisionBuilder.java @@ -34,18 +34,24 @@ import org.osgi.resource.Namespace; /** - * A builder for creating module {@link ModuleRevision} objects. A builder can only be used by - * the module {@link ModuleContainer container} to build revisions when + * A builder for creating module {@link ModuleRevision} objects. A builder can + * only be used by the module {@link ModuleContainer container} to build + * revisions when * {@link ModuleContainer#install(Module, String, ModuleRevisionBuilder, Object) - * installing} or {@link ModuleContainer#update(Module, ModuleRevisionBuilder, Object) updating} a module. + * installing} or + * {@link ModuleContainer#update(Module, ModuleRevisionBuilder, Object) + * updating} a module. *

- * The builder provides the instructions to the container for creating a {@link ModuleRevision}. - * They are not thread-safe; in the absence of external synchronization, they do not support concurrent access by multiple threads. + * The builder provides the instructions to the container for creating a + * {@link ModuleRevision}. They are not thread-safe; in the absence of external + * synchronization, they do not support concurrent access by multiple threads. + * * @since 3.10 */ public final class ModuleRevisionBuilder { private final static Class SINGLETON_MAP_CLASS = Collections.singletonMap(null, null).getClass(); - private final static Class UNMODIFIABLE_MAP_CLASS = Collections.unmodifiableMap(Collections.emptyMap()).getClass(); + private final static Class UNMODIFIABLE_MAP_CLASS = Collections.unmodifiableMap(Collections.emptyMap()) + .getClass(); /** * Provides information about a capability or requirement @@ -70,6 +76,7 @@ public String apply(GenericInfo info) { /** * Returns the namespace of this generic info + * * @return the namespace */ public String getNamespace() { @@ -78,6 +85,7 @@ public String getNamespace() { /** * Returns the directives of this generic info + * * @return the directives */ public Map getDirectives() { @@ -86,6 +94,7 @@ public Map getDirectives() { /** * Returns the attributes of this generic info + * * @return the attributes */ public Map getAttributes() { @@ -109,6 +118,7 @@ public ModuleRevisionBuilder() { /** * Sets the symbolic name for the builder + * * @param symbolicName the symbolic name */ public void setSymbolicName(String symbolicName) { @@ -117,6 +127,7 @@ public void setSymbolicName(String symbolicName) { /** * Sets the module version for the builder. + * * @param version the version */ public void setVersion(Version version) { @@ -125,6 +136,7 @@ public void setVersion(Version version) { /** * Sets the module types for the builder. + * * @param types the module types */ public void setTypes(int types) { @@ -135,16 +147,18 @@ public void setTypes(int types) { * Sets the module ID for the builder. *

* This module ID will be used if this builder is used to - * {@link ModuleContainer#install(Module, String, ModuleRevisionBuilder, Object) install} - * a module. If the ID is not set then a module ID will be generated by the module - * container at install time. If a module already exists with the specified ID - * then an error will occur when attempting to install a new module with this - * builder. + * {@link ModuleContainer#install(Module, String, ModuleRevisionBuilder, Object) + * install} a module. If the ID is not set then a module ID will be generated by + * the module container at install time. If a module already exists with the + * specified ID then an error will occur when attempting to install a new module + * with this builder. *

- * Note that the system module with location {@link Constants#SYSTEM_BUNDLE_LOCATION} - * always gets module ID of zero. The builder for the system module is not - * asked to provide the module ID for the system module at install time. - * @param id the module ID to use. Must be >= 1. + * Note that the system module with location + * {@link Constants#SYSTEM_BUNDLE_LOCATION} always gets module ID of zero. The + * builder for the system module is not asked to provide the module ID for the + * system module at install time. + * + * @param id the module ID to use. Must be >= 1. * @since 3.13 */ public void setId(long id) { @@ -159,8 +173,10 @@ void setInternalId(long id) { } /** - * Adds a capability to this builder using the specified namespace, directives and attributes - * @param namespace the namespace of the capability + * Adds a capability to this builder using the specified namespace, directives + * and attributes + * + * @param namespace the namespace of the capability * @param directives the directives of the capability * @param attributes the attributes of the capability */ @@ -170,6 +186,7 @@ public void addCapability(String namespace, Map directives, Map< /** * Returns a snapshot of the capabilities for this builder + * * @return the capabilities */ public List getCapabilities() { @@ -190,8 +207,10 @@ public List getCapabilities(String namespace) { } /** - * Adds a requirement to this builder using the specified namespace, directives and attributes - * @param namespace the namespace of the requirement + * Adds a requirement to this builder using the specified namespace, directives + * and attributes + * + * @param namespace the namespace of the requirement * @param directives the directives of the requirement * @param attributes the attributes of the requirement */ @@ -201,6 +220,7 @@ public void addRequirement(String namespace, Map directives, Map /** * Returns a snapshot of the requirements for this builder + * * @return the requirements */ public List getRequirements() { @@ -226,6 +246,7 @@ public List getRequirements(String namespace) { /** * Returns the symbolic name for this builder. + * * @return the symbolic name for this builder. */ public String getSymbolicName() { @@ -234,6 +255,7 @@ public String getSymbolicName() { /** * Returns the module version for this builder. + * * @return the module version for this builder. */ public Version getVersion() { @@ -242,6 +264,7 @@ public Version getVersion() { /** * Returns the module type for this builder. + * * @return the module type for this builder. */ public int getTypes() { @@ -249,10 +272,11 @@ public int getTypes() { } /** - * Returns the module id for this builder. A value of -1 - * indicates that the module ID will be generated by the - * module container at {@link ModuleContainer#install(Module, String, ModuleRevisionBuilder, Object) install} - * time. + * Returns the module id for this builder. A value of -1 indicates that the + * module ID will be generated by the module container at + * {@link ModuleContainer#install(Module, String, ModuleRevisionBuilder, Object) + * install} time. + * * @return the module id for this builder. * @since 3.13 */ @@ -261,16 +285,19 @@ public long getId() { } /** - * Used by the container to build a new revision for a module. - * This builder is used to build a new {@link Module#getCurrentRevision() current} - * revision for the specified module. - * @param module the module to build a new revision for - * @param revisionInfo the revision info for the new revision, may be {@code null} + * Used by the container to build a new revision for a module. This builder is + * used to build a new {@link Module#getCurrentRevision() current} revision for + * the specified module. + * + * @param module the module to build a new revision for + * @param revisionInfo the revision info for the new revision, may be + * {@code null} * @return the new new {@link Module#getCurrentRevision() current} revision. */ ModuleRevision addRevision(Module module, Object revisionInfo) { ModuleRevisions revisions = module.getRevisions(); - ModuleRevision revision = new ModuleRevision(symbolicName, version, types, capabilityInfos, requirementInfos, revisions, revisionInfo); + ModuleRevision revision = new ModuleRevision(symbolicName, version, types, capabilityInfos, requirementInfos, + revisions, revisionInfo); revisions.addRevision(revision); module.getContainer().getAdaptor().associateRevision(revision, revisionInfo); @@ -294,7 +321,8 @@ private void checkFrameworkExtensionPermission(Module module, ModuleRevision rev Module systemModule = module.getContainer().getModule(0); if (systemModule != null) { ModuleRevision systemRevision = systemModule.getCurrentRevision(); - List hostCapabilities = systemRevision.getModuleCapabilities(HostNamespace.HOST_NAMESPACE); + List hostCapabilities = systemRevision + .getModuleCapabilities(HostNamespace.HOST_NAMESPACE); for (ModuleCapability hostCapability : hostCapabilities) { Object hostNames = hostCapability.getAttributes().get(HostNamespace.HOST_NAMESPACE); if (hostNames instanceof Collection) { @@ -318,12 +346,15 @@ private void checkFrameworkExtensionPermission(Module module, ModuleRevision rev if (b != null && !b.hasPermission(new AllPermission())) { SecurityException se = new SecurityException( "Must have AllPermission granted to install an extension bundle: " + b); //$NON-NLS-1$ - // TODO this is such a hack: making the cause a bundle exception so we can throw the right one later - BundleException be = new BundleException(se.getMessage(), BundleException.SECURITY_ERROR, se); + // TODO this is such a hack: making the cause a bundle exception so we can throw + // the right one later + BundleException be = new BundleException(se.getMessage(), + BundleException.SECURITY_ERROR, se); se.initCause(be); throw se; } - module.getContainer().checkAdminPermission(module.getBundle(), AdminPermission.EXTENSIONLIFECYCLE); + module.getContainer().checkAdminPermission(module.getBundle(), + AdminPermission.EXTENSIONLIFECYCLE); } } } catch (InvalidSyntaxException e) { // ignore @@ -333,7 +364,8 @@ private void checkFrameworkExtensionPermission(Module module, ModuleRevision rev } } - private void addGenericInfo(NamespaceList.Builder infos, String namespace, Map directives, Map attributes) { + private void addGenericInfo(NamespaceList.Builder infos, String namespace, + Map directives, Map attributes) { infos.add(new GenericInfo(namespace, directives, attributes, true)); } @@ -345,7 +377,8 @@ void basicAddRequirement(String namespace, Map directives, Map infos, String namespace, Map directives, Map attributes) { + private static void basicAddGenericInfo(NamespaceList.Builder infos, String namespace, + Map directives, Map attributes) { infos.add(new GenericInfo(namespace, unmodifiableMap(directives), unmodifiableMap(attributes), false)); } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleRevisions.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleRevisions.java index 29e9a563188..9c1f9a6f82a 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleRevisions.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleRevisions.java @@ -20,12 +20,12 @@ import org.osgi.framework.wiring.BundleRevisions; /** - * An implementation of {@link BundleRevisions} which represent a - * {@link Module} installed in a {@link ModuleContainer container}. - * The ModuleRevisions provides a bridge between the revisions, the - * module and the container they are associated with. The - * ModuleRevisions holds the information about the installation of - * a module in a container such as the module id and location. + * An implementation of {@link BundleRevisions} which represent a {@link Module} + * installed in a {@link ModuleContainer container}. The ModuleRevisions + * provides a bridge between the revisions, the module and the container they + * are associated with. The ModuleRevisions holds the information about the + * installation of a module in a container such as the module id and location. + * * @since 3.10 */ public final class ModuleRevisions implements BundleRevisions { @@ -65,8 +65,9 @@ public List getRevisions() { } /** - * Same as {@link ModuleRevisions#getRevisions()} except it - * returns a list of {@link ModuleRevision}. + * Same as {@link ModuleRevisions#getRevisions()} except it returns a list of + * {@link ModuleRevision}. + * * @return the list of module revisions */ public List getModuleRevisions() { @@ -76,10 +77,11 @@ public List getModuleRevisions() { } /** - * Returns the current {@link ModuleRevision revision} associated with this revisions. + * Returns the current {@link ModuleRevision revision} associated with this + * revisions. * - * @return the current {@link ModuleRevision revision} associated with this revisions - * or {@code null} if the current revision does not exist. + * @return the current {@link ModuleRevision revision} associated with this + * revisions or {@code null} if the current revision does not exist. */ ModuleRevision getCurrentRevision() { synchronized (monitor) { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleWire.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleWire.java index 8fa836b5329..1ae7fc8ad20 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleWire.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleWire.java @@ -17,6 +17,7 @@ /** * An implementation of {@link BundleWire}. + * * @since 3.10 */ public final class ModuleWire implements BundleWire { @@ -25,10 +26,12 @@ public final class ModuleWire implements BundleWire { private final ModuleRequirement requirement; private final ModuleRevision hostingRequirer; // indicates that the wire points to valid wirings - // technically this should be a separate flag for requirer vs provider but that seems like overkill + // technically this should be a separate flag for requirer vs provider but that + // seems like overkill private volatile boolean isValid = true; - ModuleWire(ModuleCapability capability, ModuleRevision hostingProvider, ModuleRequirement requirement, ModuleRevision hostingRequirer) { + ModuleWire(ModuleCapability capability, ModuleRevision hostingProvider, ModuleRequirement requirement, + ModuleRevision hostingRequirer) { super(); this.capability = capability; this.hostingProvider = hostingProvider; diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleWiring.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleWiring.java index bd52a1db2b2..a2a7d4d7ca8 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleWiring.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/ModuleWiring.java @@ -45,6 +45,7 @@ /** * An implementation of {@link BundleWiring}. + * * @since 3.10 */ public final class ModuleWiring implements BundleWiring { @@ -254,8 +255,9 @@ public ClassLoader getClassLoader() { } /** - * Returns the module loader for this wiring. If the module - * loader does not exist yet then one will be created + * Returns the module loader for this wiring. If the module loader does not + * exist yet then one will be created + * * @return the module loader for this wiring. */ public ModuleLoader getModuleLoader() { @@ -372,17 +374,21 @@ boolean isSubtituted(ModuleCapability capability) { } /** - * Returns true if the specified package name has been substituted in this wiring + * Returns true if the specified package name has been substituted in this + * wiring + * * @param packageName the package name to check - * @return true if the specified package name has been substituted in this wiring + * @return true if the specified package name has been substituted in this + * wiring */ public boolean isSubstitutedPackage(String packageName) { return substitutedPkgNames.contains(packageName); } /** - * Returns an unmodifiable collection of package names for - * package capabilities that have been substituted. + * Returns an unmodifiable collection of package names for package capabilities + * that have been substituted. + * * @return the substituted package names */ public Collection getSubstitutedNames() { @@ -403,9 +409,10 @@ private boolean hasResourcePermission() { /** * Adds the {@link ModuleRevisionBuilder#getRequirements() requirements} from - * the specified builder to this wiring. The new requirements must be in the - * {@link PackageNamespace}. These requirements are transient - * and will not exist when loading up persistent wirings. + * the specified builder to this wiring. The new requirements must be in the + * {@link PackageNamespace}. These requirements are transient and will not exist + * when loading up persistent wirings. + * * @param builder the builder that defines the new dynamic imports. */ public void addDynamicImports(ModuleRevisionBuilder builder) { @@ -470,7 +477,8 @@ List getSubstitutionWires() { if (substitutedPkgNames.isEmpty()) { return Collections.emptyList(); } - // Could cache this, but seems unnecessary since it will only be used by the resolver + // Could cache this, but seems unnecessary since it will only be used by the + // resolver List substitutionWires = new ArrayList<>(substitutedPkgNames.size()); List current = requiredWires.getList(PackageNamespace.PACKAGE_NAMESPACE); for (ModuleWire wire : current) { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/SystemModule.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/SystemModule.java index 3c541989fcd..3328f54b567 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/SystemModule.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/SystemModule.java @@ -29,20 +29,24 @@ import org.osgi.service.resolver.ResolutionException; /** - * A special kind of module that represents the system module for the container. Additional - * methods are available on the system module for operations that effect the whole container. - * For example, initializing the container, restarting and waiting for the container to stop. + * A special kind of module that represents the system module for the container. + * Additional methods are available on the system module for operations that + * effect the whole container. For example, initializing the container, + * restarting and waiting for the container to stop. + * * @since 3.10 */ public abstract class SystemModule extends Module { private volatile AtomicReference forStop = new AtomicReference<>(); public SystemModule(ModuleContainer container) { - super(Long.valueOf(0), Constants.SYSTEM_BUNDLE_LOCATION, container, EnumSet.of(Settings.AUTO_START, Settings.USE_ACTIVATION_POLICY), Integer.valueOf(0)); + super(Long.valueOf(0), Constants.SYSTEM_BUNDLE_LOCATION, container, + EnumSet.of(Settings.AUTO_START, Settings.USE_ACTIVATION_POLICY), Integer.valueOf(0)); } /** * Initializes the module container + * * @throws BundleException if an exeption occurred while initializing */ public final void init() throws BundleException { @@ -119,9 +123,10 @@ public final void init() throws BundleException { /** * Waits until the module container has stopped. + * * @param timeout The amount of time to wait. - * @return The container event indicated why the framework stopped - * or if there was a time out waiting for stop. + * @return The container event indicated why the framework stopped or if there + * was a time out waiting for stop. * @see Framework#waitForStop(long) * @throws InterruptedException if the thread was interrupted while waiting */ @@ -238,6 +243,7 @@ public void stop(StopOptions... options) throws BundleException { /** * Restarts the module container. + * * @see Framework#update() * @throws BundleException */ @@ -253,20 +259,21 @@ public void update() throws BundleException { } // would publish an updated event here but the listener services are down switch (previousState) { - case STARTING : - init(); - break; - case ACTIVE : - start(); - default : - break; + case STARTING: + init(); + break; + case ACTIVE: + start(); + default: + break; } } @Override protected void startWorker() throws BundleException { super.startWorker(); - ((ContainerStartLevel) getRevisions().getContainer().getFrameworkStartLevel()).doContainerStartLevel(this, ContainerStartLevel.USE_BEGINNING_START_LEVEL); + ((ContainerStartLevel) getRevisions().getContainer().getFrameworkStartLevel()).doContainerStartLevel(this, + ContainerStartLevel.USE_BEGINNING_START_LEVEL); } @Override diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/builders/OSGiManifestBuilderFactory.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/builders/OSGiManifestBuilderFactory.java index 33e17c170cf..e82a5907c12 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/builders/OSGiManifestBuilderFactory.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/builders/OSGiManifestBuilderFactory.java @@ -50,7 +50,9 @@ import org.osgi.resource.Namespace; /** - * A factory for creating {@link ModuleRevisionBuilder}s based on OSGi bundle manifests. + * A factory for creating {@link ModuleRevisionBuilder}s based on OSGi bundle + * manifests. + * * @since 3.10 * @noinstantiate This class is not intended to be instantiated by clients. */ @@ -64,12 +66,17 @@ public final class OSGiManifestBuilderFactory { private static final String ATTR_TYPE_LIST = "List"; //$NON-NLS-1$ private static final String ATTR_OLD_REPRIVIDE = "reprovide"; //$NON-NLS-1$ private static final String HEADER_OLD_PROVIDE_PACKAGE = "Provide-Package"; //$NON-NLS-1$ - private static final String[] DEFINED_OSGI_VALIDATE_HEADERS = {Constants.IMPORT_PACKAGE, Constants.DYNAMICIMPORT_PACKAGE, Constants.EXPORT_PACKAGE, Constants.FRAGMENT_HOST, Constants.BUNDLE_SYMBOLICNAME, Constants.REQUIRE_BUNDLE}; - private static final Collection SYSTEM_CAPABILITIES = Collections.unmodifiableCollection(Arrays.asList(ExecutionEnvironmentNamespace.EXECUTION_ENVIRONMENT_NAMESPACE, NativeNamespace.NATIVE_NAMESPACE)); - private static final Collection PROHIBITED_CAPABILITIES = Collections.unmodifiableCollection(Arrays.asList(IdentityNamespace.IDENTITY_NAMESPACE)); + private static final String[] DEFINED_OSGI_VALIDATE_HEADERS = { Constants.IMPORT_PACKAGE, + Constants.DYNAMICIMPORT_PACKAGE, Constants.EXPORT_PACKAGE, Constants.FRAGMENT_HOST, + Constants.BUNDLE_SYMBOLICNAME, Constants.REQUIRE_BUNDLE }; + private static final Collection SYSTEM_CAPABILITIES = Collections.unmodifiableCollection(Arrays + .asList(ExecutionEnvironmentNamespace.EXECUTION_ENVIRONMENT_NAMESPACE, NativeNamespace.NATIVE_NAMESPACE)); + private static final Collection PROHIBITED_CAPABILITIES = Collections + .unmodifiableCollection(Arrays.asList(IdentityNamespace.IDENTITY_NAMESPACE)); /** * Creates a builder for the specified bundle manifest + * * @param manifest the bundle manifest * @return a builder for the specified bundle manifest * @throws BundleException if the bundle manifest is invalid @@ -79,20 +86,25 @@ public static ModuleRevisionBuilder createBuilder(Map manifest) } /** - * Creates a builder for the specified bundle manifest. An alias can be supplied - * for the symbolic name. Also extra package exports and extra provided capabilities - * may be specified outside of the supplied manifest. This is useful for creating - * a builder for the system module which takes into account the configuration - * properties {@link Constants#FRAMEWORK_SYSTEMPACKAGES_EXTRA} and - * {@link Constants#FRAMEWORK_SYSTEMCAPABILITIES_EXTRA}. - * @param manifest the bundle manifest - * @param symbolicNameAlias the symbolic name alias. A null value is allowed. - * @param extraExports the extra package exports. A null value is allowed. - * @param extraCapabilities the extra provided capabilities. A null value is allowed. + * Creates a builder for the specified bundle manifest. An alias can be supplied + * for the symbolic name. Also extra package exports and extra provided + * capabilities may be specified outside of the supplied manifest. This is + * useful for creating a builder for the system module which takes into account + * the configuration properties {@link Constants#FRAMEWORK_SYSTEMPACKAGES_EXTRA} + * and {@link Constants#FRAMEWORK_SYSTEMCAPABILITIES_EXTRA}. + * + * @param manifest the bundle manifest + * @param symbolicNameAlias the symbolic name alias. A null value + * is allowed. + * @param extraExports the extra package exports. A null value + * is allowed. + * @param extraCapabilities the extra provided capabilities. A null + * value is allowed. * @return a builder for the specified bundle manifest * @throws BundleException if the bundle manifest is invalid */ - public static ModuleRevisionBuilder createBuilder(Map manifest, String symbolicNameAlias, String extraExports, String extraCapabilities) throws BundleException { + public static ModuleRevisionBuilder createBuilder(Map manifest, String symbolicNameAlias, + String extraExports, String extraCapabilities) throws BundleException { ModuleRevisionBuilder builder = new ModuleRevisionBuilder(); int manifestVersion = getManifestVersion(manifest); @@ -103,26 +115,37 @@ public static ModuleRevisionBuilder createBuilder(Map manifest, Object symbolicName = getSymbolicNameAndVersion(builder, manifest, symbolicNameAlias, manifestVersion); Collection> exportedPackages = new ArrayList<>(); - getPackageExports(builder, ManifestElement.parseHeader(Constants.EXPORT_PACKAGE, manifest.get(Constants.EXPORT_PACKAGE)), symbolicName, exportedPackages); - getPackageExports(builder, ManifestElement.parseHeader(HEADER_OLD_PROVIDE_PACKAGE, manifest.get(HEADER_OLD_PROVIDE_PACKAGE)), symbolicName, exportedPackages); + getPackageExports(builder, + ManifestElement.parseHeader(Constants.EXPORT_PACKAGE, manifest.get(Constants.EXPORT_PACKAGE)), + symbolicName, exportedPackages); + getPackageExports(builder, + ManifestElement.parseHeader(HEADER_OLD_PROVIDE_PACKAGE, manifest.get(HEADER_OLD_PROVIDE_PACKAGE)), + symbolicName, exportedPackages); if (extraExports != null && !extraExports.isEmpty()) { - getPackageExports(builder, ManifestElement.parseHeader(Constants.EXPORT_PACKAGE, extraExports), symbolicName, exportedPackages); + getPackageExports(builder, ManifestElement.parseHeader(Constants.EXPORT_PACKAGE, extraExports), + symbolicName, exportedPackages); } getPackageImports(builder, manifest, exportedPackages, manifestVersion); - getRequireBundle(builder, ManifestElement.parseHeader(Constants.REQUIRE_BUNDLE, manifest.get(Constants.REQUIRE_BUNDLE))); + getRequireBundle(builder, + ManifestElement.parseHeader(Constants.REQUIRE_BUNDLE, manifest.get(Constants.REQUIRE_BUNDLE))); - getProvideCapabilities(builder, ManifestElement.parseHeader(Constants.PROVIDE_CAPABILITY, manifest.get(Constants.PROVIDE_CAPABILITY)), extraCapabilities == null); + getProvideCapabilities(builder, + ManifestElement.parseHeader(Constants.PROVIDE_CAPABILITY, manifest.get(Constants.PROVIDE_CAPABILITY)), + extraCapabilities == null); if (extraCapabilities != null && !extraCapabilities.isEmpty()) { - getProvideCapabilities(builder, ManifestElement.parseHeader(Constants.PROVIDE_CAPABILITY, extraCapabilities), false); + getProvideCapabilities(builder, + ManifestElement.parseHeader(Constants.PROVIDE_CAPABILITY, extraCapabilities), false); } - getRequireCapabilities(builder, ManifestElement.parseHeader(Constants.REQUIRE_CAPABILITY, manifest.get(Constants.REQUIRE_CAPABILITY))); + getRequireCapabilities(builder, + ManifestElement.parseHeader(Constants.REQUIRE_CAPABILITY, manifest.get(Constants.REQUIRE_CAPABILITY))); addRequireEclipsePlatform(builder, manifest); getEquinoxDataCapability(builder, manifest); - getFragmentHost(builder, ManifestElement.parseHeader(Constants.FRAGMENT_HOST, manifest.get(Constants.FRAGMENT_HOST))); + getFragmentHost(builder, + ManifestElement.parseHeader(Constants.FRAGMENT_HOST, manifest.get(Constants.FRAGMENT_HOST))); convertBREEs(builder, manifest); @@ -149,7 +172,8 @@ private static void validateHeaders(Map manifest, boolean allowJ checkExtensionBundle(definedOSGiValidateHeader, elements, manifest); } } else if (definedOSGiValidateHeader == Constants.BUNDLE_SYMBOLICNAME) { - throw new BundleException(Constants.BUNDLE_SYMBOLICNAME + " header is required.", BundleException.MANIFEST_ERROR); //$NON-NLS-1$ + throw new BundleException(Constants.BUNDLE_SYMBOLICNAME + " header is required.", //$NON-NLS-1$ + BundleException.MANIFEST_ERROR); } } } @@ -167,12 +191,14 @@ private static void checkImportExportSyntax(String headerKey, ManifestElement[] for (String packageName : packageNames) { if (!export && !dynamic && packages.contains(packageName)) { String message = NLS.bind(Msg.MANIFEST_INVALID_HEADER_EXCEPTION, headerKey, elements[i].toString()); - throw new BundleException(message + " : " + NLS.bind(Msg.HEADER_PACKAGE_DUPLICATES, packageName), BundleException.MANIFEST_ERROR); //$NON-NLS-1$ + throw new BundleException(message + " : " + NLS.bind(Msg.HEADER_PACKAGE_DUPLICATES, packageName), //$NON-NLS-1$ + BundleException.MANIFEST_ERROR); } // check for java.* if (export && !allowJavaExports && packageName.startsWith("java.")) { //$NON-NLS-1$ String message = NLS.bind(Msg.MANIFEST_INVALID_HEADER_EXCEPTION, headerKey, elements[i].toString()); - throw new BundleException(message + " : " + NLS.bind(Msg.HEADER_PACKAGE_JAVA, packageName), BundleException.MANIFEST_ERROR); //$NON-NLS-1$ + throw new BundleException(message + " : " + NLS.bind(Msg.HEADER_PACKAGE_JAVA, packageName), //$NON-NLS-1$ + BundleException.MANIFEST_ERROR); } packages.add(packageName); } @@ -181,24 +207,31 @@ private static void checkImportExportSyntax(String headerKey, ManifestElement[] if (version != null) { String specVersion = elements[i].getAttribute(Constants.PACKAGE_SPECIFICATION_VERSION); if (specVersion != null && !specVersion.equals(version)) - throw new BundleException(NLS.bind(Msg.HEADER_VERSION_ERROR, Constants.VERSION_ATTRIBUTE, Constants.PACKAGE_SPECIFICATION_VERSION), BundleException.MANIFEST_ERROR); + throw new BundleException(NLS.bind(Msg.HEADER_VERSION_ERROR, Constants.VERSION_ATTRIBUTE, + Constants.PACKAGE_SPECIFICATION_VERSION), BundleException.MANIFEST_ERROR); } // check for bundle-symbolic-name and bundle-version attributes on exports // (failure) if (export) { if (elements[i].getAttribute(Constants.BUNDLE_SYMBOLICNAME_ATTRIBUTE) != null) { String message = NLS.bind(Msg.MANIFEST_INVALID_HEADER_EXCEPTION, headerKey, elements[i].toString()); - throw new BundleException(message + " : " + NLS.bind(Msg.HEADER_EXPORT_ATTR_ERROR, Constants.BUNDLE_SYMBOLICNAME_ATTRIBUTE, Constants.EXPORT_PACKAGE), BundleException.MANIFEST_ERROR); //$NON-NLS-1$ + throw new BundleException( + message + " : " + NLS.bind(Msg.HEADER_EXPORT_ATTR_ERROR, //$NON-NLS-1$ + Constants.BUNDLE_SYMBOLICNAME_ATTRIBUTE, Constants.EXPORT_PACKAGE), + BundleException.MANIFEST_ERROR); } if (elements[i].getAttribute(Constants.BUNDLE_VERSION_ATTRIBUTE) != null) { String message = NLS.bind(Msg.MANIFEST_INVALID_HEADER_EXCEPTION, headerKey, elements[i].toString()); - throw new BundleException(NLS.bind(message + " : " + Msg.HEADER_EXPORT_ATTR_ERROR, Constants.BUNDLE_VERSION_ATTRIBUTE, Constants.EXPORT_PACKAGE), BundleException.MANIFEST_ERROR); //$NON-NLS-1$ + throw new BundleException(NLS.bind(message + " : " + Msg.HEADER_EXPORT_ATTR_ERROR, //$NON-NLS-1$ + Constants.BUNDLE_VERSION_ATTRIBUTE, Constants.EXPORT_PACKAGE), + BundleException.MANIFEST_ERROR); } } } } - private static void checkForDuplicateDirectivesAttributes(String headerKey, ManifestElement[] elements) throws BundleException { + private static void checkForDuplicateDirectivesAttributes(String headerKey, ManifestElement[] elements) + throws BundleException { // check for duplicate directives for (ManifestElement element : elements) { Enumeration directiveKeys = element.getDirectiveKeys(); @@ -208,7 +241,8 @@ private static void checkForDuplicateDirectivesAttributes(String headerKey, Mani String[] directives = element.getDirectives(key); if (directives.length > 1) { String message = NLS.bind(Msg.MANIFEST_INVALID_HEADER_EXCEPTION, headerKey, element.toString()); - throw new BundleException(NLS.bind(message + " : " + Msg.HEADER_DIRECTIVE_DUPLICATES, key), BundleException.MANIFEST_ERROR); //$NON-NLS-1$ + throw new BundleException(NLS.bind(message + " : " + Msg.HEADER_DIRECTIVE_DUPLICATES, key), //$NON-NLS-1$ + BundleException.MANIFEST_ERROR); } } } @@ -219,28 +253,34 @@ private static void checkForDuplicateDirectivesAttributes(String headerKey, Mani String[] attrs = element.getAttributes(key); if (attrs.length > 1) { String message = NLS.bind(Msg.MANIFEST_INVALID_HEADER_EXCEPTION, headerKey, element.toString()); - throw new BundleException(message + " : " + NLS.bind(Msg.HEADER_ATTRIBUTE_DUPLICATES, key), BundleException.MANIFEST_ERROR); //$NON-NLS-1$ + throw new BundleException(message + " : " + NLS.bind(Msg.HEADER_ATTRIBUTE_DUPLICATES, key), //$NON-NLS-1$ + BundleException.MANIFEST_ERROR); } } } } } - private static void checkExtensionBundle(String headerKey, ManifestElement[] elements, Map manifest) throws BundleException { + private static void checkExtensionBundle(String headerKey, ManifestElement[] elements, Map manifest) + throws BundleException { if (elements.length == 0) return; String hostName = elements[0].getValue(); - // XXX: The extension bundle check is done against system.bundle and org.eclipse.osgi + // XXX: The extension bundle check is done against system.bundle and + // org.eclipse.osgi if (!hostName.equals(Constants.SYSTEM_BUNDLE_SYMBOLICNAME) && !hostName.equals(EquinoxContainer.NAME)) { if (elements[0].getDirective(Constants.EXTENSION_DIRECTIVE) != null) { String message = NLS.bind(Msg.MANIFEST_INVALID_HEADER_EXCEPTION, headerKey, elements[0].toString()); - throw new BundleException(message + " : " + NLS.bind(Msg.HEADER_EXTENSION_ERROR, hostName), BundleException.MANIFEST_ERROR); //$NON-NLS-1$ + throw new BundleException(message + " : " + NLS.bind(Msg.HEADER_EXTENSION_ERROR, hostName), //$NON-NLS-1$ + BundleException.MANIFEST_ERROR); } } else { if (manifest.get(Constants.REQUIRE_BUNDLE) != null) - throw new BundleException(Msg.OSGiManifestBuilderFactory_ExtensionReqBundleError, BundleException.MANIFEST_ERROR); + throw new BundleException(Msg.OSGiManifestBuilderFactory_ExtensionReqBundleError, + BundleException.MANIFEST_ERROR); if (manifest.get(Constants.BUNDLE_NATIVECODE) != null) - throw new BundleException(Msg.OSGiManifestBuilderFactory_ExtensionNativeError, BundleException.MANIFEST_ERROR); + throw new BundleException(Msg.OSGiManifestBuilderFactory_ExtensionNativeError, + BundleException.MANIFEST_ERROR); } } @@ -250,7 +290,8 @@ private static int getManifestVersion(Map manifest) { return manifestVersionHeader == null ? 1 : Integer.parseInt(manifestVersionHeader); } - private static Object getSymbolicNameAndVersion(ModuleRevisionBuilder builder, Map manifest, String symbolicNameAlias, int manifestVersion) throws BundleException { + private static Object getSymbolicNameAndVersion(ModuleRevisionBuilder builder, Map manifest, + String symbolicNameAlias, int manifestVersion) throws BundleException { boolean isFragment = manifest.get(Constants.FRAGMENT_HOST) != null; builder.setTypes(isFragment ? BundleRevision.TYPE_FRAGMENT : 0); String version = manifest.get(Constants.BUNDLE_VERSION); @@ -258,7 +299,8 @@ private static Object getSymbolicNameAndVersion(ModuleRevisionBuilder builder, M builder.setVersion((version != null) ? Version.parseVersion(version) : Version.emptyVersion); } catch (IllegalArgumentException ex) { if (manifestVersion >= 2) { - String message = NLS.bind(Msg.OSGiManifestBuilderFactory_InvalidManifestError, Constants.BUNDLE_VERSION, version); + String message = NLS.bind(Msg.OSGiManifestBuilderFactory_InvalidManifestError, Constants.BUNDLE_VERSION, + version); throw new BundleException(message, BundleException.MANIFEST_ERROR, ex); } // prior to R4 the Bundle-Version header was not interpreted by the Framework; @@ -268,7 +310,8 @@ private static Object getSymbolicNameAndVersion(ModuleRevisionBuilder builder, M Object symbolicName = null; String symbolicNameHeader = manifest.get(Constants.BUNDLE_SYMBOLICNAME); if (symbolicNameHeader != null) { - ManifestElement[] symbolicNameElements = ManifestElement.parseHeader(Constants.BUNDLE_SYMBOLICNAME, symbolicNameHeader); + ManifestElement[] symbolicNameElements = ManifestElement.parseHeader(Constants.BUNDLE_SYMBOLICNAME, + symbolicNameHeader); if (symbolicNameElements.length > 0) { ManifestElement bsnElement = symbolicNameElements[0]; builder.setSymbolicName(bsnElement.getValue()); @@ -300,7 +343,8 @@ private static Object getSymbolicNameAndVersion(ModuleRevisionBuilder builder, M // create the host namespace // only if the directive is not never - if (!HostNamespace.FRAGMENT_ATTACHMENT_NEVER.equals(directives.get(HostNamespace.CAPABILITY_FRAGMENT_ATTACHMENT_DIRECTIVE))) { + if (!HostNamespace.FRAGMENT_ATTACHMENT_NEVER + .equals(directives.get(HostNamespace.CAPABILITY_FRAGMENT_ATTACHMENT_DIRECTIVE))) { Map hostAttributes = new HashMap<>(attributes); hostAttributes.put(HostNamespace.HOST_NAMESPACE, symbolicName); hostAttributes.put(HostNamespace.CAPABILITY_BUNDLE_VERSION_ATTRIBUTE, builder.getVersion()); @@ -312,7 +356,8 @@ private static Object getSymbolicNameAndVersion(ModuleRevisionBuilder builder, M Map identityAttributes = new HashMap<>(attributes); identityAttributes.put(IdentityNamespace.IDENTITY_NAMESPACE, builder.getSymbolicName()); identityAttributes.put(IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE, builder.getVersion()); - identityAttributes.put(IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE, isFragment ? IdentityNamespace.TYPE_FRAGMENT : IdentityNamespace.TYPE_BUNDLE); + identityAttributes.put(IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE, + isFragment ? IdentityNamespace.TYPE_FRAGMENT : IdentityNamespace.TYPE_BUNDLE); builder.addCapability(IdentityNamespace.IDENTITY_NAMESPACE, directives, identityAttributes); } } @@ -320,7 +365,8 @@ private static Object getSymbolicNameAndVersion(ModuleRevisionBuilder builder, M return symbolicName == null ? symbolicNameAlias : symbolicName; } - private static void getPackageExports(ModuleRevisionBuilder builder, ManifestElement[] exportElements, Object symbolicName, Collection> exportedPackages) throws BundleException { + private static void getPackageExports(ModuleRevisionBuilder builder, ManifestElement[] exportElements, + Object symbolicName, Collection> exportedPackages) throws BundleException { if (exportElements == null) return; for (ManifestElement exportElement : exportElements) { @@ -357,17 +403,21 @@ private static Version parsePackageVersion(String[] packageNames, String version } } - private static void getPackageImports(ModuleRevisionBuilder builder, Map manifest, Collection> exportedPackages, int manifestVersion) throws BundleException { + private static void getPackageImports(ModuleRevisionBuilder builder, Map manifest, + Collection> exportedPackages, int manifestVersion) throws BundleException { Collection importPackageNames = new ArrayList<>(); - ManifestElement[] importElements = ManifestElement.parseHeader(Constants.IMPORT_PACKAGE, manifest.get(Constants.IMPORT_PACKAGE)); - ManifestElement[] dynamicImportElements = ManifestElement.parseHeader(Constants.DYNAMICIMPORT_PACKAGE, manifest.get(Constants.DYNAMICIMPORT_PACKAGE)); + ManifestElement[] importElements = ManifestElement.parseHeader(Constants.IMPORT_PACKAGE, + manifest.get(Constants.IMPORT_PACKAGE)); + ManifestElement[] dynamicImportElements = ManifestElement.parseHeader(Constants.DYNAMICIMPORT_PACKAGE, + manifest.get(Constants.DYNAMICIMPORT_PACKAGE)); addPackageImports(builder, importElements, importPackageNames, false); addPackageImports(builder, dynamicImportElements, importPackageNames, true); if (manifestVersion < 2) addImplicitImports(builder, exportedPackages, importPackageNames); } - private static void addPackageImports(ModuleRevisionBuilder builder, ManifestElement[] importElements, Collection importPackageNames, boolean dynamic) throws BundleException { + private static void addPackageImports(ModuleRevisionBuilder builder, ManifestElement[] importElements, + Collection importPackageNames, boolean dynamic) throws BundleException { if (importElements == null) return; for (ManifestElement importElement : importElements) { @@ -382,10 +432,15 @@ private static void addPackageImports(ModuleRevisionBuilder builder, ManifestEle String versionRangeAttr = (String) attributes.remove(PackageNamespace.CAPABILITY_VERSION_ATTRIBUTE); @SuppressWarnings("deprecation") String specVersionRangeAttr = (String) attributes.remove(Constants.PACKAGE_SPECIFICATION_VERSION); - VersionRange versionRange = versionRangeAttr == null ? (specVersionRangeAttr == null ? null : new VersionRange(specVersionRangeAttr)) : new VersionRange(versionRangeAttr); - String bundleVersionRangeAttr = (String) attributes.remove(PackageNamespace.CAPABILITY_BUNDLE_VERSION_ATTRIBUTE); - VersionRange bundleVersionRange = bundleVersionRangeAttr == null ? null : new VersionRange(bundleVersionRangeAttr); - // the attribute "optional" used to be used in old versions of equinox to specify optional imports + VersionRange versionRange = versionRangeAttr == null + ? (specVersionRangeAttr == null ? null : new VersionRange(specVersionRangeAttr)) + : new VersionRange(versionRangeAttr); + String bundleVersionRangeAttr = (String) attributes + .remove(PackageNamespace.CAPABILITY_BUNDLE_VERSION_ATTRIBUTE); + VersionRange bundleVersionRange = bundleVersionRangeAttr == null ? null + : new VersionRange(bundleVersionRangeAttr); + // the attribute "optional" used to be used in old versions of equinox to + // specify optional imports // preserving behavior for compatibility Object optionalAttr = attributes.remove(Namespace.RESOLUTION_OPTIONAL); for (String packageName : packageNames) { @@ -395,14 +450,16 @@ private static void addPackageImports(ModuleRevisionBuilder builder, ManifestEle // fill in the filter directive based on the attributes Map packageDirectives = new HashMap<>(directives); StringBuilder filter = new StringBuilder(); - filter.append('(').append(PackageNamespace.PACKAGE_NAMESPACE).append('=').append(packageName).append(')'); + filter.append('(').append(PackageNamespace.PACKAGE_NAMESPACE).append('=').append(packageName) + .append(')'); int size = filter.length(); for (Map.Entry attribute : attributes.entrySet()) filter.append('(').append(attribute.getKey()).append('=').append(attribute.getValue()).append(')'); if (versionRange != null) filter.append(versionRange.toFilterString(PackageNamespace.CAPABILITY_VERSION_ATTRIBUTE)); if (bundleVersionRange != null) - filter.append(bundleVersionRange.toFilterString(PackageNamespace.CAPABILITY_BUNDLE_VERSION_ATTRIBUTE)); + filter.append( + bundleVersionRange.toFilterString(PackageNamespace.CAPABILITY_BUNDLE_VERSION_ATTRIBUTE)); if (size != filter.length()) // need to add (&...) filter.insert(0, "(&").append(')'); //$NON-NLS-1$ @@ -410,10 +467,12 @@ private static void addPackageImports(ModuleRevisionBuilder builder, ManifestEle // fill in cardinality for dynamic wild cards if (dynamic && packageName.indexOf('*') >= 0) - packageDirectives.put(PackageNamespace.REQUIREMENT_CARDINALITY_DIRECTIVE, PackageNamespace.CARDINALITY_MULTIPLE); + packageDirectives.put(PackageNamespace.REQUIREMENT_CARDINALITY_DIRECTIVE, + PackageNamespace.CARDINALITY_MULTIPLE); // check the old optional attribute - if ("true".equals(optionalAttr) && packageDirectives.get(Namespace.REQUIREMENT_RESOLUTION_DIRECTIVE) == null) { //$NON-NLS-1$ + if ("true".equals(optionalAttr) //$NON-NLS-1$ + && packageDirectives.get(Namespace.REQUIREMENT_RESOLUTION_DIRECTIVE) == null) { packageDirectives.put(Namespace.REQUIREMENT_RESOLUTION_DIRECTIVE, Namespace.RESOLUTION_OPTIONAL); } builder.addRequirement(PackageNamespace.PACKAGE_NAMESPACE, packageDirectives, new HashMap<>(0)); @@ -421,7 +480,8 @@ private static void addPackageImports(ModuleRevisionBuilder builder, ManifestEle } } - private static void addImplicitImports(ModuleRevisionBuilder builder, Collection> exportedPackages, Collection importPackageNames) { + private static void addImplicitImports(ModuleRevisionBuilder builder, + Collection> exportedPackages, Collection importPackageNames) { for (Map exportAttributes : exportedPackages) { String packageName = (String) exportAttributes.get(PackageNamespace.PACKAGE_NAMESPACE); if (importPackageNames.contains(packageName)) @@ -430,7 +490,8 @@ private static void addImplicitImports(ModuleRevisionBuilder builder, Collection Version packageVersion = (Version) exportAttributes.get(PackageNamespace.CAPABILITY_VERSION_ATTRIBUTE); StringBuilder filter = new StringBuilder(); filter.append("(&(").append(PackageNamespace.PACKAGE_NAMESPACE).append('=').append(packageName).append(')'); //$NON-NLS-1$ - filter.append('(').append(PackageNamespace.CAPABILITY_VERSION_ATTRIBUTE).append(">=").append(packageVersion).append("))"); //$NON-NLS-1$//$NON-NLS-2$ + filter.append('(').append(PackageNamespace.CAPABILITY_VERSION_ATTRIBUTE).append(">=").append(packageVersion) //$NON-NLS-1$ + .append("))"); //$NON-NLS-1$ Map directives = new HashMap<>(1); directives.put(PackageNamespace.REQUIREMENT_FILTER_DIRECTIVE, filter.toString()); builder.addRequirement(PackageNamespace.PACKAGE_NAMESPACE, directives, new HashMap<>(0)); @@ -449,7 +510,8 @@ private static Map getDirectives(ManifestElement element) { return directives; } - private static void getRequireBundle(ModuleRevisionBuilder builder, ManifestElement[] requireBundles) throws BundleException { + private static void getRequireBundle(ModuleRevisionBuilder builder, ManifestElement[] requireBundles) + throws BundleException { if (requireBundles == null) return; for (ManifestElement requireElement : requireBundles) { @@ -483,18 +545,22 @@ private static void getRequireBundle(ModuleRevisionBuilder builder, ManifestElem filter.insert(0, "(&").append(')'); //$NON-NLS-1$ bundleDirectives.put(BundleNamespace.REQUIREMENT_FILTER_DIRECTIVE, filter.toString()); // check the old compatibility attributes - if ("true".equals(optionalAttr) && bundleDirectives.get(Namespace.REQUIREMENT_RESOLUTION_DIRECTIVE) == null) { //$NON-NLS-1$ + if ("true".equals(optionalAttr) //$NON-NLS-1$ + && bundleDirectives.get(Namespace.REQUIREMENT_RESOLUTION_DIRECTIVE) == null) { bundleDirectives.put(Namespace.REQUIREMENT_RESOLUTION_DIRECTIVE, Namespace.RESOLUTION_OPTIONAL); } - if ("true".equals(reprovideAttr) && bundleDirectives.get(BundleNamespace.REQUIREMENT_VISIBILITY_DIRECTIVE) == null) { //$NON-NLS-1$ - bundleDirectives.put(BundleNamespace.REQUIREMENT_VISIBILITY_DIRECTIVE, BundleNamespace.VISIBILITY_REEXPORT); + if ("true".equals(reprovideAttr) //$NON-NLS-1$ + && bundleDirectives.get(BundleNamespace.REQUIREMENT_VISIBILITY_DIRECTIVE) == null) { + bundleDirectives.put(BundleNamespace.REQUIREMENT_VISIBILITY_DIRECTIVE, + BundleNamespace.VISIBILITY_REEXPORT); } builder.addRequirement(BundleNamespace.BUNDLE_NAMESPACE, bundleDirectives, new HashMap<>(0)); } } } - private static void getFragmentHost(ModuleRevisionBuilder builder, ManifestElement[] fragmentHosts) throws BundleException { + private static void getFragmentHost(ModuleRevisionBuilder builder, ManifestElement[] fragmentHosts) + throws BundleException { if (fragmentHosts == null || fragmentHosts.length == 0) return; @@ -521,12 +587,16 @@ private static void getFragmentHost(ModuleRevisionBuilder builder, ManifestEleme filter.insert(0, "(&").append(')'); //$NON-NLS-1$ directives.put(BundleNamespace.REQUIREMENT_FILTER_DIRECTIVE, filter.toString()); builder.addRequirement(HostNamespace.HOST_NAMESPACE, directives, new HashMap<>(0)); - // Add a fragment capability to advertise what host this resource is providing a fragment for - directives = Collections.singletonMap(EquinoxModuleDataNamespace.CAPABILITY_EFFECTIVE_DIRECTIVE, EquinoxModuleDataNamespace.EFFECTIVE_INFORMATION); - builder.addCapability(EquinoxFragmentNamespace.FRAGMENT_NAMESPACE, directives, Collections.singletonMap(EquinoxFragmentNamespace.FRAGMENT_NAMESPACE, hostName)); + // Add a fragment capability to advertise what host this resource is providing a + // fragment for + directives = Collections.singletonMap(EquinoxModuleDataNamespace.CAPABILITY_EFFECTIVE_DIRECTIVE, + EquinoxModuleDataNamespace.EFFECTIVE_INFORMATION); + builder.addCapability(EquinoxFragmentNamespace.FRAGMENT_NAMESPACE, directives, + Collections.singletonMap(EquinoxFragmentNamespace.FRAGMENT_NAMESPACE, hostName)); } - private static void getProvideCapabilities(ModuleRevisionBuilder builder, ManifestElement[] provideElements, boolean checkSystemCapabilities) throws BundleException { + private static void getProvideCapabilities(ModuleRevisionBuilder builder, ManifestElement[] provideElements, + boolean checkSystemCapabilities) throws BundleException { if (provideElements == null) return; for (ManifestElement provideElement : provideElements) { @@ -534,8 +604,11 @@ private static void getProvideCapabilities(ModuleRevisionBuilder builder, Manife Map attributes = getAttributes(provideElement); Map directives = getDirectives(provideElement); for (String namespace : namespaces) { - if (PROHIBITED_CAPABILITIES.contains(namespace) || (checkSystemCapabilities && SYSTEM_CAPABILITIES.contains(namespace))) { - throw new BundleException("A bundle is not allowed to define a capability in the " + namespace + " name space.", BundleException.MANIFEST_ERROR); //$NON-NLS-1$ //$NON-NLS-2$ + if (PROHIBITED_CAPABILITIES.contains(namespace) + || (checkSystemCapabilities && SYSTEM_CAPABILITIES.contains(namespace))) { + throw new BundleException( + "A bundle is not allowed to define a capability in the " + namespace + " name space.", //$NON-NLS-1$ //$NON-NLS-2$ + BundleException.MANIFEST_ERROR); } builder.addCapability(namespace, directives, attributes); @@ -543,7 +616,8 @@ private static void getProvideCapabilities(ModuleRevisionBuilder builder, Manife } } - private static void getRequireCapabilities(ModuleRevisionBuilder builder, ManifestElement[] requireElements) throws BundleException { + private static void getRequireCapabilities(ModuleRevisionBuilder builder, ManifestElement[] requireElements) + throws BundleException { if (requireElements == null) return; for (ManifestElement requireElement : requireElements) { @@ -568,11 +642,13 @@ private static void addRequireEclipsePlatform(ModuleRevisionBuilder builder, Map } @SuppressWarnings("deprecation") - private static void getEquinoxDataCapability(ModuleRevisionBuilder builder, Map manifest) throws BundleException { + private static void getEquinoxDataCapability(ModuleRevisionBuilder builder, Map manifest) + throws BundleException { Map attributes = new HashMap<>(); // Get the activation policy attributes - ManifestElement[] policyElements = ManifestElement.parseHeader(Constants.BUNDLE_ACTIVATIONPOLICY, manifest.get(Constants.BUNDLE_ACTIVATIONPOLICY)); + ManifestElement[] policyElements = ManifestElement.parseHeader(Constants.BUNDLE_ACTIVATIONPOLICY, + manifest.get(Constants.BUNDLE_ACTIVATIONPOLICY)); if (policyElements != null) { ManifestElement policy = policyElements[0]; String policyName = policy.getValue(); @@ -580,31 +656,40 @@ private static void getEquinoxDataCapability(ModuleRevisionBuilder builder, Map< attributes.put(EquinoxModuleDataNamespace.CAPABILITY_ACTIVATION_POLICY, policyName); String includeSpec = policy.getDirective(Constants.INCLUDE_DIRECTIVE); if (includeSpec != null) { - attributes.put(EquinoxModuleDataNamespace.CAPABILITY_LAZY_INCLUDE_ATTRIBUTE, convertValueWithNoWhitespace("List", includeSpec)); //$NON-NLS-1$ + attributes.put(EquinoxModuleDataNamespace.CAPABILITY_LAZY_INCLUDE_ATTRIBUTE, + convertValueWithNoWhitespace("List", includeSpec)); //$NON-NLS-1$ } String excludeSpec = policy.getDirective(Constants.EXCLUDE_DIRECTIVE); if (excludeSpec != null) { - attributes.put(EquinoxModuleDataNamespace.CAPABILITY_LAZY_EXCLUDE_ATTRIBUTE, convertValueWithNoWhitespace("List", excludeSpec)); //$NON-NLS-1$ + attributes.put(EquinoxModuleDataNamespace.CAPABILITY_LAZY_EXCLUDE_ATTRIBUTE, + convertValueWithNoWhitespace("List", excludeSpec)); //$NON-NLS-1$ } } } else { - policyElements = ManifestElement.parseHeader(EquinoxModuleDataNamespace.LAZYSTART_HEADER, manifest.get(EquinoxModuleDataNamespace.LAZYSTART_HEADER)); + policyElements = ManifestElement.parseHeader(EquinoxModuleDataNamespace.LAZYSTART_HEADER, + manifest.get(EquinoxModuleDataNamespace.LAZYSTART_HEADER)); if (policyElements == null) { - policyElements = ManifestElement.parseHeader(EquinoxModuleDataNamespace.AUTOSTART_HEADER, manifest.get(EquinoxModuleDataNamespace.AUTOSTART_HEADER)); + policyElements = ManifestElement.parseHeader(EquinoxModuleDataNamespace.AUTOSTART_HEADER, + manifest.get(EquinoxModuleDataNamespace.AUTOSTART_HEADER)); } if (policyElements != null) { ManifestElement policy = policyElements[0]; String excludeSpec = policy.getAttribute(EquinoxModuleDataNamespace.LAZYSTART_EXCEPTIONS_ATTRIBUTE); if ("true".equals(policy.getValue())) { //$NON-NLS-1$ - attributes.put(EquinoxModuleDataNamespace.CAPABILITY_ACTIVATION_POLICY, EquinoxModuleDataNamespace.CAPABILITY_ACTIVATION_POLICY_LAZY); + attributes.put(EquinoxModuleDataNamespace.CAPABILITY_ACTIVATION_POLICY, + EquinoxModuleDataNamespace.CAPABILITY_ACTIVATION_POLICY_LAZY); if (excludeSpec != null) { - attributes.put(EquinoxModuleDataNamespace.CAPABILITY_LAZY_EXCLUDE_ATTRIBUTE, convertValueWithNoWhitespace("List", excludeSpec)); //$NON-NLS-1$ + attributes.put(EquinoxModuleDataNamespace.CAPABILITY_LAZY_EXCLUDE_ATTRIBUTE, + convertValueWithNoWhitespace("List", excludeSpec)); //$NON-NLS-1$ } } else { - // NOTICE - the exclude list gets converted to an include list when the header is not true + // NOTICE - the exclude list gets converted to an include list when the header + // is not true if (excludeSpec != null) { - attributes.put(EquinoxModuleDataNamespace.CAPABILITY_ACTIVATION_POLICY, EquinoxModuleDataNamespace.CAPABILITY_ACTIVATION_POLICY_LAZY); - attributes.put(EquinoxModuleDataNamespace.CAPABILITY_LAZY_INCLUDE_ATTRIBUTE, convertValueWithNoWhitespace("List", excludeSpec)); //$NON-NLS-1$ + attributes.put(EquinoxModuleDataNamespace.CAPABILITY_ACTIVATION_POLICY, + EquinoxModuleDataNamespace.CAPABILITY_ACTIVATION_POLICY_LAZY); + attributes.put(EquinoxModuleDataNamespace.CAPABILITY_LAZY_INCLUDE_ATTRIBUTE, + convertValueWithNoWhitespace("List", excludeSpec)); //$NON-NLS-1$ } } } @@ -614,7 +699,8 @@ private static void getEquinoxDataCapability(ModuleRevisionBuilder builder, Map< String activator = manifest.get(Constants.BUNDLE_ACTIVATOR); if (activator == null && manifest.get(Constants.FRAGMENT_HOST) != null) { // we look for the extension activator for fragments - // probably should do this only for framework extensions, but there is no harm to check for others + // probably should do this only for framework extensions, but there is no harm + // to check for others // it is only acted upon for framework extension fragments activator = manifest.get(Constants.EXTENSION_BUNDLE_ACTIVATOR); } @@ -623,7 +709,8 @@ private static void getEquinoxDataCapability(ModuleRevisionBuilder builder, Map< } // Get the class path - ManifestElement[] classpathElements = ManifestElement.parseHeader(Constants.BUNDLE_CLASSPATH, manifest.get(Constants.BUNDLE_CLASSPATH)); + ManifestElement[] classpathElements = ManifestElement.parseHeader(Constants.BUNDLE_CLASSPATH, + manifest.get(Constants.BUNDLE_CLASSPATH)); if (classpathElements != null) { List classpath = new ArrayList<>(); for (ManifestElement element : classpathElements) { @@ -634,7 +721,8 @@ private static void getEquinoxDataCapability(ModuleRevisionBuilder builder, Map< } // Get the buddy policy list - ManifestElement[] buddyPolicies = ManifestElement.parseHeader(EquinoxModuleDataNamespace.BUDDY_POLICY_HEADER, manifest.get(EquinoxModuleDataNamespace.BUDDY_POLICY_HEADER)); + ManifestElement[] buddyPolicies = ManifestElement.parseHeader(EquinoxModuleDataNamespace.BUDDY_POLICY_HEADER, + manifest.get(EquinoxModuleDataNamespace.BUDDY_POLICY_HEADER)); if (buddyPolicies != null) { List policies = new ArrayList<>(); for (ManifestElement element : buddyPolicies) { @@ -644,7 +732,9 @@ private static void getEquinoxDataCapability(ModuleRevisionBuilder builder, Map< } // Get the registered buddy list - ManifestElement[] registeredBuddies = ManifestElement.parseHeader(EquinoxModuleDataNamespace.REGISTERED_BUDDY_HEADER, manifest.get(EquinoxModuleDataNamespace.REGISTERED_BUDDY_HEADER)); + ManifestElement[] registeredBuddies = ManifestElement.parseHeader( + EquinoxModuleDataNamespace.REGISTERED_BUDDY_HEADER, + manifest.get(EquinoxModuleDataNamespace.REGISTERED_BUDDY_HEADER)); if (registeredBuddies != null) { List buddies = new ArrayList<>(); for (ManifestElement element : registeredBuddies) { @@ -655,7 +745,9 @@ private static void getEquinoxDataCapability(ModuleRevisionBuilder builder, Map< // only create the capability if the attributes is not empty if (!attributes.isEmpty()) { - Map directives = Collections.singletonMap(EquinoxModuleDataNamespace.CAPABILITY_EFFECTIVE_DIRECTIVE, EquinoxModuleDataNamespace.EFFECTIVE_INFORMATION); + Map directives = Collections.singletonMap( + EquinoxModuleDataNamespace.CAPABILITY_EFFECTIVE_DIRECTIVE, + EquinoxModuleDataNamespace.EFFECTIVE_INFORMATION); builder.addCapability(EquinoxModuleDataNamespace.MODULE_DATA_NAMESPACE, directives, attributes); } } @@ -700,7 +792,8 @@ private static Object convertValue(String type, String value) throws BundleExcep } else if (ATTR_TYPE_VERSION.equalsIgnoreCase(type)) { return new Version(trimmed); } else if (ATTR_TYPE_SET.equalsIgnoreCase(type)) { - // just use List here so we don't have to deal with String[] in other places + // just use List here so we don't have to deal with String[] in other + // places return Collections.unmodifiableList(Arrays.asList(ManifestElement.getArrayFromList(trimmed, ","))); //$NON-NLS-1$ } // assume list type, anything else will throw an exception @@ -723,7 +816,8 @@ private static Object convertValue(String type, String value) throws BundleExcep return Collections.unmodifiableList(components); } - private static void convertBREEs(ModuleRevisionBuilder builder, Map manifest) throws BundleException { + private static void convertBREEs(ModuleRevisionBuilder builder, Map manifest) + throws BundleException { @SuppressWarnings("deprecation") String[] brees = ManifestElement.getArrayFromList(manifest.get(Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT)); if (brees == null || brees.length == 0) @@ -744,7 +838,8 @@ private static void convertBREEs(ModuleRevisionBuilder builder, Map directives = new HashMap<>(1); directives.put(ExecutionEnvironmentNamespace.REQUIREMENT_FILTER_DIRECTIVE, filterSpec); - builder.addRequirement(ExecutionEnvironmentNamespace.EXECUTION_ENVIRONMENT_NAMESPACE, directives, new HashMap<>(0)); + builder.addRequirement(ExecutionEnvironmentNamespace.EXECUTION_ENVIRONMENT_NAMESPACE, directives, + new HashMap<>(0)); } static String escapeFilterInput(final String value) { @@ -759,14 +854,14 @@ static String escapeFilterInput(final String value) { for (int i = inlen; i < outlen; i++) { char c = output[i]; switch (c) { - case '*' : - case '\\' : - case '(' : - case ')' : - output[cursor] = '\\'; - cursor++; - escaped = true; - break; + case '*': + case '\\': + case '(': + case ')': + output[cursor] = '\\'; + cursor++; + escaped = true; + break; } output[cursor] = c; @@ -794,7 +889,8 @@ private static String createOSGiEERequirementFilter(String bree) throws BundleEx // do another sanity check FilterImpl.newInstance(filterSpec); } catch (InvalidSyntaxException e1) { - throw new BundleException("Error converting required execution environment.", BundleException.MANIFEST_ERROR, e1); //$NON-NLS-1$ + throw new BundleException("Error converting required execution environment.", //$NON-NLS-1$ + BundleException.MANIFEST_ERROR, e1); } } return filterSpec; @@ -854,7 +950,7 @@ private static String[] getOSGiEENameVersion(String bree) { String eeName = ee1 + (ee2 == null ? "" : '/' + ee2); //$NON-NLS-1$ - return new String[] {escapeFilterInput(eeName), v1}; + return new String[] { escapeFilterInput(eeName), v1 }; } static class NativeClause implements Comparable { @@ -872,7 +968,8 @@ static class NativeClause implements Comparable { addToNativeCodeFilter(sb, clause, Constants.BUNDLE_NATIVECODE_OSNAME); addToNativeCodeFilter(sb, clause, Constants.BUNDLE_NATIVECODE_PROCESSOR); this.highestFloor = (Version) addToNativeCodeFilter(sb, clause, Constants.BUNDLE_NATIVECODE_OSVERSION); - this.hasLanguage = ((Boolean) addToNativeCodeFilter(sb, clause, Constants.BUNDLE_NATIVECODE_LANGUAGE)).booleanValue(); + this.hasLanguage = ((Boolean) addToNativeCodeFilter(sb, clause, Constants.BUNDLE_NATIVECODE_LANGUAGE)) + .booleanValue(); String selectionFilter = clause.getAttribute(Constants.SELECTION_FILTER_ATTRIBUTE); if (selectionFilter != null) { // do a sanity check to make sure the filter is valid @@ -892,7 +989,8 @@ static class NativeClause implements Comparable { this.filter = filterResult; } - private static Object addToNativeCodeFilter(StringBuilder filter, ManifestElement nativeCode, String attribute) { + private static Object addToNativeCodeFilter(StringBuilder filter, ManifestElement nativeCode, + String attribute) { Boolean hasLanguage = Boolean.FALSE; Version highestFloor = null; String[] attrValues = nativeCode.getAttributes(attribute); @@ -921,7 +1019,8 @@ private static Object addToNativeCodeFilter(StringBuilder filter, ManifestElemen } filter.append(range.toFilterString(filterAttribute)); } else { - filter.append('(').append(filterAttribute).append("~=").append(escapeFilterInput(attrAlias)).append(')'); //$NON-NLS-1$ + filter.append('(').append(filterAttribute).append("~=").append(escapeFilterInput(attrAlias)) //$NON-NLS-1$ + .append(')'); } } if (attrValues.length > 1) { @@ -954,8 +1053,10 @@ public int compareTo(NativeClause other) { } } - private static void getNativeCode(ModuleRevisionBuilder builder, Map manifest) throws BundleException { - ManifestElement[] elements = ManifestElement.parseHeader(Constants.BUNDLE_NATIVECODE, manifest.get(Constants.BUNDLE_NATIVECODE)); + private static void getNativeCode(ModuleRevisionBuilder builder, Map manifest) + throws BundleException { + ManifestElement[] elements = ManifestElement.parseHeader(Constants.BUNDLE_NATIVECODE, + manifest.get(Constants.BUNDLE_NATIVECODE)); if (elements == null) { return; } @@ -975,7 +1076,8 @@ private static void getNativeCode(ModuleRevisionBuilder builder, Map - * Also, the capability attribute used to specify the symbolic name of the host the - * resource is providing a fragment for. + * Also, the capability attribute used to specify the symbolic name of the host + * the resource is providing a fragment for. */ public static final String FRAGMENT_NAMESPACE = "equinox.fragment"; //$NON-NLS-1$ } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/namespaces/EquinoxModuleDataNamespace.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/namespaces/EquinoxModuleDataNamespace.java index bd51bc874ce..fdd0a26470c 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/namespaces/EquinoxModuleDataNamespace.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/container/namespaces/EquinoxModuleDataNamespace.java @@ -17,23 +17,24 @@ import org.osgi.resource.Namespace; /** - * Equinox module data capability namespace. This namespace is used - * to store immutable data about a module revision. This includes the following + * Equinox module data capability namespace. This namespace is used to store + * immutable data about a module revision. This includes the following *

    - *
  • The activation policy as specified by the {@link Constants#BUNDLE_ACTIVATIONPOLICY - * Bundle-ActivationPolicy} header.
  • - *
  • The activator as specified by the {@link Constants#BUNDLE_ACTIVATOR Bundle-Activator} - * header.
  • - *
  • The class path as specified by the {@link Constants#BUNDLE_CLASSPATH Bundle-ClassPath} - * header.
  • - *
  • The bundle class loading policy. + *
  • The activation policy as specified by the + * {@link Constants#BUNDLE_ACTIVATIONPOLICY Bundle-ActivationPolicy} + * header.
  • + *
  • The activator as specified by the {@link Constants#BUNDLE_ACTIVATOR + * Bundle-Activator} header.
  • + *
  • The class path as specified by the {@link Constants#BUNDLE_CLASSPATH + * Bundle-ClassPath} header.
  • + *
  • The bundle class loading policy. *
* - * This capability is provided for informational purposes and - * should not be considered as effective by the resolver. + * This capability is provided for informational purposes and should not be + * considered as effective by the resolver. *

* This class defines the names for the attributes and directives for this - * namespace. Capabilities in this namespace are not intended to be used to + * namespace. Capabilities in this namespace are not intended to be used to * match requirements and should not be considered as effective by a resolver. * * @Immutable @@ -47,7 +48,8 @@ public class EquinoxModuleDataNamespace extends Namespace { public final static String BUDDY_POLICY_HEADER = "Eclipse-BuddyPolicy"; //$NON-NLS-1$ /** - * The Equinox specific header for specifying a list of symbolic names to register as a buddy with. + * The Equinox specific header for specifying a list of symbolic names to + * register as a buddy with. */ public final static String REGISTERED_BUDDY_HEADER = "Eclipse-RegisterBuddy"; //$NON-NLS-1$ @@ -56,35 +58,39 @@ public class EquinoxModuleDataNamespace extends Namespace { */ public static final String LAZYSTART_HEADER = "Eclipse-LazyStart"; //$NON-NLS-1$ - /** An Eclipse-LazyStart header attribute used to specify exception classes for auto start */ + /** + * An Eclipse-LazyStart header attribute used to specify exception classes for + * auto start + */ public static final String LAZYSTART_EXCEPTIONS_ATTRIBUTE = "exceptions"; //$NON-NLS-1$ /** * The Equinox specific header for specifying the lazy start policy + * * @deprecated use {@link #LAZYSTART_HEADER} */ public static final String AUTOSTART_HEADER = "Eclipse-AutoStart"; //$NON-NLS-1$ /** - * Namespace name for equinox module data. Unlike typical name spaces - * this namespace is not intended to be used as an attribute. + * Namespace name for equinox module data. Unlike typical name spaces this + * namespace is not intended to be used as an attribute. */ public static final String MODULE_DATA_NAMESPACE = "equinox.module.data"; //$NON-NLS-1$ /** * The directive value identifying a {@link #CAPABILITY_EFFECTIVE_DIRECTIVE - * capability} that is effective for information purposes. Capabilities - * in this namespace must have an effective directive value of information. + * capability} that is effective for information purposes. Capabilities in this + * namespace must have an effective directive value of information. * * @see #CAPABILITY_EFFECTIVE_DIRECTIVE */ public final static String EFFECTIVE_INFORMATION = "information"; //$NON-NLS-1$ /** - * The capability attribute contains the {@link Constants#BUNDLE_ACTIVATIONPOLICY - * activation policy} for the providing module revision. The value of this - * attribute must be of type {@code String}. When not specified then - * the module revision uses an eager activation policy. + * The capability attribute contains the + * {@link Constants#BUNDLE_ACTIVATIONPOLICY activation policy} for the providing + * module revision. The value of this attribute must be of type {@code String}. + * When not specified then the module revision uses an eager activation policy. */ public final static String CAPABILITY_ACTIVATION_POLICY = "activation.policy"; //$NON-NLS-1$ @@ -96,49 +102,49 @@ public class EquinoxModuleDataNamespace extends Namespace { /** * When the {@link #CAPABILITY_ACTIVATION_POLICY_LAZY lazy} policy is used this - * attribute contains the package names that must - * trigger the activation when a class is loaded of these packages. - * If the attribute is not defined then the default is all package names. - * The value of this attribute must be of type {@code List}. + * attribute contains the package names that must trigger the activation when a + * class is loaded of these packages. If the attribute is not defined then the + * default is all package names. The value of this attribute must be of type + * {@code List}. */ public final static String CAPABILITY_LAZY_INCLUDE_ATTRIBUTE = "lazy.include"; //$NON-NLS-1$ /** * When the {@link #CAPABILITY_ACTIVATION_POLICY_LAZY lazy} policy is used this - * attribute contains the package names that must not - * trigger the activation when a class is loaded of these packages. - * If the attribute is not defined then the default is no package names. - * The value of this attribute must be of type {@code List}. + * attribute contains the package names that must not trigger the activation + * when a class is loaded of these packages. If the attribute is not defined + * then the default is no package names. The value of this attribute must be of + * type {@code List}. */ public final static String CAPABILITY_LAZY_EXCLUDE_ATTRIBUTE = "lazy.exclude"; //$NON-NLS-1$ /** - * The capability attribute contains the {@link Constants#BUNDLE_ACTIVATOR activator} - * for the providing module revision. The value of this attribute must be of type - * {@code String}. When not specified then the module revision has no activator. + * The capability attribute contains the {@link Constants#BUNDLE_ACTIVATOR + * activator} for the providing module revision. The value of this attribute + * must be of type {@code String}. When not specified then the module revision + * has no activator. */ public final static String CAPABILITY_ACTIVATOR = "activator"; //$NON-NLS-1$ /** - * The capability attribute contains the {@link Constants#BUNDLE_CLASSPATH class path} - * for the providing module revision. The value of this attribute must be of type - * {@code List}. When not specified the module revision uses the default - * class path of '.'. + * The capability attribute contains the {@link Constants#BUNDLE_CLASSPATH class + * path} for the providing module revision. The value of this attribute must be + * of type {@code List}. When not specified the module revision uses the + * default class path of '.'. */ public final static String CAPABILITY_CLASSPATH = "classpath"; //$NON-NLS-1$ /** - * The capability attribute contains the list buddy loading policies - * for the providing module revision as specified in the Eclipse-BuddyPolicy header. - * The value of this attribute must be of type - * {@code List}. + * The capability attribute contains the list buddy loading policies for the + * providing module revision as specified in the Eclipse-BuddyPolicy header. The + * value of this attribute must be of type {@code List}. */ public final static String CAPABILITY_BUDDY_POLICY = "buddy.policy"; //$NON-NLS-1$ /** - * The capability attribute contains the list of symbolic names the - * providing module revision is a registered buddy of as specified by - * the Eclipse-BuddyPolicy header. The value of this attribute must be of type + * The capability attribute contains the list of symbolic names the providing + * module revision is a registered buddy of as specified by the + * Eclipse-BuddyPolicy header. The value of this attribute must be of type * {@code List}. */ public final static String CAPABILITY_BUDDY_REGISTERED = "buddy.registered"; //$NON-NLS-1$ diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/framework/util/ArrayMap.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/framework/util/ArrayMap.java index fd94dfc67a7..c7bfe492f1c 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/framework/util/ArrayMap.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/framework/util/ArrayMap.java @@ -16,8 +16,8 @@ import java.util.*; /** - * Simple map when dealing with small amounts of entries. - * This class also provides a Collections view of the keys + * Simple map when dealing with small amounts of entries. This class also + * provides a Collections view of the keys * * @param The key type * @param the value type @@ -32,8 +32,9 @@ public ArrayMap(int initialCapacity) { } /** - * Note that the keys and values are not copied. Changes to this ArrayMap - * will change the values of the keys and values Lists. + * Note that the keys and values are not copied. Changes to this ArrayMap will + * change the values of the keys and values Lists. + * * @param keys * @param values */ @@ -106,18 +107,18 @@ public Iterator iterator() { final Iterator valueIter = values.iterator(); return new Iterator() { - @Override + @Override public boolean hasNext() { return keyIter.hasNext(); } - @Override + @Override public K next() { valueIter.next(); return keyIter.next(); } - @Override + @Override public void remove() { valueIter.remove(); keyIter.remove(); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/framework/util/CaseInsensitiveDictionaryMap.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/framework/util/CaseInsensitiveDictionaryMap.java index a067b6993c9..a956ad8bc58 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/framework/util/CaseInsensitiveDictionaryMap.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/framework/util/CaseInsensitiveDictionaryMap.java @@ -31,21 +31,24 @@ import org.osgi.framework.Constants; /** - * CaseInsensitiveDictionaryMap classes. This class implements Dictionary and Map with - * the following behavior: + * CaseInsensitiveDictionaryMap classes. This class implements Dictionary and + * Map with the following behavior: *

    - *
  • String keys are case-preserved, - * but the lookup operations are case-insensitive.
  • + *
  • String keys are case-preserved, but the lookup operations are + * case-insensitive.
  • *
  • Keys and values must not be null.
  • *
+ * * @since 3.13 */ public class CaseInsensitiveDictionaryMap extends Dictionary implements Map { // common core service property keys private static final CaseInsensitiveKey KEY_SERVICE_OBJECTCLASS = new CaseInsensitiveKey(Constants.OBJECTCLASS); private static final CaseInsensitiveKey KEY_SERVICE_BUNDLE_ID = new CaseInsensitiveKey(Constants.SERVICE_BUNDLEID); - private static final CaseInsensitiveKey KEY_SERVICE_CHANGECOUNT = new CaseInsensitiveKey(Constants.SERVICE_CHANGECOUNT); - private static final CaseInsensitiveKey KEY_SERVICE_DESCRIPTION = new CaseInsensitiveKey(Constants.SERVICE_DESCRIPTION); + private static final CaseInsensitiveKey KEY_SERVICE_CHANGECOUNT = new CaseInsensitiveKey( + Constants.SERVICE_CHANGECOUNT); + private static final CaseInsensitiveKey KEY_SERVICE_DESCRIPTION = new CaseInsensitiveKey( + Constants.SERVICE_DESCRIPTION); private static final CaseInsensitiveKey KEY_SERVICE_ID = new CaseInsensitiveKey(Constants.SERVICE_ID); private static final CaseInsensitiveKey KEY_SERVICE_PID = new CaseInsensitiveKey(Constants.SERVICE_PID); private static final CaseInsensitiveKey KEY_SERVICE_RANKING = new CaseInsensitiveKey(Constants.SERVICE_RANKING); @@ -69,119 +72,131 @@ public class CaseInsensitiveDictionaryMap extends Dictionary impleme // common bundle manifest headers private static final CaseInsensitiveKey KEY_JAR_MANIFESTVERSION = new CaseInsensitiveKey("Manifest-Version"); //$NON-NLS-1$ - private static final CaseInsensitiveKey KEY_BUNDLE_ACTIVATIONPOLICY = new CaseInsensitiveKey(Constants.BUNDLE_ACTIVATIONPOLICY); + private static final CaseInsensitiveKey KEY_BUNDLE_ACTIVATIONPOLICY = new CaseInsensitiveKey( + Constants.BUNDLE_ACTIVATIONPOLICY); private static final CaseInsensitiveKey KEY_BUNDLE_ACTIVATOR = new CaseInsensitiveKey(Constants.BUNDLE_ACTIVATOR); private static final CaseInsensitiveKey KEY_BUNDLE_CLASSPATH = new CaseInsensitiveKey(Constants.BUNDLE_CLASSPATH); - private static final CaseInsensitiveKey KEY_BUNDLE_DESCRIPTION = new CaseInsensitiveKey(Constants.BUNDLE_DESCRIPTION); + private static final CaseInsensitiveKey KEY_BUNDLE_DESCRIPTION = new CaseInsensitiveKey( + Constants.BUNDLE_DESCRIPTION); private static final CaseInsensitiveKey KEY_BUNDLE_LICENSE = new CaseInsensitiveKey(Constants.BUNDLE_LICENSE); - private static final CaseInsensitiveKey KEY_BUNDLE_LOCALIZATION = new CaseInsensitiveKey(Constants.BUNDLE_LOCALIZATION); - private static final CaseInsensitiveKey KEY_BUNDLE_MANIFESTVERSION = new CaseInsensitiveKey(Constants.BUNDLE_MANIFESTVERSION); + private static final CaseInsensitiveKey KEY_BUNDLE_LOCALIZATION = new CaseInsensitiveKey( + Constants.BUNDLE_LOCALIZATION); + private static final CaseInsensitiveKey KEY_BUNDLE_MANIFESTVERSION = new CaseInsensitiveKey( + Constants.BUNDLE_MANIFESTVERSION); private static final CaseInsensitiveKey KEY_BUNDLE_NAME = new CaseInsensitiveKey(Constants.BUNDLE_NAME); private static final CaseInsensitiveKey KEY_BUNDLE_NATIVECODE = new CaseInsensitiveKey(Constants.BUNDLE_NATIVECODE); @SuppressWarnings("deprecation") - private static final CaseInsensitiveKey KEY_BUNDLE_REQUIREDEXECUTIONENVIRONMENT = new CaseInsensitiveKey(Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT); + private static final CaseInsensitiveKey KEY_BUNDLE_REQUIREDEXECUTIONENVIRONMENT = new CaseInsensitiveKey( + Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT); private static final CaseInsensitiveKey KEY_BUNDLE_SCM = new CaseInsensitiveKey(Constants.BUNDLE_SCM); - private static final CaseInsensitiveKey KEY_BUNDLE_SYMBOLICNAME = new CaseInsensitiveKey(Constants.BUNDLE_SYMBOLICNAME); + private static final CaseInsensitiveKey KEY_BUNDLE_SYMBOLICNAME = new CaseInsensitiveKey( + Constants.BUNDLE_SYMBOLICNAME); private static final CaseInsensitiveKey KEY_BUNDLE_VENDOR = new CaseInsensitiveKey(Constants.BUNDLE_VENDOR); private static final CaseInsensitiveKey KEY_BUNDLE_VERSION = new CaseInsensitiveKey(Constants.BUNDLE_VERSION); - private static final CaseInsensitiveKey KEY_BUNDLE_DYNAMICIMPORT_PACKAGE = new CaseInsensitiveKey(Constants.DYNAMICIMPORT_PACKAGE); - private static final CaseInsensitiveKey KEY_BUNDLE_EXPORT_PACKAGE = new CaseInsensitiveKey(Constants.EXPORT_PACKAGE); + private static final CaseInsensitiveKey KEY_BUNDLE_DYNAMICIMPORT_PACKAGE = new CaseInsensitiveKey( + Constants.DYNAMICIMPORT_PACKAGE); + private static final CaseInsensitiveKey KEY_BUNDLE_EXPORT_PACKAGE = new CaseInsensitiveKey( + Constants.EXPORT_PACKAGE); private static final CaseInsensitiveKey KEY_BUNDLE_FRAGMENT_HOST = new CaseInsensitiveKey(Constants.FRAGMENT_HOST); - private static final CaseInsensitiveKey KEY_BUNDLE_IMPORT_PACKAGE = new CaseInsensitiveKey(Constants.IMPORT_PACKAGE); - private static final CaseInsensitiveKey KEY_BUNDLE_REQUIRE_BUNDLE = new CaseInsensitiveKey(Constants.REQUIRE_BUNDLE); - private static final CaseInsensitiveKey KEY_BUNDLE_REQUIRE_CAPABILITY = new CaseInsensitiveKey(Constants.REQUIRE_CAPABILITY); - private static final CaseInsensitiveKey KEY_BUNDLE_PROVIDE_CAPABILITY = new CaseInsensitiveKey(Constants.PROVIDE_CAPABILITY); + private static final CaseInsensitiveKey KEY_BUNDLE_IMPORT_PACKAGE = new CaseInsensitiveKey( + Constants.IMPORT_PACKAGE); + private static final CaseInsensitiveKey KEY_BUNDLE_REQUIRE_BUNDLE = new CaseInsensitiveKey( + Constants.REQUIRE_BUNDLE); + private static final CaseInsensitiveKey KEY_BUNDLE_REQUIRE_CAPABILITY = new CaseInsensitiveKey( + Constants.REQUIRE_CAPABILITY); + private static final CaseInsensitiveKey KEY_BUNDLE_PROVIDE_CAPABILITY = new CaseInsensitiveKey( + Constants.PROVIDE_CAPABILITY); @SuppressWarnings("deprecation") public static CaseInsensitiveKey findCommonKeyIndex(String key) { switch (key) { - // common core service property keys - case Constants.OBJECTCLASS : - return KEY_SERVICE_OBJECTCLASS; - case Constants.SERVICE_BUNDLEID : - return KEY_SERVICE_BUNDLE_ID; - case Constants.SERVICE_CHANGECOUNT : - return KEY_SERVICE_CHANGECOUNT; - case Constants.SERVICE_DESCRIPTION : - return KEY_SERVICE_DESCRIPTION; - case Constants.SERVICE_ID : - return KEY_SERVICE_ID; - case Constants.SERVICE_PID : - return KEY_SERVICE_PID; - case Constants.SERVICE_RANKING : - return KEY_SERVICE_RANKING; - case Constants.SERVICE_SCOPE : - return KEY_SERVICE_SCOPE; - case Constants.SERVICE_VENDOR : - return KEY_SERVICE_VENDER; - - // common SCR service property keys - case "component.name" : //$NON-NLS-1$ - return KEY_COMPONENT_NAME; - case "component.id" : //$NON-NLS-1$ - return KEY_COMPONENT_ID; - - // common meta-type property keys - case "metatype.pid" : //$NON-NLS-1$ - return KEY_METATYPE_PID; - case "metatype.factory.pid" : //$NON-NLS-1$ - return KEY_METATYPE_FACTORY_PID; - - // common event admin keys - case "event.topics" : //$NON-NLS-1$ - return KEY_EVENT_TOPICS; - case "event.filter" : //$NON-NLS-1$ - return KEY_EVENT_FILTER; - - // jmx keys - case "jmx.objectname" : //$NON-NLS-1$ - return KEY_JMX_OBJECTNAME; - - // common bundle manifest headers - case "Manifest-Version" : //$NON-NLS-1$ - return KEY_JAR_MANIFESTVERSION; - case Constants.BUNDLE_ACTIVATIONPOLICY : - return KEY_BUNDLE_ACTIVATIONPOLICY; - case Constants.BUNDLE_ACTIVATOR : - return KEY_BUNDLE_ACTIVATOR; - case Constants.BUNDLE_CLASSPATH : - return KEY_BUNDLE_CLASSPATH; - case Constants.BUNDLE_DESCRIPTION : - return KEY_BUNDLE_DESCRIPTION; - case Constants.BUNDLE_LICENSE : - return KEY_BUNDLE_LICENSE; - case Constants.BUNDLE_LOCALIZATION : - return KEY_BUNDLE_LOCALIZATION; - case Constants.BUNDLE_MANIFESTVERSION : - return KEY_BUNDLE_MANIFESTVERSION; - case Constants.BUNDLE_NAME : - return KEY_BUNDLE_NAME; - case Constants.BUNDLE_NATIVECODE : - return KEY_BUNDLE_NATIVECODE; - case Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT : - return KEY_BUNDLE_REQUIREDEXECUTIONENVIRONMENT; - case Constants.BUNDLE_SCM : - return KEY_BUNDLE_SCM; - case Constants.BUNDLE_SYMBOLICNAME : - return KEY_BUNDLE_SYMBOLICNAME; - case Constants.BUNDLE_VENDOR : - return KEY_BUNDLE_VENDOR; - case Constants.BUNDLE_VERSION : - return KEY_BUNDLE_VERSION; - case Constants.DYNAMICIMPORT_PACKAGE : - return KEY_BUNDLE_DYNAMICIMPORT_PACKAGE; - case Constants.EXPORT_PACKAGE : - return KEY_BUNDLE_EXPORT_PACKAGE; - case Constants.FRAGMENT_HOST : - return KEY_BUNDLE_FRAGMENT_HOST; - case Constants.IMPORT_PACKAGE : - return KEY_BUNDLE_IMPORT_PACKAGE; - case Constants.REQUIRE_BUNDLE : - return KEY_BUNDLE_REQUIRE_BUNDLE; - case Constants.REQUIRE_CAPABILITY : - return KEY_BUNDLE_REQUIRE_CAPABILITY; - case Constants.PROVIDE_CAPABILITY : - return KEY_BUNDLE_PROVIDE_CAPABILITY; + // common core service property keys + case Constants.OBJECTCLASS: + return KEY_SERVICE_OBJECTCLASS; + case Constants.SERVICE_BUNDLEID: + return KEY_SERVICE_BUNDLE_ID; + case Constants.SERVICE_CHANGECOUNT: + return KEY_SERVICE_CHANGECOUNT; + case Constants.SERVICE_DESCRIPTION: + return KEY_SERVICE_DESCRIPTION; + case Constants.SERVICE_ID: + return KEY_SERVICE_ID; + case Constants.SERVICE_PID: + return KEY_SERVICE_PID; + case Constants.SERVICE_RANKING: + return KEY_SERVICE_RANKING; + case Constants.SERVICE_SCOPE: + return KEY_SERVICE_SCOPE; + case Constants.SERVICE_VENDOR: + return KEY_SERVICE_VENDER; + + // common SCR service property keys + case "component.name": //$NON-NLS-1$ + return KEY_COMPONENT_NAME; + case "component.id": //$NON-NLS-1$ + return KEY_COMPONENT_ID; + + // common meta-type property keys + case "metatype.pid": //$NON-NLS-1$ + return KEY_METATYPE_PID; + case "metatype.factory.pid": //$NON-NLS-1$ + return KEY_METATYPE_FACTORY_PID; + + // common event admin keys + case "event.topics": //$NON-NLS-1$ + return KEY_EVENT_TOPICS; + case "event.filter": //$NON-NLS-1$ + return KEY_EVENT_FILTER; + + // jmx keys + case "jmx.objectname": //$NON-NLS-1$ + return KEY_JMX_OBJECTNAME; + + // common bundle manifest headers + case "Manifest-Version": //$NON-NLS-1$ + return KEY_JAR_MANIFESTVERSION; + case Constants.BUNDLE_ACTIVATIONPOLICY: + return KEY_BUNDLE_ACTIVATIONPOLICY; + case Constants.BUNDLE_ACTIVATOR: + return KEY_BUNDLE_ACTIVATOR; + case Constants.BUNDLE_CLASSPATH: + return KEY_BUNDLE_CLASSPATH; + case Constants.BUNDLE_DESCRIPTION: + return KEY_BUNDLE_DESCRIPTION; + case Constants.BUNDLE_LICENSE: + return KEY_BUNDLE_LICENSE; + case Constants.BUNDLE_LOCALIZATION: + return KEY_BUNDLE_LOCALIZATION; + case Constants.BUNDLE_MANIFESTVERSION: + return KEY_BUNDLE_MANIFESTVERSION; + case Constants.BUNDLE_NAME: + return KEY_BUNDLE_NAME; + case Constants.BUNDLE_NATIVECODE: + return KEY_BUNDLE_NATIVECODE; + case Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT: + return KEY_BUNDLE_REQUIREDEXECUTIONENVIRONMENT; + case Constants.BUNDLE_SCM: + return KEY_BUNDLE_SCM; + case Constants.BUNDLE_SYMBOLICNAME: + return KEY_BUNDLE_SYMBOLICNAME; + case Constants.BUNDLE_VENDOR: + return KEY_BUNDLE_VENDOR; + case Constants.BUNDLE_VERSION: + return KEY_BUNDLE_VERSION; + case Constants.DYNAMICIMPORT_PACKAGE: + return KEY_BUNDLE_DYNAMICIMPORT_PACKAGE; + case Constants.EXPORT_PACKAGE: + return KEY_BUNDLE_EXPORT_PACKAGE; + case Constants.FRAGMENT_HOST: + return KEY_BUNDLE_FRAGMENT_HOST; + case Constants.IMPORT_PACKAGE: + return KEY_BUNDLE_IMPORT_PACKAGE; + case Constants.REQUIRE_BUNDLE: + return KEY_BUNDLE_REQUIRE_BUNDLE; + case Constants.REQUIRE_CAPABILITY: + return KEY_BUNDLE_REQUIRE_CAPABILITY; + case Constants.PROVIDE_CAPABILITY: + return KEY_BUNDLE_PROVIDE_CAPABILITY; } return null; } @@ -207,9 +222,10 @@ public CaseInsensitiveDictionaryMap(int initialCapacity) { /** * Create a CaseInsensitiveDictionaryMap dictionary from a Dictionary. * - * @param dictionary The initial dictionary for this CaseInsensitiveDictionaryMap object. - * @throws IllegalArgumentException If a case-variants of a key are - * in the dictionary parameter. + * @param dictionary The initial dictionary for this + * CaseInsensitiveDictionaryMap object. + * @throws IllegalArgumentException If a case-variants of a key are in the + * dictionary parameter. */ public CaseInsensitiveDictionaryMap(Dictionary dictionary) { this(initialCapacity(dictionary.size())); @@ -234,8 +250,8 @@ public CaseInsensitiveDictionaryMap(Dictionary diction * Create a CaseInsensitiveDictionaryMap dictionary from a Map. * * @param map The initial map for this CaseInsensitiveDictionaryMap object. - * @throws IllegalArgumentException If a case-variants of a key are - * in the map parameter. + * @throws IllegalArgumentException If a case-variants of a key are in the map + * parameter. */ public CaseInsensitiveDictionaryMap(Map map) { this(initialCapacity(map.size())); @@ -293,8 +309,8 @@ public V get(Object key) { } /** - * Returns the specified key or, if the key is a String, returns - * a case-insensitive wrapping of the key. + * Returns the specified key or, if the key is a String, returns a + * case-insensitive wrapping of the key. * * @param key * @return The specified key or a case-insensitive wrapping of the key. @@ -432,8 +448,9 @@ public Collection values() { /** * {@inheritDoc} *

- * If the specified map has case-variants of a String key, only the last case-variant - * found while iterating over the entrySet will be present in this object. + * If the specified map has case-variants of a String key, only the last + * case-variant found while iterating over the entrySet will be present in this + * object. */ @Override public void putAll(Map m) { @@ -473,7 +490,8 @@ public Map asUnmodifiableMap() { /** * Return an unmodifiable dictionary wrapping this CaseInsensitiveDictionaryMap. * - * @return An unmodifiable dictionary wrapping this CaseInsensitiveDictionaryMap. + * @return An unmodifiable dictionary wrapping this + * CaseInsensitiveDictionaryMap. */ public Dictionary asUnmodifiableDictionary() { return unmodifiableDictionary(this); @@ -746,7 +764,8 @@ public boolean equals(Object obj) { Entry other = (Entry) obj; Object k1 = entry.getKey(); @SuppressWarnings("unchecked") - Object k2 = (other instanceof CaseInsentiveEntry) ? ((CaseInsentiveEntry) other).entry.getKey() : other.getKey(); + Object k2 = (other instanceof CaseInsentiveEntry) ? ((CaseInsentiveEntry) other).entry.getKey() + : other.getKey(); return Objects.equals(k1, k2) && Objects.equals(entry.getValue(), other.getValue()); } return false; diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/framework/util/FilePath.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/framework/util/FilePath.java index e3b5793d36a..a82ae32e36a 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/framework/util/FilePath.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/framework/util/FilePath.java @@ -18,8 +18,8 @@ /** * A utility class for manipulating file system paths. *

- * This class is not intended to be subclassed by clients but - * may be instantiated. + * This class is not intended to be subclassed by clients but may be + * instantiated. *

* * @since 3.1 @@ -37,7 +37,8 @@ public class FilePath { private final static String PARENT_DIR = ".."; //$NON-NLS-1$ private final static char SEPARATOR = '/'; private final static String UNC_SLASHES = "//"; //$NON-NLS-1$ - // if UNC, device will be \\host\share, otherwise, it will be letter/name + colon + // if UNC, device will be \\host\share, otherwise, it will be letter/name + + // colon private String device; private byte flags; private String[] segments; @@ -125,8 +126,8 @@ private String[] computeSegments(String path) { } /** - * Returns the device for this file system path, or null if - * none exists. The device string ends with a colon. + * Returns the device for this file system path, or null if none + * exists. The device string ends with a colon. * * @return the device string or null */ @@ -135,7 +136,8 @@ public String getDevice() { } /** - * Returns the segments in this path. If this path has no segments, returns an empty array. + * Returns the segments in this path. If this path has no segments, returns an + * empty array. * * @return an array containing all segments for this path */ @@ -158,8 +160,8 @@ private void initialize(String original) { // only deal with devices/UNC paths on Windows int deviceSeparatorPos = original.indexOf(DEVICE_SEPARATOR); if (deviceSeparatorPos >= 0) { - //extract device if any - //remove leading slash from device part to handle output of URL.getFile() + // extract device if any + // remove leading slash from device part to handle output of URL.getFile() int start = original.charAt(0) == SEPARATOR ? 1 : 0; device = original.substring(start, deviceSeparatorPos + 1); original = original.substring(deviceSeparatorPos + 1, original.length()); @@ -187,7 +189,8 @@ private void initialize(String original) { /** * Returns whether this path is absolute (begins with a slash). * - * @return true if this path is absolute, false otherwise + * @return true if this path is absolute, false + * otherwise */ public boolean isAbsolute() { return (flags & HAS_LEADING) != 0; @@ -196,12 +199,13 @@ public boolean isAbsolute() { /** * Returns a string representing this path as a relative to the given base path. *

- * If this path and the given path do not use the same device letter, this path's - * string representation is returned as is. + * If this path and the given path do not use the same device letter, this + * path's string representation is returned as is. *

* * @param base the path this path should be made relative to - * @return a string representation for this path as relative to the given base path + * @return a string representation for this path as relative to the given base + * path */ public String makeRelative(FilePath base) { if (base.device != null && !base.device.equalsIgnoreCase(this.device)) @@ -241,7 +245,7 @@ private int matchingFirstSegments(FilePath anotherPath) { /** * Returns a string representation of this path. * - * @return a string representation of this path + * @return a string representation of this path */ @Override public String toString() { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/framework/util/Headers.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/framework/util/Headers.java index bc6e00a50ab..7dfb6545c1b 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/framework/util/Headers.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/framework/util/Headers.java @@ -23,14 +23,15 @@ import org.osgi.framework.BundleException; /** - * Headers classes. This class implements a Dictionary that has - * the following behavior: + * Headers classes. This class implements a Dictionary that has the following + * behavior: *
    - *
  • put and remove clear throw UnsupportedOperationException. - * The Dictionary is thus read-only to others. - *
  • The String keys in the Dictionary are case-preserved, - * but the get operation is case-insensitive. + *
  • put and remove clear throw UnsupportedOperationException. The Dictionary + * is thus read-only to others. + *
  • The String keys in the Dictionary are case-preserved, but the get + * operation is case-insensitive. *
+ * * @since 3.1 * @deprecated As of 3.13. Replaced by {@link CaseInsensitiveDictionaryMap}. */ @@ -60,8 +61,8 @@ public Headers(int initialCapacity) { * Create a Headers dictionary from a Dictionary. * * @param values The initial dictionary for this Headers object. - * @exception IllegalArgumentException If a case-variant of the key is - * in the dictionary parameter. + * @exception IllegalArgumentException If a case-variant of the key is in the + * dictionary parameter. */ public Headers(Dictionary values) { this(values.size()); @@ -154,17 +155,17 @@ public synchronized V get(Object key) { /** * Set a header value or optionally replace it if it already exists. * - * @param key Key name. - * @param value Value of the key or null to remove key. - * @param replace A value of true will allow a previous - * value of the key to be replaced. A value of false - * will cause an IllegalArgumentException to be thrown - * if a previous value of the key exists. - * @return the previous value to which the key was mapped, - * or null if the key did not have a previous mapping. + * @param key Key name. + * @param value Value of the key or null to remove key. + * @param replace A value of true will allow a previous value of the key to be + * replaced. A value of false will cause an + * IllegalArgumentException to be thrown if a previous value of + * the key exists. + * @return the previous value to which the key was mapped, or null if the key + * did not have a previous mapping. * - * @exception IllegalArgumentException If a case-variant of the key is - * already present. + * @exception IllegalArgumentException If a case-variant of the key is already + * present. * @since 3.2 */ public synchronized V set(K key, V value, boolean replace) { @@ -195,13 +196,13 @@ public synchronized V set(K key, V value, boolean replace) { /** * Set a header value. * - * @param key Key name. + * @param key Key name. * @param value Value of the key or null to remove key. - * @return the previous value to which the key was mapped, - * or null if the key did not have a previous mapping. + * @return the previous value to which the key was mapped, or null if the key + * did not have a previous mapping. * - * @exception IllegalArgumentException If a case-variant of the key is - * already present. + * @exception IllegalArgumentException If a case-variant of the key is already + * present. */ public synchronized V set(K key, V value) { return set(key, value, false); @@ -214,7 +215,7 @@ public synchronized void setReadOnly() { /** * Returns the number of entries (distinct keys) in this dictionary. * - * @return the number of keys in this dictionary. + * @return the number of keys in this dictionary. */ @Override public synchronized int size() { @@ -222,12 +223,12 @@ public synchronized int size() { } /** - * Tests if this dictionary maps no keys to value. The general contract - * for the isEmpty method is that the result is true if and only - * if this dictionary contains no entries. + * Tests if this dictionary maps no keys to value. The general contract for the + * isEmpty method is that the result is true if and only if this + * dictionary contains no entries. * - * @return true if this dictionary maps no keys to values; - * false otherwise. + * @return true if this dictionary maps no keys to values; + * false otherwise. */ @Override public synchronized boolean isEmpty() { @@ -237,7 +238,7 @@ public synchronized boolean isEmpty() { /** * Always throws UnsupportedOperationException. * - * @param key header name. + * @param key header name. * @param value header value. * @throws UnsupportedOperationException */ diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/framework/util/KeyedElement.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/framework/util/KeyedElement.java index 10bc792dec5..0a4b8e9ea3a 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/framework/util/KeyedElement.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/framework/util/KeyedElement.java @@ -14,26 +14,30 @@ package org.eclipse.osgi.framework.util; /** - * NOTE: This interface defines an element that could be inserted into an internal class called - * KeyedHashSet. This internal class KeyedHashSet has been deleted. - * The KeyedElement interface has remained because of the use of it in ClasspathEntry. - * A keyed element can easily be put into a standard Map implementation by using the keyed element - * key for the mapping. + * NOTE: This interface defines an element that could be inserted into an + * internal class called KeyedHashSet. This internal class + * KeyedHashSet has been deleted. The KeyedElement interface has + * remained because of the use of it in ClasspathEntry. A keyed + * element can easily be put into a standard Map implementation by using the + * keyed element key for the mapping. *

- * An element of an KeyedHashSet. A KeyedElement privides the key which is used to hash - * the elements in an KeyedHashSet. + * An element of an KeyedHashSet. A KeyedElement privides the key + * which is used to hash the elements in an KeyedHashSet. + * * @since 3.2 */ // This class was moved from /org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/KeyedElement.java public interface KeyedElement { /** * Returns the hash code of the key + * * @return the hash code of the key */ public int getKeyHashCode(); /** * Compares this element with a specified element + * * @param other the element to compare with * @return returns true if the specified element equals this element */ @@ -41,6 +45,7 @@ public interface KeyedElement { /** * Returns the key for this element + * * @return the key for this element */ public Object getKey(); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/framework/util/ObjectPool.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/framework/util/ObjectPool.java index e684835112e..9dc12ee26fd 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/framework/util/ObjectPool.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/framework/util/ObjectPool.java @@ -19,8 +19,10 @@ import org.eclipse.osgi.internal.debug.Debug; public class ObjectPool { - //private static String OPTION_DEBUG_OBJECTPOOL_ADDS = Debug.ECLIPSE_OSGI + "/debug/objectPool/adds"; //$NON-NLS-1$ - //private static String OPTION_DEBUG_OBJECTPOOL_DUPS = Debug.ECLIPSE_OSGI + "/debug/objectPool/dups"; //$NON-NLS-1$ + // private static String OPTION_DEBUG_OBJECTPOOL_ADDS = Debug.ECLIPSE_OSGI + + // "/debug/objectPool/adds"; //$NON-NLS-1$ + // private static String OPTION_DEBUG_OBJECTPOOL_DUPS = Debug.ECLIPSE_OSGI + + // "/debug/objectPool/dups"; //$NON-NLS-1$ // TODO need to set these private static final boolean DEBUG_OBJECTPOOL_ADDS = false; private static final boolean DEBUG_OBJECTPOOL_DUPS = false; @@ -40,7 +42,8 @@ public static T intern(T obj) { } else { objectCache.put(obj, new WeakReference<>(obj)); if (DEBUG_OBJECTPOOL_ADDS) - Debug.println("[ObjectPool] Added unique object to pool: " + getObjectString(obj) + " Pool size: " + objectCache.size()); //$NON-NLS-1$ //$NON-NLS-2$ + Debug.println("[ObjectPool] Added unique object to pool: " + getObjectString(obj) + " Pool size: " //$NON-NLS-1$ //$NON-NLS-2$ + + objectCache.size()); } } return obj; diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/framework/util/SecureAction.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/framework/util/SecureAction.java index 255f3a9a2aa..5b1f6ae9727 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/framework/util/SecureAction.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/framework/util/SecureAction.java @@ -40,28 +40,31 @@ /** * Utility class to execute common privileged code. + * * @since 3.1 */ public class SecureAction { // make sure we use the correct controlContext; private AccessControlContext controlContext; - // uses initialization-on-demand holder idiom to do fast lazy loading + // uses initialization-on-demand holder idiom to do fast lazy loading private static class BootClassLoaderHolder { - // This ClassLoader is used in loadSystemClass if System.getClassLoader() returns null + // This ClassLoader is used in loadSystemClass if System.getClassLoader() + // returns null static final ClassLoader bootClassLoader = AccessController.doPrivileged(new PrivilegedAction() { @Override public ClassLoader run() { - return new ClassLoader(Object.class.getClassLoader()) { /* boot class loader */}; + return new ClassLoader(Object.class.getClassLoader()) { + /* boot class loader */}; } }); - } + } /* - * Package privaet constructor a new SecureAction object. - * The constructed SecureAction object uses the caller's AccessControlContext - * to perform security checks + * Package privaet constructor a new SecureAction object. The constructed + * SecureAction object uses the caller's AccessControlContext to perform + * security checks */ SecureAction() { // save the control context to be used. @@ -69,12 +72,17 @@ public ClassLoader run() { } /** - * Creates a privileged action that can be used to construct a SecureAction object. - * The recommended way to construct a SecureAction object is the following:

+ * Creates a privileged action that can be used to construct a SecureAction + * object. The recommended way to construct a SecureAction object is the + * following: + *

+ * *

 	 * SecureAction secureAction = (SecureAction) AccessController.doPrivileged(SecureAction.createSecureAction());
 	 * 
- * @return a privileged action object that can be used to construct a SecureAction object. + * + * @return a privileged action object that can be used to construct a + * SecureAction object. */ public static PrivilegedAction createSecureAction() { return new PrivilegedAction() { @@ -86,8 +94,8 @@ public SecureAction run() { } /** - * Returns a system property. Same as calling - * System.getProperty(String). + * Returns a system property. Same as calling System.getProperty(String). + * * @param property the property key. * @return the value of the property or null if it does not exist. */ @@ -103,8 +111,8 @@ public String run() { } /** - * Returns a system properties. Same as calling - * System.getProperties(). + * Returns a system properties. Same as calling System.getProperties(). + * * @return the system properties. */ public Properties getProperties() { @@ -119,8 +127,9 @@ public Properties run() { } /** - * Creates a FileInputStream from a File. Same as calling - * new FileInputStream(File). + * Creates a FileInputStream from a File. Same as calling new + * FileInputStream(File). + * * @param file the File to craete a FileInputStream from. * @return The FileInputStream. * @throws FileNotFoundException if the File does not exist. @@ -143,9 +152,10 @@ public FileInputStream run() throws FileNotFoundException { } /** - * Creates a FileInputStream from a File. Same as calling - * new FileOutputStream(File,boolean). - * @param file the File to create a FileOutputStream from. + * Creates a FileInputStream from a File. Same as calling new + * FileOutputStream(File,boolean). + * + * @param file the File to create a FileOutputStream from. * @param append indicates if the OutputStream should append content. * @return The FileOutputStream. * @throws FileNotFoundException if the File does not exist. @@ -168,8 +178,8 @@ public FileOutputStream run() throws FileNotFoundException { } /** - * Returns the length of a file. Same as calling - * file.length(). + * Returns the length of a file. Same as calling file.length(). + * * @param file a file object * @return the length of a file. */ @@ -185,8 +195,9 @@ public Long run() { } /** - * Returns the canonical path of a file. Same as calling + * Returns the canonical path of a file. Same as calling * file.getCanonicalPath(). + * * @param file a file object * @return the canonical path of a file. * @throws IOException on error @@ -209,8 +220,8 @@ public String run() throws IOException { } /** - * Returns the absolute file. Same as calling - * file.getAbsoluteFile(). + * Returns the absolute file. Same as calling file.getAbsoluteFile(). + * * @param file a file object * @return the absolute file. */ @@ -225,10 +236,9 @@ public File run() { }, controlContext); } - /** - * Returns the canonical file. Same as calling - * file.getCanonicalFile(). + * Returns the canonical file. Same as calling file.getCanonicalFile(). + * * @param file a file object * @return the canonical file. */ @@ -250,8 +260,9 @@ public File run() throws IOException { } /** - * Returns true if a file exists, otherwise false is returned. Same as calling + * Returns true if a file exists, otherwise false is returned. Same as calling * file.exists(). + * * @param file a file object * @return true if a file exists, otherwise false */ @@ -278,8 +289,9 @@ public Boolean run() { } /** - * Returns true if a file is a directory, otherwise false is returned. Same as calling - * file.isDirectory(). + * Returns true if a file is a directory, otherwise false is returned. Same as + * calling file.isDirectory(). + * * @param file a file object * @return true if a file is a directory, otherwise false */ @@ -295,8 +307,8 @@ public Boolean run() { } /** - * Returns a file's last modified stamp. Same as calling - * file.lastModified(). + * Returns a file's last modified stamp. Same as calling file.lastModified(). + * * @param file a file object * @return a file's last modified stamp. */ @@ -312,8 +324,8 @@ public Long run() { } /** - * Returns a file's list. Same as calling - * file.list(). + * Returns a file's list. Same as calling file.list(). + * * @param file a file object * @return a file's list. */ @@ -364,15 +376,17 @@ public ZipFile run() throws IOException { /** * Gets a URL. Same a calling * {@link URL#URL(java.lang.String, java.lang.String, int, java.lang.String, java.net.URLStreamHandler)} + * * @param protocol the protocol - * @param host the host - * @param port the port - * @param file the file - * @param handler the URLStreamHandler + * @param host the host + * @param port the port + * @param file the file + * @param handler the URLStreamHandler * @return a URL * @throws MalformedURLException */ - public URL getURL(final String protocol, final String host, final int port, final String file, final URLStreamHandler handler) throws MalformedURLException { + public URL getURL(final String protocol, final String host, final int port, final String file, + final URLStreamHandler handler) throws MalformedURLException { if (System.getSecurityManager() == null) return new URL(protocol, host, port, file, handler); try { @@ -390,10 +404,11 @@ public URL run() throws MalformedURLException { } /** - * Creates a new Thread from a Runnable. Same as calling - * new Thread(target,name).setContextClassLoader(contextLoader). - * @param target the Runnable to create the Thread from. - * @param name The name of the Thread. + * Creates a new Thread from a Runnable. Same as calling new + * Thread(target,name).setContextClassLoader(contextLoader). + * + * @param target the Runnable to create the Thread from. + * @param name The name of the Thread. * @param contextLoader the context class loader for the thread * @return The new Thread */ @@ -416,10 +431,10 @@ Thread createThread0(Runnable target, String name, ClassLoader contextLoader) { } /** - * Gets a service object. Same as calling - * context.getService(reference) + * Gets a service object. Same as calling context.getService(reference) + * * @param reference the ServiceReference - * @param context the BundleContext + * @param context the BundleContext * @return a service object */ public S getService(final ServiceReference reference, final BundleContext context) { @@ -434,8 +449,8 @@ public S run() { } /** - * Returns a Class. Same as calling - * Class.forName(name) + * Returns a Class. Same as calling Class.forName(name) + * * @param name the name of the class. * @return a Class * @throws ClassNotFoundException @@ -458,8 +473,9 @@ public Class run() throws Exception { } /** - * Returns a Class. - * Tries to load a class from the System ClassLoader or if that doesn't exist tries the boot ClassLoader + * Returns a Class. Tries to load a class from the System ClassLoader or if that + * doesn't exist tries the boot ClassLoader + * * @param name the name of the class. * @return a Class * @throws ClassNotFoundException @@ -467,14 +483,16 @@ public Class run() throws Exception { public Class loadSystemClass(final String name) throws ClassNotFoundException { if (System.getSecurityManager() == null) { ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader(); - return (systemClassLoader != null) ? systemClassLoader.loadClass(name) : BootClassLoaderHolder.bootClassLoader.loadClass(name); + return (systemClassLoader != null) ? systemClassLoader.loadClass(name) + : BootClassLoaderHolder.bootClassLoader.loadClass(name); } try { return AccessController.doPrivileged(new PrivilegedExceptionAction>() { @Override public Class run() throws Exception { ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader(); - return (systemClassLoader != null) ? systemClassLoader.loadClass(name) : BootClassLoaderHolder.bootClassLoader.loadClass(name); + return (systemClassLoader != null) ? systemClassLoader.loadClass(name) + : BootClassLoaderHolder.bootClassLoader.loadClass(name); } }, controlContext); } catch (PrivilegedActionException e) { @@ -486,6 +504,7 @@ public Class run() throws Exception { /** * Opens a ServiceTracker. Same as calling tracker.open() + * * @param tracker the ServiceTracker to open. */ public void open(final ServiceTracker tracker) { @@ -504,7 +523,8 @@ public Void run() { /** * Starts a module. - * @param module the module to start + * + * @param module the module to start * @param options the start options * @throws BundleException */ diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/framework/util/ThreadInfoReport.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/framework/util/ThreadInfoReport.java index 405b96c3a55..c745f9046f8 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/framework/util/ThreadInfoReport.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/framework/util/ThreadInfoReport.java @@ -27,7 +27,8 @@ public static String getThreadDump(String failedMonitor) { long currentId = Thread.currentThread().getId(); ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); StringBuilder dump = new StringBuilder("Thread dump"); //$NON-NLS-1$ - ThreadInfo[] infos = threadMXBean.dumpAllThreads(threadMXBean.isObjectMonitorUsageSupported(), threadMXBean.isSynchronizerUsageSupported()); + ThreadInfo[] infos = threadMXBean.dumpAllThreads(threadMXBean.isObjectMonitorUsageSupported(), + threadMXBean.isSynchronizerUsageSupported()); for (ThreadInfo info : infos) { dumpThreadIDNameState(info, dump); dumpLockInfo(currentId, failedMonitor, info, dump); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/cds/CDSBundleEntry.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/cds/CDSBundleEntry.java index 1c60e0230de..01c1788706f 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/cds/CDSBundleEntry.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/cds/CDSBundleEntry.java @@ -37,7 +37,8 @@ public class CDSBundleEntry extends BundleEntry { /** * The constructor - * @param path the path to the class file + * + * @param path the path to the class file * @param classbytes the magic cookie bytes for the class in the shared cache * @param bundleFile the bundle file where the class comes from */ @@ -58,9 +59,10 @@ private BundleEntry getWrappedEntry() { /* * (non-Javadoc) - * @see org.eclipse.osgi.baseadaptor.bundlefile.BundleEntry#getFileURL() - * uses the wrapped bundle file to get the actual file url to the content of - * the class on disk. + * + * @see org.eclipse.osgi.baseadaptor.bundlefile.BundleEntry#getFileURL() uses + * the wrapped bundle file to get the actual file url to the content of the + * class on disk. * * This should is likely never to be called. */ @@ -71,9 +73,10 @@ public URL getFileURL() { /* * (non-Javadoc) + * * @see org.eclipse.osgi.baseadaptor.bundlefile.BundleEntry#getInputStream() - * wraps the classbytes into a ByteArrayInputStream. This should not be used - * by classloading. + * wraps the classbytes into a ByteArrayInputStream. This should not be used by + * classloading. */ @Override public InputStream getInputStream() throws IOException { @@ -84,10 +87,11 @@ public InputStream getInputStream() throws IOException { /* * (non-Javadoc) - * @see org.eclipse.osgi.baseadaptor.bundlefile.BundleEntry#getBytes() - * if classbytes is not null, it returns the magic cookie for the shared class. This is used to define - * the class during class loading. - * if classbytes is null, it gets the contents from actual BundleEntry and caches it in classbytes. + * + * @see org.eclipse.osgi.baseadaptor.bundlefile.BundleEntry#getBytes() if + * classbytes is not null, it returns the magic cookie for the shared class. + * This is used to define the class during class loading. if classbytes is null, + * it gets the contents from actual BundleEntry and caches it in classbytes. */ @Override public byte[] getBytes() throws IOException { @@ -96,9 +100,10 @@ public byte[] getBytes() throws IOException { /* * (non-Javadoc) - * @see org.eclipse.osgi.baseadaptor.bundlefile.BundleEntry#getLocalURL() - * uses the wrapped bundle file to get the actual local url to the content of - * the class on disk. + * + * @see org.eclipse.osgi.baseadaptor.bundlefile.BundleEntry#getLocalURL() uses + * the wrapped bundle file to get the actual local url to the content of the + * class on disk. * * This should is likely never to be called. */ diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/cds/CDSBundleFile.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/cds/CDSBundleFile.java index beb6373b923..132440b6ca9 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/cds/CDSBundleFile.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/cds/CDSBundleFile.java @@ -41,6 +41,7 @@ public class CDSBundleFile extends BundleFileWrapper { /** * The constructor + * * @param wrapped the real bundle file */ public CDSBundleFile(BundleFile wrapped) { @@ -62,12 +63,15 @@ public CDSBundleFile(BundleFile bundleFile, SharedClassURLHelper urlHelper) { /* * (non-Javadoc) - * @see org.eclipse.osgi.storage.bundlefile.BundleFile#getEntry(java.lang.String) + * + * @see + * org.eclipse.osgi.storage.bundlefile.BundleFile#getEntry(java.lang.String) * - * If path is not for a class then just use the wrapped bundle file to answer the call. - * If the path is for a class, it returns a CDSBundleEntry object. - * If the path is for a class, it will look for the magic cookie in the - * shared classes cache. If found, the bytes representing the magic cookie are stored in CDSBundleEntry object. + * If path is not for a class then just use the wrapped bundle file to answer + * the call. If the path is for a class, it returns a CDSBundleEntry object. If + * the path is for a class, it will look for the magic cookie in the shared + * classes cache. If found, the bytes representing the magic cookie are stored + * in CDSBundleEntry object. */ @Override public BundleEntry getEntry(String path) { @@ -89,6 +93,7 @@ BundleEntry getWrappedEntry(String path) { /** * Returns the file url to the content of the actual bundle file + * * @return the file url to the content of the actual bundle file */ URL getURL() { @@ -96,8 +101,9 @@ URL getURL() { } /** - * Returns the url helper for this bundle file. This is set by the - * class loading hook + * Returns the url helper for this bundle file. This is set by the class loading + * hook + * * @return the url helper for this bundle file */ SharedClassURLHelper getURLHelper() { @@ -105,8 +111,9 @@ SharedClassURLHelper getURLHelper() { } /** - * Sets the url helper for this bundle file. This is called by the - * class loading hook. + * Sets the url helper for this bundle file. This is called by the class loading + * hook. + * * @param urlHelper the url helper */ void setURLHelper(SharedClassURLHelper urlHelper) { @@ -115,9 +122,9 @@ void setURLHelper(SharedClassURLHelper urlHelper) { } /** - * Sets the primed flag for the bundle file. This is called by the - * class loading hook after the first class has been loaded from disk for - * this bundle file. + * Sets the primed flag for the bundle file. This is called by the class loading + * hook after the first class has been loaded from disk for this bundle file. + * * @param primed the primed flag */ void setPrimed(boolean primed) { @@ -126,8 +133,10 @@ void setPrimed(boolean primed) { /** * Searches in the shared classes cache for the specified class name. + * * @param name the name of the class - * @return the magic cookie to the shared class or null if the class is not in the cache. + * @return the magic cookie to the shared class or null if the class is not in + * the cache. */ private byte[] getClassBytes(String name) { if (urlHelper == null || url == null) @@ -137,6 +146,7 @@ private byte[] getClassBytes(String name) { /** * Returns the primed flag for this bundle file. + * * @return the primed flag */ public boolean getPrimed() { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/cds/CDSHookConfigurator.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/cds/CDSHookConfigurator.java index fdd59114e19..6d4b82ae455 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/cds/CDSHookConfigurator.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/cds/CDSHookConfigurator.java @@ -57,7 +57,9 @@ public void addHooks(HookRegistry hookRegistry) { if (reportErrors) { EquinoxContainer container = hookRegistry.getContainer(); EquinoxLogServices logServices = container.getLogServices(); - logServices.log(EquinoxContainer.NAME, FrameworkLogEntry.WARNING, "The J9 Class Sharing Adaptor will not work in this configuration. You are not running on a J9 Java VM.", null); //$NON-NLS-1$ + logServices.log(EquinoxContainer.NAME, FrameworkLogEntry.WARNING, + "The J9 Class Sharing Adaptor will not work in this configuration. You are not running on a J9 Java VM.", //$NON-NLS-1$ + null); } return; } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/cds/CDSHookImpls.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/cds/CDSHookImpls.java index dfdc81998dd..36383098f27 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/cds/CDSHookImpls.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/cds/CDSHookImpls.java @@ -47,12 +47,13 @@ public class CDSHookImpls extends ClassLoaderHook implements BundleFileWrapperFa private static SharedClassHelperFactory factory = Shared.getSharedClassHelperFactory(); // With Equinox bug 226038 (v3.4), the framework will now pass an instance - // of BundleFileWrapperChain rather than the wrapped BundleFile. This is + // of BundleFileWrapperChain rather than the wrapped BundleFile. This is // so that multiple wrapping hooks can each wrap the BundleFile and all // wrappers are accessible. // // The Wrapper chain will look like below: - // WrapperChain -> Wrapper -> WrapperChain -> CDSBundleFile -> WrapperChain -> BundleFile + // WrapperChain -> Wrapper -> WrapperChain -> CDSBundleFile -> WrapperChain + // -> BundleFile // private static CDSBundleFile getCDSBundleFile(BundleFile bundleFile) { if (bundleFile instanceof BundleFileWrapperChain) { @@ -62,12 +63,15 @@ private static CDSBundleFile getCDSBundleFile(BundleFile bundleFile) { } @Override - public void recordClassDefine(String name, Class clazz, byte[] classbytes, ClasspathEntry classpathEntry, BundleEntry entry, ClasspathManager manager) { // only attempt to record the class define if: + public void recordClassDefine(String name, Class clazz, byte[] classbytes, ClasspathEntry classpathEntry, + BundleEntry entry, ClasspathManager manager) { // only attempt to record the class define if: // 1) the class was found (clazz != null) // 2) the class has the magic class number CAFEBABE indicating a real class // 3) the bundle file for the classpath entry is of type CDSBundleFile - // 4) class bytes is same as passed to weaving hook i.e. weaving hook did not modify the class bytes - if ((null == clazz) || (false == hasMagicClassNumber(classbytes)) || (null == getCDSBundleFile(classpathEntry.getBundleFile()))) { + // 4) class bytes is same as passed to weaving hook i.e. weaving hook did not + // modify the class bytes + if ((null == clazz) || (false == hasMagicClassNumber(classbytes)) + || (null == getCDSBundleFile(classpathEntry.getBundleFile()))) { return; } try { @@ -84,7 +88,8 @@ public void recordClassDefine(String name, Class clazz, byte[] classbytes, Cl } if (modified) { // Class bytes have been modified by weaving hooks. - // Such classes need to be stored as Orphans, so skip the call to storeSharedClass() + // Such classes need to be stored as Orphans, so skip the call to + // storeSharedClass() return; } } @@ -100,10 +105,12 @@ public void recordClassDefine(String name, Class clazz, byte[] classbytes, Cl return; } - // look for the urlHelper; if it does not exist then we are not sharing for this class loader + // look for the urlHelper; if it does not exist then we are not sharing for this + // class loader SharedClassURLHelper urlHelper = cdsFile.getURLHelper(); if (urlHelper == null) { - // this should never happen but just in case get the helper from the base host bundle file. + // this should never happen but just in case get the helper from the base host + // bundle file. CDSBundleFile hostBundleFile = getCDSBundleFile(manager.getGeneration().getBundleFile()); if (null != hostBundleFile) { // try getting the helper from the host base cdsFile @@ -124,8 +131,10 @@ public void recordClassDefine(String name, Class clazz, byte[] classbytes, Cl private boolean hasMagicClassNumber(byte[] classbytes) { if (classbytes == null || classbytes.length < 4) return false; - // TODO maybe there is a better way to do this? I'm not sure why I had to AND each byte with the value I was checking ... - return (classbytes[0] & 0xCA) == 0xCA && (classbytes[1] & 0xFE) == 0xFE && (classbytes[2] & 0xBA) == 0xBA && (classbytes[3] & 0xBE) == 0xBE; + // TODO maybe there is a better way to do this? I'm not sure why I had to AND + // each byte with the value I was checking ... + return (classbytes[0] & 0xCA) == 0xCA && (classbytes[1] & 0xFE) == 0xFE && (classbytes[2] & 0xBA) == 0xBA + && (classbytes[3] & 0xBE) == 0xBE; } @Override @@ -138,7 +147,8 @@ public void classLoaderCreated(ModuleClassLoader classLoader) { SharedClassURLHelper urlHelper = factory.getURLHelper(classLoader); boolean minimizeUpdateChecks = urlHelper.setMinimizeUpdateChecks(); // set the url helper for the host base CDSBundleFile - CDSBundleFile hostFile = getCDSBundleFile(classLoader.getClasspathManager().getGeneration().getBundleFile()); + CDSBundleFile hostFile = getCDSBundleFile( + classLoader.getClasspathManager().getGeneration().getBundleFile()); if (hostFile != null) { hostFile.setURLHelper(urlHelper); if (minimizeUpdateChecks) { @@ -176,11 +186,13 @@ public void classLoaderCreated(ModuleClassLoader classLoader) { } @Override - public boolean addClassPathEntry(ArrayList cpEntries, String cp, ClasspathManager hostmanager, Generation sourceGeneration) { + public boolean addClassPathEntry(ArrayList cpEntries, String cp, ClasspathManager hostmanager, + Generation sourceGeneration) { CDSBundleFile hostFile = getCDSBundleFile(hostmanager.getGeneration().getBundleFile()); CDSBundleFile sourceFile = getCDSBundleFile(sourceGeneration.getBundleFile()); if ((hostFile != sourceFile) && (null != hostFile) && (null != sourceFile)) { - // Set the helper that got set on the host base bundle file in classLoaderCreated. + // Set the helper that got set on the host base bundle file in + // classLoaderCreated. // This is to handle the case where fragments are dynamically attached SharedClassURLHelper urlHelper = hostFile.getURLHelper(); sourceFile.setURLHelper(urlHelper); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/connect/ConnectBundleFile.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/connect/ConnectBundleFile.java index 5b85e231369..f0bd0cd840e 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/connect/ConnectBundleFile.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/connect/ConnectBundleFile.java @@ -84,7 +84,8 @@ public URL getLocalURL() { private final ConnectContent content; - public ConnectBundleFile(ConnectModule module, File basefile, BundleInfo.Generation generation, MRUBundleFileList mruList, Debug debug) throws IOException { + public ConnectBundleFile(ConnectModule module, File basefile, BundleInfo.Generation generation, + MRUBundleFileList mruList, Debug debug) throws IOException { super(basefile, generation, mruList, debug); this.content = module.getContent(); } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/connect/ConnectHookConfigurator.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/connect/ConnectHookConfigurator.java index 3ac050a0499..beab2bf3946 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/connect/ConnectHookConfigurator.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/connect/ConnectHookConfigurator.java @@ -81,12 +81,14 @@ public void load(Object loadContext, DataInputStream is) throws IOException { public void validate() throws IllegalStateException { // make sure we have the module still from the factory if (hasModule && m == null) { - throw new IllegalStateException("Connect Factory no longer has the module at locataion: " + generation.getBundleInfo().getLocation()); //$NON-NLS-1$ + throw new IllegalStateException("Connect Factory no longer has the module at locataion: " //$NON-NLS-1$ + + generation.getBundleInfo().getLocation()); } } @Override - public ModuleRevisionBuilder adaptModuleRevisionBuilder(ModuleEvent operation, Module origin, ModuleRevisionBuilder builder) { + public ModuleRevisionBuilder adaptModuleRevisionBuilder(ModuleEvent operation, Module origin, + ModuleRevisionBuilder builder) { if (m != null) { CONNECT_TAG_NAMESPACES.stream().map(builder::getCapabilities).flatMap(List::stream) .forEach(c -> c.getAttributes().compute(IdentityNamespace.CAPABILITY_TAGS_ATTRIBUTE, @@ -139,7 +141,8 @@ public URLConnection handleContentConnection(Module module, String location, Inp hookRegistry.addClassLoaderHook(new ClassLoaderHook() { @Override - public ModuleClassLoader createClassLoader(ClassLoader parent, EquinoxConfiguration configuration, BundleLoader delegate, Generation generation) { + public ModuleClassLoader createClassLoader(ClassLoader parent, EquinoxConfiguration configuration, + BundleLoader delegate, Generation generation) { ConnectModule m = connectModules.getConnectModule(generation.getBundleInfo().getLocation()); if (m != null) { BundleFile bundlefile = generation.getBundleFile(); @@ -152,7 +155,8 @@ public ModuleClassLoader createClassLoader(ClassLoader parent, EquinoxConfigurat } if (bundlefile instanceof ConnectBundleFile) { return ((ConnectBundleFile) bundlefile).getClassLoader().map( - l -> new DelegatingConnectClassLoader(parent, configuration, delegate, generation, l)).orElse(null); + l -> new DelegatingConnectClassLoader(parent, configuration, delegate, generation, l)) + .orElse(null); } } return null; diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/connect/ConnectInputStream.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/connect/ConnectInputStream.java index 1d5ed6992b2..383597f917c 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/connect/ConnectInputStream.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/connect/ConnectInputStream.java @@ -36,7 +36,8 @@ public InputStream getInputStream() throws IOException { private ConnectInputStream() { } - /* This method should not be called. + /* + * This method should not be called. */ @Override public int read() throws IOException { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/connect/DelegatingConnectClassLoader.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/connect/DelegatingConnectClassLoader.java index 0b03defd444..381920995d3 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/connect/DelegatingConnectClassLoader.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/connect/DelegatingConnectClassLoader.java @@ -32,7 +32,8 @@ public class DelegatingConnectClassLoader extends EquinoxClassLoader { } private final ClassLoader connectClassLoader; - public DelegatingConnectClassLoader(ClassLoader parent, EquinoxConfiguration configuration, BundleLoader delegate, Generation generation, ClassLoader connectClassLoader) { + public DelegatingConnectClassLoader(ClassLoader parent, EquinoxConfiguration configuration, BundleLoader delegate, + Generation generation, ClassLoader connectClassLoader) { super(parent, configuration, delegate, generation); this.connectClassLoader = connectClassLoader; } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/container/AtomicLazyInitializer.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/container/AtomicLazyInitializer.java index c0d6cd7f80d..f16ff198116 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/container/AtomicLazyInitializer.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/container/AtomicLazyInitializer.java @@ -25,8 +25,9 @@ public class AtomicLazyInitializer { private final AtomicReference holder = new AtomicReference<>(); /** - * Gets the current value. If the value has not been initialized then + * Gets the current value. If the value has not been initialized then * {@code null} is returned; + * * @return the current value */ public final V get() { @@ -34,10 +35,14 @@ public final V get() { } /** - * Atomically gets the current initialized value. If the current value is {@code null} - * then the supplied initializer is called to create the value returned. - * @param initializer the initializer to call if the current value is {@code null} - * @return the initialized value. May return {@code null} if initializer returns null. + * Atomically gets the current initialized value. If the current value is + * {@code null} then the supplied initializer is called to create the value + * returned. + * + * @param initializer the initializer to call if the current value is + * {@code null} + * @return the initialized value. May return {@code null} if initializer returns + * null. */ public final V getInitialized(Callable initializer) { V result = holder.get(); @@ -61,7 +66,9 @@ public final V getInitialized(Callable initializer) { } /** - * Gets the current value and clears the value for future calls to this lazy initializer. + * Gets the current value and clears the value for future calls to this lazy + * initializer. + * * @return the current value */ public final V getAndClear() { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/container/Capabilities.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/container/Capabilities.java index 76942e892b2..6c6cb5cb7ba 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/container/Capabilities.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/container/Capabilities.java @@ -48,12 +48,14 @@ static class NamespaceSet { NamespaceSet(String name) { this.name = name; - this.matchMandatory = PackageNamespace.PACKAGE_NAMESPACE.equals(name) || BundleNamespace.BUNDLE_NAMESPACE.equals(name) || HostNamespace.HOST_NAMESPACE.equals(name); + this.matchMandatory = PackageNamespace.PACKAGE_NAMESPACE.equals(name) + || BundleNamespace.BUNDLE_NAMESPACE.equals(name) || HostNamespace.HOST_NAMESPACE.equals(name); } void addCapability(ModuleCapability capability) { if (!name.equals(capability.getNamespace())) { - throw new IllegalArgumentException("Invalid namespace: " + capability.getNamespace() + ": expecting: " + name); //$NON-NLS-1$ //$NON-NLS-2$ + throw new IllegalArgumentException( + "Invalid namespace: " + capability.getNamespace() + ": expecting: " + name); //$NON-NLS-1$ //$NON-NLS-2$ } all.add(capability); // by convention we index by the namespace attribute @@ -91,7 +93,8 @@ private void addIndex(Object indexKey, ModuleCapability capability) { void removeCapability(ModuleCapability capability) { if (!name.equals(capability.getNamespace())) { - throw new IllegalArgumentException("Invalid namespace: " + capability.getNamespace() + ": expecting: " + name); //$NON-NLS-1$//$NON-NLS-2$ + throw new IllegalArgumentException( + "Invalid namespace: " + capability.getNamespace() + ": expecting: " + name); //$NON-NLS-1$//$NON-NLS-2$ } all.remove(capability); // by convention we index by the namespace attribute @@ -127,7 +130,8 @@ private void removeIndex(Object indexKey, ModuleCapability capability) { List findCapabilities(Requirement requirement) { if (!name.equals(requirement.getNamespace())) { - throw new IllegalArgumentException("Invalid namespace: " + requirement.getNamespace() + ": expecting: " + name); //$NON-NLS-1$//$NON-NLS-2$ + throw new IllegalArgumentException( + "Invalid namespace: " + requirement.getNamespace() + ": expecting: " + name); //$NON-NLS-1$//$NON-NLS-2$ } FilterImpl f = null; String filterSpec = requirement.getDirectives().get(Namespace.REQUIREMENT_FILTER_DIRECTIVE); @@ -220,11 +224,13 @@ public static boolean matches(Filter f, Capability candidate, boolean matchManda /** * Adds the {@link ModuleRevision#getModuleCapabilities(String) capabilities} - * provided by the specified revision to this database. These capabilities must + * provided by the specified revision to this database. These capabilities must * become available for lookup with the {@link #findCapabilities(Requirement)} * method. + * * @param revision the revision which has capabilities to add - * @return a collection of package names added for the osgi.wiring.package namespace + * @return a collection of package names added for the osgi.wiring.package + * namespace */ public Collection addCapabilities(ModuleRevision revision) { Collection packageNames = null; @@ -252,9 +258,10 @@ public Collection addCapabilities(ModuleRevision revision) { /** * Removes the {@link ModuleRevision#getModuleCapabilities(String) capabilities} - * provided by the specified revision from this database. These capabilities + * provided by the specified revision from this database. These capabilities * must no longer be available for lookup with the * {@link #findCapabilities(Requirement)} method. + * * @param revision */ public void removeCapabilities(ModuleRevision revision) { @@ -267,8 +274,9 @@ public void removeCapabilities(ModuleRevision revision) { } /** - * Returns a mutable snapshot of capabilities that are candidates for - * satisfying the specified requirement. + * Returns a mutable snapshot of capabilities that are candidates for satisfying + * the specified requirement. + * * @param requirement the requirement * @return the candidates for the requirement */ diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/container/ComputeNodeOrder.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/container/ComputeNodeOrder.java index b6ad5b1f4e9..1adbbed0c5e 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/container/ComputeNodeOrder.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/container/ComputeNodeOrder.java @@ -17,10 +17,10 @@ import java.util.*; /** - * Borrowed from org.eclipse.core.internal.resources.ComputeProjectOrder - * to be used when computing the stop order. - * Implementation of a sort algorithm for computing the node order. This - * algorithm handles cycles in the node reference graph in a reasonable way. + * Borrowed from org.eclipse.core.internal.resources.ComputeProjectOrder to be + * used when computing the stop order. Implementation of a sort algorithm for + * computing the node order. This algorithm handles cycles in the node reference + * graph in a reasonable way. * * @since 3.0 */ @@ -34,9 +34,8 @@ private ComputeNodeOrder() { } /** - * A directed graph. Once the vertexes and edges of the graph have been - * defined, the graph can be queried for the depth-first finish time of each - * vertex. + * A directed graph. Once the vertexes and edges of the graph have been defined, + * the graph can be queried for the depth-first finish time of each vertex. *

* Ref: Cormen, Leiserson, and Rivest Introduction to Algorithms, * McGraw-Hill, 1990. The depth-first search algorithm is in section 23.3. @@ -44,8 +43,8 @@ private ComputeNodeOrder() { */ private static class Digraph { /** - * struct-like object for representing a vertex along with various - * values computed during depth-first search (DFS). + * struct-like object for representing a vertex along with various values + * computed during depth-first search (DFS). */ public static class Vertex { /** @@ -54,8 +53,7 @@ public static class Vertex { public static final String WHITE = "white"; //$NON-NLS-1$ /** - * Grey is for marking vertexes as discovered but visit not yet - * finished. + * Grey is for marking vertexes as discovered but visit not yet finished. */ public static final String GREY = "grey"; //$NON-NLS-1$ @@ -65,22 +63,21 @@ public static class Vertex { public static final String BLACK = "black"; //$NON-NLS-1$ /** - * Color of the vertex. One of WHITE (unvisited), - * GREY (visit in progress), or BLACK - * (visit finished). WHITE initially. + * Color of the vertex. One of WHITE (unvisited), GREY + * (visit in progress), or BLACK (visit finished). + * WHITE initially. */ public String color = WHITE; /** - * The DFS predecessor vertex, or null if there is no - * predecessor. null initially. + * The DFS predecessor vertex, or null if there is no predecessor. + * null initially. */ public Vertex predecessor = null; /** - * Timestamp indicating when the vertex was finished (became BLACK) - * in the DFS. Finish times are between 1 and the number of - * vertexes. + * Timestamp indicating when the vertex was finished (became BLACK) in the DFS. + * Finish times are between 1 and the number of vertexes. */ public int finishTime; @@ -90,9 +87,8 @@ public static class Vertex { public Object id; /** - * Ordered list of adjacent vertexes. In other words, "this" is the - * "from" vertex and the elements of this list are all "to" - * vertexes. + * Ordered list of adjacent vertexes. In other words, "this" is the "from" + * vertex and the elements of this list are all "to" vertexes. * * Element type: Vertex */ @@ -134,19 +130,17 @@ public Vertex(Object id) { private boolean initialized = false; /** - * Indicates whether the graph contains cycles. Initially - * false. + * Indicates whether the graph contains cycles. Initially false. */ private boolean cycles = false; /** * Creates a new empty directed graph object. *

- * After this graph's vertexes and edges are defined with - * addVertex and addEdge, call - * freeze to indicate that the graph is all there, and then - * call idsByDFSFinishTime to read off the vertexes ordered - * by DFS finish time. + * After this graph's vertexes and edges are defined with addVertex + * and addEdge, call freeze to indicate that the graph + * is all there, and then call idsByDFSFinishTime to read off the + * vertexes ordered by DFS finish time. *

*/ public Digraph() { @@ -154,9 +148,8 @@ public Digraph() { } /** - * Freezes this graph. No more vertexes or edges can be added to this - * graph after this method is called. Has no effect if the graph is - * already frozen. + * Freezes this graph. No more vertexes or edges can be added to this graph + * after this method is called. Has no effect if the graph is already frozen. */ public void freeze() { if (!initialized) { @@ -167,13 +160,12 @@ public void freeze() { } /** - * Defines a new vertex with the given id. The depth-first search is - * performed in the relative order in which vertexes were added to the - * graph. + * Defines a new vertex with the given id. The depth-first search is performed + * in the relative order in which vertexes were added to the graph. * * @param id the id of the vertex - * @exception IllegalArgumentException if the vertex id is - * already defined or if the graph is frozen + * @exception IllegalArgumentException if the vertex id is already defined or if + * the graph is frozen */ public void addVertex(Object id) throws IllegalArgumentException { if (initialized) { @@ -189,16 +181,15 @@ public void addVertex(Object id) throws IllegalArgumentException { } /** - * Adds a new directed edge between the vertexes with the given ids. - * Vertexes for the given ids must be defined beforehand with - * addVertex. The depth-first search is performed in the - * relative order in which adjacent "to" vertexes were added to a given - * "from" index. + * Adds a new directed edge between the vertexes with the given ids. Vertexes + * for the given ids must be defined beforehand with addVertex. The + * depth-first search is performed in the relative order in which adjacent "to" + * vertexes were added to a given "from" index. * * @param fromId the id of the "from" vertex - * @param toId the id of the "to" vertex - * @exception IllegalArgumentException if either vertex is undefined or - * if the graph is frozen + * @param toId the id of the "to" vertex + * @exception IllegalArgumentException if either vertex is undefined or if the + * graph is frozen */ public void addEdge(Object fromId, Object toId) throws IllegalArgumentException { if (initialized) { @@ -213,15 +204,15 @@ public void addEdge(Object fromId, Object toId) throws IllegalArgumentException } /** - * Returns the ids of the vertexes in this graph ordered by depth-first - * search finish time. The graph must be frozen. + * Returns the ids of the vertexes in this graph ordered by depth-first search + * finish time. The graph must be frozen. * - * @param increasing true if objects are to be arranged - * into increasing order of depth-first search finish time, and - * false if objects are to be arranged into decreasing - * order of depth-first search finish time - * @return the list of ids ordered by depth-first search finish time - * (element type: Object) + * @param increasing true if objects are to be arranged into + * increasing order of depth-first search finish time, and + * false if objects are to be arranged into + * decreasing order of depth-first search finish time + * @return the list of ids ordered by depth-first search finish time (element + * type: Object) * @exception IllegalArgumentException if the graph is not frozen */ public List idsByDFSFinishTime(boolean increasing) { @@ -245,8 +236,8 @@ public List idsByDFSFinishTime(boolean increasing) { /** * Returns whether the graph contains cycles. The graph must be frozen. * - * @return true if this graph contains at least one cycle, - * and false if this graph is cycle free + * @return true if this graph contains at least one cycle, and + * false if this graph is cycle free * @exception IllegalArgumentException if the graph is not frozen */ public boolean containsCycles() { @@ -257,13 +248,12 @@ public boolean containsCycles() { } /** - * Returns the non-trivial components of this graph. A non-trivial - * component is a set of 2 or more vertexes that were traversed - * together. The graph must be frozen. + * Returns the non-trivial components of this graph. A non-trivial component is + * a set of 2 or more vertexes that were traversed together. The graph must be + * frozen. * - * @return the possibly empty list of non-trivial components, where - * each component is an array of ids (element type: - * Object[]) + * @return the possibly empty list of non-trivial components, where each + * component is an array of ids (element type: Object[]) * @exception IllegalArgumentException if the graph is not frozen */ public List nonTrivialComponents() { @@ -301,58 +291,57 @@ public List nonTrivialComponents() { return result; } - // /** - // * Performs a depth-first search of this graph and records interesting - // * info with each vertex, including DFS finish time. Employs a recursive - // * helper method DFSVisit. - // *

- // * Although this method is not used, it is the basis of the - // * non-recursive DFS method. - // *

- // */ - // private void recursiveDFS() { - // // initialize - // // all vertex.color initially Vertex.WHITE; - // // all vertex.predecessor initially null; - // time = 0; - // for (Iterator allV = vertexList.iterator(); allV.hasNext();) { - // Vertex nextVertex = (Vertex) allV.next(); - // if (nextVertex.color == Vertex.WHITE) { - // DFSVisit(nextVertex); - // } - // } - // } + // /** + // * Performs a depth-first search of this graph and records interesting + // * info with each vertex, including DFS finish time. Employs a recursive + // * helper method DFSVisit. + // *

+ // * Although this method is not used, it is the basis of the + // * non-recursive DFS method. + // *

+ // */ + // private void recursiveDFS() { + // // initialize + // // all vertex.color initially Vertex.WHITE; + // // all vertex.predecessor initially null; + // time = 0; + // for (Iterator allV = vertexList.iterator(); allV.hasNext();) { + // Vertex nextVertex = (Vertex) allV.next(); + // if (nextVertex.color == Vertex.WHITE) { + // DFSVisit(nextVertex); + // } + // } + // } // - // /** - // * Helper method. Performs a depth first search of this graph. - // * - // * @param vertex the vertex to visit - // */ - // private void DFSVisit(Vertex vertex) { - // // mark vertex as discovered - // vertex.color = Vertex.GREY; - // List adj = vertex.adjacent; - // for (Iterator allAdjacent=adj.iterator(); allAdjacent.hasNext();) { - // Vertex adjVertex = (Vertex) allAdjacent.next(); - // if (adjVertex.color == Vertex.WHITE) { - // // explore edge from vertex to adjVertex - // adjVertex.predecessor = vertex; - // DFSVisit(adjVertex); - // } else if (adjVertex.color == Vertex.GREY) { - // // back edge (grey vertex means visit in progress) - // cycles = true; - // } - // } - // // done exploring vertex - // vertex.color = Vertex.BLACK; - // time++; - // vertex.finishTime = time; - // } + // /** + // * Helper method. Performs a depth first search of this graph. + // * + // * @param vertex the vertex to visit + // */ + // private void DFSVisit(Vertex vertex) { + // // mark vertex as discovered + // vertex.color = Vertex.GREY; + // List adj = vertex.adjacent; + // for (Iterator allAdjacent=adj.iterator(); allAdjacent.hasNext();) { + // Vertex adjVertex = (Vertex) allAdjacent.next(); + // if (adjVertex.color == Vertex.WHITE) { + // // explore edge from vertex to adjVertex + // adjVertex.predecessor = vertex; + // DFSVisit(adjVertex); + // } else if (adjVertex.color == Vertex.GREY) { + // // back edge (grey vertex means visit in progress) + // cycles = true; + // } + // } + // // done exploring vertex + // vertex.color = Vertex.BLACK; + // time++; + // vertex.finishTime = time; + // } /** - * Performs a depth-first search of this graph and records interesting - * info with each vertex, including DFS finish time. Does not employ - * recursion. + * Performs a depth-first search of this graph and records interesting info with + * each vertex, including DFS finish time. Does not employ recursion. */ private void DFS() { // state machine rendition of the standard recursive DFS algorithm @@ -376,65 +365,65 @@ private void DFS() { state = NEXT_VERTEX; nextStateLoop: while (true) { switch (state) { - case NEXT_VERTEX : - // on entry, "allV" contains vertexes yet to be visited - if (!allV.hasNext()) { - // all done - break nextStateLoop; - } - Vertex nextVertex = allV.next(); - if (nextVertex.color == Vertex.WHITE) { - stack.add(NEXT_VERTEX_OBJECT); - vertex = nextVertex; + case NEXT_VERTEX: + // on entry, "allV" contains vertexes yet to be visited + if (!allV.hasNext()) { + // all done + break nextStateLoop; + } + Vertex nextVertex = allV.next(); + if (nextVertex.color == Vertex.WHITE) { + stack.add(NEXT_VERTEX_OBJECT); + vertex = nextVertex; + state = START_DFS_VISIT; + continue nextStateLoop; + } + state = NEXT_VERTEX; + continue nextStateLoop; + case START_DFS_VISIT: + // on entry, "vertex" contains the vertex to be visited + // top of stack is return code + // mark the vertex as discovered + vertex.color = Vertex.GREY; + allAdjacent = vertex.adjacent.iterator(); + state = NEXT_ADJACENT; + continue nextStateLoop; + case NEXT_ADJACENT: + // on entry, "allAdjacent" contains adjacent vertexes to + // be visited; "vertex" contains vertex being visited + if (allAdjacent.hasNext()) { + Vertex adjVertex = allAdjacent.next(); + if (adjVertex.color == Vertex.WHITE) { + // explore edge from vertex to adjVertex + adjVertex.predecessor = vertex; + stack.add(allAdjacent); + stack.add(vertex); + stack.add(AFTER_NEXTED_DFS_VISIT_OBJECT); + vertex = adjVertex; state = START_DFS_VISIT; continue nextStateLoop; } - state = NEXT_VERTEX; - continue nextStateLoop; - case START_DFS_VISIT : - // on entry, "vertex" contains the vertex to be visited - // top of stack is return code - // mark the vertex as discovered - vertex.color = Vertex.GREY; - allAdjacent = vertex.adjacent.iterator(); - state = NEXT_ADJACENT; - continue nextStateLoop; - case NEXT_ADJACENT : - // on entry, "allAdjacent" contains adjacent vertexes to - // be visited; "vertex" contains vertex being visited - if (allAdjacent.hasNext()) { - Vertex adjVertex = allAdjacent.next(); - if (adjVertex.color == Vertex.WHITE) { - // explore edge from vertex to adjVertex - adjVertex.predecessor = vertex; - stack.add(allAdjacent); - stack.add(vertex); - stack.add(AFTER_NEXTED_DFS_VISIT_OBJECT); - vertex = adjVertex; - state = START_DFS_VISIT; - continue nextStateLoop; - } - if (adjVertex.color == Vertex.GREY) { - // back edge (grey means visit in progress) - cycles = true; - } - state = NEXT_ADJACENT; - continue nextStateLoop; + if (adjVertex.color == Vertex.GREY) { + // back edge (grey means visit in progress) + cycles = true; } - // done exploring vertex - vertex.color = Vertex.BLACK; - time++; - vertex.finishTime = time; - state = ((Integer) stack.remove(stack.size() - 1)).intValue(); - continue nextStateLoop; - case AFTER_NEXTED_DFS_VISIT : - // on entry, stack contains "vertex" and "allAjacent" - vertex = (Vertex) stack.remove(stack.size() - 1); - @SuppressWarnings("unchecked") - Iterator unchecked = (Iterator) stack.remove(stack.size() - 1); - allAdjacent = unchecked; state = NEXT_ADJACENT; continue nextStateLoop; + } + // done exploring vertex + vertex.color = Vertex.BLACK; + time++; + vertex.finishTime = time; + state = ((Integer) stack.remove(stack.size() - 1)).intValue(); + continue nextStateLoop; + case AFTER_NEXTED_DFS_VISIT: + // on entry, stack contains "vertex" and "allAjacent" + vertex = (Vertex) stack.remove(stack.size() - 1); + @SuppressWarnings("unchecked") + Iterator unchecked = (Iterator) stack.remove(stack.size() - 1); + allAdjacent = unchecked; + state = NEXT_ADJACENT; + continue nextStateLoop; } } } @@ -442,29 +431,29 @@ private void DFS() { } /** - * Sorts the given list of projects in a manner that honors the given - * project reference relationships. That is, if project A references project - * B, then the resulting order will list B before A if possible. For graphs - * that do not contain cycles, the result is the same as a conventional - * topological sort. For graphs containing cycles, the order is based on - * ordering the strongly connected components of the graph. This has the - * effect of keeping each knot of projects together without otherwise - * affecting the order of projects not involved in a cycle. For a graph G, - * the algorithm performs in O(|G|) space and time. + * Sorts the given list of projects in a manner that honors the given project + * reference relationships. That is, if project A references project B, then the + * resulting order will list B before A if possible. For graphs that do not + * contain cycles, the result is the same as a conventional topological sort. + * For graphs containing cycles, the order is based on ordering the strongly + * connected components of the graph. This has the effect of keeping each knot + * of projects together without otherwise affecting the order of projects not + * involved in a cycle. For a graph G, the algorithm performs in O(|G|) space + * and time. *

- * When there is an arbitrary choice, vertexes are ordered as supplied. - * Arranged projects in descending alphabetical order generally results in - * an order that builds "A" before "Z" when there are no other constraints. + * When there is an arbitrary choice, vertexes are ordered as supplied. Arranged + * projects in descending alphabetical order generally results in an order that + * builds "A" before "Z" when there are no other constraints. *

- *

Ref: Cormen, Leiserson, and Rivest Introduction to - * Algorithms, McGraw-Hill, 1990. The strongly-connected-components - * algorithm is in section 23.5. + *

+ * Ref: Cormen, Leiserson, and Rivest Introduction to Algorithms, + * McGraw-Hill, 1990. The strongly-connected-components algorithm is in section + * 23.5. *

* - * @param objects a list of projects (element type: - * IProject) + * @param objects a list of projects (element type: IProject) * @param references a list of project references [A,B] meaning that A - * references B (element type: IProject[]) + * references B (element type: IProject[]) * @return an object describing the resulting project order */ public static Object[][] computeNodeOrder(Object[] objects, Object[][] references) { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/container/InternalUtils.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/container/InternalUtils.java index 58e02050f52..65e63e04cce 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/container/InternalUtils.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/container/InternalUtils.java @@ -134,7 +134,8 @@ public static void filterCapabilityPermissions(Collection { - public final static Function WIRE = new Function() { + public final static Function WIRE = new Function() { public String apply(ModuleWire wire) { return wire.getCapability().getNamespace(); } @@ -258,7 +258,7 @@ public List getNamespaceElements(String namespace) { public Builder transformIntoCopy(Function transformation, Function newGetNamespace) { Builder transformedBuilder = new Builder<>(newGetNamespace, this.namespaceElements.size()); transformedBuilder.size = this.size; - for (Map.Entry> entry : namespaceElements.entrySet()) { + for (Map.Entry> entry : namespaceElements.entrySet()) { List es = entry.getValue(); List transformedElements = new ArrayList<>(es.size()); for (E e : es) { @@ -450,7 +450,7 @@ public boolean remove(Object o) { private void removeNamespaceElement(String namespace, E element) { namespaceElements.computeIfPresent(namespace, new BiFunction, List>() { - public List apply (String n, List es) { + public List apply(String n, List es) { if (es.remove(element)) { Builder.this.size--; } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/debug/Debug.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/debug/Debug.java index daee0c1407a..28c35c07281 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/debug/Debug.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/debug/Debug.java @@ -21,8 +21,9 @@ import org.eclipse.osgi.service.debug.DebugOptionsListener; /** - * This class has debug constants which can be used by the Framework implementation - * and Adaptor implementations + * This class has debug constants which can be used by the Framework + * implementation and Adaptor implementations + * * @since 3.1 */ public class Debug implements DebugOptionsListener { @@ -120,7 +121,7 @@ public class Debug implements DebugOptionsListener { /** * Bundle time debug flag. */ - public boolean DEBUG_BUNDLE_TIME = false; //"debug.bundleTime" + public boolean DEBUG_BUNDLE_TIME = false; // "debug.bundleTime" /** * Loader debug flag. */ @@ -166,11 +167,11 @@ public class Debug implements DebugOptionsListener { * PackageAdmin timing debug flag. */ // TODO remove this or use it somewhere - public boolean DEBUG_PACKAGEADMIN_TIMING = false; //"debug.packageadmin/timing" + public boolean DEBUG_PACKAGEADMIN_TIMING = false; // "debug.packageadmin/timing" /** * Message debug flag. */ - public boolean DEBUG_MESSAGE_BUNDLES = false; //"/debug/messageBundles" + public boolean DEBUG_MESSAGE_BUNDLES = false; // "/debug/messageBundles" /** * Monitor activation debug flag. */ @@ -195,7 +196,8 @@ public Debug(DebugOptions dbgOptions) { @Override public void optionsChanged(DebugOptions dbgOptions) { DEBUG_GENERAL = dbgOptions.getBooleanOption(OPTION_DEBUG_GENERAL, false); - DEBUG_BUNDLE_TIME = dbgOptions.getBooleanOption(OPTION_DEBUG_BUNDLE_TIME, false) || dbgOptions.getBooleanOption("org.eclipse.core.runtime/timing/startup", false); //$NON-NLS-1$ + DEBUG_BUNDLE_TIME = dbgOptions.getBooleanOption(OPTION_DEBUG_BUNDLE_TIME, false) + || dbgOptions.getBooleanOption("org.eclipse.core.runtime/timing/startup", false); //$NON-NLS-1$ DEBUG_LOADER = dbgOptions.getBooleanOption(OPTION_DEBUG_LOADER, false); DEBUG_STORAGE = dbgOptions.getBooleanOption(OPTION_DEBUG_STORAGE, false); DEBUG_EVENTS = dbgOptions.getBooleanOption(OPTION_DEBUG_EVENTS, false); @@ -207,7 +209,8 @@ public void optionsChanged(DebugOptions dbgOptions) { DEBUG_SECURITY = dbgOptions.getBooleanOption(OPTION_DEBUG_SECURITY, false); DEBUG_STARTLEVEL = dbgOptions.getBooleanOption(OPTION_DEBUG_STARTLEVEL, false); DEBUG_PACKAGEADMIN = dbgOptions.getBooleanOption(OPTION_DEBUG_PACKAGEADMIN, false); - DEBUG_PACKAGEADMIN_TIMING = dbgOptions.getBooleanOption(OPTION_DEBUG_PACKAGEADMIN_TIMING, false) || dbgOptions.getBooleanOption("org.eclipse.core.runtime/debug", false); //$NON-NLS-1$ + DEBUG_PACKAGEADMIN_TIMING = dbgOptions.getBooleanOption(OPTION_DEBUG_PACKAGEADMIN_TIMING, false) + || dbgOptions.getBooleanOption("org.eclipse.core.runtime/debug", false); //$NON-NLS-1$ DEBUG_MESSAGE_BUNDLES = dbgOptions.getBooleanOption(OPTION_DEBUG_MESSAGE_BUNDLES, false); SupplementDebug.STATIC_DEBUG_MESSAGE_BUNDLES = DEBUG_MESSAGE_BUNDLES; MONITOR_ACTIVATION = dbgOptions.getBooleanOption(OPTION_MONITOR_ACTIVATION, false); @@ -226,6 +229,7 @@ public void optionsChanged(DebugOptions dbgOptions) { /** * Prints x to the PrintStream + * * @param x */ public static void print(boolean x) { @@ -234,6 +238,7 @@ public static void print(boolean x) { /** * Prints x to the PrintStream + * * @param x */ public static void print(char x) { @@ -242,6 +247,7 @@ public static void print(char x) { /** * Prints x to the PrintStream + * * @param x */ public static void print(int x) { @@ -250,6 +256,7 @@ public static void print(int x) { /** * Prints x to the PrintStream + * * @param x */ public static void print(long x) { @@ -258,6 +265,7 @@ public static void print(long x) { /** * Prints x to the PrintStream + * * @param x */ public static void print(float x) { @@ -266,6 +274,7 @@ public static void print(float x) { /** * Prints x to the PrintStream + * * @param x */ public static void print(double x) { @@ -274,6 +283,7 @@ public static void print(double x) { /** * Prints x to the PrintStream + * * @param x */ public static void print(char x[]) { @@ -282,6 +292,7 @@ public static void print(char x[]) { /** * Prints x to the PrintStream + * * @param x */ public static void print(String x) { @@ -290,6 +301,7 @@ public static void print(String x) { /** * Prints x to the PrintStream + * * @param x */ public static void print(Object x) { @@ -298,6 +310,7 @@ public static void print(Object x) { /** * Prints x to the PrintStream + * * @param x */ public static void println(boolean x) { @@ -306,6 +319,7 @@ public static void println(boolean x) { /** * Prints x to the PrintStream + * * @param x */ public static void println(char x) { @@ -314,6 +328,7 @@ public static void println(char x) { /** * Prints x to the PrintStream + * * @param x */ public static void println(int x) { @@ -322,6 +337,7 @@ public static void println(int x) { /** * Prints x to the PrintStream + * * @param x */ public static void println(long x) { @@ -330,6 +346,7 @@ public static void println(long x) { /** * Prints x to the PrintStream + * * @param x */ public static void println(float x) { @@ -338,6 +355,7 @@ public static void println(float x) { /** * Prints x to the PrintStream + * * @param x */ public static void println(double x) { @@ -346,6 +364,7 @@ public static void println(double x) { /** * Prints x to the PrintStream + * * @param x */ public static void println(char x[]) { @@ -354,6 +373,7 @@ public static void println(char x[]) { /** * Prints x to the PrintStream + * * @param x */ public static void println(String x) { @@ -362,6 +382,7 @@ public static void println(String x) { /** * Prints x to the PrintStream + * * @param x */ public static void println(Object x) { @@ -370,6 +391,7 @@ public static void println(Object x) { /** * Prints t to the PrintStream + * * @param t */ public static void printStackTrace(Throwable t) { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/debug/EclipseDebugTrace.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/debug/EclipseDebugTrace.java index 13e1eb73862..fe11f67cce3 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/debug/EclipseDebugTrace.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/debug/EclipseDebugTrace.java @@ -37,9 +37,15 @@ */ class EclipseDebugTrace implements DebugTrace { - /** The system property used to specify size a trace file can grow before it is rotated */ + /** + * The system property used to specify size a trace file can grow before it is + * rotated + */ private static final String PROP_TRACE_SIZE_MAX = "eclipse.trace.size.max"; //$NON-NLS-1$ - /** The system property used to specify the maximum number of backup trace files to use */ + /** + * The system property used to specify the maximum number of backup trace files + * to use + */ private static final String PROP_TRACE_FILE_MAX = "eclipse.trace.backup.max"; //$NON-NLS-1$ /** The trace message for a thread stack dump */ private final static String MESSAGE_THREAD_DUMP = "Thread Stack dump: "; //$NON-NLS-1$ @@ -59,16 +65,25 @@ class EclipseDebugTrace implements DebugTrace { private final static String TRACE_FILE_VERSION = "1.1"; //$NON-NLS-1$ /** The new session identifier to be written whenever a new session starts */ private final static String TRACE_NEW_SESSION = "!SESSION "; //$NON-NLS-1$ - /** The date attribute written to the header of the trace file to show when this file was created */ + /** + * The date attribute written to the header of the trace file to show when this + * file was created + */ private final static String TRACE_FILE_DATE = "Time of creation: "; //$NON-NLS-1$ - /** Trace date formatter using the pattern: yyyy-MM-dd HH:mm:ss.SSS */ + /** Trace date formatter using the pattern: yyyy-MM-dd HH:mm:ss.SSS */ private final static DateTimeFormatter TRACE_FILE_DATE_FORMATTER = DateTimeFormatter .ofPattern("yyyy-MM-dd HH:mm:ss.SSS").withZone(ZoneId.systemDefault()); //$NON-NLS-1$ /** The comment character used by the trace file */ private final static String TRACE_COMMENT = "#"; //$NON-NLS-1$ - /** The delimiter used to separate trace elements such as the time stamp, message, etc */ + /** + * The delimiter used to separate trace elements such as the time stamp, + * message, etc + */ private final static String TRACE_ELEMENT_DELIMITER = "|"; //$NON-NLS-1$ - /** The string written in place of the {@link EclipseDebugTrace#TRACE_TRACE_ELEMENT_DELIMITER} in entries */ + /** + * The string written in place of the + * {@link EclipseDebugTrace#TRACE_TRACE_ELEMENT_DELIMITER} in entries + */ private final static String TRACE_ELEMENT_DELIMITER_ENCODED = "|"; //$NON-NLS-1$ /** OS-specific line separator */ private static final String LINE_SEPARATOR; @@ -90,7 +105,7 @@ class EclipseDebugTrace implements DebugTrace { private static final int DEFAULT_TRACE_FILE_MIN_SIZE = 10; /** The extension used for log files */ private static final String TRACE_FILE_EXTENSION = ".trace"; //$NON-NLS-1$ - /** The extension markup to use for backup log files*/ + /** The extension markup to use for backup log files */ private static final String BACKUP_MARK = ".bak_"; //$NON-NLS-1$ /** The maximum size that a trace file should grow (0 = unlimited) */ private int maxTraceFileSize = DEFAULT_TRACE_FILE_SIZE; // The value is in KB. @@ -99,27 +114,36 @@ class EclipseDebugTrace implements DebugTrace { /** The index of the currently backed-up trace file */ private int backupTraceFileIndex = 0; - /** An optional argument to specify the name of the class used by clients to trace messages. If no trace class is specified - * then the class calling this API is assumed to be the class being traced. - */ + /** + * An optional argument to specify the name of the class used by clients to + * trace messages. If no trace class is specified then the class calling this + * API is assumed to be the class being traced. + */ private String traceClass = null; /** The symbolic name of the bundle being traced */ private String bundleSymbolicName = null; - /** DebugOptions are used to determine if the specified bundle symbolic name + option-path has debugging enabled */ + /** + * DebugOptions are used to determine if the specified bundle symbolic name + + * option-path has debugging enabled + */ private FrameworkDebugOptions debugOptions = null; private final boolean consoleLog; /** - * Construct a new EclipseDebugTrace for the specified bundle symbolic name and write messages to the specified - * trace file. + * Construct a new EclipseDebugTrace for the specified bundle symbolic name and + * write messages to the specified trace file. * * @param bundleSymbolicName The symbolic name of the bundle being traced - * @param debugOptions Used to determine if the specified bundle symbolic name + option-path has tracing enabled - * @param traceClass The class that the client is using to perform trace API calls + * @param debugOptions Used to determine if the specified bundle symbolic + * name + option-path has tracing enabled + * @param traceClass The class that the client is using to perform trace + * API calls */ - EclipseDebugTrace(final String bundleSymbolicName, final FrameworkDebugOptions debugOptions, final Class traceClass) { - this.consoleLog = "true".equals(debugOptions.getConfiguration().getConfiguration(EclipseStarter.PROP_CONSOLE_LOG)); //$NON-NLS-1$ + EclipseDebugTrace(final String bundleSymbolicName, final FrameworkDebugOptions debugOptions, + final Class traceClass) { + this.consoleLog = "true" //$NON-NLS-1$ + .equals(debugOptions.getConfiguration().getConfiguration(EclipseStarter.PROP_CONSOLE_LOG)); this.traceClass = traceClass != null ? traceClass.getName() : null; this.debugOptions = debugOptions; this.bundleSymbolicName = bundleSymbolicName; @@ -130,7 +154,8 @@ class EclipseDebugTrace implements DebugTrace { * Is debugging enabled for the specified option-path * * @param optionPath The option-path - * @return Returns true if debugging is enabled for the specified option-path on this bundle; Otherwise false. + * @return Returns true if debugging is enabled for the specified option-path on + * this bundle; Otherwise false. */ private final boolean isDebuggingEnabled(final String optionPath) { if (optionPath == null) @@ -145,39 +170,51 @@ private final boolean isDebuggingEnabled(final String optionPath) { /* * (non-Javadoc) - * @see org.eclipse.osgi.framework.debug.FrameworkDebugTrace#trace(java.lang.String, java.lang.String) + * + * @see + * org.eclipse.osgi.framework.debug.FrameworkDebugTrace#trace(java.lang.String, + * java.lang.String) */ @Override public void trace(final String optionPath, final String message) { if (isDebuggingEnabled(optionPath)) { - final FrameworkDebugTraceEntry record = new FrameworkDebugTraceEntry(bundleSymbolicName, optionPath, message, traceClass); + final FrameworkDebugTraceEntry record = new FrameworkDebugTraceEntry(bundleSymbolicName, optionPath, + message, traceClass); writeRecord(record); } } /* * (non-Javadoc) - * @see org.eclipse.osgi.framework.debug.FrameworkDebugTrace#trace(java.lang.String, java.lang.String, java.lang.Throwable) + * + * @see + * org.eclipse.osgi.framework.debug.FrameworkDebugTrace#trace(java.lang.String, + * java.lang.String, java.lang.Throwable) */ @Override public void trace(final String optionPath, final String message, final Throwable error) { if (isDebuggingEnabled(optionPath)) { - final FrameworkDebugTraceEntry record = new FrameworkDebugTraceEntry(bundleSymbolicName, optionPath, message, error, traceClass); + final FrameworkDebugTraceEntry record = new FrameworkDebugTraceEntry(bundleSymbolicName, optionPath, + message, error, traceClass); writeRecord(record); } } /* * (non-Javadoc) - * @see org.eclipse.osgi.framework.debug.FrameworkDebugTrace#traceEntry(java.lang.String) + * + * @see + * org.eclipse.osgi.framework.debug.FrameworkDebugTrace#traceEntry(java.lang. + * String) */ @Override public void traceEntry(final String optionPath) { if (isDebuggingEnabled(optionPath)) { - final FrameworkDebugTraceEntry record = new FrameworkDebugTraceEntry(bundleSymbolicName, optionPath, null, traceClass); + final FrameworkDebugTraceEntry record = new FrameworkDebugTraceEntry(bundleSymbolicName, optionPath, null, + traceClass); record.setMessage(createMessage(record, EclipseDebugTrace.MESSAGE_ENTER_METHOD_NO_PARAMS)); writeRecord(record); } @@ -185,19 +222,25 @@ public void traceEntry(final String optionPath) { /* * (non-Javadoc) - * @see org.eclipse.osgi.framework.debug.FrameworkDebugTrace#traceEntry(java.lang.String, java.lang.Object) + * + * @see + * org.eclipse.osgi.framework.debug.FrameworkDebugTrace#traceEntry(java.lang. + * String, java.lang.Object) */ @Override public void traceEntry(final String optionPath, final Object methodArgument) { if (isDebuggingEnabled(optionPath)) { - traceEntry(optionPath, new Object[] {methodArgument}); + traceEntry(optionPath, new Object[] { methodArgument }); } } /* * (non-Javadoc) - * @see org.eclipse.osgi.framework.debug.FrameworkDebugTrace#traceEntry(java.lang.String, java.lang.Object[]) + * + * @see + * org.eclipse.osgi.framework.debug.FrameworkDebugTrace#traceEntry(java.lang. + * String, java.lang.Object[]) */ @Override public void traceEntry(final String optionPath, final Object[] methodArguments) { @@ -230,13 +273,17 @@ public void traceEntry(final String optionPath, final Object[] methodArguments) /* * (non-Javadoc) - * @see org.eclipse.osgi.framework.debug.FrameworkDebugTrace#traceExit(java.lang.String) + * + * @see + * org.eclipse.osgi.framework.debug.FrameworkDebugTrace#traceExit(java.lang. + * String) */ @Override public void traceExit(final String optionPath) { if (isDebuggingEnabled(optionPath)) { - final FrameworkDebugTraceEntry record = new FrameworkDebugTraceEntry(bundleSymbolicName, optionPath, null, traceClass); + final FrameworkDebugTraceEntry record = new FrameworkDebugTraceEntry(bundleSymbolicName, optionPath, null, + traceClass); record.setMessage(createMessage(record, EclipseDebugTrace.MESSAGE_EXIT_METHOD_NO_RESULTS)); writeRecord(record); } @@ -244,7 +291,10 @@ public void traceExit(final String optionPath) { /* * (non-Javadoc) - * @see org.eclipse.osgi.framework.debug.FrameworkDebugTrace#traceExit(java.lang.String, java.lang.Object) + * + * @see + * org.eclipse.osgi.framework.debug.FrameworkDebugTrace#traceExit(java.lang. + * String, java.lang.Object) */ @Override public void traceExit(final String optionPath, final Object result) { @@ -267,7 +317,10 @@ public void traceExit(final String optionPath, final Object result) { /* * (non-Javadoc) - * @see org.eclipse.osgi.framework.debug.FrameworkDebugTrace#traceDumpStack(java.lang.String) + * + * @see + * org.eclipse.osgi.framework.debug.FrameworkDebugTrace#traceDumpStack(java.lang + * .String) */ @Override public void traceDumpStack(final String optionPath) { @@ -276,7 +329,8 @@ public void traceDumpStack(final String optionPath) { final StringBuilder messageBuffer = new StringBuilder(EclipseDebugTrace.MESSAGE_THREAD_DUMP); StackTraceElement[] elements = new Exception().getStackTrace(); // the first element in this stack trace is going to be this class, so ignore it - // the second element in this stack trace is going to either be the caller or the trace class. Ignore it only if a traceClass is defined + // the second element in this stack trace is going to either be the caller or + // the trace class. Ignore it only if a traceClass is defined // the rest of the elements should be included in the file array int firstIndex = (traceClass == null) ? 1 : 2; int endIndex = elements.length - firstIndex; @@ -288,7 +342,8 @@ public void traceDumpStack(final String optionPath) { firstIndex++; } messageBuffer.append(convertStackTraceElementsToString(newElements)); - final FrameworkDebugTraceEntry record = new FrameworkDebugTraceEntry(bundleSymbolicName, optionPath, messageBuffer.toString(), traceClass); + final FrameworkDebugTraceEntry record = new FrameworkDebugTraceEntry(bundleSymbolicName, optionPath, + messageBuffer.toString(), traceClass); writeRecord(record); } } @@ -317,10 +372,10 @@ private final String createMessage(final FrameworkDebugTraceEntry record, final } /** - * Utility method to convert an array of StackTraceElement objects to form a String representation of a stack dump + * Utility method to convert an array of StackTraceElement objects to form a + * String representation of a stack dump * - * @param elements - * The array of StackTraceElement objects + * @param elements The array of StackTraceElement objects * @return A String of the stack dump produced by the list of elements */ private final String convertStackTraceElementsToString(final StackTraceElement[] elements) { @@ -402,10 +457,12 @@ private void readLogProperties() { } /** - * Checks the trace file size. If the file size reaches the limit then the trace file is rotated. + * Checks the trace file size. If the file size reaches the limit then the trace + * file is rotated. * * @param traceFile The tracing file - * @param timestamp the timestamp for the session; this is the same timestamp as the first entry + * @param timestamp the timestamp for the session; this is the same timestamp as + * the first entry * @return false if an error occurred trying to rotate the trace file */ private boolean checkTraceFileSize(final File traceFile, long timestamp) { @@ -420,7 +477,9 @@ private boolean checkTraceFileSize(final File traceFile, long timestamp) { // Delete old backup file that will be replaced. String backupFilename = ""; //$NON-NLS-1$ if (traceFileName.toLowerCase().endsWith(TRACE_FILE_EXTENSION)) { - backupFilename = traceFileName.substring(0, traceFileName.length() - TRACE_FILE_EXTENSION.length()) + BACKUP_MARK + backupTraceFileIndex + TRACE_FILE_EXTENSION; + backupFilename = traceFileName.substring(0, + traceFileName.length() - TRACE_FILE_EXTENSION.length()) + BACKUP_MARK + + backupTraceFileIndex + TRACE_FILE_EXTENSION; } else { backupFilename = traceFileName + BACKUP_MARK + backupTraceFileIndex; } @@ -428,7 +487,8 @@ private boolean checkTraceFileSize(final File traceFile, long timestamp) { if (backupFile.exists()) { if (!backupFile.delete()) { System.err.println("Error when trying to delete old trace file: " + backupFile.getName());//$NON-NLS-1$ - if (backupFile.renameTo(new File(backupFile.getAbsolutePath() + System.currentTimeMillis()))) { + if (backupFile + .renameTo(new File(backupFile.getAbsolutePath() + System.currentTimeMillis()))) { System.err.println("So we rename it to filename: " + backupFile.getName()); //$NON-NLS-1$ } else { System.err.println("And we also cannot rename it!"); //$NON-NLS-1$ @@ -444,16 +504,19 @@ private boolean checkTraceFileSize(final File traceFile, long timestamp) { isBackupOK = false; } /* - * Write a header to new log file stating that this new file is a continuation file. - * This method should already be called with the file lock set so we should be safe - * to update it here. - */ + * Write a header to new log file stating that this new file is a continuation + * file. This method should already be called with the file lock set so we + * should be safe to update it here. + */ Writer traceWriter = null; try { traceWriter = openWriter(traceFile); - writeComment(traceWriter, "This is a continuation of trace file " + backupFile.getAbsolutePath()); //$NON-NLS-1$ - writeComment(traceWriter, EclipseDebugTrace.TRACE_FILE_VERSION_COMMENT + EclipseDebugTrace.TRACE_FILE_VERSION); - writeComment(traceWriter, EclipseDebugTrace.TRACE_FILE_VERBOSE_COMMENT + debugOptions.isVerbose()); + writeComment(traceWriter, + "This is a continuation of trace file " + backupFile.getAbsolutePath()); //$NON-NLS-1$ + writeComment(traceWriter, + EclipseDebugTrace.TRACE_FILE_VERSION_COMMENT + EclipseDebugTrace.TRACE_FILE_VERSION); + writeComment(traceWriter, + EclipseDebugTrace.TRACE_FILE_VERBOSE_COMMENT + debugOptions.isVerbose()); writeComment(traceWriter, EclipseDebugTrace.TRACE_FILE_DATE + getFormattedDate(timestamp)); traceWriter.flush(); } catch (IOException ioEx) { @@ -472,7 +535,7 @@ private boolean checkTraceFileSize(final File traceFile, long timestamp) { * Writes a comment to the trace file * * @param traceWriter the trace writer - * @param comment the comment to be written to the trace file + * @param comment the comment to be written to the trace file * @throws IOException If an error occurs while writing the comment */ private void writeComment(final Writer traceWriter, final String comment) throws IOException { @@ -487,18 +550,20 @@ private void writeComment(final Writer traceWriter, final String comment) throws /** * Accessor to retrieve the time stamp in a formatted manner. * - * @return A formatted time stamp based on the {@link EclipseDebugTrace#TRACE_FILE_DATE_FORMATTER} formatter + * @return A formatted time stamp based on the + * {@link EclipseDebugTrace#TRACE_FILE_DATE_FORMATTER} formatter */ private final String getFormattedDate(long timestamp) { return TRACE_FILE_DATE_FORMATTER.format(Instant.ofEpochMilli(timestamp)); } /** - * Accessor to retrieve the text of a {@link Throwable} in a formatted manner so that it can be written to the - * trace file. + * Accessor to retrieve the text of a {@link Throwable} in a formatted manner so + * that it can be written to the trace file. * * @param error The {@lnk Throwable} to format - * @return The complete text of a {@link Throwable} as a {@link String} or null if the input error is null. + * @return The complete text of a {@link Throwable} as a {@link String} or null + * if the input error is null. */ private final String getFormattedThrowable(Throwable error) { @@ -517,7 +582,8 @@ private final String getFormattedThrowable(Throwable error) { * Writes header information to a new trace file * * @param traceWriter the trace writer - * @param timestamp the timestamp for the session; this is the same timestamp as the first entry + * @param timestamp the timestamp for the session; this is the same timestamp + * as the first entry * @throws IOException If an error occurs while writing this session information */ private void writeSession(final Writer traceWriter, long timestamp) throws IOException { @@ -538,7 +604,7 @@ private void writeSession(final Writer traceWriter, long timestamp) throws IOExc * each element of the entry. * * @param traceWriter the trace writer - * @param entry The trace entry object to write to the trace file + * @param entry The trace entry object to write to the trace file * @throws IOException If an error occurs while writing this message */ private void writeMessage(final Writer traceWriter, final FrameworkDebugTraceEntry entry) throws IOException { @@ -554,7 +620,8 @@ private void writeMessage(final Writer traceWriter, final FrameworkDebugTraceEnt message.append(EclipseDebugTrace.TRACE_ELEMENT_DELIMITER); message.append(" "); //$NON-NLS-1$ if (!debugOptions.isVerbose()) { - // format the trace entry for quiet tracing: only the thread name, timestamp, trace message, and exception (if necessary) + // format the trace entry for quiet tracing: only the thread name, timestamp, + // trace message, and exception (if necessary) message.append(encodeText(entry.getMessage())); } else { // format the trace entry for verbose tracing @@ -596,16 +663,18 @@ private void writeMessage(final Writer traceWriter, final FrameworkDebugTraceEnt } /** - * Encodes the specified string to replace any occurrence of the {@link EclipseDebugTrace#TRACE_ELEMENT_DELIMITER} - * string with the {@link EclipseDebugTrace#TRACE_ELEMENT_DELIMITER_ENCODED} - * string. This can be used to ensure that the delimiter character does not break parsing when - * the entry text contains the delimiter character. + * Encodes the specified string to replace any occurrence of the + * {@link EclipseDebugTrace#TRACE_ELEMENT_DELIMITER} string with the + * {@link EclipseDebugTrace#TRACE_ELEMENT_DELIMITER_ENCODED} string. This can be + * used to ensure that the delimiter character does not break parsing when the + * entry text contains the delimiter character. * * @param inputString The original string to be written to the trace file. * @return The original input string with all occurrences of - * {@link EclipseDebugTrace#TRACE_ELEMENT_DELIMITER} replaced with - * {@link EclipseDebugTrace#TRACE_ELEMENT_DELIMITER_ENCODED}. A null value will be - * returned if the input string is null. + * {@link EclipseDebugTrace#TRACE_ELEMENT_DELIMITER} replaced with + * {@link EclipseDebugTrace#TRACE_ELEMENT_DELIMITER_ENCODED}. A + * null value will be returned if the input string is + * null. */ private static String encodeText(final String inputString) { return inputString == null ? null @@ -614,6 +683,7 @@ private static String encodeText(final String inputString) { /** * Returns a Writer for the given OutputStream + * * @param output an OutputStream to use for the Writer * @return A Writer for the given OutputStream */ @@ -622,8 +692,8 @@ private Writer logForStream(OutputStream output) { } /** - * Creates the trace writer. - * If the tracing file is null then the writer will use System.out to print any messages. + * Creates the trace writer. If the tracing file is null then the writer will + * use System.out to print any messages. * * @param traceFile The tracing file * @return Returns a new Writer object @@ -634,7 +704,8 @@ private Writer openWriter(final File traceFile) { try { out = secureAction.getFileOutputStream(traceFile, true); } catch (IOException ioEx) { - // ignore and fall back to system.out; but print error message to indicate what happened + // ignore and fall back to system.out; but print error message to indicate what + // happened System.err.println("Unable to open trace file: " + traceFile + ": " + ioEx.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$ } } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/debug/FrameworkDebugOptions.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/debug/FrameworkDebugOptions.java index ffa400f3dfa..3cb4a60c121 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/debug/FrameworkDebugOptions.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/debug/FrameworkDebugOptions.java @@ -36,18 +36,22 @@ import org.osgi.util.tracker.ServiceTrackerCustomizer; /** - * The DebugOptions implementation class that allows accessing the list of debug options specified - * for the application as well as creating {@link DebugTrace} objects for the purpose of having - * dynamic enablement of debug tracing. + * The DebugOptions implementation class that allows accessing the list of debug + * options specified for the application as well as creating {@link DebugTrace} + * objects for the purpose of having dynamic enablement of debug tracing. * * @since 3.1 */ -public class FrameworkDebugOptions implements DebugOptions, ServiceTrackerCustomizer { +public class FrameworkDebugOptions + implements DebugOptions, ServiceTrackerCustomizer { private static final String OSGI_DEBUG = "osgi.debug"; //$NON-NLS-1$ private static final String OSGI_DEBUG_VERBOSE = "osgi.debug.verbose"; //$NON-NLS-1$ public static final String PROP_TRACEFILE = "osgi.tracefile"; //$NON-NLS-1$ - /** The default name of the .options file if loading when the -debug command-line argument is used */ + /** + * The default name of the .options file if loading when the -debug command-line + * argument is used + */ private static final String OPTIONS = ".options"; //$NON-NLS-1$ /** A lock object used to synchronize access to the trace file */ @@ -56,15 +60,27 @@ public class FrameworkDebugOptions implements DebugOptions, ServiceTrackerCustom private final Object lock = new Object(); /** A current map of all the options with values set */ private Properties options = null; - /** A map of all the disabled options with values set at the time debug was disabled */ + /** + * A map of all the disabled options with values set at the time debug was + * disabled + */ private Properties disabledOptions = null; - /** A cache of all of the bundles DebugTrace in the format --> */ + /** + * A cache of all of the bundles DebugTrace in the format + * --> + */ protected final Map debugTraceCache = new HashMap<>(); - /** The File object to store messages. This value may be null. */ + /** The File object to store messages. This value may be null. */ protected File outFile = null; - /** Is verbose debugging enabled? Changing this value causes a new tracing session to start. */ + /** + * Is verbose debugging enabled? Changing this value causes a new tracing + * session to start. + */ protected boolean verboseDebug = true; - /** A flag to determine if the message being written is done to a new file (i.e. should the header information be written) */ + /** + * A flag to determine if the message being written is done to a new file (i.e. + * should the header information be written) + */ private boolean newSession = true; private final EquinoxConfiguration environmentInfo; private volatile BundleContext context; @@ -72,8 +88,10 @@ public class FrameworkDebugOptions implements DebugOptions, ServiceTrackerCustom public FrameworkDebugOptions(EquinoxConfiguration environmentInfo) { this.environmentInfo = environmentInfo; - // check if verbose debugging was set during initialization. This needs to be set even if debugging is disabled - this.verboseDebug = Boolean.valueOf(environmentInfo.getConfiguration(OSGI_DEBUG_VERBOSE, Boolean.TRUE.toString())).booleanValue(); + // check if verbose debugging was set during initialization. This needs to be + // set even if debugging is disabled + this.verboseDebug = Boolean + .valueOf(environmentInfo.getConfiguration(OSGI_DEBUG_VERBOSE, Boolean.TRUE.toString())).booleanValue(); // if no debug option was specified, don't even bother to try. // Must ensure that the options slot is null as this is the signal to the // platform that debugging is not enabled. @@ -169,7 +187,7 @@ public int getIntegerOption(String option, int defaultValue) { } } - @SuppressWarnings({"unchecked", "rawtypes"}) + @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Map getOptions() { Map snapShot = new HashMap<>(); @@ -184,6 +202,7 @@ else if (disabledOptions != null) /* * (non-Javadoc) + * * @see org.eclipse.osgi.service.debug.DebugOptions#getAllOptions() */ String[] getAllOptions() { @@ -200,14 +219,17 @@ String[] getAllOptions() { } } if (optionsArray == null) { - optionsArray = new String[1]; // TODO this is strange; null is the only element so we can print null in writeSession + optionsArray = new String[1]; // TODO this is strange; null is the only element so we can print null in + // writeSession } return optionsArray; } /* * (non-Javadoc) - * @see org.eclipse.osgi.service.debug.DebugOptions#removeOption(java.lang.String) + * + * @see + * org.eclipse.osgi.service.debug.DebugOptions#removeOption(java.lang.String) */ @Override public void removeOption(String option) { @@ -227,7 +249,9 @@ public void removeOption(String option) { /* * (non-Javadoc) - * @see org.eclipse.osgi.service.debug.DebugOptions#setOption(java.lang.String, java.lang.String) + * + * @see org.eclipse.osgi.service.debug.DebugOptions#setOption(java.lang.String, + * java.lang.String) */ @Override public void setOption(String option, String value) { @@ -277,7 +301,8 @@ public void setOptions(Map ops) { Properties newOptions = new Properties(); for (Map.Entry entry : ops.entrySet()) { if (!(entry.getKey() instanceof String) || !(entry.getValue() instanceof String)) - throw new IllegalArgumentException("Option keys and values must be of type String: " + entry.getKey() + "=" + entry.getValue()); //$NON-NLS-1$ //$NON-NLS-2$ + throw new IllegalArgumentException( + "Option keys and values must be of type String: " + entry.getKey() + "=" + entry.getValue()); //$NON-NLS-1$ //$NON-NLS-2$ newOptions.put(entry.getKey(), entry.getValue().trim()); } Set fireChangesTo = null; @@ -317,6 +342,7 @@ public void setOptions(Map ops) { /* * (non-Javadoc) + * * @see org.eclipse.osgi.service.debug.DebugOptions#isDebugEnabled() */ @Override @@ -328,6 +354,7 @@ public boolean isDebugEnabled() { /* * (non-Javadoc) + * * @see org.eclipse.osgi.service.debug.DebugOptions#setDebugEnabled() */ @Override @@ -372,7 +399,9 @@ public void setDebugEnabled(boolean enabled) { /* * (non-Javadoc) - * @see org.eclipse.osgi.service.debug.DebugOptions#createTrace(java.lang.String) + * + * @see + * org.eclipse.osgi.service.debug.DebugOptions#createTrace(java.lang.String) */ @Override public final DebugTrace newDebugTrace(String bundleSymbolicName) { @@ -382,7 +411,10 @@ public final DebugTrace newDebugTrace(String bundleSymbolicName) { /* * (non-Javadoc) - * @see org.eclipse.osgi.service.debug.DebugOptions#createTrace(java.lang.String, java.lang.Class) + * + * @see + * org.eclipse.osgi.service.debug.DebugOptions#createTrace(java.lang.String, + * java.lang.Class) */ @Override public final DebugTrace newDebugTrace(String bundleSymbolicName, Class traceEntryClass) { @@ -400,6 +432,7 @@ public final DebugTrace newDebugTrace(String bundleSymbolicName, Class traceE /* * (non-Javadoc) + * * @see org.eclipse.osgi.service.debug.DebugOptions#getFile() */ @Override @@ -410,6 +443,7 @@ public final File getFile() { /* * (non-Javadoc) + * * @see org.eclipse.osgi.service.debug.DebugOptions#setFile(java.io.File) */ @Override @@ -441,6 +475,7 @@ Object getWriteLock() { /* * (non-Javadoc) + * * @see org.eclipse.osgi.service.debug.DebugOptions#getVerbose() */ boolean isVerbose() { @@ -454,6 +489,7 @@ EquinoxConfiguration getConfiguration() { /* * (non-Javadoc) + * * @see org.eclipse.osgi.service.debug.DebugOptions#setVerbose(boolean) */ public void setVerbose(final boolean verbose) { @@ -465,7 +501,9 @@ public void setVerbose(final boolean verbose) { } /** - * Notifies the trace listener for the specified bundle that its option-path has changed. + * Notifies the trace listener for the specified bundle that its option-path has + * changed. + * * @param bundleSymbolicName The bundle of the owning trace listener to notify. */ private void optionsChanged(String bundleSymbolicName) { @@ -473,11 +511,13 @@ private void optionsChanged(String bundleSymbolicName) { BundleContext bc = context; if (bc == null) return; - // do not use the service tracker because that is only used to call all listeners initially when they are registered + // do not use the service tracker because that is only used to call all + // listeners initially when they are registered // here we only want the services with the specified name. ServiceReference[] listenerRefs = null; try { - listenerRefs = bc.getServiceReferences(DebugOptionsListener.class.getName(), "(" + DebugOptions.LISTENER_SYMBOLICNAME + "=" + bundleSymbolicName + ")"); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ + listenerRefs = bc.getServiceReferences(DebugOptionsListener.class.getName(), + "(" + DebugOptions.LISTENER_SYMBOLICNAME + "=" + bundleSymbolicName + ")"); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ } catch (InvalidSyntaxException e) { // consider logging; should not happen } @@ -489,7 +529,7 @@ private void optionsChanged(String bundleSymbolicName) { continue; try { service.optionsChanged(this); - }catch (Throwable t) { + } catch (Throwable t) { // TODO consider logging } finally { bc.ungetService(listenerRef); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/debug/FrameworkDebugTraceEntry.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/debug/FrameworkDebugTraceEntry.java index 20393e2dbed..7804958671d 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/debug/FrameworkDebugTraceEntry.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/debug/FrameworkDebugTraceEntry.java @@ -14,10 +14,14 @@ package org.eclipse.osgi.internal.debug; /** - * A framework trace entry is a bean containing all of the attributes for a single trace message. + * A framework trace entry is a bean containing all of the attributes for a + * single trace message. */ public class FrameworkDebugTraceEntry { - /** If a bundles symbolic name is not specified then the default value of /debug can be used */ + /** + * If a bundles symbolic name is not specified then the default value of /debug + * can be used + */ public final static String DEFAULT_OPTION_PATH = "/debug"; //$NON-NLS-1$ /** @@ -69,34 +73,27 @@ public class FrameworkDebugTraceEntry { /** * Construct a new FrameworkTraceRecord object * - * @param bundleSymbolicName - * The symbolic name of the bundle being traced - * @param optionPath - * The trace optionPath - * @param message - * The trace message - * @param traceClass - * The class that calls the trace API + * @param bundleSymbolicName The symbolic name of the bundle being traced + * @param optionPath The trace optionPath + * @param message The trace message + * @param traceClass The class that calls the trace API */ - public FrameworkDebugTraceEntry(final String bundleSymbolicName, final String optionPath, final String message, final String traceClass) { + public FrameworkDebugTraceEntry(final String bundleSymbolicName, final String optionPath, final String message, + final String traceClass) { this(bundleSymbolicName, optionPath, message, null, traceClass); } /** * Construct a new FrameworkTraceRecord object * - * @param bundleSymbolicName - * The symbolic name of the bundle being traced - * @param optionPath - * The trace optionPath - * @param message - * The trace message - * @param error - * An exception to be traced - * @param traceClass - * The class that calls the trace API + * @param bundleSymbolicName The symbolic name of the bundle being traced + * @param optionPath The trace optionPath + * @param message The trace message + * @param error An exception to be traced + * @param traceClass The class that calls the trace API */ - public FrameworkDebugTraceEntry(String bundleSymbolicName, final String optionPath, final String message, final Throwable error, final String traceClass) { + public FrameworkDebugTraceEntry(String bundleSymbolicName, final String optionPath, final String message, + final Throwable error, final String traceClass) { threadName = Thread.currentThread().getName(); if (optionPath == null) { this.optionPath = FrameworkDebugTraceEntry.DEFAULT_OPTION_PATH; @@ -111,19 +108,21 @@ public FrameworkDebugTraceEntry(String bundleSymbolicName, final String optionPa String determineClassName = null; String determineMethodName = null; int determineLineNumber = 0; - // dynamically determine the class name, method name, and line number of the method calling the trace framework + // dynamically determine the class name, method name, and line number of the + // method calling the trace framework StackTraceElement[] stackElements = new Exception().getStackTrace(); int i = 0; while (i < stackElements.length) { String fullClassName = stackElements[i].getClassName(); - if (!fullClassName.equals(Thread.class.getName()) && !fullClassName.equals(FrameworkDebugTraceEntry.class.getName()) && !fullClassName.equals(EclipseDebugTrace.class.getName())) { + if (!fullClassName.equals(Thread.class.getName()) + && !fullClassName.equals(FrameworkDebugTraceEntry.class.getName()) + && !fullClassName.equals(EclipseDebugTrace.class.getName())) { /* - * The first class which is non-JDK or framework related has been hit. - * If a traceClass has been specified then this current stack element - * is likely that class so we should find out who called it. If a - * trace class has not been specified, or has been specified and this - * stack element is not that class, then we assume this stack element - * is the caller of the trace API. + * The first class which is non-JDK or framework related has been hit. If a + * traceClass has been specified then this current stack element is likely that + * class so we should find out who called it. If a trace class has not been + * specified, or has been specified and this stack element is not that class, + * then we assume this stack element is the caller of the trace API. */ if ((traceClass == null) || !fullClassName.equals(traceClass)) { determineClassName = stackElements[i].getClassName(); @@ -242,8 +241,8 @@ public final String getMethodName() { } /** - * Accessor for the option-path being traced. The <option-path> part of the debug option string - * required for the Eclipse debugging framework. + * Accessor for the option-path being traced. The <option-path> + * part of the debug option string required for the Eclipse debugging framework. * *
 	 *    Examples:
@@ -262,7 +261,8 @@ public final String getOptionPath() {
 	/**
 	 * Return the line number in the class/method where the trace originator
 	 *
-	 * @return The line number from the class and method where the trace request originated
+	 * @return The line number from the class and method where the trace request
+	 *         originated
 	 */
 	public final int getLineNumber() {
 
diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/AliasMapper.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/AliasMapper.java
index 0bff770df10..342892bc191 100644
--- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/AliasMapper.java
+++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/AliasMapper.java
@@ -33,7 +33,8 @@ public class AliasMapper {
 		getTables("processor.aliases", processorAliasTable, processorCanonicalTable); //$NON-NLS-1$
 	}
 
-	private static void getTables(String resourceName, Map> aliasTable, Map canonicalTable) {
+	private static void getTables(String resourceName, Map> aliasTable,
+			Map canonicalTable) {
 		InputStream in = AliasMapper.class.getResourceAsStream(resourceName);
 		if (in != null) {
 			try {
@@ -101,7 +102,8 @@ private Collection getAlias(String name, Map>
 	 * @param in InputStream from which to read alias data.
 	 * @return Map of aliases.
 	 */
-	private static Map> initAliases(InputStream in, Map> aliasTable, Map canonicalTable) {
+	private static Map> initAliases(InputStream in,
+			Map> aliasTable, Map canonicalTable) {
 		try {
 			BufferedReader br = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
 			Map> multiMaster = new HashMap<>();
diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/BundleContextImpl.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/BundleContextImpl.java
index 544c1cb60ca..7761a35e3ee 100644
--- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/BundleContextImpl.java
+++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/BundleContextImpl.java
@@ -66,9 +66,8 @@
 /**
  * Bundle's execution context.
  *
- * This object is given out to bundles and provides the
- * implementation to the BundleContext for a host bundle.
- * It is destroyed when a bundle is stopped.
+ * This object is given out to bundles and provides the implementation to the
+ * BundleContext for a host bundle. It is destroyed when a bundle is stopped.
  */
 
 public class BundleContextImpl implements BundleContext, EventDispatcher {
@@ -85,8 +84,10 @@ public class BundleContextImpl implements BundleContext, EventDispatcher, ServiceUse> servicesInUse;
 
@@ -97,8 +98,7 @@ public class BundleContextImpl implements BundleContext, EventDispatchernull if
-	 * the property is undefined.
+	 * @return The value of the requested property, or null if the
+	 *         property is undefined.
 	 */
 	@Override
 	public String getProperty(String key) {
@@ -187,8 +187,8 @@ public Bundle installBundle(String location, InputStream in) throws BundleExcept
 	 * Retrieve the bundle that has the given unique identifier.
 	 *
 	 * @param id The identifier of the bundle to retrieve.
-	 * @return A Bundle object, or null
-	 * if the identifier doesn't match any installed bundle.
+	 * @return A Bundle object, or null if the identifier doesn't match
+	 *         any installed bundle.
 	 */
 	@Override
 	public Bundle getBundle(long id) {
@@ -213,13 +213,11 @@ public Bundle getBundle(String location) {
 	}
 
 	/**
-	 * Retrieve a list of all installed bundles.
-	 * The list is valid at the time
-	 * of the call to getBundles, but the framework is a very dynamic
-	 * environment and bundles can be installed or uninstalled at anytime.
+	 * Retrieve a list of all installed bundles. The list is valid at the time of
+	 * the call to getBundles, but the framework is a very dynamic environment and
+	 * bundles can be installed or uninstalled at anytime.
 	 *
-	 * @return An array of {@link Bundle} objects, one
-	 * object per installed bundle.
+	 * @return An array of {@link Bundle} objects, one object per installed bundle.
 	 */
 	@Override
 	public Bundle[] getBundles() {
@@ -279,9 +277,10 @@ public void addServiceListener(ServiceListener listener, String filter) throws I
 	/**
 	 * Add a service listener.
 	 *
-	 * 

This method is the same as calling - * {@link #addServiceListener(ServiceListener, String)} - * with filter set to null. + *

+ * This method is the same as calling + * {@link #addServiceListener(ServiceListener, String)} with filter set to + * null. * * @see #addServiceListener(ServiceListener, String) */ @@ -298,17 +297,16 @@ public void addServiceListener(ServiceListener listener) { } /** - * Remove a service listener. - * The listener is removed from the context bundle's list of listeners. - * See {@link #getBundle() getBundle()} - * for a definition of context bundle. + * Remove a service listener. The listener is removed from the context bundle's + * list of listeners. See {@link #getBundle() getBundle()} for a definition of + * context bundle. * - *

If this method is called with a listener which is not registered, - * then this method does nothing. + *

+ * If this method is called with a listener which is not registered, then this + * method does nothing. * * @param listener The service listener to remove. - * @exception java.lang.IllegalStateException - * If the bundle context has stopped. + * @exception java.lang.IllegalStateException If the bundle context has stopped. */ @Override public void removeServiceListener(ServiceListener listener) { @@ -321,16 +319,13 @@ public void removeServiceListener(ServiceListener listener) { } /** - * Add a bundle listener. - * {@link BundleListener}s are notified when a bundle has a lifecycle - * state change. - * The listener is added to the context bundle's list of listeners. - * See {@link #getBundle() getBundle()} - * for a definition of context bundle. + * Add a bundle listener. {@link BundleListener}s are notified when a bundle has + * a lifecycle state change. The listener is added to the context bundle's list + * of listeners. See {@link #getBundle() getBundle()} for a definition of + * context bundle. * * @param listener The bundle listener to add. - * @exception java.lang.IllegalStateException - * If the bundle context has stopped. + * @exception java.lang.IllegalStateException If the bundle context has stopped. * @see BundleEvent * @see BundleListener */ @@ -342,7 +337,8 @@ public void addBundleListener(BundleListener listener) { } if (debug.DEBUG_EVENTS) { - String listenerName = listener.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(listener)); //$NON-NLS-1$ + String listenerName = listener.getClass().getName() + "@" //$NON-NLS-1$ + + Integer.toHexString(System.identityHashCode(listener)); Debug.println("addBundleListener[" + bundle + "](" + listenerName + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } @@ -350,17 +346,16 @@ public void addBundleListener(BundleListener listener) { } /** - * Remove a bundle listener. - * The listener is removed from the context bundle's list of listeners. - * See {@link #getBundle() getBundle()} - * for a definition of context bundle. + * Remove a bundle listener. The listener is removed from the context bundle's + * list of listeners. See {@link #getBundle() getBundle()} for a definition of + * context bundle. * - *

If this method is called with a listener which is not registered, - * then this method does nothing. + *

+ * If this method is called with a listener which is not registered, then this + * method does nothing. * * @param listener The bundle listener to remove. - * @exception java.lang.IllegalStateException - * If the bundle context has stopped. + * @exception java.lang.IllegalStateException If the bundle context has stopped. */ @Override public void removeBundleListener(BundleListener listener) { @@ -370,7 +365,8 @@ public void removeBundleListener(BundleListener listener) { } if (debug.DEBUG_EVENTS) { - String listenerName = listener.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(listener)); //$NON-NLS-1$ + String listenerName = listener.getClass().getName() + "@" //$NON-NLS-1$ + + Integer.toHexString(System.identityHashCode(listener)); Debug.println("removeBundleListener[" + bundle + "](" + listenerName + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } @@ -378,15 +374,13 @@ public void removeBundleListener(BundleListener listener) { } /** - * Add a general framework listener. - * {@link FrameworkListener}s are notified of general framework events. - * The listener is added to the context bundle's list of listeners. - * See {@link #getBundle() getBundle()} - * for a definition of context bundle. + * Add a general framework listener. {@link FrameworkListener}s are notified of + * general framework events. The listener is added to the context bundle's list + * of listeners. See {@link #getBundle() getBundle()} for a definition of + * context bundle. * * @param listener The framework listener to add. - * @exception java.lang.IllegalStateException - * If the bundle context has stopped. + * @exception java.lang.IllegalStateException If the bundle context has stopped. * @see FrameworkEvent * @see FrameworkListener */ @@ -398,7 +392,8 @@ public void addFrameworkListener(FrameworkListener listener) { } if (debug.DEBUG_EVENTS) { - String listenerName = listener.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(listener)); //$NON-NLS-1$ + String listenerName = listener.getClass().getName() + "@" //$NON-NLS-1$ + + Integer.toHexString(System.identityHashCode(listener)); Debug.println("addFrameworkListener[" + bundle + "](" + listenerName + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } @@ -406,17 +401,16 @@ public void addFrameworkListener(FrameworkListener listener) { } /** - * Remove a framework listener. - * The listener is removed from the context bundle's list of listeners. - * See {@link #getBundle() getBundle()} - * for a definition of context bundle. + * Remove a framework listener. The listener is removed from the context + * bundle's list of listeners. See {@link #getBundle() getBundle()} for a + * definition of context bundle. * - *

If this method is called with a listener which is not registered, - * then this method does nothing. + *

+ * If this method is called with a listener which is not registered, then this + * method does nothing. * * @param listener The framework listener to remove. - * @exception java.lang.IllegalStateException - * If the bundle context has stopped. + * @exception java.lang.IllegalStateException If the bundle context has stopped. */ @Override public void removeFrameworkListener(FrameworkListener listener) { @@ -426,7 +420,8 @@ public void removeFrameworkListener(FrameworkListener listener) { } if (debug.DEBUG_EVENTS) { - String listenerName = listener.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(listener)); //$NON-NLS-1$ + String listenerName = listener.getClass().getName() + "@" //$NON-NLS-1$ + + Integer.toHexString(System.identityHashCode(listener)); Debug.println("removeFrameworkListener[" + bundle + "](" + listenerName + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } @@ -434,63 +429,70 @@ public void removeFrameworkListener(FrameworkListener listener) { } /** - * Register a service with multiple names. - * This method registers the given service object with the given properties - * under the given class names. - * A {@link ServiceRegistration} object is returned. - * The {@link ServiceRegistration} object is for the private use of the bundle - * registering the service and should not be shared with other bundles. - * The registering bundle is defined to be the context bundle. - * See {@link #getBundle()} for a definition of context bundle. - * Other bundles can locate the service by using either the - * {@link #getServiceReferences getServiceReferences} or - * {@link #getServiceReference getServiceReference} method. + * Register a service with multiple names. This method registers the given + * service object with the given properties under the given class names. A + * {@link ServiceRegistration} object is returned. The + * {@link ServiceRegistration} object is for the private use of the bundle + * registering the service and should not be shared with other bundles. The + * registering bundle is defined to be the context bundle. See + * {@link #getBundle()} for a definition of context bundle. Other bundles can + * locate the service by using either the {@link #getServiceReferences + * getServiceReferences} or {@link #getServiceReference getServiceReference} + * method. * - *

A bundle can register a service object that implements the - * {@link ServiceFactory} interface to - * have more flexiblity in providing service objects to different - * bundles. + *

+ * A bundle can register a service object that implements the + * {@link ServiceFactory} interface to have more flexiblity in providing service + * objects to different bundles. * - *

The following steps are followed to register a service: + *

+ * The following steps are followed to register a service: *

    - *
  1. If the service parameter is not a {@link ServiceFactory}, - * an IllegalArgumentException is thrown if the - * service parameter is not an instanceof - * all the classes named. - *
  2. The service is added to the framework's service registry - * and may now be used by other bundles. - *
  3. A {@link ServiceEvent} of type {@link ServiceEvent#REGISTERED} - * is synchronously sent. - *
  4. A {@link ServiceRegistration} object for this registration - * is returned. + *
  5. If the service parameter is not a {@link ServiceFactory}, an + * IllegalArgumentException is thrown if the service parameter is + * not an instanceof all the classes named. + *
  6. The service is added to the framework's service registry and may now be + * used by other bundles. + *
  7. A {@link ServiceEvent} of type {@link ServiceEvent#REGISTERED} is + * synchronously sent. + *
  8. A {@link ServiceRegistration} object for this registration is returned. *
* - * @param clazzes The class names under which the service can be located. - * The class names in this array will be stored in the service's - * properties under the key "objectClass". - * @param service The service object or a {@link ServiceFactory} object. - * @param properties The properties for this service. - * The keys in the properties object must all be Strings. - * Changes should not be made to this object after calling this method. - * To update the service's properties call the - * {@link ServiceRegistration#setProperties ServiceRegistration.setProperties} - * method. - * This parameter may be null if the service has no properties. + * @param clazzes The class names under which the service can be located. The + * class names in this array will be stored in the service's + * properties under the key "objectClass". + * @param service The service object or a {@link ServiceFactory} object. + * @param properties The properties for this service. The keys in the properties + * object must all be Strings. Changes should not be made to + * this object after calling this method. To update the + * service's properties call the + * {@link ServiceRegistration#setProperties + * ServiceRegistration.setProperties} method. This parameter + * may be null if the service has no properties. * @return A {@link ServiceRegistration} object for use by the bundle - * registering the service to update the - * service's properties or to unregister the service. - * @exception java.lang.IllegalArgumentException If one of the following is true: - *
    - *
  • The service parameter is null. - *
  • The service parameter is not a {@link ServiceFactory} and is not an - * instanceof all the named classes in the clazzes parameter. - *
- * @exception java.lang.SecurityException If the caller does not have - * {@link ServicePermission} permission to "register" the service for - * all the named classes - * and the Java runtime environment supports permissions. - * @exception java.lang.IllegalStateException - * If the bundle context has stopped. + * registering the service to update the service's properties or to + * unregister the service. + * @exception java.lang.IllegalArgumentException If one of the following is + * true: + *
    + *
  • The service parameter is + * null. + *
  • The service parameter is + * not a {@link ServiceFactory} + * and is not an + * instanceof all the + * named classes in the clazzes + * parameter. + *
+ * @exception java.lang.SecurityException If the caller does not have + * {@link ServicePermission} + * permission to "register" the + * service for all the named + * classes and the Java runtime + * environment supports + * permissions. + * @exception java.lang.IllegalStateException If the bundle context has + * stopped. * @see ServiceRegistration * @see ServiceFactory */ @@ -501,66 +503,75 @@ public ServiceRegistration registerService(String[] clazzes, Object service, } /** - * Register a service with a single name. - * This method registers the given service object with the given properties - * under the given class name. + * Register a service with a single name. This method registers the given + * service object with the given properties under the given class name. * - *

This method is otherwise identical to + *

+ * This method is otherwise identical to * {@link #registerService(java.lang.String[], java.lang.Object, java.util.Dictionary)} - * and is provided as a convenience when the service parameter will only be registered - * under a single class name. + * and is provided as a convenience when the service parameter will only be + * registered under a single class name. * - * @see #registerService(java.lang.String[], java.lang.Object, java.util.Dictionary) + * @see #registerService(java.lang.String[], java.lang.Object, + * java.util.Dictionary) */ @Override public ServiceRegistration registerService(String clazz, Object service, Dictionary properties) { - String[] clazzes = new String[] {clazz}; + String[] clazzes = new String[] { clazz }; return registerService(clazzes, service, properties); } /** - * Returns a list of ServiceReference objects. This method returns a list of - * ServiceReference objects for services which implement and were registered under - * the specified class and match the specified filter criteria. + * Returns a list of ServiceReference objects. This method returns a + * list of ServiceReference objects for services which implement and + * were registered under the specified class and match the specified filter + * criteria. * - *

The list is valid at the time of the call to this method, however as the Framework is - * a very dynamic environment, services can be modified or unregistered at anytime. + *

+ * The list is valid at the time of the call to this method, however as the + * Framework is a very dynamic environment, services can be modified or + * unregistered at anytime. * - *

filter is used to select the registered service whose - * properties objects contain keys and values which satisfy the filter. - * See {@link Filter}for a description of the filter string syntax. + *

+ * filter is used to select the registered service whose properties + * objects contain keys and values which satisfy the filter. See + * {@link Filter}for a description of the filter string syntax. * - *

If filter is null, all registered services - * are considered to match the filter. - *

If filter cannot be parsed, an {@link InvalidSyntaxException} will + *

+ * If filter is null, all registered services are considered + * to match the filter. + *

+ * If filter cannot be parsed, an {@link InvalidSyntaxException} will * be thrown with a human readable message where the filter became unparsable. * - *

The following steps are required to select a service: + *

+ * The following steps are required to select a service: *

    - *
  1. If the Java Runtime Environment supports permissions, the caller is checked for the - * ServicePermission to get the service with the specified class. - * If the caller does not have the correct permission, null is returned. - *
  2. If the filter string is not null, the filter string is - * parsed and the set of registered services which satisfy the filter is - * produced. - * If the filter string is null, then all registered services - * are considered to satisfy the filter. + *
  3. If the Java Runtime Environment supports permissions, the caller is + * checked for the ServicePermission to get the service with the + * specified class. If the caller does not have the correct permission, + * null is returned. + *
  4. If the filter string is not null, the filter string is parsed + * and the set of registered services which satisfy the filter is produced. If + * the filter string is null, then all registered services are + * considered to satisfy the filter. *
  5. If clazz is not null, the set is further reduced to - * those services which are an instanceof and were registered under the specified class. - * The complete list of classes of which a service is an instance and which - * were specified when the service was registered is available from the - * service's {@link Constants#OBJECTCLASS}property. - *
  6. An array of ServiceReference to the selected services is returned. + * those services which are an instanceof and were registered under the + * specified class. The complete list of classes of which a service is an + * instance and which were specified when the service was registered is + * available from the service's {@link Constants#OBJECTCLASS}property. + *
  7. An array of ServiceReference to the selected services is + * returned. *
* - * @param clazz The class name with which the service was registered, or - * null for all services. + * @param clazz The class name with which the service was registered, or + * null for all services. * @param filter The filter criteria. - * @return An array of ServiceReference objects, or - * null if no services are registered which satisfy the search. - * @exception InvalidSyntaxException If filter contains - * an invalid filter string which cannot be parsed. + * @return An array of ServiceReference objects, or null if no + * services are registered which satisfy the search. + * @exception InvalidSyntaxException If filter contains an invalid + * filter string which cannot be parsed. */ @Override public ServiceReference[] getServiceReferences(String clazz, String filter) throws InvalidSyntaxException { @@ -575,23 +586,24 @@ public ServiceReference[] getAllServiceReferences(String clazz, String filter } /** - * Get a service reference. - * Retrieves a {@link ServiceReference} for a service + * Get a service reference. Retrieves a {@link ServiceReference} for a service * which implements the named class. * - *

This reference is valid at the time - * of the call to this method, but since the framework is a very dynamic - * environment, services can be modified or unregistered at anytime. + *

+ * This reference is valid at the time of the call to this method, but since the + * framework is a very dynamic environment, services can be modified or + * unregistered at anytime. * - *

This method is provided as a convenience for when the caller is - * interested in any service which implements a named class. This method is - * the same as calling {@link #getServiceReferences getServiceReferences} - * with a null filter string but only a single {@link ServiceReference} - * is returned. + *

+ * This method is provided as a convenience for when the caller is interested in + * any service which implements a named class. This method is the same as + * calling {@link #getServiceReferences getServiceReferences} with a + * null filter string but only a single {@link ServiceReference} is + * returned. * * @param clazz The class name which the service must implement. - * @return A {@link ServiceReference} object, or null - * if no services are registered which implement the named class. + * @return A {@link ServiceReference} object, or null if no + * services are registered which implement the named class. * @see #getServiceReferences */ @Override @@ -602,52 +614,50 @@ public ServiceReference getServiceReference(String clazz) { } /** - * Get a service's service object. - * Retrieves the service object for a service. - * A bundle's use of a service is tracked by a - * use count. Each time a service's service object is returned by - * {@link #getService}, the context bundle's use count for the service - * is incremented by one. Each time the service is release by - * {@link #ungetService}, the context bundle's use count - * for the service is decremented by one. - * When a bundle's use count for a service - * drops to zero, the bundle should no longer use the service. - * See {@link #getBundle()} for a definition of context bundle. + * Get a service's service object. Retrieves the service object for a service. A + * bundle's use of a service is tracked by a use count. Each time a service's + * service object is returned by {@link #getService}, the context bundle's use + * count for the service is incremented by one. Each time the service is release + * by {@link #ungetService}, the context bundle's use count for the service is + * decremented by one. When a bundle's use count for a service drops to zero, + * the bundle should no longer use the service. See {@link #getBundle()} for a + * definition of context bundle. * - *

This method will always return null when the - * service associated with this reference has been unregistered. + *

+ * This method will always return null when the service associated + * with this reference has been unregistered. * - *

The following steps are followed to get the service object: + *

+ * The following steps are followed to get the service object: *

    - *
  1. If the service has been unregistered, - * null is returned. + *
  2. If the service has been unregistered, null is returned. *
  3. The context bundle's use count for this service is incremented by one. - *
  4. If the context bundle's use count for the service is now one and - * the service was registered with a {@link ServiceFactory}, - * the {@link ServiceFactory#getService ServiceFactory.getService} method - * is called to create a service object for the context bundle. - * This service object is cached by the framework. - * While the context bundle's use count for the service is greater than zero, - * subsequent calls to get the services's service object for the context bundle - * will return the cached service object. - *
    If the service object returned by the {@link ServiceFactory} - * is not an instanceof - * all the classes named when the service was registered or - * the {@link ServiceFactory} throws an exception, - * null is returned and a - * {@link FrameworkEvent} of type {@link FrameworkEvent#ERROR} is broadcast. + *
  5. If the context bundle's use count for the service is now one and the + * service was registered with a {@link ServiceFactory}, the + * {@link ServiceFactory#getService ServiceFactory.getService} method is called + * to create a service object for the context bundle. This service object is + * cached by the framework. While the context bundle's use count for the service + * is greater than zero, subsequent calls to get the services's service object + * for the context bundle will return the cached service object.
    + * If the service object returned by the {@link ServiceFactory} is not an + * instanceof all the classes named when the service was registered + * or the {@link ServiceFactory} throws an exception, null is + * returned and a {@link FrameworkEvent} of type {@link FrameworkEvent#ERROR} is + * broadcast. *
  6. The service object for the service is returned. *
* * @param reference A reference to the service whose service object is desired. - * @return A service object for the service associated with this - * reference, or null if the service is not registered. - * @exception java.lang.SecurityException If the caller does not have - * {@link ServicePermission} permission to "get" the service - * using at least one of the named classes the service was registered under - * and the Java runtime environment supports permissions. - * @exception java.lang.IllegalStateException - * If the bundle context has stopped. + * @return A service object for the service associated with this reference, or + * null if the service is not registered. + * @exception java.lang.SecurityException If the caller does not have + * {@link ServicePermission} + * permission to "get" the service + * using at least one of the named + * classes the service was registered + * under and the Java runtime + * environment supports permissions. + * @exception java.lang.IllegalStateException If the bundle context has stopped. * @see #ungetService * @see ServiceFactory */ @@ -662,37 +672,35 @@ public S getService(ServiceReference reference) { } /** - * Unget a service's service object. - * Releases the service object for a service. + * Unget a service's service object. Releases the service object for a service. * If the context bundle's use count for the service is zero, this method * returns false. Otherwise, the context bundle's use count for the - * service is decremented by one. - * See {@link #getBundle()} for a definition of context bundle. + * service is decremented by one. See {@link #getBundle()} for a definition of + * context bundle. * - *

The service's service object - * should no longer be used and all references to it should be destroyed - * when a bundle's use count for the service - * drops to zero. + *

+ * The service's service object should no longer be used and all references to + * it should be destroyed when a bundle's use count for the service drops to + * zero. * - *

The following steps are followed to unget the service object: + *

+ * The following steps are followed to unget the service object: *

    - *
  1. If the context bundle's use count for the service is zero or - * the service has been unregistered, - * false is returned. + *
  2. If the context bundle's use count for the service is zero or the service + * has been unregistered, false is returned. *
  3. The context bundle's use count for this service is decremented by one. - *
  4. If the context bundle's use count for the service is now zero and - * the service was registered with a {@link ServiceFactory}, - * the {@link ServiceFactory#ungetService ServiceFactory.ungetService} method - * is called to release the service object for the context bundle. + *
  5. If the context bundle's use count for the service is now zero and the + * service was registered with a {@link ServiceFactory}, the + * {@link ServiceFactory#ungetService ServiceFactory.ungetService} method is + * called to release the service object for the context bundle. *
  6. true is returned. *
* * @param reference A reference to the service to be released. * @return false if the context bundle's use count for the service - * is zero or if the service has been unregistered, - * otherwise true. - * @exception java.lang.IllegalStateException - * If the bundle context has stopped. + * is zero or if the service has been unregistered, otherwise + * true. + * @exception java.lang.IllegalStateException If the bundle context has stopped. * @see #getService * @see ServiceFactory */ @@ -704,28 +712,26 @@ public boolean ungetService(ServiceReference reference) { } /** - * Creates a File object for a file in the - * persistent storage area provided for the bundle by the framework. - * If the adaptor does not have file system support, this method will - * return null. + * Creates a File object for a file in the persistent storage area + * provided for the bundle by the framework. If the adaptor does not have file + * system support, this method will return null. * - *

A File object for the base directory of the - * persistent storage area provided for the context bundle by the framework - * can be obtained by calling this method with the empty string ("") - * as the parameter. - * See {@link #getBundle()} for a definition of context bundle. + *

+ * A File object for the base directory of the persistent storage + * area provided for the context bundle by the framework can be obtained by + * calling this method with the empty string ("") as the parameter. See + * {@link #getBundle()} for a definition of context bundle. * - *

If the Java runtime environment supports permissions, - * the framework the will ensure that the bundle has - * java.io.FilePermission with actions + *

+ * If the Java runtime environment supports permissions, the framework the will + * ensure that the bundle has java.io.FilePermission with actions * "read","write","execute","delete" for all files (recursively) in the * persistent storage area provided for the context bundle by the framework. * * @param filename A relative name to the file to be accessed. * @return A File object that represents the requested file or - * null if the adaptor does not have file system support. - * @exception java.lang.IllegalStateException - * If the bundle context has stopped. + * null if the adaptor does not have file system support. + * @exception java.lang.IllegalStateException If the bundle context has stopped. */ @Override public File getDataFile(String filename) { @@ -736,13 +742,13 @@ public File getDataFile(String filename) { } /** - * Call bundle's BundleActivator.start() - * This method is called by Bundle.startWorker to start the bundle. + * Call bundle's BundleActivator.start() This method is called by + * Bundle.startWorker to start the bundle. * - * @exception BundleException if - * the bundle has a class that implements the BundleActivator interface, - * but Framework couldn't instantiate it, or the BundleActivator.start() - * method failed + * @exception BundleException if the bundle has a class that implements the + * BundleActivator interface, but Framework couldn't + * instantiate it, or the BundleActivator.start() + * method failed */ protected void start() throws BundleException { long start = 0; @@ -770,16 +776,20 @@ protected void start() throws BundleException { throw be; } finally { if (debug.DEBUG_BUNDLE_TIME) { - Debug.println((System.currentTimeMillis() - start) + " ms to load and start the activator of " + bundle); //$NON-NLS-1$ + Debug.println( + (System.currentTimeMillis() - start) + " ms to load and start the activator of " + bundle); //$NON-NLS-1$ } } } - /* activator completed successfully. We must use this - same activator object when we stop this bundle. */ + /* + * activator completed successfully. We must use this same activator object when + * we stop this bundle. + */ } - private BundleActivator loadBundleActivator() throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { + private BundleActivator loadBundleActivator() throws ClassNotFoundException, InstantiationException, + IllegalAccessException, InvocationTargetException, NoSuchMethodException { ModuleWiring wiring = bundle.getModule().getCurrentRevision().getWiring(); if (wiring == null) { return null; @@ -788,12 +798,14 @@ private BundleActivator loadBundleActivator() throws ClassNotFoundException, Ins if (loader == null) { return null; } - List metadata = wiring.getRevision().getCapabilities(EquinoxModuleDataNamespace.MODULE_DATA_NAMESPACE); + List metadata = wiring.getRevision() + .getCapabilities(EquinoxModuleDataNamespace.MODULE_DATA_NAMESPACE); if (metadata.isEmpty()) { return null; } - String activatorName = (String) metadata.get(0).getAttributes().get(EquinoxModuleDataNamespace.CAPABILITY_ACTIVATOR); + String activatorName = (String) metadata.get(0).getAttributes() + .get(EquinoxModuleDataNamespace.CAPABILITY_ACTIVATOR); if (activatorName == null) { return null; } @@ -803,6 +815,7 @@ private BundleActivator loadBundleActivator() throws ClassNotFoundException, Ins /** * Calls the start method of a BundleActivator. + * * @param bundleActivator that activator to start */ private void startActivator(final BundleActivator bundleActivator) throws BundleException { @@ -836,7 +849,10 @@ public Void run() throws Exception { String clazz = null; clazz = bundleActivator.getClass().getName(); - throw new BundleException(NLS.bind(Msg.BUNDLE_ACTIVATOR_EXCEPTION, new Object[] {clazz, "start", bundle.getSymbolicName() == null ? "" + bundle.getBundleId() : bundle.getSymbolicName()}), BundleException.ACTIVATOR_ERROR, t); //$NON-NLS-1$ //$NON-NLS-2$ + throw new BundleException( + NLS.bind(Msg.BUNDLE_ACTIVATOR_EXCEPTION, new Object[] { clazz, "start", //$NON-NLS-1$ + bundle.getSymbolicName() == null ? "" + bundle.getBundleId() : bundle.getSymbolicName() }), //$NON-NLS-1$ + BundleException.ACTIVATOR_ERROR, t); } } @@ -854,12 +870,12 @@ Object setContextFinder() { } /** - * Call bundle's BundleActivator.stop() - * This method is called by Bundle.stopWorker to stop the bundle. + * Call bundle's BundleActivator.stop() This method is called by + * Bundle.stopWorker to stop the bundle. * - * @exception BundleException if - * the bundle has a class that implements the BundleActivator interface, - * and the BundleActivator.stop() method failed + * @exception BundleException if the bundle has a class that implements the + * BundleActivator interface, and the + * BundleActivator.stop() method failed */ protected void stop() throws BundleException { try { @@ -892,7 +908,10 @@ public Void run() throws Exception { String clazz = (activator == null) ? "" : activator.getClass().getName(); //$NON-NLS-1$ - throw new BundleException(NLS.bind(Msg.BUNDLE_ACTIVATOR_EXCEPTION, new Object[] {clazz, "stop", bundle.getSymbolicName() == null ? "" + bundle.getBundleId() : bundle.getSymbolicName()}), BundleException.ACTIVATOR_ERROR, t); //$NON-NLS-1$ //$NON-NLS-2$ + throw new BundleException( + NLS.bind(Msg.BUNDLE_ACTIVATOR_EXCEPTION, new Object[] { clazz, "stop", //$NON-NLS-1$ + bundle.getSymbolicName() == null ? "" + bundle.getBundleId() : bundle.getSymbolicName() }), //$NON-NLS-1$ + BundleException.ACTIVATOR_ERROR, t); } finally { activator = null; } @@ -901,8 +920,9 @@ public Void run() throws Exception { /** * Return the map of ServiceRegistrationImpl to ServiceUse for services being * used by this context. + * * @return A map of ServiceRegistrationImpl to ServiceUse for services in use by - * this context. + * this context. */ public Map, ServiceUse> getServicesInUseMap() { synchronized (contextLock) { @@ -926,9 +946,9 @@ public void provisionServicesInUseMap() { * Bottom level event dispatcher for the BundleContext. * * @param originalListener listener object registered under. - * @param l listener to call (may be filtered). - * @param action Event class type - * @param object Event object + * @param l listener to call (may be filtered). + * @param action Event class type + * @param object Event object */ @Override public void dispatchEvent(Object originalListener, Object l, int action, Object object) { @@ -937,45 +957,48 @@ public void dispatchEvent(Object originalListener, Object l, int action, Object // if context still valid or the system bundle if (isValid() || bundle.getBundleId() == 0) { switch (action) { - case EquinoxEventPublisher.BUNDLEEVENT : - case EquinoxEventPublisher.BUNDLEEVENTSYNC : { - BundleListener listener = (BundleListener) l; - - if (debug.DEBUG_EVENTS) { - String listenerName = listener.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(listener)); //$NON-NLS-1$ - Debug.println("dispatchBundleEvent[" + bundle + "](" + listenerName + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - - listener.bundleChanged((BundleEvent) object); - break; + case EquinoxEventPublisher.BUNDLEEVENT: + case EquinoxEventPublisher.BUNDLEEVENTSYNC: { + BundleListener listener = (BundleListener) l; + + if (debug.DEBUG_EVENTS) { + String listenerName = listener.getClass().getName() + "@" //$NON-NLS-1$ + + Integer.toHexString(System.identityHashCode(listener)); + Debug.println("dispatchBundleEvent[" + bundle + "](" + listenerName + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } - case ServiceRegistry.SERVICEEVENT : { - ServiceEvent event = (ServiceEvent) object; + listener.bundleChanged((BundleEvent) object); + break; + } - ServiceListener listener = (ServiceListener) l; - if (debug.DEBUG_EVENTS) { - String listenerName = listener.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(listener)); //$NON-NLS-1$ - Debug.println("dispatchServiceEvent[" + bundle + "](" + listenerName + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - listener.serviceChanged(event); - break; - } + case ServiceRegistry.SERVICEEVENT: { + ServiceEvent event = (ServiceEvent) object; - case EquinoxEventPublisher.FRAMEWORKEVENT : { - FrameworkListener listener = (FrameworkListener) l; + ServiceListener listener = (ServiceListener) l; + if (debug.DEBUG_EVENTS) { + String listenerName = listener.getClass().getName() + "@" //$NON-NLS-1$ + + Integer.toHexString(System.identityHashCode(listener)); + Debug.println("dispatchServiceEvent[" + bundle + "](" + listenerName + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + listener.serviceChanged(event); + break; + } - if (debug.DEBUG_EVENTS) { - String listenerName = listener.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(listener)); //$NON-NLS-1$ - Debug.println("dispatchFrameworkEvent[" + bundle + "](" + listenerName + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } + case EquinoxEventPublisher.FRAMEWORKEVENT: { + FrameworkListener listener = (FrameworkListener) l; - listener.frameworkEvent((FrameworkEvent) object); - break; - } - default : { - throw new InternalError(); + if (debug.DEBUG_EVENTS) { + String listenerName = listener.getClass().getName() + "@" //$NON-NLS-1$ + + Integer.toHexString(System.identityHashCode(listener)); + Debug.println("dispatchFrameworkEvent[" + bundle + "](" + listenerName + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } + + listener.frameworkEvent((FrameworkEvent) object); + break; + } + default: { + throw new InternalError(); + } } } } catch (Throwable t) { @@ -1002,15 +1025,14 @@ public void dispatchEvent(Object originalListener, Object l, int action, Object } /** - * Construct a Filter object. This filter object may be used - * to match a ServiceReference or a Dictionary. - * See Filter - * for a description of the filter string syntax. + * Construct a Filter object. This filter object may be used to match a + * ServiceReference or a Dictionary. See Filter for a description of the filter + * string syntax. * * @param filter The filter string. * @return A Filter object encapsulating the filter string. - * @exception InvalidSyntaxException If the filter parameter contains - * an invalid filter string which cannot be parsed. + * @exception InvalidSyntaxException If the filter parameter contains an invalid + * filter string which cannot be parsed. */ @Override public Filter createFilter(String filter) throws InvalidSyntaxException { @@ -1020,11 +1042,10 @@ public Filter createFilter(String filter) throws InvalidSyntaxException { } /** - * This method checks that the context is still valid. If the context is - * no longer valid, an IllegalStateException is thrown. + * This method checks that the context is still valid. If the context is no + * longer valid, an IllegalStateException is thrown. * - * @exception java.lang.IllegalStateException - * If the context bundle has stopped. + * @exception java.lang.IllegalStateException If the context bundle has stopped. */ public void checkValid() { if (!isValid()) { @@ -1044,14 +1065,17 @@ protected boolean isValid() { @Override public ServiceRegistration registerService(Class clazz, S service, Dictionary properties) { @SuppressWarnings("unchecked") - ServiceRegistration registration = (ServiceRegistration) registerService(clazz.getName(), service, properties); + ServiceRegistration registration = (ServiceRegistration) registerService(clazz.getName(), service, + properties); return registration; } @Override - public ServiceRegistration registerService(Class clazz, ServiceFactory factory, Dictionary properties) { + public ServiceRegistration registerService(Class clazz, ServiceFactory factory, + Dictionary properties) { @SuppressWarnings("unchecked") - ServiceRegistration registration = (ServiceRegistration) registerService(clazz.getName(), factory, properties); + ServiceRegistration registration = (ServiceRegistration) registerService(clazz.getName(), factory, + properties); return registration; } @@ -1063,7 +1087,8 @@ public ServiceReference getServiceReference(Class clazz) { } @Override - public Collection> getServiceReferences(Class clazz, String filter) throws InvalidSyntaxException { + public Collection> getServiceReferences(Class clazz, String filter) + throws InvalidSyntaxException { @SuppressWarnings("unchecked") ServiceReference[] refs = (ServiceReference[]) getServiceReferences(clazz.getName(), filter); if (refs == null) { @@ -1084,7 +1109,8 @@ public ServiceObjects getServiceObjects(ServiceReference reference) { if (reference == null) throw new NullPointerException("A null service reference is not allowed."); //$NON-NLS-1$ provisionServicesInUseMap(); - ServiceObjects serviceObjects = container.getServiceRegistry().getServiceObjects(this, (ServiceReferenceImpl) reference); + ServiceObjects serviceObjects = container.getServiceRegistry().getServiceObjects(this, + (ServiceReferenceImpl) reference); return serviceObjects; } } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/ContextFinder.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/ContextFinder.java index 4fce976028f..bdf241b99ad 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/ContextFinder.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/ContextFinder.java @@ -36,8 +36,10 @@ public Class[] getClassContext() { } } - //This is used to detect cycle that could be caused while delegating the loading to other classloaders - //It keeps track on a thread basis of the set of requested classes and resources + // This is used to detect cycle that could be caused while delegating the + // loading to other classloaders + // It keeps track on a thread basis of the set of requested classes and + // resources private static ThreadLocal> cycleDetector = new ThreadLocal<>(); static ClassLoader finderClassLoader; static Finder contextFinder; @@ -62,9 +64,10 @@ public ContextFinder(ClassLoader contextClassLoader, ClassLoader bootLoader) { } // Return a list of all classloaders on the stack that are neither the - // ContextFinder classloader nor the boot classloader. The last classloader + // ContextFinder classloader nor the boot classloader. The last classloader // in the list is either a bundle classloader or the framework's classloader - // We assume that the bootclassloader never uses the context classloader to find classes in itself. + // We assume that the bootclassloader never uses the context classloader to find + // classes in itself. List basicFindClassLoaders() { Class[] stack = contextFinder.getClassContext(); List result = new ArrayList<>(1); @@ -87,7 +90,7 @@ List basicFindClassLoaders() { } // ensures that a classloader does not have the ContextFinder as part of the - // parent hierachy. A classloader which has the ContextFinder as a parent must + // parent hierachy. A classloader which has the ContextFinder as a parent must // not be used as a delegate, otherwise we endup in endless recursion. private boolean checkClassLoader(ClassLoader classloader) { if (classloader == null || classloader == getParent()) @@ -109,8 +112,8 @@ public List run() { return basicFindClassLoaders(); } - //Return whether the request for loading "name" should proceed. - //False is returned when a cycle is being detected + // Return whether the request for loading "name" should proceed. + // False is returned when a cycle is being detected private boolean startLoading(String name) { Set classesAndResources = cycleDetector.get(); if (classesAndResources != null && classesAndResources.contains(name)) @@ -130,7 +133,7 @@ private void stopLoading(String name) { @Override protected Class loadClass(String arg0, boolean arg1) throws ClassNotFoundException { - //Shortcut cycle + // Shortcut cycle if (startLoading(arg0) == false) throw new ClassNotFoundException(arg0); @@ -142,7 +145,8 @@ protected Class loadClass(String arg0, boolean arg1) throws ClassNotFoundExce } catch (ClassNotFoundException e) { // go to the next class loader } - // avoid calling super.loadClass here because it checks the local cache (bug 127963) + // avoid calling super.loadClass here because it checks the local cache (bug + // 127963) return parentContextClassLoader.loadClass(arg0); } finally { stopLoading(arg0); @@ -151,7 +155,7 @@ protected Class loadClass(String arg0, boolean arg1) throws ClassNotFoundExce @Override public URL getResource(String arg0) { - //Shortcut cycle + // Shortcut cycle if (startLoading(arg0) == false) return null; try { @@ -170,7 +174,7 @@ public URL getResource(String arg0) { @Override public Enumeration getResources(String arg0) throws IOException { - //Shortcut cycle + // Shortcut cycle if (!startLoading(arg0)) { return Collections.emptyEnumeration(); } @@ -180,7 +184,8 @@ public Enumeration getResources(String arg0) throws IOException { for (ClassLoader classLoader : toConsult) { result = classLoader.getResources(arg0); if (result != null && result.hasMoreElements()) { - // For context finder we do not compound results after this first loader that has resources + // For context finder we do not compound results after this first loader that + // has resources break; } // no results yet, go to the next class loader diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/DTOBuilder.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/DTOBuilder.java index 9a643db0180..f1608ba7b2e 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/DTOBuilder.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/DTOBuilder.java @@ -420,7 +420,8 @@ public static ServiceReferenceDTO[] newArrayServiceReferenceDTO(ServiceReference } private static Object mapValue(Object v) { - if ((v == null) || v instanceof Number || v instanceof Boolean || v instanceof Character || v instanceof String || v instanceof DTO) { + if ((v == null) || v instanceof Number || v instanceof Boolean || v instanceof Character || v instanceof String + || v instanceof DTO) { return v; } if (v instanceof Map) { @@ -460,7 +461,10 @@ private static Object mapValue(Object v) { } private static Class mapComponentType(Class componentType) { - if (componentType.isPrimitive() || componentType.isArray() || Object.class.equals(componentType) || Number.class.isAssignableFrom(componentType) || Boolean.class.isAssignableFrom(componentType) || Character.class.isAssignableFrom(componentType) || String.class.isAssignableFrom(componentType) || DTO.class.isAssignableFrom(componentType)) { + if (componentType.isPrimitive() || componentType.isArray() || Object.class.equals(componentType) + || Number.class.isAssignableFrom(componentType) || Boolean.class.isAssignableFrom(componentType) + || Character.class.isAssignableFrom(componentType) || String.class.isAssignableFrom(componentType) + || DTO.class.isAssignableFrom(componentType)) { return componentType; } if (Map.class.isAssignableFrom(componentType)) { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/EquinoxBundle.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/EquinoxBundle.java index 5eb8022cb8e..fb6019a818c 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/EquinoxBundle.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/EquinoxBundle.java @@ -117,12 +117,22 @@ public String get(Object key) { return null; String sKey = (String) key; - if (Constants.EXPORT_PACKAGE.equalsIgnoreCase(sKey) || Constants.PROVIDE_CAPABILITY.equalsIgnoreCase(sKey)) { - String systemProvideHeader = getEquinoxContainer().getConfiguration().getConfiguration(EquinoxConfiguration.PROP_SYSTEM_PROVIDE_HEADER, EquinoxConfiguration.SYSTEM_PROVIDE_HEADER_SYSTEM_EXTRA); - boolean useSystemExtra = systemProvideHeader.equals(EquinoxConfiguration.SYSTEM_PROVIDE_HEADER_SYSTEM_EXTRA); - boolean useSystem = systemProvideHeader.equals(EquinoxConfiguration.SYSTEM_PROVIDE_HEADER_SYSTEM) || useSystemExtra; - String systemProp = useSystem ? (Constants.EXPORT_PACKAGE.equalsIgnoreCase(sKey) ? Constants.FRAMEWORK_SYSTEMPACKAGES : Constants.FRAMEWORK_SYSTEMCAPABILITIES) : null; - String systemExtraProp = useSystemExtra ? (Constants.EXPORT_PACKAGE.equalsIgnoreCase(sKey) ? Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA : Constants.FRAMEWORK_SYSTEMCAPABILITIES_EXTRA) : null; + if (Constants.EXPORT_PACKAGE.equalsIgnoreCase(sKey) + || Constants.PROVIDE_CAPABILITY.equalsIgnoreCase(sKey)) { + String systemProvideHeader = getEquinoxContainer().getConfiguration().getConfiguration( + EquinoxConfiguration.PROP_SYSTEM_PROVIDE_HEADER, + EquinoxConfiguration.SYSTEM_PROVIDE_HEADER_SYSTEM_EXTRA); + boolean useSystemExtra = systemProvideHeader + .equals(EquinoxConfiguration.SYSTEM_PROVIDE_HEADER_SYSTEM_EXTRA); + boolean useSystem = systemProvideHeader.equals(EquinoxConfiguration.SYSTEM_PROVIDE_HEADER_SYSTEM) + || useSystemExtra; + String systemProp = useSystem + ? (Constants.EXPORT_PACKAGE.equalsIgnoreCase(sKey) ? Constants.FRAMEWORK_SYSTEMPACKAGES + : Constants.FRAMEWORK_SYSTEMCAPABILITIES) + : null; + String systemExtraProp = useSystemExtra ? (Constants.EXPORT_PACKAGE.equalsIgnoreCase(sKey) + ? Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA + : Constants.FRAMEWORK_SYSTEMCAPABILITIES_EXTRA) : null; return getExtra(sKey, systemProp, systemExtraProp); } @@ -130,8 +140,12 @@ public String get(Object key) { } private String getExtra(String header, String systemProp, String systemExtraProp) { - String systemValue = systemProp != null ? getEquinoxContainer().getConfiguration().getConfiguration(systemProp) : null; - String systemExtraValue = systemExtraProp != null ? getEquinoxContainer().getConfiguration().getConfiguration(systemExtraProp) : null; + String systemValue = systemProp != null + ? getEquinoxContainer().getConfiguration().getConfiguration(systemProp) + : null; + String systemExtraValue = systemExtraProp != null + ? getEquinoxContainer().getConfiguration().getConfiguration(systemExtraProp) + : null; if (systemValue == null) systemValue = systemExtraValue; else if (systemExtraValue != null && systemExtraValue.trim().length() > 0) @@ -225,7 +239,8 @@ public void run() { try { stop(); } catch (Throwable e) { - SystemBundle.this.getEquinoxContainer().getLogServices().log(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, "Error stopping the framework.", e); //$NON-NLS-1$ + SystemBundle.this.getEquinoxContainer().getLogServices().log(EquinoxContainer.NAME, + FrameworkLogEntry.ERROR, "Error stopping the framework.", e); //$NON-NLS-1$ } } }, "Framework stop - " + getEquinoxContainer().toString()); //$NON-NLS-1$ @@ -249,7 +264,8 @@ public void run() { try { update(); } catch (Throwable e) { - SystemBundle.this.getEquinoxContainer().getLogServices().log(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, "Error updating the framework.", e); //$NON-NLS-1$ + SystemBundle.this.getEquinoxContainer().getLogServices().log(EquinoxContainer.NAME, + FrameworkLogEntry.ERROR, "Error updating the framework.", e); //$NON-NLS-1$ } } }, "Framework update - " + getEquinoxContainer().toString()); //$NON-NLS-1$ @@ -376,7 +392,8 @@ protected void stopWorker() throws BundleException { stopWorker0(); } - public EquinoxModule(Long id, String location, ModuleContainer container, EnumSet settings, int startlevel) { + public EquinoxModule(Long id, String location, ModuleContainer container, EnumSet settings, + int startlevel) { super(id, location, container, settings, startlevel); } @@ -401,7 +418,8 @@ protected void cleanup(ModuleRevision revision) { this.module = createSystemModule(moduleContainer); } - public EquinoxBundle(Long id, String location, ModuleContainer moduleContainer, EnumSet settings, int startlevel, EquinoxContainer equinoxContainer) { + public EquinoxBundle(Long id, String location, ModuleContainer moduleContainer, EnumSet settings, + int startlevel, EquinoxContainer equinoxContainer) { this.equinoxContainer = equinoxContainer; this.module = new EquinoxModule(id, location, moduleContainer, settings, startlevel); } @@ -419,21 +437,21 @@ public int compareTo(Bundle bundle) { @Override public int getState() { switch (module.getState()) { - case INSTALLED : - return Bundle.INSTALLED; - case RESOLVED : - return Bundle.RESOLVED; - case STARTING : - case LAZY_STARTING : - return Bundle.STARTING; - case ACTIVE : - return Bundle.ACTIVE; - case STOPPING : - return Bundle.STOPPING; - case UNINSTALLED : - return Bundle.UNINSTALLED; - default : - throw new IllegalStateException("No valid bundle state for module state: " + module.getState()); //$NON-NLS-1$ + case INSTALLED: + return Bundle.INSTALLED; + case RESOLVED: + return Bundle.RESOLVED; + case STARTING: + case LAZY_STARTING: + return Bundle.STARTING; + case ACTIVE: + return Bundle.ACTIVE; + case STOPPING: + return Bundle.STOPPING; + case UNINSTALLED: + return Bundle.UNINSTALLED; + default: + throw new IllegalStateException("No valid bundle state for module state: " + module.getState()); //$NON-NLS-1$ } } @@ -476,7 +494,7 @@ private StopOptions[] getStopOptions(int options) { if ((options & Bundle.STOP_TRANSIENT) == 0) { return new StopOptions[0]; } - return new StopOptions[] {StopOptions.TRANSIENT}; + return new StopOptions[] { StopOptions.TRANSIENT }; } @Override @@ -498,7 +516,8 @@ public void update() throws BundleException { @Override public void uninstall() throws BundleException { - // be sure to prime the headers with default local; calling priv method to avoid permission check + // be sure to prime the headers with default local; calling priv method to avoid + // permission check privGetHeaders(null); Storage storage = equinoxContainer.getStorage(); storage.getModuleContainer().uninstall(module); @@ -554,11 +573,12 @@ public boolean hasPermission(Object permission) { SecurityManager sm = System.getSecurityManager(); if (sm instanceof EquinoxSecurityManager) { /* - * If the FrameworkSecurityManager is active, we need to do checks the "right" way. - * We can exploit our knowledge that the security context of FrameworkSecurityManager - * is an AccessControlContext to invoke it properly with the ProtectionDomain. + * If the FrameworkSecurityManager is active, we need to do checks the "right" + * way. We can exploit our knowledge that the security context of + * FrameworkSecurityManager is an AccessControlContext to invoke it properly + * with the ProtectionDomain. */ - AccessControlContext acc = new AccessControlContext(new ProtectionDomain[] {domain}); + AccessControlContext acc = new AccessControlContext(new ProtectionDomain[] { domain }); try { sm.checkPermission((Permission) permission, acc); return true; @@ -590,7 +610,8 @@ public URL getResource(String name) { return classLoader.getResource(name); } - return new ClasspathManager((Generation) module.getCurrentRevision().getRevisionInfo(), null).findLocalResource(name); + return new ClasspathManager((Generation) module.getCurrentRevision().getRevisionInfo(), null) + .findLocalResource(name); } @Override @@ -629,7 +650,8 @@ public Class loadClass(String name) throws ClassNotFoundException { try { module.start(StartOptions.LAZY_TRIGGER); } catch (BundleException e1) { - equinoxContainer.getLogServices().log(EquinoxContainer.NAME, FrameworkLogEntry.WARNING, e.getMessage(), e); + equinoxContainer.getLogServices().log(EquinoxContainer.NAME, FrameworkLogEntry.WARNING, + e.getMessage(), e); } } throw e; @@ -641,7 +663,8 @@ private ModuleClassLoader getModuleClassLoader(boolean logResolveError) { ResolutionReport report = resolve(); if (logResolveError && !Module.RESOLVED_SET.contains(module.getState())) { String reportMessage = report.getResolutionReportMessage(module.getCurrentRevision()); - equinoxContainer.getEventPublisher().publishFrameworkEvent(FrameworkEvent.ERROR, this, new BundleException(reportMessage, BundleException.RESOLVE_ERROR)); + equinoxContainer.getEventPublisher().publishFrameworkEvent(FrameworkEvent.ERROR, this, + new BundleException(reportMessage, BundleException.RESOLVE_ERROR)); } return AccessController.doPrivileged(new PrivilegedAction() { @Override @@ -674,7 +697,8 @@ public Enumeration getResources(String name) throws IOException { if (classLoader != null) { result = classLoader.getResources(name); } else { - result = new ClasspathManager((Generation) module.getCurrentRevision().getRevisionInfo(), null).findLocalResources(name); + result = new ClasspathManager((Generation) module.getCurrentRevision().getRevisionInfo(), null) + .findLocalResources(name); } return result != null && result.hasMoreElements() ? result : null; } @@ -795,7 +819,7 @@ private A adapt0(Class adapterType) { if (AccessControlContext.class.equals(adapterType)) { Generation current = (Generation) module.getCurrentRevision().getRevisionInfo(); ProtectionDomain domain = current.getDomain(); - return (A) (domain == null ? null : new AccessControlContext(new ProtectionDomain[] {domain})); + return (A) (domain == null ? null : new AccessControlContext(new ProtectionDomain[] { domain })); } if (BundleContext.class.equals(adapterType)) { @@ -895,7 +919,8 @@ private A adapt0(Class adapterType) { return null; } BundleContextImpl current = getBundleContextImpl(); - ServiceReference[] references = (current == null) ? null : equinoxContainer.getServiceRegistry().getRegisteredServices(current); + ServiceReference[] references = (current == null) ? null + : equinoxContainer.getServiceRegistry().getRegisteredServices(current); return (A) DTOBuilder.newArrayServiceReferenceDTO(references); } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/EquinoxConfiguration.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/EquinoxConfiguration.java index 9a852810b80..14f398dcd39 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/EquinoxConfiguration.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/EquinoxConfiguration.java @@ -164,14 +164,19 @@ public class EquinoxConfiguration implements EnvironmentInfo { public static final String PROP_OSGI_JAVA_PROFILE = "osgi.java.profile"; //$NON-NLS-1$ public static final String PROP_OSGI_JAVA_PROFILE_NAME = "osgi.java.profile.name"; //$NON-NLS-1$ - // OSGi java profile bootdelegation; used to indicate how the org.osgi.framework.bootdelegation - // property defined in the java profile should be processed, (ingnore, override, none). default is ignore + // OSGi java profile bootdelegation; used to indicate how the + // org.osgi.framework.bootdelegation + // property defined in the java profile should be processed, (ingnore, override, + // none). default is ignore public static final String PROP_OSGI_JAVA_PROFILE_BOOTDELEGATION = "osgi.java.profile.bootdelegation"; //$NON-NLS-1$ - // indicates that the org.osgi.framework.bootdelegation in the java profile should be ingored + // indicates that the org.osgi.framework.bootdelegation in the java profile + // should be ingored public static final String PROP_OSGI_BOOTDELEGATION_IGNORE = "ignore"; //$NON-NLS-1$ - // indicates that the org.osgi.framework.bootdelegation in the java profile should override the system property + // indicates that the org.osgi.framework.bootdelegation in the java profile + // should override the system property public static final String PROP_OSGI_BOOTDELEGATION_OVERRIDE = "override"; //$NON-NLS-1$ - // indicates that the org.osgi.framework.bootdelegation in the java profile AND the system properties should be ignored + // indicates that the org.osgi.framework.bootdelegation in the java profile AND + // the system properties should be ignored public static final String PROP_OSGI_BOOTDELEGATION_NONE = "none"; //$NON-NLS-1$ public static final String PROP_CONTEXT_BOOTDELEGATION = "osgi.context.bootdelegation"; //$NON-NLS-1$ @@ -192,7 +197,8 @@ public class EquinoxConfiguration implements EnvironmentInfo { public static final String PROP_PARENT_CLASSLOADER = "osgi.parentClassloader"; //$NON-NLS-1$ // A parent classloader type that specifies the framework classlaoder public static final String PARENT_CLASSLOADER_FWK = "fwk"; //$NON-NLS-1$ - // System property used to set the context classloader parent classloader type (ccl is the default) + // System property used to set the context classloader parent classloader type + // (ccl is the default) public static final String PROP_CONTEXTCLASSLOADER_PARENT = "osgi.contextClassLoaderParent"; //$NON-NLS-1$ public static final String CONTEXTCLASSLOADER_PARENT_APP = "app"; //$NON-NLS-1$ public static final String CONTEXTCLASSLOADER_PARENT_EXT = "ext"; //$NON-NLS-1$ @@ -242,7 +248,8 @@ public class EquinoxConfiguration implements EnvironmentInfo { public static final String SYSTEM_PROVIDE_HEADER_SYSTEM_EXTRA = "system.extra"; //$NON-NLS-1$ public static final String PROP_DEFAULT_SUFFIX = ".default"; //$NON-NLS-1$ - public static final Collection PROP_WITH_ECLIPSE_STARTER_DEFAULTS = Collections.unmodifiableList(Arrays.asList(PROP_COMPATIBILITY_BOOTDELEGATION, PROP_DS_DELAYED_KEEPINSTANCES)); + public static final Collection PROP_WITH_ECLIPSE_STARTER_DEFAULTS = Collections + .unmodifiableList(Arrays.asList(PROP_COMPATIBILITY_BOOTDELEGATION, PROP_DS_DELAYED_KEEPINSTANCES)); public static final String PROP_INIT_UUID = "equinox.init.uuid"; //$NON-NLS-1$ public static final String PROP_ACTIVE_THREAD_TYPE = "osgi.framework.activeThreadType"; //$NON-NLS-1$ @@ -271,12 +278,13 @@ public static final class ConfigValues { /** * Value of {@link #localConfig} properties that should be considered * null and for which access should not fall back to - * {@link System#getProperty(String)}. - * The instance must be compared by identity (==, not equals) and must not - * be leaked outside this class. + * {@link System#getProperty(String)}. The instance must be compared by identity + * (==, not equals) and must not be leaked outside this class. */ private final static String NULL_CONFIG = new String("org.eclipse.equinox.configuration.null.value"); //$NON-NLS-1$ - private final static Collection populateInitConfig = Arrays.asList(PROP_OSGI_ARCH, PROP_OSGI_OS, PROP_OSGI_WS, PROP_OSGI_NL, FRAMEWORK_OS_NAME, FRAMEWORK_OS_VERSION, FRAMEWORK_PROCESSOR, FRAMEWORK_LANGUAGE); + private final static Collection populateInitConfig = Arrays.asList(PROP_OSGI_ARCH, PROP_OSGI_OS, + PROP_OSGI_WS, PROP_OSGI_NL, FRAMEWORK_OS_NAME, FRAMEWORK_OS_VERSION, FRAMEWORK_PROCESSOR, + FRAMEWORK_LANGUAGE); private final boolean useSystemProperties; private final Map initialConfig; @@ -288,8 +296,10 @@ public ConfigValues(Map initialConfiguration, Map this.exceptions = exceptions; this.initialConfig = initialConfiguration == null ? new HashMap<>(0) : new HashMap<>(initialConfiguration); Object useSystemPropsValue = initialConfig.get(PROP_USE_SYSTEM_PROPERTIES); - this.useSystemProperties = useSystemPropsValue == null ? false : Boolean.parseBoolean(useSystemPropsValue.toString()); - Properties tempConfiguration = useSystemProperties ? EquinoxContainer.secureAction.getProperties() : new Properties(); + this.useSystemProperties = useSystemPropsValue == null ? false + : Boolean.parseBoolean(useSystemPropsValue.toString()); + Properties tempConfiguration = useSystemProperties ? EquinoxContainer.secureAction.getProperties() + : new Properties(); // do this the hard way to handle null values for (Map.Entry initialEntry : this.initialConfig.entrySet()) { if (initialEntry.getValue() == null) { @@ -353,10 +363,12 @@ void finalizeValues() { consoleProp = consoleProp == null ? null : consoleProp.trim(); if (consoleProp == null || consoleProp.length() > 0) { // no -console was specified or it has specified none or a port for telnet; - // need to make sure the gogo shell does not create an interactive console on standard in/out + // need to make sure the gogo shell does not create an interactive console on + // standard in/out setConfiguration(PROP_GOSH_ARGS, "--nointeractive"); //$NON-NLS-1$ } else { - // Need to make sure we don't shutdown the framework if no console is around (bug 362412) + // Need to make sure we don't shutdown the framework if no console is around + // (bug 362412) setConfiguration(PROP_GOSH_ARGS, "--noshutdown"); //$NON-NLS-1$ } } @@ -395,7 +407,7 @@ private Properties loadProperties(URL location) { private Properties substituteVars(Properties result) { if (result == null) { - //nothing todo. + // nothing todo. return null; } for (Enumeration eKeys = result.keys(); eKeys.hasMoreElements();) { @@ -429,8 +441,8 @@ public String substituteVars(String path, boolean preserveDelimiters) { if (prop == null) { try { // try using the System.getenv method if it exists (bug 126921) - Method getenv = System.class.getMethod("getenv", new Class[] {String.class}); //$NON-NLS-1$ - prop = (String) getenv.invoke(null, new Object[] {var}); + Method getenv = System.class.getMethod("getenv", new Class[] { String.class }); //$NON-NLS-1$ + prop = (String) getenv.invoke(null, new Object[] { var }); } catch (Throwable t) { // do nothing; // on 1.4 VMs this throws an error @@ -461,13 +473,15 @@ public String substituteVars(String path, boolean preserveDelimiters) { } } if (var != null) - // found a case of $var at the end of the path with no trailing $; just append it as is. + // found a case of $var at the end of the path with no trailing $; just append + // it as is. buf.append(VARIABLE_DELIM_CHAR).append(var); return buf.toString(); } public String getProperty(String key) { - // have to access configuration directly instead of using getConfiguration to get access to NULL_CONFIG values + // have to access configuration directly instead of using getConfiguration to + // get access to NULL_CONFIG values String result = internalGet(key); if (result == NULL_CONFIG) { return null; @@ -552,17 +566,23 @@ public Map getInitialConfig() { EquinoxConfiguration(Map initialConfiguration, HookRegistry hookRegistry) { this.hookRegistry = hookRegistry; // Care must be taken to bootstrap of the config values properly - // A separate class is used to hold the configuration maps so that we can pass them - // to the EquionxLocations before the EquinoxConfiguration has been fully constructed + // A separate class is used to hold the configuration maps so that we can pass + // them + // to the EquionxLocations before the EquinoxConfiguration has been fully + // constructed this.configValues = new ConfigValues(initialConfiguration, exceptions); - // We need to initialize some properties always before constructing the EquinoxLocations + // We need to initialize some properties always before constructing the + // EquinoxLocations initializeProperties(); - // At this point we do not know if we want to debug locations because we have not determined if osgi.debug is set yet - // We use an AttomicBoolean to hold the setting so we can set it after the config.ini has been loaded + // At this point we do not know if we want to debug locations because we have + // not determined if osgi.debug is set yet + // We use an AttomicBoolean to hold the setting so we can set it after the + // config.ini has been loaded AtomicBoolean debugLocations = new AtomicBoolean(); - this.equinoxLocations = new EquinoxLocations(this.configValues, this.hookRegistry.getContainer(), debugLocations, exceptions); + this.equinoxLocations = new EquinoxLocations(this.configValues, this.hookRegistry.getContainer(), + debugLocations, exceptions); this.configValues.loadConfigIni(getConfigIni(equinoxLocations, false)); this.configValues.loadConfigIni(getConfigIni(equinoxLocations, true)); this.configValues.finalizeValues(); @@ -587,7 +607,8 @@ public Map getInitialConfig() { devLastModified = f.lastModified(); } - // Check the osgi.dev property to see if dev classpath entries have been defined. + // Check the osgi.dev property to see if dev classpath entries have been + // defined. try { loadDevProperties(LocationHelper.getStream(location)); devMode = true; @@ -604,10 +625,15 @@ public Map getInitialConfig() { contextBootDelegation = "true".equals(getConfiguration(PROP_CONTEXT_BOOTDELEGATION, "true")); //$NON-NLS-1$ //$NON-NLS-2$ compatibilityBootDelegation = "true".equals(getConfiguration(PROP_COMPATIBILITY_BOOTDELEGATION)); //$NON-NLS-1$ - compatibilityLazyTriggerOnFailLoad = "true".equals(getConfiguration(PROP_COMPATIBILITY_START_LAZY_ON_FAIL_CLASSLOAD)); //$NON-NLS-1$ + compatibilityLazyTriggerOnFailLoad = "true" //$NON-NLS-1$ + .equals(getConfiguration(PROP_COMPATIBILITY_START_LAZY_ON_FAIL_CLASSLOAD)); COPY_NATIVES = Boolean.valueOf(getConfiguration(PROP_COPY_NATIVES)).booleanValue(); - String[] libExtensions = ManifestElement.getArrayFromList(getConfiguration(EquinoxConfiguration.PROP_FRAMEWORK_LIBRARY_EXTENSIONS, getConfiguration(org.osgi.framework.Constants.FRAMEWORK_LIBRARY_EXTENSIONS, getOSLibraryExtDefaults())), ","); //$NON-NLS-1$ + String[] libExtensions = ManifestElement + .getArrayFromList( + getConfiguration(EquinoxConfiguration.PROP_FRAMEWORK_LIBRARY_EXTENSIONS, getConfiguration( + org.osgi.framework.Constants.FRAMEWORK_LIBRARY_EXTENSIONS, getOSLibraryExtDefaults())), + ","); //$NON-NLS-1$ for (int i = 0; i < libExtensions.length; i++) if (libExtensions[i].length() > 0 && libExtensions[i].charAt(0) != '.') libExtensions[i] = '.' + libExtensions[i]; @@ -633,8 +659,10 @@ public Map getInitialConfig() { // A specified osgi.dev property but unspecified osgi.checkConfiguration // property implies osgi.checkConfiguration = true. - inCheckConfigurationMode = Boolean.valueOf(getConfiguration(PROP_CHECK_CONFIGURATION, Boolean.toString(devMode))); - // Must ensure the check configuration property is set if in osgi.dev mode (bug 443340) + inCheckConfigurationMode = Boolean + .valueOf(getConfiguration(PROP_CHECK_CONFIGURATION, Boolean.toString(devMode))); + // Must ensure the check configuration property is set if in osgi.dev mode (bug + // 443340) if (inCheckConfigurationMode && getConfiguration(PROP_CHECK_CONFIGURATION) == null) { setConfiguration(PROP_CHECK_CONFIGURATION, "true"); //$NON-NLS-1$ } @@ -676,7 +704,7 @@ private URL getConfigIni(EquinoxLocations locations, boolean parent) { try { return new URL(configArea.getURL().toExternalForm() + CONFIG_FILE); } catch (MalformedURLException e) { - // its ok. This should never happen + // its ok. This should never happen } return null; } @@ -770,17 +798,20 @@ public String getWS() { } public void setAllArgs(String[] allArgs) { - // do not check if this is set already to allow arguments to change when multiple applications are launched + // do not check if this is set already to allow arguments to change when + // multiple applications are launched this.allArgs = allArgs; } public void setAppArgs(String[] appArgs) { - // do not check if this is set already to allow arguments to change when multiple applications are launched + // do not check if this is set already to allow arguments to change when + // multiple applications are launched this.appArgs = appArgs; } public void setFrameworkArgs(String[] frameworkArgs) { - // do not check if this is set already to allow arguments to change when multiple applications are launched + // do not check if this is set already to allow arguments to change when + // multiple applications are launched this.frameworkArgs = frameworkArgs; } @@ -894,7 +925,8 @@ private void updateDevProperties() { } } - private static String[] getDevClassPath(BundleRevision bundle, Map properties, String[] defaultClasspath) { + private static String[] getDevClassPath(BundleRevision bundle, Map properties, + String[] defaultClasspath) { String[] result = null; String id = bundle.getSymbolicName(); if (id != null && properties != null) { @@ -910,6 +942,7 @@ private static String[] getDevClassPath(BundleRevision bundle, Map * *

- * This method takes the string format of a locale and creates the locale object from it. + * This method takes the string format of a locale and creates the locale object + * from it. *

* *

- * This method validates the input strictly. The language code must be lowercase. The country - * code must be uppercase. The separator must be an underscore. The length must be correct. + * This method validates the input strictly. The language code must be + * lowercase. The country code must be uppercase. The separator must be an + * underscore. The length must be correct. *

* *

- * This method is inspired by org.apache.commons.lang.LocaleUtils.toLocale(String) - * by fixing the parsing error for uncommon Locales like having a language and a variant code - * but no country code, or a Locale that only consists of a country code. + * This method is inspired by + * org.apache.commons.lang.LocaleUtils.toLocale(String) by fixing + * the parsing error for uncommon Locales like having a language and a variant + * code but no country code, or a Locale that only consists of a country code. *

* - * @param str - * the locale String to convert - * @param defaultLocale - * the Locale that should be returned in case of an invalid Locale String - * @return a Locale that matches the specified locale String. If the given input String is - * null or can not be parsed because of an invalid format, the given - * default {@link Locale} will be returned. + * @param str the locale String to convert + * @param defaultLocale the Locale that should be returned in case of an invalid + * Locale String + * @return a Locale that matches the specified locale String. If the given input + * String is null or can not be parsed because of an + * invalid format, the given default {@link Locale} will be returned. */ public static Locale toLocale(String str, Locale defaultLocale) { if (str == null) { @@ -1192,7 +1232,8 @@ public static Locale toLocale(String str, Locale defaultLocale) { String variant = ""; //$NON-NLS-1$ String[] localeParts = str.split("_"); //$NON-NLS-1$ - if (localeParts.length == 0 || localeParts.length > 3 || (localeParts.length == 1 && localeParts[0].length() == 0)) { + if (localeParts.length == 0 || localeParts.length > 3 + || (localeParts.length == 1 && localeParts[0].length() == 0)) { System.err.println(NLS.bind(Msg.error_badNL, str)); return defaultLocale; } @@ -1234,7 +1275,8 @@ public EquinoxLocations getEquinoxLocations() { void logMessages(EquinoxLogServices logServices) { for (Map.Entry exception : exceptions.entrySet()) { - logServices.log(EquinoxContainer.NAME, exception.getValue(), exception.getKey().getMessage(), exception.getKey()); + logServices.log(EquinoxContainer.NAME, exception.getValue(), exception.getKey().getMessage(), + exception.getKey()); } exceptions.clear(); } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/EquinoxContainer.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/EquinoxContainer.java index 0f7beb764c0..183e267c16d 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/EquinoxContainer.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/EquinoxContainer.java @@ -113,7 +113,8 @@ public EquinoxContainer(Map configuration, ModuleConnector moduleConn this.eventPublisher = new EquinoxEventPublisher(this); // set the boot delegation according to the osgi boot delegation property - // TODO unfortunately this has to be done after constructing storage so the vm profile is loaded + // TODO unfortunately this has to be done after constructing storage so the vm + // profile is loaded // TODO ideally this should be in equinox configuration or perhaps in storage String bootDelegationProp = equinoxConfig.getConfiguration(Constants.FRAMEWORK_BOOTDELEGATION); String[] bootPackages = ManifestElement.getArrayFromList(bootDelegationProp, ","); //$NON-NLS-1$ @@ -152,7 +153,7 @@ private static void initConnectFramework(ModuleConnector moduleConnector, Equino } URL configUrl = equinoxConfig.getEquinoxLocations().getConfigurationLocation().getURL(); final File fwkStore = new File(configUrl.getPath()); - @SuppressWarnings({"rawtypes", "unchecked"}) + @SuppressWarnings({ "rawtypes", "unchecked" }) Map config = (Map) equinoxConfig.getInitialConfig(); moduleConnector.initialize(fwkStore, Collections.unmodifiableMap(config)); } @@ -342,7 +343,8 @@ StorageSaver getStorageSaver() { @Override public Thread newThread(Runnable r) { - String type = equinoxConfig.getConfiguration(EquinoxConfiguration.PROP_ACTIVE_THREAD_TYPE, EquinoxConfiguration.ACTIVE_THREAD_TYPE_NORMAL); + String type = equinoxConfig.getConfiguration(EquinoxConfiguration.PROP_ACTIVE_THREAD_TYPE, + EquinoxConfiguration.ACTIVE_THREAD_TYPE_NORMAL); Thread t = new Thread(r, "Active Thread: " + toString()); //$NON-NLS-1$ if (EquinoxConfiguration.ACTIVE_THREAD_TYPE_NORMAL.equals(type)) { t.setDaemon(false); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/EquinoxContainerAdaptor.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/EquinoxContainerAdaptor.java index b00ab1ef58e..1251dceb645 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/EquinoxContainerAdaptor.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/EquinoxContainerAdaptor.java @@ -74,7 +74,8 @@ public EquinoxContainerAdaptor(EquinoxContainer container, Storage storage, Map< this.storage = storage; this.hooks = new OSGiFrameworkHooks(container, storage); this.initial = initial; - this.moduleClassLoaderParent = getModuleClassLoaderParent(container.getConfiguration(), container.getBootLoader()); + this.moduleClassLoaderParent = getModuleClassLoaderParent(container.getConfiguration(), + container.getBootLoader()); this.lastSecurityAdminFlush = new AtomicLong(); EquinoxConfiguration config = container.getConfiguration(); @@ -84,12 +85,14 @@ public EquinoxContainerAdaptor(EquinoxContainer container, Storage storage, Map< int resolverThreadCnt; try { - // note that resolver thread count defaults to -1 (compute based on processor number) + // note that resolver thread count defaults to -1 (compute based on processor + // number) resolverThreadCnt = resolverThreadCntProp == null ? -1 : Integer.parseInt(resolverThreadCntProp); } catch (NumberFormatException e) { resolverThreadCnt = -1; } - String startLevelThreadCntProp = config.getConfiguration(EquinoxConfiguration.PROP_EQUINOX_START_LEVEL_THREAD_COUNT); + String startLevelThreadCntProp = config + .getConfiguration(EquinoxConfiguration.PROP_EQUINOX_START_LEVEL_THREAD_COUNT); int startLevelThreadCnt; try { // Note that start-level thread count defaults to 1 (synchronous start) @@ -98,22 +101,25 @@ public EquinoxContainerAdaptor(EquinoxContainer container, Storage storage, Map< startLevelThreadCnt = 1; } - // Use two different executors for resolver and start-level because of the different queue requirements + // Use two different executors for resolver and start-level because of the + // different queue requirements // For the resolver we must use a SynchronousQueue because multiple threads // can kick off a resolution operation and block one of the executor threads // per resolution operation. // If the number of concurrent resolution operations reaches the number of // executor threads then each executor thread may end up blocked causing the - // executor to no longer accept work. A SynchronousQueue prevents that from + // executor to no longer accept work. A SynchronousQueue prevents that from // happening. this.resolverExecutor = new AtomicLazyInitializer<>(); this.lazyResolverExecutorCreator = createLazyExecutorCreator( // "Equinox resolver thread - " + EquinoxContainerAdaptor.this.toString(), //$NON-NLS-1$ resolverThreadCnt, new SynchronousQueue<>()); - // For the start-level we can safely use a growing queue because the thread feeding the - // start-level executor with work is a single thread and it can safely block waiting + // For the start-level we can safely use a growing queue because the thread + // feeding the + // start-level executor with work is a single thread and it can safely block + // waiting // for the work of the executor threads to finish. this.startLevelExecutor = new AtomicLazyInitializer<>(); this.lazyStartLevelExecutorCreator = createLazyExecutorCreator(// @@ -122,7 +128,8 @@ public EquinoxContainerAdaptor(EquinoxContainer container, Storage storage, Map< } - private Callable createLazyExecutorCreator(final String threadName, int threadCnt, final BlockingQueue queue) { + private Callable createLazyExecutorCreator(final String threadName, int threadCnt, + final BlockingQueue queue) { // use the number of processors when configured value is <=0 final int maxThreads = threadCnt <= 0 ? Runtime.getRuntime().availableProcessors() : threadCnt; return new Callable() { @@ -150,10 +157,12 @@ public Thread newThread(Runnable r) { return t; } }; - // use a rejection policy that simply runs the task in the current thread once the max pool size is reached + // use a rejection policy that simply runs the task in the current thread once + // the max pool size is reached RejectedExecutionHandler rejectHandler = new ThreadPoolExecutor.CallerRunsPolicy(); - ThreadPoolExecutor executor = new ThreadPoolExecutor(coreThreads, maxThreads, idleTimeout, TimeUnit.SECONDS, queue, threadFactory, rejectHandler); + ThreadPoolExecutor executor = new ThreadPoolExecutor(coreThreads, maxThreads, idleTimeout, + TimeUnit.SECONDS, queue, threadFactory, rejectHandler); executor.allowCoreThreadTimeOut(true); return executor; } @@ -174,10 +183,12 @@ private static ClassLoader getModuleClassLoaderParent(EquinoxConfiguration confi // check the osgi defined property first String type = configuration.getConfiguration(Constants.FRAMEWORK_BUNDLE_PARENT); if (type == null) { - type = configuration.getConfiguration(EquinoxConfiguration.PROP_PARENT_CLASSLOADER, Constants.FRAMEWORK_BUNDLE_PARENT_BOOT); + type = configuration.getConfiguration(EquinoxConfiguration.PROP_PARENT_CLASSLOADER, + Constants.FRAMEWORK_BUNDLE_PARENT_BOOT); } - if (Constants.FRAMEWORK_BUNDLE_PARENT_FRAMEWORK.equalsIgnoreCase(type) || EquinoxConfiguration.PARENT_CLASSLOADER_FWK.equalsIgnoreCase(type)) { + if (Constants.FRAMEWORK_BUNDLE_PARENT_FRAMEWORK.equalsIgnoreCase(type) + || EquinoxConfiguration.PARENT_CLASSLOADER_FWK.equalsIgnoreCase(type)) { ClassLoader cl = EquinoxContainer.class.getClassLoader(); return cl == null ? bootLoader : cl; } @@ -203,7 +214,8 @@ public ResolverHookFactory getResolverHookFactory() { } @Override - public void publishContainerEvent(ContainerEvent type, Module module, Throwable error, FrameworkListener... listeners) { + public void publishContainerEvent(ContainerEvent type, Module module, Throwable error, + FrameworkListener... listeners) { EquinoxEventPublisher publisher = container.getEventPublisher(); if (publisher != null) { publisher.publishFrameworkEvent(getType(type), module.getBundle(), error, listeners); @@ -220,7 +232,8 @@ public void publishModuleEvent(ModuleEvent type, Module module, Module origin) { @Override public Module createModule(String location, long id, EnumSet settings, int startlevel) { - EquinoxBundle bundle = new EquinoxBundle(id, location, storage.getModuleContainer(), settings, startlevel, container); + EquinoxBundle bundle = new EquinoxBundle(id, location, storage.getModuleContainer(), settings, startlevel, + container); return bundle.getModule(); } @@ -264,7 +277,8 @@ public void invalidateWiring(ModuleWiring moduleWiring, ModuleLoader current) { bundleLoader.close(); } long updatedTimestamp = storage.getModuleDatabase().getRevisionsTimestamp(); - if (System.getSecurityManager() != null && updatedTimestamp != lastSecurityAdminFlush.getAndSet(updatedTimestamp)) { + if (System.getSecurityManager() != null + && updatedTimestamp != lastSecurityAdminFlush.getAndSet(updatedTimestamp)) { storage.getSecurityAdmin().clearCaches(); List modules = storage.getModuleContainer().getModules(); for (Module module : modules) { @@ -286,9 +300,11 @@ private void clearManifestCache(ModuleWiring moduleWiring) { boolean frameworkActive = Module.ACTIVE_SET.contains(storage.getModuleContainer().getModule(0).getState()); ModuleRevision revision = moduleWiring.getRevision(); Module module = revision.getRevisions().getModule(); - boolean isUninstallingOrUninstalled = State.UNINSTALLED.equals(module.getState()) ^ module.holdsTransitionEventLock(ModuleEvent.UNINSTALLED); + boolean isUninstallingOrUninstalled = State.UNINSTALLED.equals(module.getState()) + ^ module.holdsTransitionEventLock(ModuleEvent.UNINSTALLED); if (!frameworkActive || !isUninstallingOrUninstalled) { - // only do this when the framework is not active or when the bundle is not uninstalled + // only do this when the framework is not active or when the bundle is not + // uninstalled Generation generation = (Generation) moduleWiring.getRevision().getRevisionInfo(); generation.clearManifestCache(); } @@ -296,57 +312,57 @@ private void clearManifestCache(ModuleWiring moduleWiring) { static int getType(ContainerEvent type) { switch (type) { - case ERROR : - return FrameworkEvent.ERROR; - case INFO : - return FrameworkEvent.INFO; - case WARNING : - return FrameworkEvent.WARNING; - case REFRESH : - return FrameworkEvent.PACKAGES_REFRESHED; - case START_LEVEL : - return FrameworkEvent.STARTLEVEL_CHANGED; - case STARTED : - return FrameworkEvent.STARTED; - case STOPPED : - return FrameworkEvent.STOPPED; - case STOPPED_REFRESH : - return FrameworkEvent.STOPPED_SYSTEM_REFRESHED; - case STOPPED_UPDATE : - return FrameworkEvent.STOPPED_UPDATE; - case STOPPED_TIMEOUT : - return FrameworkEvent.WAIT_TIMEDOUT; - default : - // default to error - return FrameworkEvent.ERROR; + case ERROR: + return FrameworkEvent.ERROR; + case INFO: + return FrameworkEvent.INFO; + case WARNING: + return FrameworkEvent.WARNING; + case REFRESH: + return FrameworkEvent.PACKAGES_REFRESHED; + case START_LEVEL: + return FrameworkEvent.STARTLEVEL_CHANGED; + case STARTED: + return FrameworkEvent.STARTED; + case STOPPED: + return FrameworkEvent.STOPPED; + case STOPPED_REFRESH: + return FrameworkEvent.STOPPED_SYSTEM_REFRESHED; + case STOPPED_UPDATE: + return FrameworkEvent.STOPPED_UPDATE; + case STOPPED_TIMEOUT: + return FrameworkEvent.WAIT_TIMEDOUT; + default: + // default to error + return FrameworkEvent.ERROR; } } private int getType(ModuleEvent type) { switch (type) { - case INSTALLED : - return BundleEvent.INSTALLED; - case LAZY_ACTIVATION : - return BundleEvent.LAZY_ACTIVATION; - case RESOLVED : - return BundleEvent.RESOLVED; - case STARTED : - return BundleEvent.STARTED; - case STARTING : - return BundleEvent.STARTING; - case STOPPING : - return BundleEvent.STOPPING; - case STOPPED : - return BundleEvent.STOPPED; - case UNINSTALLED : - return BundleEvent.UNINSTALLED; - case UNRESOLVED : - return BundleEvent.UNRESOLVED; - case UPDATED : - return BundleEvent.UPDATED; - default : - // TODO log error? - return 0; + case INSTALLED: + return BundleEvent.INSTALLED; + case LAZY_ACTIVATION: + return BundleEvent.LAZY_ACTIVATION; + case RESOLVED: + return BundleEvent.RESOLVED; + case STARTED: + return BundleEvent.STARTED; + case STARTING: + return BundleEvent.STARTING; + case STOPPING: + return BundleEvent.STOPPING; + case STOPPED: + return BundleEvent.STOPPED; + case UNINSTALLED: + return BundleEvent.UNINSTALLED; + case UNRESOLVED: + return BundleEvent.UNRESOLVED; + case UPDATED: + return BundleEvent.UPDATED; + default: + // TODO log error? + return 0; } } @@ -410,7 +426,8 @@ public void shutdownExecutors() { } @Override - public ModuleRevisionBuilder adaptModuleRevisionBuilder(ModuleEvent operation, Module origin, ModuleRevisionBuilder builder, Object revisionInfo) { + public ModuleRevisionBuilder adaptModuleRevisionBuilder(ModuleEvent operation, Module origin, + ModuleRevisionBuilder builder, Object revisionInfo) { Generation generation = (Generation) revisionInfo; return generation.adaptModuleRevisionBuilder(operation, origin, builder); } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/EquinoxEventPublisher.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/EquinoxEventPublisher.java index 6fed57fc2db..218407ac925 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/EquinoxEventPublisher.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/EquinoxEventPublisher.java @@ -56,11 +56,10 @@ public class EquinoxEventPublisher { private EventManager eventManager; /* - * The following maps objects keep track of event listeners - * by BundleContext. Each element is a Map that is the set - * of event listeners for a particular BundleContext. The max number of - * elements each of the following maps will have is the number of bundles - * installed in the Framework. + * The following maps objects keep track of event listeners by BundleContext. + * Each element is a Map that is the set of event listeners for a particular + * BundleContext. The max number of elements each of the following maps will + * have is the number of bundles installed in the Framework. */ // Map of BundleContexts for bundle's BundleListeners. private final Map> allBundleListeners = new LinkedHashMap<>(); @@ -118,12 +117,9 @@ private boolean isEventManagerSet() { * Deliver a BundleEvent to SynchronousBundleListeners (synchronous) and * BundleListeners (asynchronous). * - * @param type - * BundleEvent type. - * @param bundle - * Affected bundle or null. - * @param origin - * The origin of the event + * @param type BundleEvent type. + * @param bundle Affected bundle or null. + * @param origin The origin of the event */ public void publishBundleEvent(int type, Bundle bundle, Bundle origin) { if (origin != null) { @@ -149,8 +145,8 @@ void publishBundleEventPrivileged(BundleEvent event) { return; } /* - * We must collect the snapshots of the sync and async listeners - * BEFORE we dispatch the event. + * We must collect the snapshots of the sync and async listeners BEFORE we + * dispatch the event. */ /* Collect snapshot of SynchronousBundleListeners */ /* Build the listener snapshot */ @@ -159,10 +155,13 @@ void publishBundleEventPrivileged(BundleEvent event) { Set> systemBundleListenersSync = null; synchronized (allSyncBundleListeners) { listenersSync = new LinkedHashMap<>(allSyncBundleListeners.size()); - for (Map.Entry> entry : allSyncBundleListeners.entrySet()) { - CopyOnWriteIdentityMap listeners = entry.getValue(); + for (Map.Entry> entry : allSyncBundleListeners + .entrySet()) { + CopyOnWriteIdentityMap listeners = entry + .getValue(); if (!listeners.isEmpty()) { - Set> listenerEntries = listeners.entrySet(); + Set> listenerEntries = listeners + .entrySet(); if (entry.getKey().getBundleImpl().getBundleId() == 0) { systemContext = entry.getKey(); // record the snapshot; no need to create another copy @@ -173,13 +172,17 @@ void publishBundleEventPrivileged(BundleEvent event) { } } } - /* Collect snapshot of BundleListeners; only if the event is NOT STARTING or STOPPING or LAZY_ACTIVATION */ + /* + * Collect snapshot of BundleListeners; only if the event is NOT STARTING or + * STOPPING or LAZY_ACTIVATION + */ Map>> listenersAsync = null; Set> systemBundleListenersAsync = null; if ((event.getType() & (BundleEvent.STARTING | BundleEvent.STOPPING | BundleEvent.LAZY_ACTIVATION)) == 0) { synchronized (allBundleListeners) { listenersAsync = new LinkedHashMap<>(allBundleListeners.size()); - for (Map.Entry> entry : allBundleListeners.entrySet()) { + for (Map.Entry> entry : allBundleListeners + .entrySet()) { CopyOnWriteIdentityMap listeners = entry.getValue(); if (!listeners.isEmpty()) { Set> listenerEntries = listeners.entrySet(); @@ -195,16 +198,17 @@ void publishBundleEventPrivileged(BundleEvent event) { } } - /* shrink the snapshot. - * keySet returns a Collection which cannot be added to and - * removals from that collection will result in removals of the - * entry from the snapshot. + /* + * shrink the snapshot. keySet returns a Collection which cannot be added to and + * removals from that collection will result in removals of the entry from the + * snapshot. */ Collection shrinkable; if (listenersAsync == null) { shrinkable = asBundleContexts(listenersSync.keySet()); } else { - shrinkable = new ShrinkableCollection<>(asBundleContexts(listenersSync.keySet()), asBundleContexts(listenersAsync.keySet())); + shrinkable = new ShrinkableCollection<>(asBundleContexts(listenersSync.keySet()), + asBundleContexts(listenersAsync.keySet())); } notifyEventHooksPrivileged(event, shrinkable); @@ -220,9 +224,11 @@ void publishBundleEventPrivileged(BundleEvent event) { /* Dispatch the event to the snapshot for sync listeners */ if (!listenersSync.isEmpty()) { ListenerQueue queue = newListenerQueue(); - for (Map.Entry>> entry : listenersSync.entrySet()) { - @SuppressWarnings({"rawtypes", "unchecked"}) - EventDispatcher dispatcher = (EventDispatcher) entry.getKey(); + for (Map.Entry>> entry : listenersSync + .entrySet()) { + @SuppressWarnings({ "rawtypes", "unchecked" }) + EventDispatcher dispatcher = (EventDispatcher) entry + .getKey(); Set> listeners = entry.getValue(); queue.queueListeners(listeners, dispatcher); } @@ -232,9 +238,11 @@ void publishBundleEventPrivileged(BundleEvent event) { /* Dispatch the event to the snapshot for async listeners */ if ((listenersAsync != null) && !listenersAsync.isEmpty()) { ListenerQueue queue = newListenerQueue(); - for (Map.Entry>> entry : listenersAsync.entrySet()) { - @SuppressWarnings({"rawtypes", "unchecked"}) - EventDispatcher dispatcher = (EventDispatcher) entry.getKey(); + for (Map.Entry>> entry : listenersAsync + .entrySet()) { + @SuppressWarnings({ "rawtypes", "unchecked" }) + EventDispatcher dispatcher = (EventDispatcher) entry + .getKey(); Set> listeners = entry.getValue(); queue.queueListeners(listeners, dispatcher); } @@ -256,18 +264,16 @@ private void notifyEventHooksPrivileged(final BundleEvent event, final Collectio /** * Deliver a FrameworkEvent. * - * @param type - * FrameworkEvent type. - * @param bundle - * Affected bundle or null for system bundle. - * @param throwable - * Related exception or null. + * @param type FrameworkEvent type. + * @param bundle Affected bundle or null for system bundle. + * @param throwable Related exception or null. */ public void publishFrameworkEvent(int type, Bundle bundle, Throwable throwable) { publishFrameworkEvent(type, bundle, throwable, (FrameworkListener[]) null); } - public void publishFrameworkEvent(int type, Bundle bundle, Throwable throwable, final FrameworkListener... listeners) { + public void publishFrameworkEvent(int type, Bundle bundle, Throwable throwable, + final FrameworkListener... listeners) { if (bundle == null) bundle = container.getStorage().getModuleContainer().getModule(0).getBundle(); final FrameworkEvent event = new FrameworkEvent(type, bundle, throwable); @@ -289,7 +295,8 @@ public void publishFrameworkEventPrivileged(FrameworkEvent event, FrameworkListe Map>> listenerSnapshot; synchronized (allFrameworkListeners) { listenerSnapshot = new LinkedHashMap<>(allFrameworkListeners.size()); - for (Map.Entry> entry : allFrameworkListeners.entrySet()) { + for (Map.Entry> entry : allFrameworkListeners + .entrySet()) { CopyOnWriteIdentityMap listeners = entry.getValue(); if (!listeners.isEmpty()) { listenerSnapshot.put(entry.getKey(), listeners.entrySet()); @@ -310,16 +317,19 @@ public void publishFrameworkEventPrivileged(FrameworkEvent event, FrameworkListe } // We use the system bundle context as the dispatcher if (listeners.size() > 0) { - BundleContextImpl systemContext = (BundleContextImpl) container.getStorage().getModuleContainer().getModule(0).getBundle().getBundleContext(); - @SuppressWarnings({"rawtypes", "unchecked"}) + BundleContextImpl systemContext = (BundleContextImpl) container.getStorage().getModuleContainer() + .getModule(0).getBundle().getBundleContext(); + @SuppressWarnings({ "rawtypes", "unchecked" }) EventDispatcher dispatcher = (EventDispatcher) systemContext; queue.queueListeners(listeners.entrySet(), dispatcher); } } - for (Map.Entry>> entry : listenerSnapshot.entrySet()) { - @SuppressWarnings({"rawtypes", "unchecked"}) - EventDispatcher dispatcher = (EventDispatcher) entry.getKey(); + for (Map.Entry>> entry : listenerSnapshot + .entrySet()) { + @SuppressWarnings({ "rawtypes", "unchecked" }) + EventDispatcher dispatcher = (EventDispatcher) entry + .getKey(); Set> listeners = entry.getValue(); queue.queueListeners(listeners, dispatcher); } @@ -332,8 +342,9 @@ public void publishFrameworkEventPrivileged(FrameworkEvent event, FrameworkListe } /** - * Coerce the generic type of a collection from Collection - * to Collection + * Coerce the generic type of a collection from Collection to + * Collection + * * @param c Collection to be coerced. * @return c coerced to Collection */ @@ -346,7 +357,8 @@ void addBundleListener(BundleListener listener, BundleContextImpl context) { if (listener instanceof SynchronousBundleListener) { container.checkAdminPermission(context.getBundle(), AdminPermission.LISTENER); synchronized (allSyncBundleListeners) { - CopyOnWriteIdentityMap listeners = allSyncBundleListeners.get(context); + CopyOnWriteIdentityMap listeners = allSyncBundleListeners + .get(context); if (listeners == null) { listeners = new CopyOnWriteIdentityMap<>(); allSyncBundleListeners.put(context, listeners); @@ -369,7 +381,8 @@ void removeBundleListener(BundleListener listener, BundleContextImpl context) { if (listener instanceof SynchronousBundleListener) { container.checkAdminPermission(context.getBundle(), AdminPermission.LISTENER); synchronized (allSyncBundleListeners) { - CopyOnWriteIdentityMap listeners = allSyncBundleListeners.get(context); + CopyOnWriteIdentityMap listeners = allSyncBundleListeners + .get(context); if (listeners != null) listeners.remove(listener); } @@ -421,7 +434,7 @@ void flushFrameworkEvents() { EventDispatcher dispatcher = (el, lo, ea, signal) -> signal.countDown(); ListenerQueue queue = newListenerQueue(); - queue.queueListeners(Collections. singletonMap(dispatcher, dispatcher).entrySet(), dispatcher); + queue.queueListeners(Collections.singletonMap(dispatcher, dispatcher).entrySet(), dispatcher); // fire event with the flushedSignal latch CountDownLatch flushedSignal = new CountDownLatch(1); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/FilterImpl.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/FilterImpl.java index d30701f7778..e18701d98f8 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/FilterImpl.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/FilterImpl.java @@ -148,9 +148,7 @@ * *
  * Dictionary d = new Hashtable();
- * d.put("cn", new String[] {
- * 		"a", "b", "c"
- * });
+ * d.put("cn", new String[] { "a", "b", "c" });
  * 
* * d will match {@code (cn=a)} and also {@code (cn=b)} @@ -163,15 +161,15 @@ public abstract class FilterImpl implements Filter { private transient String filterString; /** - * Creates a {@link FilterImpl} object. This filter object may be used to - * match a {@link ServiceReference} or a Dictionary. + * Creates a {@link FilterImpl} object. This filter object may be used to match + * a {@link ServiceReference} or a Dictionary. *

* If the filter cannot be parsed, an {@link InvalidSyntaxException} will be * thrown with a human readable message where the filter became unparsable. * * @param filterString the filter string. - * @throws InvalidSyntaxException If the filter parameter contains an - * invalid filter string that cannot be parsed. + * @throws InvalidSyntaxException If the filter parameter contains an invalid + * filter string that cannot be parsed. */ public static FilterImpl newInstance(String filterString) throws InvalidSyntaxException { return newInstance(filterString, false); @@ -188,14 +186,13 @@ public static FilterImpl newInstance(String filterString, boolean debug) throws /** * Filter using a service's properties. *

- * This {@code Filter} is executed using the keys and values of the - * referenced service's properties. The keys are looked up in a case - * insensitive manner. + * This {@code Filter} is executed using the keys and values of the referenced + * service's properties. The keys are looked up in a case insensitive manner. * - * @param reference The reference to the service whose properties are used - * in the match. - * @return {@code true} if the service's properties match this - * {@code Filter}; {@code false} otherwise. + * @param reference The reference to the service whose properties are used in + * the match. + * @return {@code true} if the service's properties match this {@code Filter}; + * {@code false} otherwise. */ @Override public boolean match(ServiceReference reference) { @@ -204,15 +201,15 @@ public boolean match(ServiceReference reference) { /** * Filter using a {@code Dictionary} with case insensitive key lookup. This - * {@code Filter} is executed using the specified {@code Dictionary}'s keys - * and values. The keys are looked up in a case insensitive manner. + * {@code Filter} is executed using the specified {@code Dictionary}'s keys and + * values. The keys are looked up in a case insensitive manner. * - * @param dictionary The {@code Dictionary} whose key/value pairs are used - * in the match. - * @return {@code true} if the {@code Dictionary}'s values match this - * filter; {@code false} otherwise. - * @throws IllegalArgumentException If {@code dictionary} contains case - * variants of the same key name. + * @param dictionary The {@code Dictionary} whose key/value pairs are used in + * the match. + * @return {@code true} if the {@code Dictionary}'s values match this filter; + * {@code false} otherwise. + * @throws IllegalArgumentException If {@code dictionary} contains case variants + * of the same key name. */ @Override public boolean match(Dictionary dictionary) { @@ -220,14 +217,14 @@ public boolean match(Dictionary dictionary) { } /** - * Filter using a {@code Dictionary}. This {@code Filter} is executed using - * the specified {@code Dictionary}'s keys and values. The keys are looked - * up in a normal manner respecting case. + * Filter using a {@code Dictionary}. This {@code Filter} is executed using the + * specified {@code Dictionary}'s keys and values. The keys are looked up in a + * normal manner respecting case. * - * @param dictionary The {@code Dictionary} whose key/value pairs are used - * in the match. - * @return {@code true} if the {@code Dictionary}'s values match this - * filter; {@code false} otherwise. + * @param dictionary The {@code Dictionary} whose key/value pairs are used in + * the match. + * @return {@code true} if the {@code Dictionary}'s values match this filter; + * {@code false} otherwise. * @since 1.3 */ @Override @@ -237,12 +234,12 @@ public boolean matchCase(Dictionary dictionary) { /** * Filter using a {@code Map}. This {@code Filter} is executed using the - * specified {@code Map}'s keys and values. The keys are looked up in a - * normal manner respecting case. + * specified {@code Map}'s keys and values. The keys are looked up in a normal + * manner respecting case. * - * @param map The {@code Map} whose key/value pairs are used in the match. - * Maps with {@code null} key or values are not supported. A - * {@code null} value is considered not present to the filter. + * @param map The {@code Map} whose key/value pairs are used in the match. Maps + * with {@code null} key or values are not supported. A {@code null} + * value is considered not present to the filter. * @return {@code true} if the {@code Map}'s values match this filter; * {@code false} otherwise. * @since 1.6 @@ -257,8 +254,8 @@ public boolean matches(Map map) { /** * Returns this {@code Filter}'s filter string. *

- * The filter string is normalized by removing whitespace which does not - * affect the meaning of the filter. + * The filter string is normalized by removing whitespace which does not affect + * the meaning of the filter. * * @return This {@code Filter}'s filter string. */ @@ -274,8 +271,8 @@ public String toString() { /** * Returns this {@code Filter}'s normalized filter string. *

- * The filter string is normalized by removing whitespace which does not - * affect the meaning of the filter. + * The filter string is normalized by removing whitespace which does not affect + * the meaning of the filter. * * @return This {@code Filter}'s filter string. */ @@ -346,12 +343,15 @@ StringBuilder normalize(StringBuilder sb) { @Override public String getPrimaryKeyValue(String primaryKey) { - // just checking for simple filters here where primaryKey is the only attr or it is one attr of a base '&' clause + // just checking for simple filters here where primaryKey is the only attr or it + // is one attr of a base '&' clause // (primaryKey=org.acme.BrickService) OK // (&(primaryKey=org.acme.BrickService)(|(vendor=IBM)(vendor=SUN))) OK // (primaryKey=org.acme.*) NOT OK - // (|(primaryKey=org.acme.BrickService)(primaryKey=org.acme.CementService)) NOT OK - // (&(primaryKey=org.acme.BrickService)(primaryKey=org.acme.CementService)) OK but only the first primaryKey is returned + // (|(primaryKey=org.acme.BrickService)(primaryKey=org.acme.CementService)) NOT + // OK + // (&(primaryKey=org.acme.BrickService)(primaryKey=org.acme.CementService)) OK + // but only the first primaryKey is returned for (FilterImpl operand : operands) { if (operand instanceof Equal) { String result = operand.getPrimaryKeyValue(primaryKey); @@ -702,15 +702,15 @@ static StringBuilder encodeValue(StringBuilder sb, String value) { for (int i = 0, len = value.length(); i < len; i++) { char c = value.charAt(i); switch (c) { - case '(' : - case '*' : - case ')' : - case '\\' : - sb.append('\\'); - // FALL-THROUGH - default : - sb.append(c); - break; + case '(': + case '*': + case ')': + case '\\': + sb.append('\\'); + // FALL-THROUGH + default: + sb.append(c); + break; } } return sb; @@ -1201,7 +1201,8 @@ boolean compare_Character(char charval) { } catch (IndexOutOfBoundsException e) { return false; } - return (charval == charval2) || (Character.toUpperCase(charval) == Character.toUpperCase(charval2)) || (Character.toLowerCase(charval) == Character.toLowerCase(charval2)); + return (charval == charval2) || (Character.toUpperCase(charval) == Character.toUpperCase(charval2)) + || (Character.toLowerCase(charval) == Character.toLowerCase(charval2)); } @Override @@ -1211,9 +1212,8 @@ StringBuilder normalize(StringBuilder sb) { } /** - * Map a string for an APPROX (~=) comparison. This implementation - * removes white spaces. This is the minimum implementation allowed by - * the OSGi spec. + * Map a string for an APPROX (~=) comparison. This implementation removes white + * spaces. This is the minimum implementation allowed by the OSGi spec. * * @param input Input string. * @return String ready for APPROX comparison. @@ -1247,27 +1247,34 @@ public Map getStandardOSGiAttributes(String... versions) { } /** - * Returns the leftmost required objectClass value for the filter to evaluate to true. + * Returns the leftmost required objectClass value for the filter to evaluate to + * true. * - * @return The leftmost required objectClass value or null if none could be determined. + * @return The leftmost required objectClass value or null if none could be + * determined. */ public String getRequiredObjectClass() { return getPrimaryKeyValue(Constants.OBJECTCLASS); } /** - * Returns the leftmost required primary key value for the filter to evaluate to true. - * This is useful for indexing candidates to match against this filter. + * Returns the leftmost required primary key value for the filter to evaluate to + * true. This is useful for indexing candidates to match against this filter. + * * @param primaryKey the primary key - * @return The leftmost required primary key value or null if none could be determined. + * @return The leftmost required primary key value or null if none could be + * determined. */ public String getPrimaryKeyValue(String primaryKey) { - // just checking for simple filters here where primaryKey is the only attr or it is one attr of a base '&' clause + // just checking for simple filters here where primaryKey is the only attr or it + // is one attr of a base '&' clause // (primaryKey=org.acme.BrickService) OK // (&(primaryKey=org.acme.BrickService)(|(vendor=IBM)(vendor=SUN))) OK // (primaryKey=org.acme.*) NOT OK - // (|(primaryKey=org.acme.BrickService)(primaryKey=org.acme.CementService)) NOT OK - // (&(primaryKey=org.acme.BrickService)(primaryKey=org.acme.CementService)) OK but only the first objectClass is returned + // (|(primaryKey=org.acme.BrickService)(primaryKey=org.acme.CementService)) NOT + // OK + // (&(primaryKey=org.acme.BrickService)(primaryKey=org.acme.CementService)) OK + // but only the first objectClass is returned return null; } @@ -1277,6 +1284,7 @@ public List getChildren() { /** * Returns all the attributes contained within this filter + * * @return all the attributes contained within this filter */ public String[] getAttributes() { @@ -1309,9 +1317,8 @@ public Map getStandardOSGiAttributes(String... versions) { abstract void addAttributes(Map attributes, Map versionAttrs, boolean not); /** - * Parser class for OSGi filter strings. This class parses the complete - * filter string and builds a tree of FilterImpl objects rooted at the - * parent. + * Parser class for OSGi filter strings. This class parses the complete filter + * string and builds a tree of FilterImpl objects rooted at the parent. */ static private final class Parser { private final boolean debug; @@ -1335,7 +1342,8 @@ FilterImpl parse() throws InvalidSyntaxException { } if (pos != filterChars.length) { - throw new InvalidSyntaxException(NLS.bind(Msg.FILTER_TRAILING_CHARACTERS, filterstring.substring(pos)), filterstring); + throw new InvalidSyntaxException(NLS.bind(Msg.FILTER_TRAILING_CHARACTERS, filterstring.substring(pos)), + filterstring); } return filter; } @@ -1345,7 +1353,8 @@ private FilterImpl parse_filter() throws InvalidSyntaxException { skipWhiteSpace(); if (filterChars[pos] != '(') { - throw new InvalidSyntaxException(NLS.bind(Msg.FILTER_MISSING_LEFTPAREN, filterstring.substring(pos)), filterstring); + throw new InvalidSyntaxException(NLS.bind(Msg.FILTER_MISSING_LEFTPAREN, filterstring.substring(pos)), + filterstring); } pos++; @@ -1355,7 +1364,8 @@ private FilterImpl parse_filter() throws InvalidSyntaxException { skipWhiteSpace(); if (filterChars[pos] != ')') { - throw new InvalidSyntaxException(NLS.bind(Msg.FILTER_MISSING_RIGHTPAREN, filterstring.substring(pos)), filterstring); + throw new InvalidSyntaxException(NLS.bind(Msg.FILTER_MISSING_RIGHTPAREN, filterstring.substring(pos)), + filterstring); } pos++; @@ -1371,18 +1381,18 @@ private FilterImpl parse_filtercomp() throws InvalidSyntaxException { char c = filterChars[pos]; switch (c) { - case '&' : { - pos++; - return parse_and(); - } - case '|' : { - pos++; - return parse_or(); - } - case '!' : { - pos++; - return parse_not(); - } + case '&': { + pos++; + return parse_and(); + } + case '|': { + pos++; + return parse_or(); + } + case '!': { + pos++; + return parse_not(); + } } return parse_item(); } @@ -1445,56 +1455,57 @@ private FilterImpl parse_item() throws InvalidSyntaxException { skipWhiteSpace(); switch (filterChars[pos]) { - case '~' : { - if (filterChars[pos + 1] == '=') { - pos += 2; - return new FilterImpl.Approx(attr, parse_value(), debug); - } - break; + case '~': { + if (filterChars[pos + 1] == '=') { + pos += 2; + return new FilterImpl.Approx(attr, parse_value(), debug); } - case '>' : { - if (filterChars[pos + 1] == '=') { - pos += 2; - return new FilterImpl.GreaterEqual(attr, parse_value(), debug); - } - break; + break; + } + case '>': { + if (filterChars[pos + 1] == '=') { + pos += 2; + return new FilterImpl.GreaterEqual(attr, parse_value(), debug); } - case '<' : { - if (filterChars[pos + 1] == '=') { - pos += 2; - return new FilterImpl.LessEqual(attr, parse_value(), debug); - } - break; + break; + } + case '<': { + if (filterChars[pos + 1] == '=') { + pos += 2; + return new FilterImpl.LessEqual(attr, parse_value(), debug); } - case '=' : { - if (filterChars[pos + 1] == '*') { - int oldpos = pos; - pos += 2; - skipWhiteSpace(); - if (filterChars[pos] == ')') { - return new FilterImpl.Present(attr, debug); - } - pos = oldpos; + break; + } + case '=': { + if (filterChars[pos + 1] == '*') { + int oldpos = pos; + pos += 2; + skipWhiteSpace(); + if (filterChars[pos] == ')') { + return new FilterImpl.Present(attr, debug); } + pos = oldpos; + } - pos++; - String[] substrings = parse_substring(); + pos++; + String[] substrings = parse_substring(); - int length = substrings.length; - if (length == 0) { - return new FilterImpl.Equal(attr, "", debug); //$NON-NLS-1$ - } - if (length == 1) { - String single = substrings[0]; - if (single != null) { - return new FilterImpl.Equal(attr, single, debug); - } + int length = substrings.length; + if (length == 0) { + return new FilterImpl.Equal(attr, "", debug); //$NON-NLS-1$ + } + if (length == 1) { + String single = substrings[0]; + if (single != null) { + return new FilterImpl.Equal(attr, single, debug); } - return new FilterImpl.Substring(attr, substrings, debug); } + return new FilterImpl.Substring(attr, substrings, debug); + } } - throw new InvalidSyntaxException(NLS.bind(Msg.FILTER_INVALID_OPERATOR, filterstring.substring(pos)), filterstring); + throw new InvalidSyntaxException(NLS.bind(Msg.FILTER_INVALID_OPERATOR, filterstring.substring(pos)), + filterstring); } private String parse_attr() throws InvalidSyntaxException { @@ -1518,7 +1529,8 @@ private String parse_attr() throws InvalidSyntaxException { int length = end - begin; if (length == 0) { - throw new InvalidSyntaxException(NLS.bind(Msg.FILTER_MISSING_ATTR, filterstring.substring(pos)), filterstring); + throw new InvalidSyntaxException(NLS.bind(Msg.FILTER_MISSING_ATTR, filterstring.substring(pos)), + filterstring); } return new String(filterChars, begin, length); @@ -1531,30 +1543,32 @@ private String parse_value() throws InvalidSyntaxException { char c = filterChars[pos]; switch (c) { - case ')' : { - break parseloop; - } + case ')': { + break parseloop; + } - case '(' : { - throw new InvalidSyntaxException(NLS.bind(Msg.FILTER_INVALID_VALUE, filterstring.substring(pos)), filterstring); - } + case '(': { + throw new InvalidSyntaxException(NLS.bind(Msg.FILTER_INVALID_VALUE, filterstring.substring(pos)), + filterstring); + } - case '\\' : { - pos++; - c = filterChars[pos]; - /* fall through into default */ - } + case '\\': { + pos++; + c = filterChars[pos]; + /* fall through into default */ + } - default : { - sb.append(c); - pos++; - break; - } + default: { + sb.append(c); + pos++; + break; + } } } if (sb.length() == 0) { - throw new InvalidSyntaxException(NLS.bind(Msg.FILTER_MISSING_VALUE, filterstring.substring(pos)), filterstring); + throw new InvalidSyntaxException(NLS.bind(Msg.FILTER_MISSING_VALUE, filterstring.substring(pos)), + filterstring); } return sb.toString(); @@ -1569,42 +1583,43 @@ private String[] parse_substring() throws InvalidSyntaxException { char c = filterChars[pos]; switch (c) { - case ')' : { - if (sb.length() > 0) { - operands.add(sb.toString()); - } - - break parseloop; + case ')': { + if (sb.length() > 0) { + operands.add(sb.toString()); } - case '(' : { - throw new InvalidSyntaxException(NLS.bind(Msg.FILTER_INVALID_VALUE, filterstring.substring(pos)), filterstring); - } + break parseloop; + } - case '*' : { - if (sb.length() > 0) { - operands.add(sb.toString()); - } + case '(': { + throw new InvalidSyntaxException(NLS.bind(Msg.FILTER_INVALID_VALUE, filterstring.substring(pos)), + filterstring); + } - sb.setLength(0); + case '*': { + if (sb.length() > 0) { + operands.add(sb.toString()); + } - operands.add(null); - pos++; + sb.setLength(0); - break; - } + operands.add(null); + pos++; - case '\\' : { - pos++; - c = filterChars[pos]; - /* fall through into default */ - } + break; + } - default : { - sb.append(c); - pos++; - break; - } + case '\\': { + pos++; + c = filterChars[pos]; + /* fall through into default */ + } + + default: { + sb.append(c); + pos++; + break; + } } } @@ -1619,10 +1634,9 @@ private void skipWhiteSpace() { } /** - * This Map is used for key lookup during filter - * evaluation. This Map implementation only supports the get operation using - * a String key as no other operations are used by the Filter - * implementation. + * This Map is used for key lookup during filter evaluation. This Map + * implementation only supports the get operation using a String key as no other + * operations are used by the Filter implementation. */ private static final class DictionaryMap extends AbstractMap implements Map { static Map asMap(Dictionary dictionary) { @@ -1640,8 +1654,8 @@ private static final class DictionaryMap extends AbstractMap imp * Create a case insensitive map from the specified dictionary. * * @param dictionary - * @throws IllegalArgumentException If {@code dictionary} contains case - * variants of the same key name. + * @throws IllegalArgumentException If {@code dictionary} contains case variants + * of the same key name. */ DictionaryMap(Dictionary dictionary) { this.dictionary = requireNonNull(dictionary); @@ -1660,9 +1674,8 @@ public Set> entrySet() { /** * This Map is used for key lookup from a ServiceReference during filter - * evaluation. This Map implementation only supports the get operation using - * a String key as no other operations are used by the Filter - * implementation. + * evaluation. This Map implementation only supports the get operation using a + * String key as no other operations are used by the Filter implementation. */ private static final class ServiceReferenceMap extends AbstractMap implements Map { static Map asMap(ServiceReference reference) { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/OSGiFrameworkHooks.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/OSGiFrameworkHooks.java index 3318d63f249..cd127650dbd 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/OSGiFrameworkHooks.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/OSGiFrameworkHooks.java @@ -72,29 +72,30 @@ public BundleCollisionHook(EquinoxContainer container) { @Override public void filterCollisions(int operationType, Module target, Collection collisionCandidates) { switch (container.getConfiguration().BSN_VERSION) { - case EquinoxConfiguration.BSN_VERSION_SINGLE : { - return; - } - case EquinoxConfiguration.BSN_VERSION_MULTIPLE : { - collisionCandidates.clear(); - return; - } - case EquinoxConfiguration.BSN_VERSION_MANAGED : { - Bundle targetBundle = target.getBundle(); - ArrayMap candidateBundles = new ArrayMap<>(collisionCandidates.size()); - for (Module module : collisionCandidates) { - candidateBundles.put(module.getBundle(), module); - } - notifyCollisionHooks(operationType, targetBundle, candidateBundles); - collisionCandidates.retainAll(candidateBundles.getValues()); - return; + case EquinoxConfiguration.BSN_VERSION_SINGLE: { + return; + } + case EquinoxConfiguration.BSN_VERSION_MULTIPLE: { + collisionCandidates.clear(); + return; + } + case EquinoxConfiguration.BSN_VERSION_MANAGED: { + Bundle targetBundle = target.getBundle(); + ArrayMap candidateBundles = new ArrayMap<>(collisionCandidates.size()); + for (Module module : collisionCandidates) { + candidateBundles.put(module.getBundle(), module); } - default : - throw new IllegalStateException("Bad configuration: " + container.getConfiguration().BSN_VERSION); //$NON-NLS-1$ + notifyCollisionHooks(operationType, targetBundle, candidateBundles); + collisionCandidates.retainAll(candidateBundles.getValues()); + return; + } + default: + throw new IllegalStateException("Bad configuration: " + container.getConfiguration().BSN_VERSION); //$NON-NLS-1$ } } - private void notifyCollisionHooks(final int operationType, final Bundle target, Collection collisionCandidates) { + private void notifyCollisionHooks(final int operationType, final Bundle target, + Collection collisionCandidates) { // Note that collision hook results are honored for the system bundle. final Collection shrinkable = new ShrinkableCollection<>(collisionCandidates); if (System.getSecurityManager() == null) { @@ -107,9 +108,11 @@ private void notifyCollisionHooks(final int operationType, final Bundle target, } } - void notifyCollisionHooksPriviledged(final int operationType, final Bundle target, final Collection collisionCandidates) { + void notifyCollisionHooksPriviledged(final int operationType, final Bundle target, + final Collection collisionCandidates) { if (debug.DEBUG_HOOKS) { - Debug.println("notifyCollisionHooks(" + operationType + ", " + target + ", " + collisionCandidates + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + Debug.println( + "notifyCollisionHooks(" + operationType + ", " + target + ", " + collisionCandidates + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } ServiceRegistry registry = container.getServiceRegistry(); if (registry != null) { @@ -120,9 +123,10 @@ void notifyCollisionHooksPriviledged(final int operationType, final Bundle targe } /** - * This class encapsulates the delegation to ResolverHooks that are registered with the service - * registry. This way the resolver implementation only has to call out to a single hook - * which does all the necessary service registry lookups. + * This class encapsulates the delegation to ResolverHooks that are registered + * with the service registry. This way the resolver implementation only has to + * call out to a single hook which does all the necessary service registry + * lookups. * * This class is not thread safe and expects external synchronization. * @@ -131,7 +135,8 @@ static class CoreResolverHookFactory implements ResolverHookFactory { // need a tuple to hold the service reference and hook object // do not use a map for performance reasons; no need to hash based on a key. static class HookReference { - public HookReference(ServiceReferenceImpl reference, ResolverHook hook, BundleContextImpl context) { + public HookReference(ServiceReferenceImpl reference, ResolverHook hook, + BundleContextImpl context) { this.reference = reference; this.hook = hook; this.context = context; @@ -163,11 +168,13 @@ void handleHookException(Throwable t, Object hook, String method) { throw new RuntimeException(message, new BundleException(message, BundleException.REJECTED_BY_HOOK, t)); } - private ServiceReferenceImpl[] getHookReferences(final ServiceRegistry registry, final BundleContextImpl context) { + private ServiceReferenceImpl[] getHookReferences(final ServiceRegistry registry, + final BundleContextImpl context) { return AccessController.doPrivileged((PrivilegedAction[]>) () -> { try { @SuppressWarnings("unchecked") - ServiceReferenceImpl[] result = (ServiceReferenceImpl[]) registry.getServiceReferences(context, ResolverHookFactory.class.getName(), null, false); + ServiceReferenceImpl[] result = (ServiceReferenceImpl[]) registry + .getServiceReferences(context, ResolverHookFactory.class.getName(), null, false); return result; } catch (InvalidSyntaxException e) { // cannot happen; no filter @@ -189,11 +196,11 @@ public ResolverHook begin(Collection triggers) { return new CoreResolverHook(Collections.emptyList(), systemModule); } - BundleContextImpl context = (BundleContextImpl) EquinoxContainer.secureAction.getContext(systemModule.getBundle()); + BundleContextImpl context = (BundleContextImpl) EquinoxContainer.secureAction + .getContext(systemModule.getBundle()); ServiceReferenceImpl[] refs = getHookReferences(registry, context); - List hookRefs = refs == null ? Collections.emptyList() - : new ArrayList<>(refs.length); + List hookRefs = refs == null ? Collections.emptyList() : new ArrayList<>(refs.length); if (refs != null) { for (ServiceReferenceImpl hookRef : refs) { ResolverHookFactory factory = EquinoxContainer.secureAction.getService(hookRef, context); @@ -234,7 +241,8 @@ public void filterResolvable(Collection candidates) { Debug.println("ResolverHook.filterResolvable(" + candidates + ")"); //$NON-NLS-1$ //$NON-NLS-2$ } if (isBootInit()) { - // only allow the system bundle and its fragments resolve during boot up and init + // only allow the system bundle and its fragments resolve during boot up and + // init for (Iterator iCandidates = candidates.iterator(); iCandidates.hasNext();) { BundleRevision revision = iCandidates.next(); if ((revision.getTypes() & BundleRevision.TYPE_FRAGMENT) == 0) { @@ -243,7 +251,8 @@ public void filterResolvable(Collection candidates) { iCandidates.remove(); } } - // just leave all fragments. Only the ones that are system bundle fragments will resolve + // just leave all fragments. Only the ones that are system bundle fragments will + // resolve // since we removed all the other possible hosts. } } @@ -270,9 +279,11 @@ private boolean isBootInit() { } @Override - public void filterSingletonCollisions(BundleCapability singleton, Collection collisionCandidates) { + public void filterSingletonCollisions(BundleCapability singleton, + Collection collisionCandidates) { if (debug.DEBUG_HOOKS) { - Debug.println("ResolverHook.filterSingletonCollisions(" + singleton + ", " + collisionCandidates + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + Debug.println( + "ResolverHook.filterSingletonCollisions(" + singleton + ", " + collisionCandidates + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } if (hooks.isEmpty()) return; @@ -323,7 +334,8 @@ public void end() { Throwable endError = null; HookReference endBadHook = null; for (HookReference hookRef : hooks) { - // We do not remove unregistered services here because we are going to remove all of them at the end + // We do not remove unregistered services here because we are going to remove + // all of them at the end if (hookRef.reference.getBundle() == null) { if (missingHook == null) missingHook = hookRef; diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/StorageSaver.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/StorageSaver.java index 13f239fbc26..4310bdd2a69 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/StorageSaver.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/StorageSaver.java @@ -30,7 +30,8 @@ public void run() { try { container.getStorage().save(); } catch (IOException e) { - container.getLogServices().log(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, "Error saving on update", e); //$NON-NLS-1$ + container.getLogServices().log(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, "Error saving on update", //$NON-NLS-1$ + e); } } } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/SystemBundleActivator.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/SystemBundleActivator.java index 65381c4f9e7..8d70db76429 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/SystemBundleActivator.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/SystemBundleActivator.java @@ -96,7 +96,6 @@ public void start(BundleContext bc) throws Exception { register(bc, PermissionAdmin.class, sa, null); register(bc, ConditionalPermissionAdmin.class, sa, null); - props.clear(); props.put(Constants.SERVICE_RANKING, Integer.MIN_VALUE); register(bc, Resolver.class, new ResolverImpl(new Logger(0), null), false, props); @@ -111,15 +110,19 @@ public void start(BundleContext bc) throws Exception { } props.clear(); - props.put("protocol", new String[] {BundleResourceHandler.OSGI_ENTRY_URL_PROTOCOL, BundleResourceHandler.OSGI_RESOURCE_URL_PROTOCOL}); //$NON-NLS-1$ + props.put("protocol", new String[] { BundleResourceHandler.OSGI_ENTRY_URL_PROTOCOL, //$NON-NLS-1$ + BundleResourceHandler.OSGI_RESOURCE_URL_PROTOCOL }); register(bc, URLConverter.class, new BundleURLConverter(), props); register(bc, BundleLocalization.class, new BundleLocalizationImpl(), null); - boolean setTccl = "true".equals(bundle.getEquinoxContainer().getConfiguration().getConfiguration("eclipse.parsers.setTCCL", "true")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + boolean setTccl = "true".equals( //$NON-NLS-1$ + bundle.getEquinoxContainer().getConfiguration().getConfiguration("eclipse.parsers.setTCCL", "true")); //$NON-NLS-1$ //$NON-NLS-2$ try { - register(bc, "javax.xml.parsers.SAXParserFactory", new XMLParsingServiceFactory(true, setTccl), false, null); //$NON-NLS-1$ - register(bc, "javax.xml.parsers.DocumentBuilderFactory", new XMLParsingServiceFactory(false, setTccl), false, null); //$NON-NLS-1$ + register(bc, "javax.xml.parsers.SAXParserFactory", new XMLParsingServiceFactory(true, setTccl), false, //$NON-NLS-1$ + null); + register(bc, "javax.xml.parsers.DocumentBuilderFactory", new XMLParsingServiceFactory(false, setTccl), //$NON-NLS-1$ + false, null); } catch (NoClassDefFoundError e) { // ignore; on a platform with no javax.xml (Java 8 SE compact1 profile) } @@ -208,7 +211,8 @@ public void stop(BundleContext bc) throws Exception { bundle.getEquinoxContainer().getStorage().getExtensionInstaller().stopExtensionActivators(bc); - FrameworkDebugOptions dbgOptions = (FrameworkDebugOptions) bundle.getEquinoxContainer().getConfiguration().getDebugOptions(); + FrameworkDebugOptions dbgOptions = (FrameworkDebugOptions) bundle.getEquinoxContainer().getConfiguration() + .getDebugOptions(); dbgOptions.stop(bc); urlFactoryManager.uninstallHandlerFactories(); @@ -228,15 +232,18 @@ private void unintallSecurityManager() { setSecurityManagner = null; } - private void register(BundleContext context, Class serviceClass, Object service, Dictionary properties) { + private void register(BundleContext context, Class serviceClass, Object service, + Dictionary properties) { register(context, serviceClass.getName(), service, true, properties); } - private void register(BundleContext context, Class serviceClass, Object service, boolean setRanking, Dictionary properties) { + private void register(BundleContext context, Class serviceClass, Object service, boolean setRanking, + Dictionary properties) { register(context, serviceClass.getName(), service, setRanking, properties); } - private void register(BundleContext context, String serviceClass, Object service, boolean setRanking, Dictionary properties) { + private void register(BundleContext context, String serviceClass, Object service, boolean setRanking, + Dictionary properties) { if (properties == null) properties = new Hashtable<>(); if (setRanking) { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/XMLParsingServiceFactory.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/XMLParsingServiceFactory.java index 29ea4aa59fa..867c793c918 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/XMLParsingServiceFactory.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/XMLParsingServiceFactory.java @@ -35,15 +35,13 @@ public Object getService(Bundle bundle, ServiceRegistration registration if (!setTccl || bundle == null) return createService(); /* - * Set the TCCL while creating jaxp factory instances to the - * requesting bundles class loader. This is needed to - * work around bug 285505. There are issues if multiple - * xerces implementations are available on the bundles class path + * Set the TCCL while creating jaxp factory instances to the requesting bundles + * class loader. This is needed to work around bug 285505. There are issues if + * multiple xerces implementations are available on the bundles class path * - * The real issue is that the ContextFinder will only delegate - * to the framework class loader in this case. This class - * loader forces the requesting bundle to be delegated to for - * TCCL loads. + * The real issue is that the ContextFinder will only delegate to the framework + * class loader in this case. This class loader forces the requesting bundle to + * be delegated to for TCCL loads. */ final ClassLoader savedClassLoader = Thread.currentThread().getContextClassLoader(); try { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/legacy/PackageAdminImpl.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/legacy/PackageAdminImpl.java index a4402065a1b..bfae9b027a2 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/legacy/PackageAdminImpl.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/framework/legacy/PackageAdminImpl.java @@ -110,7 +110,8 @@ public ExportedPackage[] getExportedPackages(String name) { String filter = "(" + PackageNamespace.PACKAGE_NAMESPACE + "=" + (name == null ? "*" : name) + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$//$NON-NLS-4$ Map directives = Collections.singletonMap(Namespace.REQUIREMENT_FILTER_DIRECTIVE, filter); Map attributes = Collections.singletonMap(Capabilities.SYNTHETIC_REQUIREMENT, Boolean.TRUE); - Requirement packageReq = ModuleContainer.createRequirement(PackageNamespace.PACKAGE_NAMESPACE, directives, attributes); + Requirement packageReq = ModuleContainer.createRequirement(PackageNamespace.PACKAGE_NAMESPACE, directives, + attributes); Collection packageCaps = frameworkWiring.findProviders(packageReq); InternalUtils.filterCapabilityPermissions(packageCaps); List result = new ArrayList<>(); @@ -136,8 +137,7 @@ public ExportedPackage[] getExportedPackages(String name) { } for (ModuleWiring moduleWiring : wirings) { Object pkgName = capability.getAttributes().get(PackageNamespace.PACKAGE_NAMESPACE); - if (pkgName instanceof String - && !moduleWiring.isSubstitutedPackage((String) pkgName)) { + if (pkgName instanceof String && !moduleWiring.isSubstitutedPackage((String) pkgName)) { result.add(new ExportedPackageImpl((ModuleCapability) capability, moduleWiring)); } } @@ -158,10 +158,12 @@ public boolean resolveBundles(Bundle[] input) { @Override public RequiredBundle[] getRequiredBundles(String symbolicName) { - String filter = "(" + BundleNamespace.BUNDLE_NAMESPACE + "=" + (symbolicName == null ? "*" : symbolicName) + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$//$NON-NLS-4$ + String filter = "(" + BundleNamespace.BUNDLE_NAMESPACE + "=" + (symbolicName == null ? "*" : symbolicName) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + + ")"; //$NON-NLS-1$ Map directives = Collections.singletonMap(Namespace.REQUIREMENT_FILTER_DIRECTIVE, filter); Map attributes = Collections.singletonMap(Capabilities.SYNTHETIC_REQUIREMENT, Boolean.TRUE); - Requirement bundleReq = ModuleContainer.createRequirement(BundleNamespace.BUNDLE_NAMESPACE, directives, attributes); + Requirement bundleReq = ModuleContainer.createRequirement(BundleNamespace.BUNDLE_NAMESPACE, directives, + attributes); Collection bundleCaps = frameworkWiring.findProviders(bundleReq); InternalUtils.filterCapabilityPermissions(bundleCaps); Collection result = new ArrayList<>(); @@ -184,8 +186,11 @@ public Bundle[] getBundles(String symbolicName, String versionRange) { symbolicName = EquinoxContainer.NAME; } VersionRange range = versionRange == null ? null : new VersionRange(versionRange); - String filter = (range != null ? "(&" : "") + "(" + IdentityNamespace.IDENTITY_NAMESPACE + "=" + symbolicName + ")" + (range != null ? range.toFilterString(IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE) + ")" : ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ - Requirement identityReq = ModuleContainer.createRequirement(IdentityNamespace.IDENTITY_NAMESPACE, Collections.singletonMap(Namespace.REQUIREMENT_FILTER_DIRECTIVE, filter), Collections.emptyMap()); + String filter = (range != null ? "(&" : "") + "(" + IdentityNamespace.IDENTITY_NAMESPACE + "=" + symbolicName //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + + ")" //$NON-NLS-1$ + + (range != null ? range.toFilterString(IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE) + ")" : ""); //$NON-NLS-1$ //$NON-NLS-2$ + Requirement identityReq = ModuleContainer.createRequirement(IdentityNamespace.IDENTITY_NAMESPACE, + Collections.singletonMap(Namespace.REQUIREMENT_FILTER_DIRECTIVE, filter), Collections.emptyMap()); Collection identityCaps = frameworkWiring.findProviders(identityReq); if (identityCaps.isEmpty()) { @@ -332,7 +337,8 @@ public Bundle[] getImportingBundles() { private static void addRequirers(Set importing, ModuleWiring wiring, String packageName) { List requirerWires = wiring.getProvidedModuleWires(BundleNamespace.BUNDLE_NAMESPACE); if (requirerWires == null) { - // we don't hold locks while checking the graph, just return if no longer isInUse + // we don't hold locks while checking the graph, just return if no longer + // isInUse return; } for (ModuleWire requireBundleWire : requirerWires) { @@ -343,18 +349,21 @@ private static void addRequirers(Set importing, ModuleWiring wiring, Str importing.add(requirer); // if reexported then need to add any requirers of the reexporter - String reExport = requireBundleWire.getRequirement().getDirectives().get(BundleNamespace.REQUIREMENT_VISIBILITY_DIRECTIVE); + String reExport = requireBundleWire.getRequirement().getDirectives() + .get(BundleNamespace.REQUIREMENT_VISIBILITY_DIRECTIVE); ModuleWiring requirerWiring = requireBundleWire.getRequirerWiring(); if (BundleNamespace.VISIBILITY_REEXPORT.equals(reExport)) { addRequirers(importing, requirerWiring, packageName); } - // also need to add any importers of the same package as the wiring exports; case of aggregations + // also need to add any importers of the same package as the wiring exports; + // case of aggregations if (!requirerWiring.equals(wiring)) { List providedPackages = requirerWiring .getProvidedModuleWires(PackageNamespace.PACKAGE_NAMESPACE); if (providedPackages != null) { for (ModuleWire packageWire : providedPackages) { - if (packageName.equals(packageWire.getCapability().getAttributes().get(PackageNamespace.PACKAGE_NAMESPACE))) { + if (packageName.equals(packageWire.getCapability().getAttributes() + .get(PackageNamespace.PACKAGE_NAMESPACE))) { importing.add(packageWire.getRequirer().getBundle()); if (packageWire.getRequirerWiring().isSubstitutedPackage(packageName)) { addRequirers(importing, packageWire.getRequirerWiring(), packageName); @@ -366,7 +375,6 @@ private static void addRequirers(Set importing, ModuleWiring wiring, Str } } - /** * @deprecated */ @@ -377,7 +385,8 @@ public String getSpecificationVersion() { @Override public Version getVersion() { - Version version = (Version) packageCapability.getAttributes().get(PackageNamespace.CAPABILITY_VERSION_ATTRIBUTE); + Version version = (Version) packageCapability.getAttributes() + .get(PackageNamespace.CAPABILITY_VERSION_ATTRIBUTE); return version == null ? Version.emptyVersion : version; } @@ -428,7 +437,8 @@ public Bundle[] getRequiringBundles() { private static void addRequirers(Set requiring, ModuleWiring providerWiring) { List requirerWires = providerWiring.getProvidedModuleWires(BundleNamespace.BUNDLE_NAMESPACE); if (requirerWires == null) { - // we don't hold locks while checking the graph, just return if no longer isInUse + // we don't hold locks while checking the graph, just return if no longer + // isInUse return; } for (ModuleWire requireBundleWire : requirerWires) { @@ -437,7 +447,8 @@ private static void addRequirers(Set requiring, ModuleWiring providerWir continue; } requiring.add(requirer); - String reExport = requireBundleWire.getRequirement().getDirectives().get(BundleNamespace.REQUIREMENT_VISIBILITY_DIRECTIVE); + String reExport = requireBundleWire.getRequirement().getDirectives() + .get(BundleNamespace.REQUIREMENT_VISIBILITY_DIRECTIVE); if (BundleNamespace.VISIBILITY_REEXPORT.equals(reExport)) { addRequirers(requiring, requireBundleWire.getRequirerWiring()); } @@ -446,7 +457,8 @@ private static void addRequirers(Set requiring, ModuleWiring providerWir @Override public Version getVersion() { - Version version = (Version) bundleCapability.getAttributes().get(PackageNamespace.CAPABILITY_VERSION_ATTRIBUTE); + Version version = (Version) bundleCapability.getAttributes() + .get(PackageNamespace.CAPABILITY_VERSION_ATTRIBUTE); return version == null ? Version.emptyVersion : version; } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/hookregistry/ActivatorHookFactory.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/hookregistry/ActivatorHookFactory.java index 1115d1e5768..5b13a9fa02d 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/hookregistry/ActivatorHookFactory.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/hookregistry/ActivatorHookFactory.java @@ -16,14 +16,12 @@ import org.osgi.framework.BundleActivator; /** - * A factory for creating bundle activators for an - * equinox hook. + * A factory for creating bundle activators for an equinox hook. */ public interface ActivatorHookFactory { /** - * Creates an activator for an equinox hook. The returned - * activator will be called when the system bundle is - * started and stopped. + * Creates an activator for an equinox hook. The returned activator will be + * called when the system bundle is started and stopped. * */ public BundleActivator createActivator(); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/hookregistry/BundleFileWrapperFactoryHook.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/hookregistry/BundleFileWrapperFactoryHook.java index 6d38949f3b2..52e31dabdf8 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/hookregistry/BundleFileWrapperFactoryHook.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/hookregistry/BundleFileWrapperFactoryHook.java @@ -23,13 +23,15 @@ */ public interface BundleFileWrapperFactoryHook { /** - * Wraps a bundle file for the given content and base data. If the - * specified bundle file should not be wrapped then null is returned + * Wraps a bundle file for the given content and base data. If the specified + * bundle file should not be wrapped then null is returned + * * @param bundleFile the bundle file to be wrapped * @param generation the generation the bundle file is for - * @param base true if the content is for the base bundle (not an inner jar, directory etc.) - * @return a wrapped bundle file for the specified content, or null if the bundle content - * is not wrapped. + * @param base true if the content is for the base bundle (not an inner + * jar, directory etc.) + * @return a wrapped bundle file for the specified content, or null if the + * bundle content is not wrapped. */ BundleFileWrapper wrapBundleFile(BundleFile bundleFile, Generation generation, boolean base); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/hookregistry/ClassLoaderHook.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/hookregistry/ClassLoaderHook.java index 3a906b9e0af..6657753a329 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/hookregistry/ClassLoaderHook.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/hookregistry/ClassLoaderHook.java @@ -32,54 +32,74 @@ */ public abstract class ClassLoaderHook { /** - * Gets called by a classpath manager before defining a class. This method allows a class loading hook - * to process the bytes of a class that is about to be defined and return a transformed byte array. - * @param name the name of the class being defined - * @param classbytes the bytes of the class being defined - * @param classpathEntry the ClasspathEntry where the class bytes have been read from. - * @param entry the BundleEntry source of the class bytes - * @param manager the class path manager used to define the requested class - * @return a transformed array of classbytes or null if the original bytes should be used. + * Gets called by a classpath manager before defining a class. This method + * allows a class loading hook to process the bytes of a class that is about to + * be defined and return a transformed byte array. + * + * @param name the name of the class being defined + * @param classbytes the bytes of the class being defined + * @param classpathEntry the ClasspathEntry where the class bytes have been read + * from. + * @param entry the BundleEntry source of the class bytes + * @param manager the class path manager used to define the requested + * class + * @return a transformed array of classbytes or null if the original bytes + * should be used. */ - public byte[] processClass(String name, byte[] classbytes, ClasspathEntry classpathEntry, BundleEntry entry, ClasspathManager manager) { + public byte[] processClass(String name, byte[] classbytes, ClasspathEntry classpathEntry, BundleEntry entry, + ClasspathManager manager) { return null; } /** - * Gets called by a classpath manager before defining a class. This method allows a class loading hook - * to reject a transformation to the class bytes by a - * {@link #processClass(String, byte[], ClasspathEntry, BundleEntry, ClasspathManager) processClass} method. - * @param name the name of the class being defined + * Gets called by a classpath manager before defining a class. This method + * allows a class loading hook to reject a transformation to the class bytes by + * a + * {@link #processClass(String, byte[], ClasspathEntry, BundleEntry, ClasspathManager) + * processClass} method. + * + * @param name the name of the class being defined * @param transformedBytes the transformed bytes of the class being defined - * @param classpathEntry the ClasspathEntry where the class bytes have been read from - * @param entry the BundleEntry source of the class bytes - * @param manager the class path manager used to define the requested class - * @return returns true if the modified bytes should be rejected; otherwise false is returned + * @param classpathEntry the ClasspathEntry where the class bytes have been + * read from + * @param entry the BundleEntry source of the class bytes + * @param manager the class path manager used to define the requested + * class + * @return returns true if the modified bytes should be rejected; otherwise + * false is returned */ - public boolean rejectTransformation(String name, byte[] transformedBytes, ClasspathEntry classpathEntry, BundleEntry entry, ClasspathManager manager) { + public boolean rejectTransformation(String name, byte[] transformedBytes, ClasspathEntry classpathEntry, + BundleEntry entry, ClasspathManager manager) { return false; } /** - * Gets called by a classpath manager when looking for ClasspathEntry objects. This method allows - * a class loading hook to add additional ClasspathEntry objects - * @param cpEntries the list of ClasspathEntry objects currently available for the requested classpath - * @param cp the name of the requested classpath - * @param hostmanager the classpath manager the requested ClasspathEntry is for + * Gets called by a classpath manager when looking for ClasspathEntry objects. + * This method allows a class loading hook to add additional ClasspathEntry + * objects + * + * @param cpEntries the list of ClasspathEntry objects currently + * available for the requested classpath + * @param cp the name of the requested classpath + * @param hostmanager the classpath manager the requested ClasspathEntry is + * for * @param sourceGeneration the source generation of the requested ClasspathEntry * @return true if a ClasspathEntry has been added to cpEntries */ - public boolean addClassPathEntry(ArrayList cpEntries, String cp, ClasspathManager hostmanager, Generation sourceGeneration) { + public boolean addClassPathEntry(ArrayList cpEntries, String cp, ClasspathManager hostmanager, + Generation sourceGeneration) { return false; } /** - * Gets called by a base data during {@link ModuleClassLoader#findLibrary(String)}. - * A this method is called for each configured class loading hook until one - * class loading hook returns a non-null value. If no class loading hook returns - * a non-null value then the default behavior will be used. + * Gets called by a base data during + * {@link ModuleClassLoader#findLibrary(String)}. A this method is called for + * each configured class loading hook until one class loading hook returns a + * non-null value. If no class loading hook returns a non-null value then the + * default behavior will be used. + * * @param generation the bundle generation to find a native library for. - * @param libName the name of the native library. + * @param libName the name of the native library. * @return The absolute path name of the native library or null. */ public String findLocalLibrary(Generation generation, String libName) { @@ -87,28 +107,31 @@ public String findLocalLibrary(Generation generation, String libName) { } /** - * Gets called by a bundle loader when {@link BundleLoader#getClassLoader()} - * is called the first time in order to allow a hook to create the class loader. - * This should rarely, if ever be overridden. The default implementation - * returns null indicating the built-in implementation should be used. - * Only one hook is able to provide the implementation of the module class loader - * and the first one to return non-null wins. + * Gets called by a bundle loader when {@link BundleLoader#getClassLoader()} is + * called the first time in order to allow a hook to create the class loader. + * This should rarely, if ever be overridden. The default implementation returns + * null indicating the built-in implementation should be used. Only one hook is + * able to provide the implementation of the module class loader and the first + * one to return non-null wins. * - * @param parent the parent classloader + * @param parent the parent classloader * @param configuration the equinox configuration - * @param delegate the delegate for this classloader - * @param generation the generation for this class loader - * @return returns an implementation of a module class loader or null - * if the built-in implemention is to be used. + * @param delegate the delegate for this classloader + * @param generation the generation for this class loader + * @return returns an implementation of a module class loader or + * null if the built-in implemention is to be used. */ - public ModuleClassLoader createClassLoader(ClassLoader parent, EquinoxConfiguration configuration, BundleLoader delegate, Generation generation) { + public ModuleClassLoader createClassLoader(ClassLoader parent, EquinoxConfiguration configuration, + BundleLoader delegate, Generation generation) { // do nothing return null; } /** * Gets called by a classpath manager at the end of - * {@link BundleLoader#getClassLoader()} is called the first time and a class loader is created. + * {@link BundleLoader#getClassLoader()} is called the first time and a class + * loader is created. + * * @param classLoader the newly created bundle classloader */ public void classLoaderCreated(ModuleClassLoader classLoader) { @@ -116,41 +139,53 @@ public void classLoaderCreated(ModuleClassLoader classLoader) { } /** - * Called by a {@link BundleLoader#findClass(String)} method before delegating to the resolved constraints and - * local bundle for a class load. If this method returns null then normal delegation is done. If this method - * returns a non-null value then the rest of the delegation process is skipped and the returned value is used. - * If this method throws a ClassNotFoundException then the calling + * Called by a {@link BundleLoader#findClass(String)} method before delegating + * to the resolved constraints and local bundle for a class load. If this method + * returns null then normal delegation is done. If this method returns a + * non-null value then the rest of the delegation process is skipped and the + * returned value is used. If this method throws a + * ClassNotFoundException then the calling * {@link BundleLoader#findClass(String)} method re-throws the exception. - * @param name the name of the class to find + * + * @param name the name of the class to find * @param classLoader the module class loader - * @return the class found by this hook or null if normal delegation should continue - * @throws ClassNotFoundException to terminate the delegation and throw an exception + * @return the class found by this hook or null if normal delegation should + * continue + * @throws ClassNotFoundException to terminate the delegation and throw an + * exception */ public Class preFindClass(String name, ModuleClassLoader classLoader) throws ClassNotFoundException { return null; } /** - * Called by a {@link BundleLoader#findClass(String)} method after delegating to the resolved constraints and - * local bundle for a class load. This method will only be called if no class was found - * from the normal delegation. - * @param name the name of the class to find + * Called by a {@link BundleLoader#findClass(String)} method after delegating to + * the resolved constraints and local bundle for a class load. This method will + * only be called if no class was found from the normal delegation. + * + * @param name the name of the class to find * @param classLoader the bundle class loader - * @return the class found by this hook or null if normal delegation should continue - * @throws ClassNotFoundException to terminate the delegation and throw an exception + * @return the class found by this hook or null if normal delegation should + * continue + * @throws ClassNotFoundException to terminate the delegation and throw an + * exception */ public Class postFindClass(String name, ModuleClassLoader classLoader) throws ClassNotFoundException { return null; } /** - * Called by a {@link BundleLoader#findResource(String)} before delegating to the resolved constraints and - * local bundle for a resource load. If this method returns null then normal delegation is done. - * If this method returns a non-null value then the rest of the delegation process is skipped and the returned value is used. - * If this method throws an FileNotFoundException then the delegation is terminated. - * @param name the name of the resource to find + * Called by a {@link BundleLoader#findResource(String)} before delegating to + * the resolved constraints and local bundle for a resource load. If this method + * returns null then normal delegation is done. If this method returns a + * non-null value then the rest of the delegation process is skipped and the + * returned value is used. If this method throws an + * FileNotFoundException then the delegation is terminated. + * + * @param name the name of the resource to find * @param classLoader the bundle class loader - * @return the resource found by this hook or null if normal delegation should continue + * @return the resource found by this hook or null if normal delegation should + * continue * @throws FileNotFoundException to terminate the delegation */ public URL preFindResource(String name, ModuleClassLoader classLoader) throws FileNotFoundException { @@ -158,12 +193,14 @@ public URL preFindResource(String name, ModuleClassLoader classLoader) throws Fi } /** - * Called by a {@link BundleLoader#findResource(String)} after delegating to the resolved constraints and - * local bundle for a resource load. This method will only be called if no resource was found - * from the normal delegation. - * @param name the name of the resource to find + * Called by a {@link BundleLoader#findResource(String)} after delegating to the + * resolved constraints and local bundle for a resource load. This method will + * only be called if no resource was found from the normal delegation. + * + * @param name the name of the resource to find * @param classLoader the bundle class loader - * @return the resource found by this hook or null if normal delegation should continue + * @return the resource found by this hook or null if normal delegation should + * continue * @throws FileNotFoundException to terminate the delegation */ public URL postFindResource(String name, ModuleClassLoader classLoader) throws FileNotFoundException { @@ -171,13 +208,17 @@ public URL postFindResource(String name, ModuleClassLoader classLoader) throws F } /** - * Called by a {@link BundleLoader#findResources(String)} before delegating to the resolved constraints and - * local bundle for a resource load. If this method returns null then normal delegation is done. - * If this method returns a non-null value then the rest of the delegation process is skipped and the returned value is used. - * If this method throws an FileNotFoundException then the delegation is terminated - * @param name the name of the resource to find + * Called by a {@link BundleLoader#findResources(String)} before delegating to + * the resolved constraints and local bundle for a resource load. If this method + * returns null then normal delegation is done. If this method returns a + * non-null value then the rest of the delegation process is skipped and the + * returned value is used. If this method throws an + * FileNotFoundException then the delegation is terminated + * + * @param name the name of the resource to find * @param classLoader the bundle class loader - * @return the resources found by this hook or null if normal delegation should continue + * @return the resources found by this hook or null if normal delegation should + * continue * @throws FileNotFoundException to terminate the delegation */ public Enumeration preFindResources(String name, ModuleClassLoader classLoader) throws FileNotFoundException { @@ -185,12 +226,14 @@ public Enumeration preFindResources(String name, ModuleClassLoader classLoa } /** - * Called by a {@link BundleLoader#findResources(String)} after delegating to the resolved constraints and - * local bundle for a resource load. This method will only be called if no resources were found - * from the normal delegation. - * @param name the name of the resource to find + * Called by a {@link BundleLoader#findResources(String)} after delegating to + * the resolved constraints and local bundle for a resource load. This method + * will only be called if no resources were found from the normal delegation. + * + * @param name the name of the resource to find * @param classLoader the bundle class loader - * @return the resources found by this hook or null if normal delegation should continue + * @return the resources found by this hook or null if normal delegation should + * continue * @throws FileNotFoundException to terminate the delegation */ public Enumeration postFindResources(String name, ModuleClassLoader classLoader) throws FileNotFoundException { @@ -198,12 +241,14 @@ public Enumeration postFindResources(String name, ModuleClassLoader classLo } /** - * Called by a {@link ClasspathManager} before normal delegation. If this method returns - * a non-null value then the rest of the delegation process is skipped and the returned value - * is used. - * @param name the name of the library to find + * Called by a {@link ClasspathManager} before normal delegation. If this method + * returns a non-null value then the rest of the delegation process is skipped + * and the returned value is used. + * + * @param name the name of the library to find * @param classLoader the bundle class loader - * @return the library found by this hook or null if normal delegation should continue + * @return the library found by this hook or null if normal delegation should + * continue * @throws FileNotFoundException to terminate the delegation */ public String preFindLibrary(String name, ModuleClassLoader classLoader) throws FileNotFoundException { @@ -211,22 +256,27 @@ public String preFindLibrary(String name, ModuleClassLoader classLoader) throws } /** - * Called by a {@link ClasspathManager} after normal delegation. This method will only be called - * if no library was found from the normal delegation. - * @param name the name of the library to find + * Called by a {@link ClasspathManager} after normal delegation. This method + * will only be called if no library was found from the normal delegation. + * + * @param name the name of the library to find * @param classLoader the bundle class loader - * @return the library found by this hook or null if normal delegation should continue + * @return the library found by this hook or null if normal delegation should + * continue */ public String postFindLibrary(String name, ModuleClassLoader classLoader) { return null; } /** - * Gets called by a classpath manager during {@link ClasspathManager#findLocalClass(String)} before - * searching the local classloader for a class. A classpath manager will call this method for - * each configured class loading hook. - * @param name the name of the requested class - * @param manager the classpath manager used to find and load the requested class + * Gets called by a classpath manager during + * {@link ClasspathManager#findLocalClass(String)} before searching the local + * classloader for a class. A classpath manager will call this method for each + * configured class loading hook. + * + * @param name the name of the requested class + * @param manager the classpath manager used to find and load the requested + * class * @throws ClassNotFoundException to prevent the requested class from loading */ public void preFindLocalClass(String name, ClasspathManager manager) throws ClassNotFoundException { @@ -234,24 +284,32 @@ public void preFindLocalClass(String name, ClasspathManager manager) throws Clas } /** - * Gets called by a classpath manager during {@link ClasspathManager#findLocalClass(String)} after - * searching the local classloader for a class. A classpath manager will call this method for - * each configured class loading hook. - * @param name the name of the requested class - * @param clazz the loaded class or null if not found - * @param manager the classpath manager used to find and load the requested class - * @throws ClassNotFoundException to prevent the requested class from loading. This is highly discouraged - * because if the class is non-null it is already too late to throw an exception. + * Gets called by a classpath manager during + * {@link ClasspathManager#findLocalClass(String)} after searching the local + * classloader for a class. A classpath manager will call this method for each + * configured class loading hook. + * + * @param name the name of the requested class + * @param clazz the loaded class or null if not found + * @param manager the classpath manager used to find and load the requested + * class + * @throws ClassNotFoundException to prevent the requested class from loading. + * This is highly discouraged because if the + * class is non-null it is already too late to + * throw an exception. */ - public void postFindLocalClass(String name, Class clazz, ClasspathManager manager) throws ClassNotFoundException { + public void postFindLocalClass(String name, Class clazz, ClasspathManager manager) + throws ClassNotFoundException { // do nothing } /** - * Gets called by a classpath manager during {@link ClasspathManager#findLocalResource(String)} before - * searching the local classloader for a resource. A classpath manager will call this method for + * Gets called by a classpath manager during + * {@link ClasspathManager#findLocalResource(String)} before searching the local + * classloader for a resource. A classpath manager will call this method for * each configured class loading hook. - * @param name the name of the requested resource + * + * @param name the name of the requested resource * @param manager the classpath manager used to find the requested resource * @throws NoSuchElementException will prevent the local resource from loading */ @@ -260,12 +318,14 @@ public void preFindLocalResource(String name, ClasspathManager manager) { } /** - * Gets called by a classpath manager during {@link ClasspathManager#findLocalResource(String)} after - * searching the local classloader for a resource. A classpath manager will call this method for + * Gets called by a classpath manager during + * {@link ClasspathManager#findLocalResource(String)} after searching the local + * classloader for a resource. A classpath manager will call this method for * each configured class loading hook. - * @param name the name of the requested resource + * + * @param name the name of the requested resource * @param resource the URL to the requested resource or null if not found - * @param manager the classpath manager used to find the requested resource + * @param manager the classpath manager used to find the requested resource * @throws NoSuchElementException will prevent the local resource from loading */ public void postFindLocalResource(String name, URL resource, ClasspathManager manager) { @@ -273,24 +333,29 @@ public void postFindLocalResource(String name, URL resource, ClasspathManager ma } /** - * Gets called by a classpath manager after an attempt is made to define a class. This method allows - * a class loading hook to record data about a class definition. - * @param name the name of the class that got defined - * @param clazz the class object that got defined or null if an error occurred while defining a class - * @param classbytes the class bytes used to define the class + * Gets called by a classpath manager after an attempt is made to define a + * class. This method allows a class loading hook to record data about a class + * definition. + * + * @param name the name of the class that got defined + * @param clazz the class object that got defined or null if an error + * occurred while defining a class + * @param classbytes the class bytes used to define the class * @param classpathEntry the ClasspathEntry where the class bytes got read from - * @param entry the BundleEntyr source of the class bytes - * @param manager the classpath manager used to define the class + * @param entry the BundleEntyr source of the class bytes + * @param manager the classpath manager used to define the class */ - public void recordClassDefine(String name, Class clazz, byte[] classbytes, ClasspathEntry classpathEntry, BundleEntry entry, ClasspathManager manager) { + public void recordClassDefine(String name, Class clazz, byte[] classbytes, ClasspathEntry classpathEntry, + BundleEntry entry, ClasspathManager manager) { // do nothing } /** - * Returns the parent class loader to be used by all ModuleClassLoaders. - * A {@code null} value may be returned if this hook does not supply the parent. - * Only one hook is able to provide the implementation of the parent class loader - * and the first one to return non-null wins. + * Returns the parent class loader to be used by all ModuleClassLoaders. A + * {@code null} value may be returned if this hook does not supply the parent. + * Only one hook is able to provide the implementation of the parent class + * loader and the first one to return non-null wins. + * * @param configuration the equinox configuration * @return the parent class loader to be used by all ModuleClassLoaders */ @@ -301,11 +366,12 @@ public ClassLoader getModuleClassLoaderParent(EquinoxConfiguration configuration /** * Returns true if this hook can support invoking - * {@link ClassLoaderHook#processClass(String, byte[], ClasspathEntry, BundleEntry, ClasspathManager) processClass} - * recursively for the same class name. If false is returned then a class - * loading error will occur if recursive class processing is detected. + * {@link ClassLoaderHook#processClass(String, byte[], ClasspathEntry, BundleEntry, ClasspathManager) + * processClass} recursively for the same class name. If false is returned then + * a class loading error will occur if recursive class processing is detected. *

* This method must return a constant boolean value. + * * @return true if recursing class processing is supported */ public boolean isProcessClassRecursionSupported() { @@ -313,16 +379,21 @@ public boolean isProcessClassRecursionSupported() { } /** - * Returns the filtered list of ClasspathEntry instances for the given class, resource or entry. - * A {@code null} value may be returned in which case the find process will go over all the host and - * fragment entries in order to find the given entity which is the default behavior. - * Any non-null return value including an empty list will only look at the entries in the returned list. + * Returns the filtered list of ClasspathEntry instances for the given class, + * resource or entry. A {@code null} value may be returned in which case the + * find process will go over all the host and fragment entries in order to find + * the given entity which is the default behavior. Any non-null return value + * including an empty list will only look at the entries in the returned list. * - * This method is used within {@link ClasspathManager#findLocalResource(String)}, {@link ClasspathManager#findLocalResources(String)}, - * {@link ClasspathManager#findLocalClass(String) } and {@link ClasspathManager#findLocalEntry(String) } + * This method is used within + * {@link ClasspathManager#findLocalResource(String)}, + * {@link ClasspathManager#findLocalResources(String)}, + * {@link ClasspathManager#findLocalClass(String) } and + * {@link ClasspathManager#findLocalEntry(String) } * - * @param name the name of the requested class, resource or entry - * @param manager the classpath manager used to find the requested class, resource or entry + * @param name the name of the requested class, resource or entry + * @param manager the classpath manager used to find the requested class, + * resource or entry * @return the array of ClassPathEntry objects to use to load this given entity */ public ClasspathEntry[] getClassPathEntries(String name, ClasspathManager manager) { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/hookregistry/HookConfigurator.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/hookregistry/HookConfigurator.java index f4a842c439e..6e753a1fceb 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/hookregistry/HookConfigurator.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/hookregistry/HookConfigurator.java @@ -16,11 +16,13 @@ /** * A hook configurator is used to add hooks to the hook registry. + * * @see HookRegistry */ public interface HookConfigurator { /** * Adds hooks to the specified hook registry. + * * @param hookRegistry the hook registry used to add hooks */ public void addHooks(HookRegistry hookRegistry); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/hookregistry/HookRegistry.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/hookregistry/HookRegistry.java index 5990f4ced4a..d35e8f7856e 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/hookregistry/HookRegistry.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/hookregistry/HookRegistry.java @@ -34,43 +34,49 @@ import org.eclipse.osgi.util.ManifestElement; /** - * The hook registry is used to store all the hooks which are - * configured by the hook configurators. + * The hook registry is used to store all the hooks which are configured by the + * hook configurators. + * * @see HookConfigurator */ public final class HookRegistry { /** - * The hook configurators properties file ("hookconfigurators.properties")

- * A framework extension may supply a hook configurators properties file to specify a - * list of hook configurators. + * The hook configurators properties file + * ("hookconfigurators.properties") + *

+ * A framework extension may supply a hook configurators properties file to + * specify a list of hook configurators. + * * @see #HOOK_CONFIGURATORS */ public static final String HOOK_CONFIGURATORS_FILE = "hookconfigurators.properties"; //$NON-NLS-1$ /** - * The hook configurators property key ("hookconfigurators.properties") used in - * a hook configurators properties file to specify a comma separated list of fully - * qualified hook configurator classes. + * The hook configurators property key + * ("hookconfigurators.properties") used in a hook configurators + * properties file to specify a comma separated list of fully qualified hook + * configurator classes. */ public static final String HOOK_CONFIGURATORS = "hook.configurators"; //$NON-NLS-1$ /** - * A system property ("osgi.hook.configurators.include") used to add additional - * hook configurators. This is helpful for configuring optional hook configurators. + * A system property ("osgi.hook.configurators.include") used to add + * additional hook configurators. This is helpful for configuring optional hook + * configurators. */ public static final String PROP_HOOK_CONFIGURATORS_INCLUDE = "osgi.hook.configurators.include"; //$NON-NLS-1$ /** - * A system property ("osgi.hook.configurators.exclude") used to exclude - * any hook configurators. This is helpful for disabling hook + * A system property ("osgi.hook.configurators.exclude") used to + * exclude any hook configurators. This is helpful for disabling hook * configurators that is specified in hook configurator properties files. */ public static final String PROP_HOOK_CONFIGURATORS_EXCLUDE = "osgi.hook.configurators.exclude"; //$NON-NLS-1$ /** - * A system property ("osgi.hook.configurators") used to specify the list - * of hook configurators. If this property is set then the list of configurators - * specified will be the only configurators used. + * A system property ("osgi.hook.configurators") used to specify the + * list of hook configurators. If this property is set then the list of + * configurators specified will be the only configurators used. */ public static final String PROP_HOOK_CONFIGURATORS = "osgi.hook.configurators"; //$NON-NLS-1$ @@ -81,26 +87,41 @@ public final class HookRegistry { private final List classLoaderHooks = new ArrayList<>(); private final List classLoaderHooksRO = Collections.unmodifiableList(classLoaderHooks); private final List> storageHookFactories = new ArrayList<>(); - private final List> storageHookFactoriesRO = Collections.unmodifiableList(storageHookFactories); + private final List> storageHookFactoriesRO = Collections + .unmodifiableList(storageHookFactories); private final List bundleFileWrapperFactoryHooks = new ArrayList<>(); - private final List bundleFileWrapperFactoryHooksRO = Collections.unmodifiableList(bundleFileWrapperFactoryHooks); + private final List bundleFileWrapperFactoryHooksRO = Collections + .unmodifiableList(bundleFileWrapperFactoryHooks); private final List activatorHookFactories = new ArrayList<>(); - private final List activatorHookFactoriesRO = Collections.unmodifiableList(activatorHookFactories); + private final List activatorHookFactoriesRO = Collections + .unmodifiableList(activatorHookFactories); public HookRegistry(EquinoxContainer container) { this.container = container; } /** - * Initializes the hook configurators. The following steps are used to initialize the hook configurators.

- * 1. Get a list of hook configurators from all hook configurators properties files on the classpath, - * add this list to the overall list of hook configurators, remove duplicates.

- * 2. Get a list of hook configurators from the ("osgi.hook.configurators.include") system property - * and add this list to the overall list of hook configurators, remove duplicates.

- * 3. Get a list of hook configurators from the ("osgi.hook.configurators.exclude") system property - * and remove this list from the overall list of hook configurators.

- * 4. Load each hook configurator class, create a new instance, then call the {@link HookConfigurator#addHooks(HookRegistry)} method

- * 5. Set this HookRegistry object to read only to prevent any other hooks from being added.

+ * Initializes the hook configurators. The following steps are used to + * initialize the hook configurators. + *

+ * 1. Get a list of hook configurators from all hook configurators properties + * files on the classpath, add this list to the overall list of hook + * configurators, remove duplicates. + *

+ * 2. Get a list of hook configurators from the + * ("osgi.hook.configurators.include") system property and add this + * list to the overall list of hook configurators, remove duplicates. + *

+ * 3. Get a list of hook configurators from the + * ("osgi.hook.configurators.exclude") system property and remove this + * list from the overall list of hook configurators. + *

+ * 4. Load each hook configurator class, create a new instance, then call the + * {@link HookConfigurator#addHooks(HookRegistry)} method + *

+ * 5. Set this HookRegistry object to read only to prevent any other hooks from + * being added. + *

*/ public void initialize() { List configurators = new ArrayList<>(5); @@ -129,9 +150,11 @@ private void mergeFileHookConfigurators(List configuratorList, List hookConfigurators; try { - hookConfigurators = cl != null ? cl.getResources(HookRegistry.HOOK_CONFIGURATORS_FILE) : ClassLoader.getSystemResources(HookRegistry.HOOK_CONFIGURATORS_FILE); + hookConfigurators = cl != null ? cl.getResources(HookRegistry.HOOK_CONFIGURATORS_FILE) + : ClassLoader.getSystemResources(HookRegistry.HOOK_CONFIGURATORS_FILE); } catch (IOException e) { - errors.add(new FrameworkLogEntry(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, 0, "getResources error on " + HookRegistry.HOOK_CONFIGURATORS_FILE, 0, e, null)); //$NON-NLS-1$ + errors.add(new FrameworkLogEntry(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, 0, + "getResources error on " + HookRegistry.HOOK_CONFIGURATORS_FILE, 0, e, null)); //$NON-NLS-1$ return; } int curBuiltin = 0; @@ -158,7 +181,8 @@ private void mergeFileHookConfigurators(List configuratorList, List configuratorList, List configuratorList) { // see if there is a configurators list - String[] configurators = ManifestElement.getArrayFromList(container.getConfiguration().getConfiguration(HookRegistry.PROP_HOOK_CONFIGURATORS), ","); //$NON-NLS-1$ + String[] configurators = ManifestElement.getArrayFromList( + container.getConfiguration().getConfiguration(HookRegistry.PROP_HOOK_CONFIGURATORS), ","); //$NON-NLS-1$ if (configurators.length > 0) { configuratorList.clear(); // clear the list, we are only going to use the configurators from the list for (String configurator : configurators) { @@ -184,14 +209,16 @@ private void mergePropertyHookConfigurators(List configuratorList) { return; // don't do anything else } // Make sure the configurators from the include property are in the list - String[] includeConfigurators = ManifestElement.getArrayFromList(container.getConfiguration().getConfiguration(HookRegistry.PROP_HOOK_CONFIGURATORS_INCLUDE), ","); //$NON-NLS-1$ + String[] includeConfigurators = ManifestElement.getArrayFromList( + container.getConfiguration().getConfiguration(HookRegistry.PROP_HOOK_CONFIGURATORS_INCLUDE), ","); //$NON-NLS-1$ for (String includeConfigurator : includeConfigurators) { if (!configuratorList.contains(includeConfigurator)) { configuratorList.add(includeConfigurator); } } // Make sure the configurators from the exclude property are no in the list - String[] excludeHooks = ManifestElement.getArrayFromList(container.getConfiguration().getConfiguration(HookRegistry.PROP_HOOK_CONFIGURATORS_EXCLUDE), ","); //$NON-NLS-1$ + String[] excludeHooks = ManifestElement.getArrayFromList( + container.getConfiguration().getConfiguration(HookRegistry.PROP_HOOK_CONFIGURATORS_EXCLUDE), ","); //$NON-NLS-1$ for (String excludeHook : excludeHooks) { configuratorList.remove(excludeHook); } @@ -209,13 +236,15 @@ private void loadConfigurators(List configurators, List getClassLoaderHooks() { @@ -224,6 +253,7 @@ public List getClassLoaderHooks() { /** * Returns the list of configured storage hooks. + * * @return the list of configured storage hooks. */ public List> getStorageHookFactories() { @@ -232,6 +262,7 @@ public List getClassLoaderHooks() { /** * Returns the configured bundle file wrapper factories + * * @return the configured bundle file wrapper factories */ public List getBundleFileWrapperFactoryHooks() { @@ -240,6 +271,7 @@ public List getBundleFileWrapperFactoryHooks() { /** * Returns the configured activator hook factories + * * @return the configured activator hook factories */ public List getActivatorHookFactories() { @@ -254,6 +286,7 @@ private void add(H hook, List hooks) { /** * Adds a class loader hook to this hook registry. + * * @param classLoaderHook a class loading hook object. */ public void addClassLoaderHook(ClassLoaderHook classLoaderHook) { @@ -262,6 +295,7 @@ public void addClassLoaderHook(ClassLoaderHook classLoaderHook) { /** * Adds a storage hook to this hook registry. + * * @param storageHookFactory a storage hook object. */ public void addStorageHookFactory(StorageHookFactory storageHookFactory) { @@ -270,6 +304,7 @@ public void addStorageHookFactory(StorageHookFactory storageHookFactory /** * Adds a bundle file wrapper factory for this hook registry + * * @param factory a bundle file wrapper factory object. */ public void addBundleFileWrapperFactoryHook(BundleFileWrapperFactoryHook factory) { @@ -277,8 +312,9 @@ public void addBundleFileWrapperFactoryHook(BundleFileWrapperFactoryHook factory } /** - * Adds an activator hook factory. The activators created by this factory will be started and stopped - * when the system bundle is started and stopped. + * Adds an activator hook factory. The activators created by this factory will + * be started and stopped when the system bundle is started and stopped. + * * @param activatorHookFactory the activator hook factory. */ public void addActivatorHookFactory(ActivatorHookFactory activatorHookFactory) { @@ -287,6 +323,7 @@ public void addActivatorHookFactory(ActivatorHookFactory activatorHookFactory) { /** * Returns the configuration associated with this hook registry. + * * @return the configuration associated with this hook registry. */ public EquinoxConfiguration getConfiguration() { @@ -295,6 +332,7 @@ public EquinoxConfiguration getConfiguration() { /** * Returns the equinox container associated with this hook registry. + * * @return the equinox container associated with this hook registry. */ public EquinoxContainer getContainer() { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/hookregistry/StorageHookFactory.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/hookregistry/StorageHookFactory.java index 261e81367d1..dd471ace210 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/hookregistry/StorageHookFactory.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/hookregistry/StorageHookFactory.java @@ -30,8 +30,11 @@ import org.osgi.framework.BundleException; /** - * A StorageHookFactory hooks into the persistent storage loading and saving of bundle {@link Generation generations}. - * A factory creates StorageHook instances that get associated with each Generation object installed.

+ * A StorageHookFactory hooks into the persistent storage loading and saving of + * bundle {@link Generation generations}. A factory creates StorageHook + * instances that get associated with each Generation object installed. + *

+ * * @see Generation#getStorageHook(Class) * @param the save context type * @param the load context type @@ -41,10 +44,11 @@ public abstract class StorageHookFactory factoryClass = getClass(); Class factoryClassOfStorageHook = result.getFactoryClass(); if (!factoryClass.equals(factoryClassOfStorageHook)) - throw new IllegalStateException(String.format("The factory class '%s' of storage hook '%s' does not match the creating factory class of '%s'", factoryClassOfStorageHook.getName(), result, factoryClass.getName())); //$NON-NLS-1$ + throw new IllegalStateException(String.format( + "The factory class '%s' of storage hook '%s' does not match the creating factory class of '%s'", //$NON-NLS-1$ + factoryClassOfStorageHook.getName(), result, factoryClass.getName())); return result; } /** - * Allows a storage hook factory to handle the {@link URLConnection connection} to the - * content for bundle install or update operation. - * @param module the module being updated. Will be {@code null} for install operations - * @param location the bundle location be installed. Will be {@code null} for update operations - * @param in the input stream for the install or update operation. May be {@code null} - * @return a connection to the content or {@code null} to let the framework handle the content - * @throws IOException if any error occurs which will result in a {@link BundleException} being - * thrown from the update or install operation. + * Allows a storage hook factory to handle the {@link URLConnection connection} + * to the content for bundle install or update operation. + * + * @param module the module being updated. Will be {@code null} for install + * operations + * @param location the bundle location be installed. Will be {@code null} for + * update operations + * @param in the input stream for the install or update operation. May be + * {@code null} + * @return a connection to the content or {@code null} to let the framework + * handle the content + * @throws IOException if any error occurs which will result in a + * {@link BundleException} being thrown from the update or + * install operation. */ public URLConnection handleContentConnection(Module module, String location, InputStream in) throws IOException { return null; } /** - * A storage hook for a specific generation object. This hook - * is responsible for persisting and loading data associated - * with a specific generation. + * A storage hook for a specific generation object. This hook is responsible for + * persisting and loading data associated with a specific generation. * * @param the save context type * @param the load context type @@ -154,13 +170,15 @@ public static class StorageHook { private final Class>> factoryClass; private final Generation generation; - public StorageHook(Generation generation, Class>> factoryClass) { + public StorageHook(Generation generation, + Class>> factoryClass) { this.generation = generation; this.factoryClass = factoryClass; } /** * The generation associated with this hook. + * * @return the generation associated with this hook. */ public Generation getGeneration() { @@ -168,8 +186,9 @@ public Generation getGeneration() { } /** - * Initializes this storage hook with the content of the specified bundle manifest. - * This method is called when a bundle is installed or updated. + * Initializes this storage hook with the content of the specified bundle + * manifest. This method is called when a bundle is installed or updated. + * * @param manifest the bundle manifest to load into this storage hook * @throws BundleException if any error occurs */ @@ -178,32 +197,46 @@ public void initialize(Dictionary manifest) throws BundleExcepti } /** - * Allows a builder to be modified before it is used by the framework to create a {@link ModuleRevision revision} - * associated with the bundle {@link #getGeneration() generation} being installed or updated. - * @param operation The lifecycle operation event that is in progress using the supplied builder. - * This will be either {@link ModuleEvent#INSTALLED installed} or {@link ModuleEvent#UPDATED updated}. - * @param origin The module which originated the lifecycle operation. The origin may be {@code null} for - * {@link ModuleEvent#INSTALLED installed} operations. This is the module - * passed to the {@link ModuleContainer#install(Module, String, ModuleRevisionBuilder, Object) install} or - * {@link ModuleContainer#update(Module, ModuleRevisionBuilder, Object) update} method. - * @param builder the builder that will be used to create a new {@link ModuleRevision}. - * @return The modified builder or a completely new builder to be used by the bundle. A {@code null} value - * indicates the original builder should be used, which may have been modified by adding requirements or - * capabilities. - * @see ModuleContainerAdaptor#adaptModuleRevisionBuilder(ModuleEvent, Module, ModuleRevisionBuilder, Object) + * Allows a builder to be modified before it is used by the framework to create + * a {@link ModuleRevision revision} associated with the bundle + * {@link #getGeneration() generation} being installed or updated. + * + * @param operation The lifecycle operation event that is in progress using the + * supplied builder. This will be either + * {@link ModuleEvent#INSTALLED installed} or + * {@link ModuleEvent#UPDATED updated}. + * @param origin The module which originated the lifecycle operation. The + * origin may be {@code null} for {@link ModuleEvent#INSTALLED + * installed} operations. This is the module passed to the + * {@link ModuleContainer#install(Module, String, ModuleRevisionBuilder, Object) + * install} or + * {@link ModuleContainer#update(Module, ModuleRevisionBuilder, Object) + * update} method. + * @param builder the builder that will be used to create a new + * {@link ModuleRevision}. + * @return The modified builder or a completely new builder to be used by the + * bundle. A {@code null} value indicates the original builder should be + * used, which may have been modified by adding requirements or + * capabilities. + * @see ModuleContainerAdaptor#adaptModuleRevisionBuilder(ModuleEvent, Module, + * ModuleRevisionBuilder, Object) */ - public ModuleRevisionBuilder adaptModuleRevisionBuilder(ModuleEvent operation, Module origin, ModuleRevisionBuilder builder) { + public ModuleRevisionBuilder adaptModuleRevisionBuilder(ModuleEvent operation, Module origin, + ModuleRevisionBuilder builder) { // do nothing return null; } /** - * Loads the data from the specified - * input stream into the storage hook. This method is called during startup to - * load all the persistently installed bundles.

- * It is important that this method and the {@link #save(Object, DataOutputStream)} method - * stay in sync. This method must be able to successfully read the data saved by the + * Loads the data from the specified input stream into the storage hook. This + * method is called during startup to load all the persistently installed + * bundles. + *

+ * It is important that this method and the + * {@link #save(Object, DataOutputStream)} method stay in sync. This method must + * be able to successfully read the data saved by the * {@link #save(Object, DataOutputStream)} method. + * * @param is an input stream used to load the storage hook's data from. * @see #save(Object, DataOutputStream) * @throws IOException if any error occurs @@ -213,11 +246,14 @@ public void load(L loadContext, DataInputStream is) throws IOException { } /** - * Saves the data from this storage hook into the specified output stream. This method - * is called if some persistent data has changed for the bundle.

- * It is important that this method and the {@link #load(Object, DataInputStream)} - * method stay in sync. This method must be able to save data which the - * {@link #load(Object, DataInputStream)} method can ready successfully. + * Saves the data from this storage hook into the specified output stream. This + * method is called if some persistent data has changed for the bundle. + *

+ * It is important that this method and the + * {@link #load(Object, DataInputStream)} method stay in sync. This method must + * be able to save data which the {@link #load(Object, DataInputStream)} method + * can ready successfully. + * * @see #load(Object, DataInputStream) * @param os an output stream used to save the storage hook's data from. * @throws IOException if any error occurs @@ -227,16 +263,17 @@ public void save(S saveContext, DataOutputStream os) throws IOException { } /** - * Gets called during {@link Generation#delete()} to inform the hook that the generation - * associated with the hook is being deleted. + * Gets called during {@link Generation#delete()} to inform the hook that the + * generation associated with the hook is being deleted. */ public void deletingGeneration() { // do nothing by default } /** - * Validates the data in this storage hook, if the data is invalid then an illegal state - * exception is thrown + * Validates the data in this storage hook, if the data is invalid then an + * illegal state exception is thrown + * * @throws IllegalStateException if the data is invalid */ public void validate() throws IllegalStateException { @@ -245,6 +282,7 @@ public void validate() throws IllegalStateException { /** * The storage hook factory class of this storage hook + * * @return the storage hook factory class */ public Class>> getFactoryClass() { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/hooks/DevClassLoadingHook.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/hooks/DevClassLoadingHook.java index c707e4c7698..cc0c4e08f84 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/hooks/DevClassLoadingHook.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/hooks/DevClassLoadingHook.java @@ -43,31 +43,37 @@ public DevClassLoadingHook(EquinoxConfiguration configuration) { } @Override - public boolean addClassPathEntry(ArrayList cpEntries, String cp, ClasspathManager hostmanager, Generation sourceGeneration) { + public boolean addClassPathEntry(ArrayList cpEntries, String cp, ClasspathManager hostmanager, + Generation sourceGeneration) { // if this is a connect bundle just ignore if (sourceGeneration.getContentType() == Type.CONNECT) { return false; } // first check that we are in devmode for this sourcedata - String[] devClassPaths = !configuration.inDevelopmentMode() ? null : configuration.getDevClassPath(sourceGeneration.getRevision()); + String[] devClassPaths = !configuration.inDevelopmentMode() ? null + : configuration.getDevClassPath(sourceGeneration.getRevision()); if (devClassPaths == null || devClassPaths.length == 0) return false; // not in dev mode return - // check that dev classpath entries have not already been added; we mark this in the first entry below + // check that dev classpath entries have not already been added; we mark this in + // the first entry below if (!cpEntries.isEmpty() && cpEntries.get(0).getUserObject(KEY) != null) return false; // this source has already had its dev classpath entries added. - // get the specified classpath from the Bundle-ClassPath header to check for dups - List moduleDatas = sourceGeneration.getRevision().getModuleCapabilities(EquinoxModuleDataNamespace.MODULE_DATA_NAMESPACE); + // get the specified classpath from the Bundle-ClassPath header to check for + // dups + List moduleDatas = sourceGeneration.getRevision() + .getModuleCapabilities(EquinoxModuleDataNamespace.MODULE_DATA_NAMESPACE); @SuppressWarnings("unchecked") - List specifiedCP = Optional.ofNullable(moduleDatas.isEmpty() - ? - null - : (List) moduleDatas.get(0).getAttributes().get(EquinoxModuleDataNamespace.CAPABILITY_CLASSPATH)) + List specifiedCP = Optional + .ofNullable(moduleDatas.isEmpty() ? null + : (List) moduleDatas.get(0).getAttributes() + .get(EquinoxModuleDataNamespace.CAPABILITY_CLASSPATH)) .orElse(Collections.singletonList(".")); //$NON-NLS-1$ boolean result = false; for (String devClassPath : devClassPaths) { if (specifiedCP.contains(devClassPath)) { - // dev properties contained a duplicate of an entry on the Bundle-ClassPath header + // dev properties contained a duplicate of an entry on the Bundle-ClassPath + // header // don't add anything, the framework will do it for us continue; } @@ -81,7 +87,8 @@ public boolean addClassPathEntry(ArrayList cpEntries, String cp, File base = sourceGeneration.getBundleFile().getBaseFile(); if (base != null && base.isDirectory()) { // this is only supported for directory bundles - ClasspathEntry entry = hostmanager.getExternalClassPath(new File(base, devCP).getAbsolutePath(), sourceGeneration); + ClasspathEntry entry = hostmanager.getExternalClassPath(new File(base, devCP).getAbsolutePath(), + sourceGeneration); if (entry != null) { cpEntries.add(entry); result = true; @@ -89,7 +96,7 @@ public boolean addClassPathEntry(ArrayList cpEntries, String cp, } } else { // if in dev mode, try using the cp as an absolute path - // we assume absolute entries come from fragments. Find the source + // we assume absolute entries come from fragments. Find the source if (fromFragment) devCP = devCP.substring(0, devCP.length() - FRAGMENT.length()); Generation fragSource = findFragmentSource(sourceGeneration, devCP, hostmanager, fromFragment); @@ -104,13 +111,15 @@ public boolean addClassPathEntry(ArrayList cpEntries, String cp, } } // mark the first entry of the list. - // This way we can quickly tell that dev classpath entries have been added to the list + // This way we can quickly tell that dev classpath entries have been added to + // the list if (result && !cpEntries.isEmpty()) cpEntries.get(0).addUserObject(this); return result; } - private Generation findFragmentSource(Generation hostGeneration, String cp, ClasspathManager manager, boolean fromFragment) { + private Generation findFragmentSource(Generation hostGeneration, String cp, ClasspathManager manager, + boolean fromFragment) { if (hostGeneration != manager.getGeneration()) return hostGeneration; diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/hooks/EclipseLazyStarter.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/hooks/EclipseLazyStarter.java index 32ce76d0e9b..3c90b2fc607 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/hooks/EclipseLazyStarter.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/hooks/EclipseLazyStarter.java @@ -51,7 +51,8 @@ public class EclipseLazyStarter extends ClassLoaderHook { // used to store exceptions that occurred while activating a bundle // keyed by ClasspathManager->Exception // WeakHashMap is used to prevent pinning the ClasspathManager objects. - private final Map errors = Collections.synchronizedMap(new WeakHashMap()); + private final Map errors = Collections + .synchronizedMap(new WeakHashMap()); private final EquinoxContainer container; @@ -67,10 +68,12 @@ public void preFindLocalClass(String name, ClasspathManager manager) throws Clas ModuleRevision revision = manager.getGeneration().getRevision(); Module module = revision.getRevisions().getModule(); // If the bundle is active, uninstalled or stopping then the bundle has already - // been initialized (though it may have been destroyed) so just return the class. + // been initialized (though it may have been destroyed) so just return the + // class. if (alreadyActive.contains(module.getState())) return; - // The bundle is not active and does not require activation, just return the class + // The bundle is not active and does not require activation, just return the + // class if (!shouldActivateFor(name, module, revision, manager)) return; Deque stack = activationStack.get(); @@ -87,7 +90,8 @@ public void preFindLocalClass(String name, ClasspathManager manager) throws Clas } @Override - public void postFindLocalClass(String name, Class clazz, ClasspathManager manager) throws ClassNotFoundException { + public void postFindLocalClass(String name, Class clazz, ClasspathManager manager) + throws ClassNotFoundException { if (initiatingClassName.get() != name) return; initiatingClassName.set(null); @@ -109,7 +113,8 @@ public void postFindLocalClass(String name, Class clazz, ClasspathManager man // The bundle must be started. // Note that another thread may already be starting this bundle; - // In this case we will timeout after a default of 5 seconds and record the BundleException + // In this case we will timeout after a default of 5 seconds and record the + // BundleException long startTime = System.currentTimeMillis(); Module m = managerElement.getGeneration().getRevision().getRevisions().getModule(); try { @@ -118,23 +123,28 @@ public void postFindLocalClass(String name, Class clazz, ClasspathManager man } catch (BundleException e) { Bundle bundle = managerElement.getGeneration().getRevision().getBundle(); if (e.getType() == BundleException.STATECHANGE_ERROR) { - String message = NLS.bind(Msg.ECLIPSE_CLASSLOADER_CONCURRENT_STARTUP, new Object[] {Thread.currentThread(), name, m.getStateChangeOwner(), bundle, Long.valueOf(System.currentTimeMillis() - startTime)}); + String message = NLS.bind(Msg.ECLIPSE_CLASSLOADER_CONCURRENT_STARTUP, + new Object[] { Thread.currentThread(), name, m.getStateChangeOwner(), bundle, + Long.valueOf(System.currentTimeMillis() - startTime) }); container.getLogServices().log(EquinoxContainer.NAME, FrameworkLogEntry.WARNING, message, e); continue; } - String message = NLS.bind(Msg.ECLIPSE_CLASSLOADER_ACTIVATION, bundle.getSymbolicName(), Long.toString(bundle.getBundleId())); + String message = NLS.bind(Msg.ECLIPSE_CLASSLOADER_ACTIVATION, bundle.getSymbolicName(), + Long.toString(bundle.getBundleId())); ClassNotFoundException error = new ClassNotFoundException(message, e); errors.put(managerElement, error); if (container.getConfiguration().throwErrorOnFailedStart) { container.getLogServices().log(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, message, e, null); throw error; } - container.getEventPublisher().publishFrameworkEvent(FrameworkEvent.ERROR, bundle, new BundleException(message, e)); + container.getEventPublisher().publishFrameworkEvent(FrameworkEvent.ERROR, bundle, + new BundleException(message, e)); } } } - private boolean shouldActivateFor(String className, Module module, ModuleRevision revision, ClasspathManager manager) throws ClassNotFoundException { + private boolean shouldActivateFor(String className, Module module, ModuleRevision revision, + ClasspathManager manager) throws ClassNotFoundException { State state = module.getState(); if (!State.LAZY_STARTING.equals(state)) { if (State.STARTING.equals(state) && manager.getClassLoader().getBundleLoader().isTriggerSet()) { @@ -149,11 +159,15 @@ private boolean shouldActivateFor(String className, Module module, ModuleRevisio if (error != null) throw error; } - // The module is persistently started and has the lazy activation policy but has not entered the LAZY_STARTING state + // The module is persistently started and has the lazy activation policy but has + // not entered the LAZY_STARTING state // There are 2 cases where this can happen - // 1) The start-level thread has not gotten to transitioning the bundle to LAZY_STARTING yet - // 2) The bundle is marked for eager activation and the start-level thread has not activated it yet - // In both cases we need to fire the lazy start trigger to activate the bundle if the start-level is met + // 1) The start-level thread has not gotten to transitioning the bundle to + // LAZY_STARTING yet + // 2) The bundle is marked for eager activation and the start-level thread has + // not activated it yet + // In both cases we need to fire the lazy start trigger to activate the bundle + // if the start-level is met return module.isPersistentlyStarted() && isLazyStartable(className, revision); } return false; @@ -166,16 +180,19 @@ private boolean isLazyStartable(String className, ModuleRevision revision) { if (!revision.hasLazyActivatePolicy()) { return false; } - List moduleDatas = revision.getModuleCapabilities(EquinoxModuleDataNamespace.MODULE_DATA_NAMESPACE); + List moduleDatas = revision + .getModuleCapabilities(EquinoxModuleDataNamespace.MODULE_DATA_NAMESPACE); if (moduleDatas.isEmpty()) { return false; } Map moduleDataAttrs = moduleDatas.get(0).getAttributes(); @SuppressWarnings("unchecked") - List excludes = (List) moduleDataAttrs.get(EquinoxModuleDataNamespace.CAPABILITY_LAZY_EXCLUDE_ATTRIBUTE); + List excludes = (List) moduleDataAttrs + .get(EquinoxModuleDataNamespace.CAPABILITY_LAZY_EXCLUDE_ATTRIBUTE); @SuppressWarnings("unchecked") - List includes = (List) moduleDataAttrs.get(EquinoxModuleDataNamespace.CAPABILITY_LAZY_INCLUDE_ATTRIBUTE); + List includes = (List) moduleDataAttrs + .get(EquinoxModuleDataNamespace.CAPABILITY_LAZY_INCLUDE_ATTRIBUTE); // no exceptions, it is easy to figure it out if (excludes == null && includes == null) return true; @@ -185,7 +202,8 @@ private boolean isLazyStartable(String className, ModuleRevision revision) { if (dotPosition == -1) return true; String packageName = className.substring(0, dotPosition); - return ((includes == null || includes.contains(packageName)) && (excludes == null || !excludes.contains(packageName))); + return ((includes == null || includes.contains(packageName)) + && (excludes == null || !excludes.contains(packageName))); } @Override diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/BundleLoader.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/BundleLoader.java index 190ae673946..136630c7b5b 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/BundleLoader.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/BundleLoader.java @@ -64,22 +64,24 @@ import org.osgi.framework.wiring.BundleWiring; /** - * This object is responsible for all classloader delegation for a bundle. - * It represents the loaded state of the bundle. BundleLoader objects - * are created lazily; care should be taken not to force the creation - * of a BundleLoader unless it is necessary. + * This object is responsible for all classloader delegation for a bundle. It + * represents the loaded state of the bundle. BundleLoader objects are created + * lazily; care should be taken not to force the creation of a BundleLoader + * unless it is necessary. + * * @see org.eclipse.osgi.internal.loader.BundleLoaderSources */ public class BundleLoader extends ModuleLoader { public final static String DEFAULT_PACKAGE = "."; //$NON-NLS-1$ public final static String JAVA_PACKAGE = "java."; //$NON-NLS-1$ - public final static ClassContext CLASS_CONTEXT = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public ClassContext run() { - return new ClassContext(); - } - }); + public final static ClassContext CLASS_CONTEXT = AccessController + .doPrivileged(new PrivilegedAction() { + @Override + public ClassContext run() { + return new ClassContext(); + } + }); public final static ClassLoader FW_CLASSLOADER = getClassLoader(EquinoxContainer.class); private static final int PRE_CLASS = 1; @@ -100,7 +102,9 @@ public ClassContext run() { private final Collection exportedPackages; private final BundleLoaderSources exportSources; - /* cache of required package sources. Key is packagename, value is PackageSource */ + /* + * cache of required package sources. Key is packagename, value is PackageSource + */ private final Map requiredSources = new HashMap<>(); /* cache of imported packages. Key is packagename, Value is PackageSource */ private final Map importedSources = new HashMap<>(); @@ -126,12 +130,11 @@ public ClassContext run() { private final AtomicBoolean firstUseOfInvalidLoader = new AtomicBoolean(false); /** - * Returns the package name from the specified class name. - * The returned package is dot seperated. + * Returns the package name from the specified class name. The returned package + * is dot seperated. * - * @param name Name of a class. - * @return Dot separated package name or null if the class - * has no package name. + * @param name Name of a class. + * @return Dot separated package name or null if the class has no package name. */ public final static String getPackageName(String name) { if (name != null) { @@ -143,16 +146,16 @@ public final static String getPackageName(String name) { } /** - * Returns the package name from the specified resource name. - * The returned package is dot seperated. + * Returns the package name from the specified resource name. The returned + * package is dot seperated. * - * @param name Name of a resource. - * @return Dot separated package name or null if the resource - * has no package name. + * @param name Name of a resource. + * @return Dot separated package name or null if the resource has no package + * name. */ public final static String getResourcePackageName(String name) { if (name != null) { - /* check for leading slash*/ + /* check for leading slash */ int begin = ((name.length() > 1) && (name.charAt(0) == '/')) ? 1 : 0; int end = name.lastIndexOf('/'); /* index of last slash */ if (end > begin) @@ -171,7 +174,8 @@ public BundleLoader(ModuleWiring wiring, EquinoxContainer container, ClassLoader exportSources = new BundleLoaderSources(this); List exports = wiring.getModuleCapabilities(PackageNamespace.PACKAGE_NAMESPACE); exports = exports == null ? Collections.emptyList() : exports; - exportedPackages = Collections.synchronizedCollection(exports.size() > 10 ? new HashSet(exports.size()) : new ArrayList(exports.size())); + exportedPackages = Collections.synchronizedCollection( + exports.size() > 10 ? new HashSet(exports.size()) : new ArrayList(exports.size())); initializeExports(exports, exportSources, exportedPackages); // init the dynamic imports tables @@ -179,12 +183,16 @@ public BundleLoader(ModuleWiring wiring, EquinoxContainer container, ClassLoader // initialize the required bundle wires List currentRequireBundleWires = wiring.getRequiredModuleWires(BundleNamespace.BUNDLE_NAMESPACE); - requiredBundleWires = currentRequireBundleWires == null || currentRequireBundleWires.isEmpty() ? Collections.emptyList() : Collections.unmodifiableList(currentRequireBundleWires); + requiredBundleWires = currentRequireBundleWires == null || currentRequireBundleWires.isEmpty() + ? Collections.emptyList() + : Collections.unmodifiableList(currentRequireBundleWires); - //Initialize the policy handler - List moduleDatas = wiring.getRevision().getModuleCapabilities(EquinoxModuleDataNamespace.MODULE_DATA_NAMESPACE); + // Initialize the policy handler + List moduleDatas = wiring.getRevision() + .getModuleCapabilities(EquinoxModuleDataNamespace.MODULE_DATA_NAMESPACE); @SuppressWarnings("unchecked") - List buddyList = (List) (moduleDatas.isEmpty() ? null : moduleDatas.get(0).getAttributes().get(EquinoxModuleDataNamespace.CAPABILITY_BUDDY_POLICY)); + List buddyList = (List) (moduleDatas.isEmpty() ? null + : moduleDatas.get(0).getAttributes().get(EquinoxModuleDataNamespace.CAPABILITY_BUDDY_POLICY)); policy = buddyList != null ? new PolicyHandler(this, buddyList, container.getStorage().getModuleContainer().getFrameworkWiring(), container.getBootLoader()) @@ -204,7 +212,8 @@ public void addFragmentExports(List exports) { initializeExports(exports, exportSources, exportedPackages); } - private static void initializeExports(List exports, BundleLoaderSources sources, Collection exportNames) { + private static void initializeExports(List exports, BundleLoaderSources sources, + Collection exportNames) { if (exports != null) { for (ModuleCapability export : exports) { String name = (String) export.getAttributes().get(PackageNamespace.PACKAGE_NAMESPACE); @@ -228,10 +237,11 @@ final PackageSource createExportPackageSource(ModuleWire importWire, Collection< return createMultiSource(name, new PackageSource[0]); } PackageSource requiredSource = providerLoader.findRequiredSource(name, visited); - PackageSource exportSource = providerLoader.exportSources.createPackageSource(importWire.getCapability(), false); + PackageSource exportSource = providerLoader.exportSources.createPackageSource(importWire.getCapability(), + false); if (requiredSource == null) return exportSource; - return createMultiSource(name, new PackageSource[] {requiredSource, exportSource}); + return createMultiSource(name, new PackageSource[] { requiredSource, exportSource }); } private static PackageSource createMultiSource(String packageName, PackageSource[] sources) { @@ -255,24 +265,29 @@ public ModuleClassLoader getModuleClassLoader() { return result; } // doing optimistic class loader creating here to avoid holding any locks, - // this may result in multiple classloaders being constructed but only one will be used. + // this may result in multiple classloaders being constructed but only one will + // be used. final List hooks = container.getConfiguration().getHookRegistry().getClassLoaderHooks(); final Generation generation = (Generation) wiring.getRevision().getRevisionInfo(); if (System.getSecurityManager() == null) { - result = createClassLoaderPrivledged(parent, generation.getBundleInfo().getStorage().getConfiguration(), this, generation, hooks); + result = createClassLoaderPrivledged(parent, generation.getBundleInfo().getStorage().getConfiguration(), + this, generation, hooks); } else { final ClassLoader cl = parent; result = AccessController.doPrivileged(new PrivilegedAction() { @Override public ModuleClassLoader run() { - return createClassLoaderPrivledged(cl, generation.getBundleInfo().getStorage().getConfiguration(), BundleLoader.this, generation, hooks); + return createClassLoaderPrivledged(cl, generation.getBundleInfo().getStorage().getConfiguration(), + BundleLoader.this, generation, hooks); } }); } - // Synchronize on classLoaderCreatedMonitor in order to ensure hooks are called before returning. + // Synchronize on classLoaderCreatedMonitor in order to ensure hooks are called + // before returning. // Note that we do hold a lock here while calling hooks. - // Not ideal, but hooks really should do little work from classLoaderCreated method. + // Not ideal, but hooks really should do little work from classLoaderCreated + // method. synchronized (classLoaderCreatedMonitor) { if (classLoaderCreated == null) { // must set createdClassloader before calling hooks; otherwise we could enter @@ -280,7 +295,8 @@ public ModuleClassLoader run() { classLoaderCreated = result; // only send to hooks if this thread wins in creating the class loader. final ModuleClassLoader cl = result; - // protect with doPriv to avoid bubbling up permission checks that hooks may require + // protect with doPriv to avoid bubbling up permission checks that hooks may + // require AccessController.doPrivileged(new PrivilegedAction() { @Override public Object run() { @@ -332,7 +348,8 @@ void loadClassLoaderFragments(Collection fragments) { } } - static ModuleClassLoader createClassLoaderPrivledged(ClassLoader parent, EquinoxConfiguration configuration, BundleLoader delegate, Generation generation, List hooks) { + static ModuleClassLoader createClassLoaderPrivledged(ClassLoader parent, EquinoxConfiguration configuration, + BundleLoader delegate, Generation generation, List hooks) { // allow hooks to extend the ModuleClassLoader implementation for (ClassLoaderHook hook : hooks) { ModuleClassLoader hookClassLoader = hook.createClassLoader(parent, configuration, delegate, generation); @@ -369,10 +386,9 @@ public ClassLoader getParentClassLoader() { } /** - * This method gets a resource from the bundle. The resource is searched - * for in the same manner as it would if it was being loaded from a bundle - * (i.e. all hosts, fragments, import, required bundles and - * local resources are searched). + * This method gets a resource from the bundle. The resource is searched for in + * the same manner as it would if it was being loaded from a bundle (i.e. all + * hosts, fragments, import, required bundles and local resources are searched). * * @param name the name of the desired resource. * @return the resulting resource URL or null if it does not exist. @@ -382,7 +398,9 @@ final URL getResource(String name) { } /** - * Finds a class local to this bundle. Only the classloader for this bundle is searched. + * Finds a class local to this bundle. Only the classloader for this bundle is + * searched. + * * @param name The name of the class to find. * @return The loaded Class or null if the class is not found. * @throws ClassNotFoundException @@ -410,7 +428,8 @@ public Class findLocalClass(String name) throws ClassNotFoundException { } /** - * Finds the class for a bundle. This method is used for delegation by the bundle's classloader. + * Finds the class for a bundle. This method is used for delegation by the + * bundle's classloader. */ public Class findClass(String name) throws ClassNotFoundException { return findClass0(name, true, true); @@ -442,7 +461,8 @@ private Class findClass0(String name, boolean parentDelegation, boolean gener throws ClassNotFoundException { if (parentDelegation && parent != null && name.startsWith(JAVA_PACKAGE)) { // 1) if startsWith "java." delegate to parent and terminate search - // we want to throw ClassNotFoundExceptions if a java.* class cannot be loaded from the parent. + // we want to throw ClassNotFoundExceptions if a java.* class cannot be loaded + // from the parent. return parent.loadClass(name); } @@ -453,7 +473,8 @@ private Class findClass0(String name, boolean parentDelegation, boolean gener boolean bootDelegation = false; // follow the OSGi delegation model if (parentDelegation && parent != null && container.isBootDelegationPackage(pkgName)) { - // 2) if part of the bootdelegation list then delegate to parent and continue of failure + // 2) if part of the bootdelegation list then delegate to parent and continue of + // failure try { return parent.loadClass(name); } catch (ClassNotFoundException cnfe) { @@ -500,7 +521,8 @@ private Class findClass0(String name, boolean parentDelegation, boolean gener result = findLocalClass(name); if (result != null) return result; - // 6) attempt to find a dynamic import source; only do this if a required source was not found + // 6) attempt to find a dynamic import source; only do this if a required source + // was not found if (source == null) { source = findDynamicSource(pkgName); if (source != null) { @@ -557,24 +579,24 @@ private E searchHooks(String name, int type) throws ClassNotFoundException, E result = null; for (ClassLoaderHook hook : loaderHooks) { switch (type) { - case PRE_CLASS : - result = (E) hook.preFindClass(name, getModuleClassLoader()); - break; - case POST_CLASS : - result = (E) hook.postFindClass(name, getModuleClassLoader()); - break; - case PRE_RESOURCE : - result = (E) hook.preFindResource(name, getModuleClassLoader()); - break; - case POST_RESOURCE : - result = (E) hook.postFindResource(name, getModuleClassLoader()); - break; - case PRE_RESOURCES : - result = (E) hook.preFindResources(name, getModuleClassLoader()); - break; - case POST_RESOURCES : - result = (E) hook.postFindResources(name, getModuleClassLoader()); - break; + case PRE_CLASS: + result = (E) hook.preFindClass(name, getModuleClassLoader()); + break; + case POST_CLASS: + result = (E) hook.postFindClass(name, getModuleClassLoader()); + break; + case PRE_RESOURCE: + result = (E) hook.preFindResource(name, getModuleClassLoader()); + break; + case POST_RESOURCE: + result = (E) hook.postFindResource(name, getModuleClassLoader()); + break; + case PRE_RESOURCES: + result = (E) hook.preFindResources(name, getModuleClassLoader()); + break; + case POST_RESOURCES: + result = (E) hook.postFindResources(name, getModuleClassLoader()); + break; } if (result != null) { return result; @@ -586,26 +608,32 @@ private E searchHooks(String name, int type) throws ClassNotFoundException, private boolean isRequestFromVM() { if (!container.getConfiguration().contextBootDelegation) return false; - // works around VM bugs that require all classloaders to have access to parent packages + // works around VM bugs that require all classloaders to have access to parent + // packages Class[] context = CLASS_CONTEXT.getClassContext(); if (context == null || context.length < 2) return false; // skip the first class; it is the ClassContext class for (int i = 1; i < context.length; i++) { Class clazz = context[i]; - // Find the first class in the context which is not BundleLoader or the ModuleClassLoader; + // Find the first class in the context which is not BundleLoader or the + // ModuleClassLoader; // We ignore ClassLoader because ModuleClassLoader extends it. // We ignore Class because of Class.forName (bug 471551) - if (clazz != BundleLoader.class && !ModuleClassLoader.class.isAssignableFrom(clazz) && clazz != ClassLoader.class && clazz != Class.class && !clazz.getName().equals("java.lang.J9VMInternals")) { //$NON-NLS-1$ + if (clazz != BundleLoader.class && !ModuleClassLoader.class.isAssignableFrom(clazz) + && clazz != ClassLoader.class && clazz != Class.class + && !clazz.getName().equals("java.lang.J9VMInternals")) { //$NON-NLS-1$ if (Bundle.class.isAssignableFrom(clazz)) { // We ignore any requests from Bundle (e.g. Bundle.loadClass case) return false; } // only find in parent if the class is not loaded with a ModuleClassLoader ClassLoader cl = getClassLoader(clazz); - // extra check incase an adaptor adds another class into the stack besides an instance of ClassLoader + // extra check incase an adaptor adds another class into the stack besides an + // instance of ClassLoader if (cl != FW_CLASSLOADER) { - // if the class is loaded from a class loader implemented by a bundle then we do not boot delegate + // if the class is loaded from a class loader implemented by a bundle then we do + // not boot delegate ClassLoader last = null; while (cl != null && cl != last) { last = cl; @@ -635,7 +663,8 @@ public ClassLoader run() { } /** - * Finds the resource for a bundle. This method is used for delegation by the bundle's classloader. + * Finds the resource for a bundle. This method is used for delegation by the + * bundle's classloader. */ public URL findResource(String name) { if (debug.DEBUG_LOADER) @@ -645,14 +674,16 @@ public URL findResource(String name) { String pkgName = getResourcePackageName(name); boolean bootDelegation = false; // follow the OSGi delegation model - // First check the parent classloader for system resources, if it is a java resource. + // First check the parent classloader for system resources, if it is a java + // resource. if (parent != null) { if (pkgName.startsWith(JAVA_PACKAGE)) // 1) if startsWith "java." delegate to parent and terminate search // we never delegate java resource requests past the parent return parent.getResource(name); else if (container.isBootDelegationPackage(pkgName)) { - // 2) if part of the bootdelegation list then delegate to parent and continue of failure + // 2) if part of the bootdelegation list then delegate to parent and continue of + // failure URL result = parent.getResource(name); if (result != null) return result; @@ -693,7 +724,8 @@ else if (container.isBootDelegationPackage(pkgName)) { result = findLocalResource(name); if (result != null) return result; - // 6) attempt to find a dynamic import source; only do this if a required source was not found + // 6) attempt to find a dynamic import source; only do this if a required source + // was not found if (source == null) { source = findDynamicSource(pkgName); if (source != null) @@ -716,26 +748,30 @@ else if (container.isBootDelegationPackage(pkgName)) { return result; // hack to support backwards compatibility for bootdelegation // or last resort; do class context trick to work around VM bugs - if (parent != null && !bootDelegation && (container.getConfiguration().compatibilityBootDelegation || isRequestFromVM())) + if (parent != null && !bootDelegation + && (container.getConfiguration().compatibilityBootDelegation || isRequestFromVM())) // we don't need to continue if the resource is not found here return parent.getResource(name); return result; } /** - * Finds the resources for a bundle. This method is used for delegation by the bundle's classloader. + * Finds the resources for a bundle. This method is used for delegation by the + * bundle's classloader. */ public Enumeration findResources(String name) throws IOException { if (debug.DEBUG_LOADER) Debug.println("BundleLoader[" + this + "].findResources(" + name + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - // do not delegate to parent because ClassLoader#getResources already did and it is final!! + // do not delegate to parent because ClassLoader#getResources already did and it + // is final!! if ((name.length() > 1) && (name.charAt(0) == '/')) /* if name has a leading slash */ name = name.substring(1); /* remove leading slash before search */ String pkgName = getResourcePackageName(name); Enumeration result = Collections.emptyEnumeration(); boolean bootDelegation = false; // follow the OSGi delegation model - // First check the parent classloader for system resources, if it is a java resource. + // First check the parent classloader for system resources, if it is a java + // resource. if (parent != null) { if (pkgName.startsWith(JAVA_PACKAGE)) // 1) if startsWith "java." delegate to parent and terminate search @@ -780,7 +816,8 @@ else if (container.isBootDelegationPackage(pkgName)) { // compound the required source results with the local ones Enumeration localResults = findLocalResources(name); result = compoundEnumerations(result, localResults); - // 6) attempt to find a dynamic import source; only do this if a required source was not found + // 6) attempt to find a dynamic import source; only do this if a required source + // was not found if (source == null && !result.hasMoreElements()) { source = findDynamicSource(pkgName); if (source != null) @@ -802,7 +839,8 @@ else if (container.isBootDelegationPackage(pkgName)) { // hack to support backwards compatibility for bootdelegation // or last resort; do class context trick to work around VM bugs if (!result.hasMoreElements()) { - if (parent != null && !bootDelegation && (container.getConfiguration().compatibilityBootDelegation || isRequestFromVM())) + if (parent != null && !bootDelegation + && (container.getConfiguration().compatibilityBootDelegation || isRequestFromVM())) // we don't need to continue if the resource is not found here return parent.getResources(name); } @@ -810,7 +848,8 @@ else if (container.isBootDelegationPackage(pkgName)) { } private boolean isSubPackage(String parentPackage, String subPackage) { - String prefix = (parentPackage.length() == 0 || parentPackage.equals(DEFAULT_PACKAGE)) ? "" : parentPackage + '.'; //$NON-NLS-1$ + String prefix = (parentPackage.length() == 0 || parentPackage.equals(DEFAULT_PACKAGE)) ? "" //$NON-NLS-1$ + : parentPackage + '.'; return subPackage.startsWith(prefix); } @@ -863,7 +902,8 @@ protected Collection listResources(String path, String filePattern, int String packagePath = name.replace('.', '/'); Collection externalResources = externalSource.listResources(packagePath, filePattern); for (String resource : externalResources) { - if (!result.contains(resource)) // prevent duplicates; could happen if the package is split or exporter has fragments/multiple jars + if (!result.contains(resource)) // prevent duplicates; could happen if the package is split or + // exporter has fragments/multiple jars result.add(resource); } } @@ -896,14 +936,16 @@ public static Enumeration compoundEnumerations(Enumeration list1, Enum List compoundResults = Collections.list(list1); while (list2.hasMoreElements()) { E item = list2.nextElement(); - if (!compoundResults.contains(item)) //don't add duplicates + if (!compoundResults.contains(item)) // don't add duplicates compoundResults.add(item); } return Collections.enumeration(compoundResults); } /** - * Finds a resource local to this bundle. Only the classloader for this bundle is searched. + * Finds a resource local to this bundle. Only the classloader for this bundle + * is searched. + * * @param name The name of the resource to find. * @return The URL to the resource or null if the resource is not found. */ @@ -912,10 +954,10 @@ public URL findLocalResource(final String name) { } /** - * Returns an Enumeration of URLs representing all the resources with - * the given name. Only the classloader for this bundle is searched. + * Returns an Enumeration of URLs representing all the resources with the given + * name. Only the classloader for this bundle is searched. * - * @param name the resource name + * @param name the resource name * @return an Enumeration of URLs for the resources */ public Enumeration findLocalResources(String name) { @@ -924,6 +966,7 @@ public Enumeration findLocalResources(String name) { /** * Return a string representation of this loader. + * * @return String */ @Override @@ -936,8 +979,8 @@ public final String toString() { } /** - * Return true if the target package name matches - * a name in the DynamicImport-Package manifest header. + * Return true if the target package name matches a name in the + * DynamicImport-Package manifest header. * * @param pkgname The name of the requested class' package. * @return true if the package should be imported. @@ -973,7 +1016,8 @@ private final boolean isDynamicallyImported(String pkgname) { return false; } - final void addExportedProvidersFor(String packageName, List result, Collection visited) { + final void addExportedProvidersFor(String packageName, List result, + Collection visited) { if (visited.contains(this)) return; visited.add(this); @@ -987,7 +1031,8 @@ else if (isSubstitutedExport(packageName)) { } // Must search required bundles that are exported first. for (ModuleWire bundleWire : requiredBundleWires) { - if (local != null || BundleNamespace.VISIBILITY_REEXPORT.equals(bundleWire.getRequirement().getDirectives().get(BundleNamespace.REQUIREMENT_VISIBILITY_DIRECTIVE))) { + if (local != null || BundleNamespace.VISIBILITY_REEXPORT.equals(bundleWire.getRequirement().getDirectives() + .get(BundleNamespace.REQUIREMENT_VISIBILITY_DIRECTIVE))) { // always add required bundles first if we locally provide the package // This allows a bundle to provide a package from a required bundle without // re-exporting the whole required bundle. @@ -1006,16 +1051,19 @@ private BundleLoader getProviderLoader(ModuleWire wire) { ModuleWiring provider = wire.getProviderWiring(); if (provider == null) { if (firstUseOfInvalidLoader.getAndSet(true)) { - // publish a framework event once per loader, include an exception to show the stack + // publish a framework event once per loader, include an exception to show the + // stack String message = "Invalid class loader from a refreshed bundle is being used: " + toString(); //$NON-NLS-1$ - container.getEventPublisher().publishFrameworkEvent(FrameworkEvent.ERROR, wiring.getBundle(), new IllegalStateException(message)); + container.getEventPublisher().publishFrameworkEvent(FrameworkEvent.ERROR, wiring.getBundle(), + new IllegalStateException(message)); } return null; } return (BundleLoader) provider.getModuleLoader(); } - final void addProvidedPackageNames(String packageName, List result, boolean subPackages, Collection visited) { + final void addProvidedPackageNames(String packageName, List result, boolean subPackages, + Collection visited) { if (visited.contains(this)) return; visited.add(this); @@ -1034,7 +1082,8 @@ final void addProvidedPackageNames(String packageName, List result, bool } } for (ModuleWire bundleWire : requiredBundleWires) { - if (BundleNamespace.VISIBILITY_REEXPORT.equals(bundleWire.getRequirement().getDirectives().get(BundleNamespace.REQUIREMENT_VISIBILITY_DIRECTIVE))) { + if (BundleNamespace.VISIBILITY_REEXPORT.equals(bundleWire.getRequirement().getDirectives() + .get(BundleNamespace.REQUIREMENT_VISIBILITY_DIRECTIVE))) { BundleLoader loader = getProviderLoader(bundleWire); if (loader != null) { loader.addProvidedPackageNames(packageName, result, subPackages, visited); @@ -1057,8 +1106,10 @@ private void addDynamicImportPackage(List packageImports) { } List dynamicImports = new ArrayList<>(packageImports.size()); for (ModuleRequirement packageImport : packageImports) { - if (PackageNamespace.RESOLUTION_DYNAMIC.equals(packageImport.getDirectives().get(PackageNamespace.REQUIREMENT_RESOLUTION_DIRECTIVE))) { - Matcher matcher = PACKAGENAME_FILTER.matcher(packageImport.getDirectives().get(PackageNamespace.REQUIREMENT_FILTER_DIRECTIVE)); + if (PackageNamespace.RESOLUTION_DYNAMIC + .equals(packageImport.getDirectives().get(PackageNamespace.REQUIREMENT_RESOLUTION_DIRECTIVE))) { + Matcher matcher = PACKAGENAME_FILTER + .matcher(packageImport.getDirectives().get(PackageNamespace.REQUIREMENT_FILTER_DIRECTIVE)); if (matcher.find()) { String dynamicName = matcher.group(1); if (dynamicName != null) { @@ -1072,10 +1123,11 @@ private void addDynamicImportPackage(List packageImports) { } /** - * Adds a list of DynamicImport-Package manifest elements to the dynamic - * import tables of this BundleLoader. Duplicate packages are checked and - * not added again. This method is not thread safe. Callers should ensure - * synchronization when calling this method. + * Adds a list of DynamicImport-Package manifest elements to the dynamic import + * tables of this BundleLoader. Duplicate packages are checked and not added + * again. This method is not thread safe. Callers should ensure synchronization + * when calling this method. + * * @param packages the DynamicImport-Package elements to add. */ private void addDynamicImportPackage(String[] packages) { @@ -1131,9 +1183,10 @@ private void addDynamicImportPackage(String[] packages) { } /** - * Adds a list of DynamicImport-Package manifest elements to the dynamic - * import tables of this BundleLoader. Duplicate packages are checked and - * not added again. + * Adds a list of DynamicImport-Package manifest elements to the dynamic import + * tables of this BundleLoader. Duplicate packages are checked and not added + * again. + * * @param packages the DynamicImport-Package elements to add. */ public final void addDynamicImportPackage(ManifestElement[] packages) { @@ -1168,8 +1221,8 @@ public final void addDynamicImportPackage(ManifestElement[] packages) { } /* - * Finds a packagesource that is either imported or required from another bundle. - * This will not include an local package source + * Finds a packagesource that is either imported or required from another + * bundle. This will not include an local package source */ private PackageSource findSource(String pkgName) { if (pkgName == null) @@ -1177,7 +1230,8 @@ private PackageSource findSource(String pkgName) { PackageSource result = findImportedSource(pkgName, null); if (result != null) return result; - // Note that dynamic imports are not checked to avoid aggressive wiring (bug 105779) + // Note that dynamic imports are not checked to avoid aggressive wiring (bug + // 105779) return findRequiredSource(pkgName, null); } @@ -1213,7 +1267,8 @@ private PackageSource findDynamicSource(String pkgName) { Debug.println("BundleLoader[" + this + "] attempting to resolve dynamic package: " + pkgName); //$NON-NLS-1$ //$NON-NLS-2$ } ModuleRevision revision = wiring.getRevision(); - ModuleWire dynamicWire = revision.getRevisions().getModule().getContainer().resolveDynamic(pkgName, revision); + ModuleWire dynamicWire = revision.getRevisions().getModule().getContainer().resolveDynamic(pkgName, + revision); if (dynamicWire != null) { PackageSource source = createExportPackageSource(dynamicWire, null); if (debug.DEBUG_LOADER) { @@ -1269,9 +1324,9 @@ private PackageSource findRequiredSource(String pkgName, Collection directives = packageCapability.getDirectives(); - return directives.get(PackageNamespace.CAPABILITY_INCLUDE_DIRECTIVE) != null || directives.get(PackageNamespace.CAPABILITY_EXCLUDE_DIRECTIVE) != null; + return directives.get(PackageNamespace.CAPABILITY_INCLUDE_DIRECTIVE) != null + || directives.get(PackageNamespace.CAPABILITY_EXCLUDE_DIRECTIVE) != null; } - // creates a PackageSource from an ExportPackageDescription. This is called when initializing - // a BundleLoader to ensure that the proper PackageSource gets created and used for - // filtered and reexport packages. The storeSource flag is used by initialize to indicate - // that the source for special case package sources (filtered or re-exported should be stored - // in the cache. if this flag is set then a normal SinglePackageSource will not be created + // creates a PackageSource from an ExportPackageDescription. This is called when + // initializing + // a BundleLoader to ensure that the proper PackageSource gets created and used + // for + // filtered and reexport packages. The storeSource flag is used by initialize to + // indicate + // that the source for special case package sources (filtered or re-exported + // should be stored + // in the cache. if this flag is set then a normal SinglePackageSource will not + // be created // (i.e. it will be created lazily) public PackageSource createPackageSource(ModuleCapability packageCapability, boolean storeSource) { PackageSource pkgSource = null; @@ -74,7 +80,8 @@ public PackageSource createPackageSource(ModuleCapability packageCapability, boo } } } else { - // we are not storing the special case sources, but pkgSource == null this means this + // we are not storing the special case sources, but pkgSource == null this means + // this // is a normal package source; get it and return it. if (pkgSource == null) { pkgSource = getPackageSource(name); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/EquinoxClassLoader.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/EquinoxClassLoader.java index 0b01cd33937..c834e453413 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/EquinoxClassLoader.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/EquinoxClassLoader.java @@ -34,25 +34,29 @@ public class EquinoxClassLoader extends ModuleClassLoader { private final Debug debug; private final BundleLoader delegate; private final Generation generation; - // TODO Note that PDE has internal dependency on this field type/name (bug 267238) + // TODO Note that PDE has internal dependency on this field type/name (bug + // 267238) private final ClasspathManager manager; private final boolean isRegisteredAsParallel; /** * Constructs a new DefaultClassLoader. - * @param parent the parent classloader + * + * @param parent the parent classloader * @param configuration the equinox configuration - * @param delegate the delegate for this classloader - * @param generation the generation for this class loader + * @param delegate the delegate for this classloader + * @param generation the generation for this class loader */ - public EquinoxClassLoader(ClassLoader parent, EquinoxConfiguration configuration, BundleLoader delegate, Generation generation) { + public EquinoxClassLoader(ClassLoader parent, EquinoxConfiguration configuration, BundleLoader delegate, + Generation generation) { super(parent); this.configuration = configuration; this.debug = configuration.getDebug(); this.delegate = delegate; this.generation = generation; this.manager = new ClasspathManager(generation, this); - this.isRegisteredAsParallel = (ModuleClassLoader.REGISTERED_AS_PARALLEL && EQUINOX_REGISTERED_AS_PARALLEL) || this.configuration.PARALLEL_CAPABLE; + this.isRegisteredAsParallel = (ModuleClassLoader.REGISTERED_AS_PARALLEL && EQUINOX_REGISTERED_AS_PARALLEL) + || this.configuration.PARALLEL_CAPABLE; } @Override diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/ModuleClassLoader.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/ModuleClassLoader.java index ede519ad212..affd72d5d92 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/ModuleClassLoader.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/ModuleClassLoader.java @@ -44,7 +44,8 @@ public abstract class ModuleClassLoader extends ClassLoader implements BundleRef public static class GenerationProtectionDomain extends ProtectionDomain implements BundleReference { private final Generation generation; - public GenerationProtectionDomain(CodeSource codesource, PermissionCollection permissions, Generation generation) { + public GenerationProtectionDomain(CodeSource codesource, PermissionCollection permissions, + Generation generation) { super(codesource, permissions); this.generation = generation; } @@ -56,7 +57,8 @@ public Bundle getBundle() { } /** - * A PermissionCollection for AllPermissions; shared across all ProtectionDomains when security is disabled + * A PermissionCollection for AllPermissions; shared across all + * ProtectionDomains when security is disabled */ protected static final PermissionCollection ALLPERMISSIONS; protected static final boolean REGISTERED_AS_PARALLEL; @@ -87,8 +89,8 @@ public static class DefineClassResult { */ public final Class clazz; /** - * Set to true if the class object got defined; set to false if the class - * did not get defined correctly or the class was found as a previously loaded + * Set to true if the class object got defined; set to false if the class did + * not get defined correctly or the class was found as a previously loaded * class. */ public final boolean defined; @@ -104,6 +106,7 @@ public DefineClassResult(Class clazz, boolean defined) { /** * Constructs a new ModuleClassLoader. + * * @param parent the parent classloader */ public ModuleClassLoader(ClassLoader parent) { @@ -112,51 +115,55 @@ public ModuleClassLoader(ClassLoader parent) { /** * Returns the generation of the host revision associated with this class loader + * * @return the generation for this class loader */ protected abstract Generation getGeneration(); /** * Returns the Debug object for the Framework instance + * * @return the Debug object for the Framework instance */ protected abstract Debug getDebug(); /** * Returns the classpath manager for this class loader + * * @return the classpath manager for this class loader */ public abstract ClasspathManager getClasspathManager(); /** * Returns the configuration for the Framework instance + * * @return the configuration for the Framework instance */ protected abstract EquinoxConfiguration getConfiguration(); /** * Returns the bundle loader for this class loader + * * @return the bundle loader for this class loader */ public abstract BundleLoader getBundleLoader(); /** - * Returns true if this class loader implementation has been - * registered with the JVM as a parallel class loader. - * This requires Java 7 or later. - * @return true if this class loader implementation has been - * registered with the JVM as a parallel class loader; otherwise - * false is returned. + * Returns true if this class loader implementation has been registered with the + * JVM as a parallel class loader. This requires Java 7 or later. + * + * @return true if this class loader implementation has been registered with the + * JVM as a parallel class loader; otherwise false is returned. */ public abstract boolean isRegisteredAsParallel(); /** - * Loads a class for the bundle. First delegate.findClass(name) is called. - * The delegate will query the system class loader, bundle imports, bundle - * local classes, bundle hosts and fragments. The delegate will call - * BundleClassLoader.findLocalClass(name) to find a class local to this - * bundle. - * @param name the name of the class to load. + * Loads a class for the bundle. First delegate.findClass(name) is called. The + * delegate will query the system class loader, bundle imports, bundle local + * classes, bundle hosts and fragments. The delegate will call + * BundleClassLoader.findLocalClass(name) to find a class local to this bundle. + * + * @param name the name of the class to load. * @param resolve indicates whether to resolve the loaded class or not. * @return The Class object. * @throws ClassNotFoundException if the class is not found. @@ -188,11 +195,12 @@ protected Class findClass(String name) throws ClassNotFoundException { } /** - * Gets a resource for the bundle. First delegate.findResource(name) is - * called. The delegate will query the system class loader, bundle imports, - * bundle local resources, bundle hosts and fragments. The delegate will - * call BundleClassLoader.findLocalResource(name) to find a resource local - * to this bundle. + * Gets a resource for the bundle. First delegate.findResource(name) is called. + * The delegate will query the system class loader, bundle imports, bundle local + * resources, bundle hosts and fragments. The delegate will call + * BundleClassLoader.findLocalResource(name) to find a resource local to this + * bundle. + * * @param name The resource path to get. * @return The URL of the resource or null if it does not exist. */ @@ -224,11 +232,12 @@ protected URL findResource(String name) { } /** - * Gets resources for the bundle. First delegate.findResources(name) is - * called. The delegate will query the system class loader, bundle imports, - * bundle local resources, bundle hosts and fragments. The delegate will - * call BundleClassLoader.findLocalResources(name) to find a resource local - * to this bundle. + * Gets resources for the bundle. First delegate.findResources(name) is called. + * The delegate will query the system class loader, bundle imports, bundle local + * resources, bundle hosts and fragments. The delegate will call + * BundleClassLoader.findLocalResources(name) to find a resource local to this + * bundle. + * * @param name The resource path to get. * @return The Enumeration of the resource URLs. */ @@ -252,8 +261,9 @@ protected Enumeration findResources(String name) throws IOException { } /** - * Finds a library for this bundle. Simply calls - * manager.findLibrary(libname) to find the library. + * Finds a library for this bundle. Simply calls manager.findLibrary(libname) to + * find the library. + * * @param libname The library to find. * @return The absolution path to the library or null if not found */ @@ -268,7 +278,8 @@ public ClasspathEntry createClassPathEntry(BundleFile bundlefile, Generation ent } public DefineClassResult defineClass(String name, byte[] classbytes, ClasspathEntry classpathEntry) { - // Note that we must check findLoadedClass again here since no locks are held between + // Note that we must check findLoadedClass again here since no locks are held + // between // calling findLoadedClass the first time and defineClass. // This is to allow weavers to get called while holding no locks. // See ClasspathManager.findLocalClass(String) @@ -316,10 +327,13 @@ public Package publicGetPackage(String pkgname) { } } - public Package publicDefinePackage(String name, String specTitle, String specVersion, String specVendor, String implTitle, String implVersion, String implVendor, URL sealBase) { + public Package publicDefinePackage(String name, String specTitle, String specVersion, String specVendor, + String implTitle, String implVersion, String implVendor, URL sealBase) { synchronized (pkgLock) { Package pkg = getPackage(name); - return pkg != null ? pkg : definePackage(name, specTitle, specVersion, specVendor, implTitle, implVersion, implVendor, sealBase); + return pkg != null ? pkg + : definePackage(name, specTitle, specVersion, specVendor, implTitle, implVersion, implVendor, + sealBase); } } @@ -336,14 +350,18 @@ public Class findLocalClass(String classname) throws ClassNotFoundException { } /** - * Creates a ProtectionDomain which uses specified BundleFile and the permissions of the baseDomain - * @param bundlefile The source bundlefile the domain is for. + * Creates a ProtectionDomain which uses specified BundleFile and the + * permissions of the baseDomain + * + * @param bundlefile The source bundlefile the domain is for. * @param domainGeneration the source generation for the domain - * @return a ProtectionDomain which uses specified BundleFile and the permissions of the baseDomain + * @return a ProtectionDomain which uses specified BundleFile and the + * permissions of the baseDomain */ @SuppressWarnings("deprecation") protected ProtectionDomain createProtectionDomain(BundleFile bundlefile, Generation domainGeneration) { - // create a protection domain which knows about the codesource for this classpath entry (bug 89904) + // create a protection domain which knows about the codesource for this + // classpath entry (bug 89904) ProtectionDomain baseDomain = domainGeneration.getDomain(); try { // use the permissions supplied by the domain passed in from the framework @@ -351,7 +369,7 @@ protected ProtectionDomain createProtectionDomain(BundleFile bundlefile, Generat if (baseDomain != null) { permissions = baseDomain.getPermissions(); } else { - // no domain specified. Better use a collection that has all permissions + // no domain specified. Better use a collection that has all permissions // this is done just incase someone sets the security manager later permissions = ALLPERMISSIONS; } @@ -367,9 +385,12 @@ protected ProtectionDomain createProtectionDomain(BundleFile bundlefile, Generat } } File file = bundlefile.getBaseFile(); - // Bug 477787: file will be null when the osgi.framework configuration property contains an invalid value. - return new GenerationProtectionDomain(file == null ? null : new CodeSource(file.toURL(), certs), permissions, getGeneration()); - //return new ProtectionDomain(new CodeSource(bundlefile.getBaseFile().toURL(), certs), permissions); + // Bug 477787: file will be null when the osgi.framework configuration property + // contains an invalid value. + return new GenerationProtectionDomain(file == null ? null : new CodeSource(file.toURL(), certs), + permissions, getGeneration()); + // return new ProtectionDomain(new CodeSource(bundlefile.getBaseFile().toURL(), + // certs), permissions); } catch (MalformedURLException e) { // Failed to create our own domain; just return the baseDomain return baseDomain; @@ -399,7 +420,8 @@ public String toString() { StringBuilder result = new StringBuilder(super.toString()); if (b == null) return result.toString(); - return result.append('[').append(b.getSymbolicName()).append(':').append(b.getVersion()).append("(id=").append(b.getBundleId()).append(")]").toString(); //$NON-NLS-1$//$NON-NLS-2$ + return result.append('[').append(b.getSymbolicName()).append(':').append(b.getVersion()).append("(id=") //$NON-NLS-1$ + .append(b.getBundleId()).append(")]").toString(); //$NON-NLS-1$ } public void loadFragments(Collection fragments) { @@ -425,7 +447,8 @@ private boolean lockClassName(String classname) { } } catch (InterruptedException e) { previousInterruption = true; - // must not throw LinkageError or ClassNotFoundException here because that will cause all threads + // must not throw LinkageError or ClassNotFoundException here because that will + // cause all threads // to fail to load the class (see bug 490902) throw new Error("Interrupted while waiting for classname lock: " + classname, e); //$NON-NLS-1$ } finally { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/SystemBundleLoader.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/SystemBundleLoader.java index 11099cfd459..9c4bd56588f 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/SystemBundleLoader.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/SystemBundleLoader.java @@ -28,8 +28,8 @@ import org.osgi.framework.BundleException; /** - * The System Bundle's BundleLoader. This BundleLoader is used by ImportClassLoaders - * to load a resource that is exported by the System Bundle. + * The System Bundle's BundleLoader. This BundleLoader is used by + * ImportClassLoaders to load a resource that is exported by the System Bundle. */ public class SystemBundleLoader extends BundleLoader { public static final String EQUINOX_EE = "x-equinox-ee"; //$NON-NLS-1$ @@ -39,12 +39,14 @@ public class SystemBundleLoader extends BundleLoader { public SystemBundleLoader(ModuleWiring wiring, EquinoxContainer container, ClassLoader frameworkLoader) { super(wiring, container, frameworkLoader.getParent()); this.classLoader = frameworkLoader; - this.moduleClassLoader = new SystemModuleClassLoader(classLoader.getParent(), container.getConfiguration(), this, (Generation) wiring.getRevision().getRevisionInfo()); + this.moduleClassLoader = new SystemModuleClassLoader(classLoader.getParent(), container.getConfiguration(), + this, (Generation) wiring.getRevision().getRevisionInfo()); } /** * The ClassLoader that loads OSGi framework classes is used to find the class. - * This method never gets called because there is no BundleClassLoader for the framework. + * This method never gets called because there is no BundleClassLoader for the + * framework. */ @Override public Class findClass(String name) throws ClassNotFoundException { @@ -68,7 +70,8 @@ public Class findLocalClass(String name) { } /** - * The ClassLoader that loads OSGi framework classes is used to find the resource. + * The ClassLoader that loads OSGi framework classes is used to find the + * resource. */ @Override public URL findLocalResource(String name) { @@ -76,7 +79,8 @@ public URL findLocalResource(String name) { } /** - * The ClassLoader that loads OSGi framework classes is used to find the resource. + * The ClassLoader that loads OSGi framework classes is used to find the + * resource. */ @Override public Enumeration findLocalResources(String name) { @@ -89,8 +93,9 @@ public Enumeration findLocalResources(String name) { } /** - * The ClassLoader that loads OSGi framework classes is used to find the resource. - * This method never gets called because there is no ModuleClassLoader for the framework. + * The ClassLoader that loads OSGi framework classes is used to find the + * resource. This method never gets called because there is no ModuleClassLoader + * for the framework. */ @Override public URL findResource(String name) { @@ -98,8 +103,10 @@ public URL findResource(String name) { } /** - * The ClassLoader that loads OSGi framework classes is used to find the resource. - * This method never gets called because there is no ModuleClassLoader for the framework. + * The ClassLoader that loads OSGi framework classes is used to find the + * resource. This method never gets called because there is no ModuleClassLoader + * for the framework. + * * @throws IOException */ @Override @@ -124,7 +131,8 @@ void loadClassLoaderFragments(Collection fragments) { class SystemModuleClassLoader extends EquinoxClassLoader { - public SystemModuleClassLoader(ClassLoader parent, EquinoxConfiguration configuration, BundleLoader delegate, Generation generation) { + public SystemModuleClassLoader(ClassLoader parent, EquinoxConfiguration configuration, BundleLoader delegate, + Generation generation) { super(parent, configuration, delegate, generation); } @@ -137,7 +145,8 @@ protected Class loadClass(String name, boolean resolve) throws ClassNotFoundE public void loadFragments(Collection fragments) { Module systemModule = getWiring().getRevision().getRevisions().getModule(); try { - this.getGeneration().getBundleInfo().getStorage().getExtensionInstaller().addExtensionContent(fragments, systemModule); + this.getGeneration().getBundleInfo().getStorage().getExtensionInstaller().addExtensionContent(fragments, + systemModule); } catch (BundleException e) { systemModule.getContainer().getAdaptor().publishContainerEvent(ContainerEvent.ERROR, systemModule, e); } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/buddy/DependentPolicy.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/buddy/DependentPolicy.java index 24ca5159e5e..8e5da3f910d 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/buddy/DependentPolicy.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/buddy/DependentPolicy.java @@ -27,22 +27,22 @@ import org.osgi.framework.namespace.PackageNamespace; /** - * DependentPolicy is an implementation of a buddy policy. - * It is responsible for looking up a class in the dependents of the bundle - * to which this policy is attached to. + * DependentPolicy is an implementation of a buddy policy. It is responsible for + * looking up a class in the dependents of the bundle to which this policy is + * attached to. */ public class DependentPolicy implements IBuddyPolicy { BundleLoader buddyRequester; - int lastDependentOfAdded = -1; //remember the index of the bundle for which we last added the dependent - List allDependents = null; //the list of all dependents known so far + int lastDependentOfAdded = -1; // remember the index of the bundle for which we last added the dependent + List allDependents = null; // the list of all dependents known so far public DependentPolicy(BundleLoader requester) { buddyRequester = requester; - //Initialize with the first level of dependent the list + // Initialize with the first level of dependent the list allDependents = new ArrayList<>(); basicAddImmediateDependents(requester.getWiring()); - //If there is no dependent, reset to null + // If there is no dependent, reset to null if (allDependents.size() == 0) allDependents = null; } @@ -52,7 +52,7 @@ public Class loadClass(String name) { if (allDependents == null) { return null; } - //size may change, so we must check it every time + // size may change, so we must check it every time for (int i = 0; i < allDependents.size(); i++) { ModuleWiring searchWiring = allDependents.get(i); BundleLoader searchLoader = (BundleLoader) searchWiring.getModuleLoader(); @@ -80,7 +80,7 @@ public URL loadResource(String name) { return null; URL result = null; - //size may change, so we must check it every time + // size may change, so we must check it every time for (int i = 0; i < allDependents.size() && result == null; i++) { ModuleWiring searchWiring = allDependents.get(i); BundleLoader searchLoader = (BundleLoader) searchWiring.getModuleLoader(); @@ -100,7 +100,7 @@ public Enumeration loadResources(String name) { return null; Enumeration results = null; - //size may change, so we must check it every time + // size may change, so we must check it every time for (int i = 0; i < allDependents.size(); i++) { ModuleWiring searchWiring = allDependents.get(i); BundleLoader searchLoader = (BundleLoader) searchWiring.getModuleLoader(); @@ -109,7 +109,7 @@ public Enumeration loadResources(String name) { results = BundleLoader.compoundEnumerations(results, searchLoader.findResources(name)); addDependent(i, searchWiring); } catch (IOException e) { - //Ignore and keep looking + // Ignore and keep looking } } } @@ -134,7 +134,8 @@ private void basicAddImmediateDependents(ModuleWiring wiring) { if (providedWires != null) { for (ModuleWire wire : providedWires) { String namespace = wire.getRequirement().getNamespace(); - if (PackageNamespace.PACKAGE_NAMESPACE.equals(namespace) || BundleNamespace.BUNDLE_NAMESPACE.equals(namespace)) { + if (PackageNamespace.PACKAGE_NAMESPACE.equals(namespace) + || BundleNamespace.BUNDLE_NAMESPACE.equals(namespace)) { ModuleWiring dependent = wire.getRequirerWiring(); if (!allDependents.contains(dependent)) { allDependents.add(dependent); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/buddy/GlobalPolicy.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/buddy/GlobalPolicy.java index 16bab2eae77..aa4f4f8ea8e 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/buddy/GlobalPolicy.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/buddy/GlobalPolicy.java @@ -33,8 +33,8 @@ import org.osgi.resource.Namespace; /** - * Global policy is an implementation of a buddy policy. It is responsible - * for looking up a class within the global set of exported classes. If multiple + * Global policy is an implementation of a buddy policy. It is responsible for + * looking up a class within the global set of exported classes. If multiple * version of the same package are exported in the system, the exported package * with the highest version will be returned. */ @@ -64,8 +64,8 @@ public Enumeration loadResources(String name) { for (BundleLoader exporter : exporters) { try { results = BundleLoader.compoundEnumerations(results, exporter.findResources(name)); - }catch (IOException e) { - //ignore IO problems and try next package + } catch (IOException e) { + // ignore IO problems and try next package } } return results; diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/buddy/PolicyHandler.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/buddy/PolicyHandler.java index 001ab47c09d..2c126783547 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/buddy/PolicyHandler.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/buddy/PolicyHandler.java @@ -30,7 +30,7 @@ import org.osgi.framework.wiring.FrameworkWiring; public class PolicyHandler implements SynchronousBundleListener { - //Key for the framework buddies + // Key for the framework buddies private final static String DEPENDENT_POLICY = "dependent"; //$NON-NLS-1$ private final static String GLOBAL_POLICY = "global"; //$NON-NLS-1$ private final static String REGISTERED_POLICY = "registered"; //$NON-NLS-1$ @@ -39,13 +39,16 @@ public class PolicyHandler implements SynchronousBundleListener { private final static String BOOT_POLICY = "boot"; //$NON-NLS-1$ private final static String PARENT_POLICY = "parent"; //$NON-NLS-1$ - //The loader to which this policy is attached. + // The loader to which this policy is attached. private final BundleLoader policedLoader; private final List originalBuddyList; - //List of the policies as well as cache for the one that have been created. The size of this array never changes over time. This is why the synchronization is not done when iterating over it. + // List of the policies as well as cache for the one that have been created. The + // size of this array never changes over time. This is why the synchronization + // is not done when iterating over it. private volatile Object[] policies = null; - //Support to cut class / resource loading cycles in the context of one thread. The contained object is a set of classname + // Support to cut class / resource loading cycles in the context of one thread. + // The contained object is a set of classname private final ThreadLocal> beingLoaded; private final FrameworkWiring frameworkWiring; private final ClassLoader bootLoader; @@ -110,33 +113,36 @@ private IBuddyPolicy getPolicyImplementation(Object[] policiesSnapshot, int poli } // Not a valid buddy policy EquinoxBundle bundle = (EquinoxBundle) policedLoader.getModuleClassLoader().getBundle(); - bundle.getModule().getContainer().getAdaptor().publishContainerEvent(ContainerEvent.ERROR, bundle.getModule(), new RuntimeException("Invalid buddy policy: " + buddyName)); //$NON-NLS-1$ + bundle.getModule().getContainer().getAdaptor().publishContainerEvent(ContainerEvent.ERROR, + bundle.getModule(), new RuntimeException("Invalid buddy policy: " + buddyName)); //$NON-NLS-1$ policiesSnapshot[policyOrder] = null; - // //Buddy policy can be provided by service implementations - // BundleContext fwkCtx = policedLoader.bundle.framework.systemBundle.context; - // ServiceReference[] matchingBuddies = null; - // try { - // matchingBuddies = fwkCtx.getAllServiceReferences(IBuddyPolicy.class.getName(), "buddyName=" + buddyName); - // } catch (InvalidSyntaxException e) { - // //The filter is valid - // } - // if (matchingBuddies == null) - // return new IBuddyPolicy() { - // public Class loadClass(String name) { - // return null; - // } + // //Buddy policy can be provided by service implementations + // BundleContext fwkCtx = policedLoader.bundle.framework.systemBundle.context; + // ServiceReference[] matchingBuddies = null; + // try { + // matchingBuddies = + // fwkCtx.getAllServiceReferences(IBuddyPolicy.class.getName(), "buddyName=" + + // buddyName); + // } catch (InvalidSyntaxException e) { + // //The filter is valid + // } + // if (matchingBuddies == null) + // return new IBuddyPolicy() { + // public Class loadClass(String name) { + // return null; + // } // - // public URL loadResource(String name) { - // return null; - // } + // public URL loadResource(String name) { + // return null; + // } // - // public Enumeration loadResources(String name) { - // return null; - // } - // }; + // public Enumeration loadResources(String name) { + // return null; + // } + // }; // - // //The policies loaded through service are not cached - // return ((IBuddyPolicy) fwkCtx.getService(matchingBuddies[0])); + // //The policies loaded through service are not cached + // return ((IBuddyPolicy) fwkCtx.getService(matchingBuddies[0])); } return (IBuddyPolicy) policiesSnapshot[policyOrder]; } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/buddy/RegisteredPolicy.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/buddy/RegisteredPolicy.java index 3301285ba56..1d7b835386d 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/buddy/RegisteredPolicy.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/buddy/RegisteredPolicy.java @@ -25,25 +25,28 @@ import org.eclipse.osgi.internal.loader.BundleLoader; /** - *Registered policy is an implementation of a buddy policy. - * It is responsible for looking up a class in the bundles (registrant) that declare interest in the bundle that require the buddy loading. - * Note that the registrants must have a direct dependency on the bundle needing buddy. + * Registered policy is an implementation of a buddy policy. It is responsible + * for looking up a class in the bundles (registrant) that declare interest in + * the bundle that require the buddy loading. Note that the registrants must + * have a direct dependency on the bundle needing buddy. */ public class RegisteredPolicy extends DependentPolicy { public RegisteredPolicy(BundleLoader requester) { super(requester); - //Filter the dependents; + // Filter the dependents; if (allDependents == null) return; String requesterName = requester.getWiring().getRevision().getSymbolicName(); for (Iterator iter = allDependents.iterator(); iter.hasNext();) { ModuleWiring wiring = iter.next(); - List moduleDatas = wiring.getRevision().getModuleCapabilities(EquinoxModuleDataNamespace.MODULE_DATA_NAMESPACE); + List moduleDatas = wiring.getRevision() + .getModuleCapabilities(EquinoxModuleDataNamespace.MODULE_DATA_NAMESPACE); @SuppressWarnings("unchecked") - List registeredList = (List) (moduleDatas.isEmpty() ? null : moduleDatas.get(0).getAttributes().get(EquinoxModuleDataNamespace.CAPABILITY_BUDDY_REGISTERED)); + List registeredList = (List) (moduleDatas.isEmpty() ? null + : moduleDatas.get(0).getAttributes().get(EquinoxModuleDataNamespace.CAPABILITY_BUDDY_REGISTERED)); if (registeredList == null || registeredList.isEmpty()) { iter.remove(); } else { @@ -60,7 +63,8 @@ public RegisteredPolicy(BundleLoader requester) { } } - //After the filtering, if nothing is left then null out the variable for optimization + // After the filtering, if nothing is left then null out the variable for + // optimization if (allDependents.size() == 0) allDependents = null; } @@ -116,7 +120,7 @@ public Enumeration loadResources(String name) { results = BundleLoader.compoundEnumerations(results, searchLoader.findResources(name)); } } catch (IOException e) { - //Ignore and keep looking + // Ignore and keep looking } } return results; diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/buddy/SystemPolicy.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/buddy/SystemPolicy.java index 27b18f22dbc..cdea8f5b03c 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/buddy/SystemPolicy.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/buddy/SystemPolicy.java @@ -32,13 +32,14 @@ public class SystemPolicy implements IBuddyPolicy { public static SystemPolicy getInstance(final byte type, final ClassLoader bootLoader) { if (instances[type] == null) { instances[type] = new SystemPolicy(); - instances[type].classLoader = AccessController.doPrivileged((PrivilegedAction) () -> createClassLoader(type, bootLoader)); + instances[type].classLoader = AccessController + .doPrivileged((PrivilegedAction) () -> createClassLoader(type, bootLoader)); } return instances[type]; } public SystemPolicy() { - //Nothing to do + // Nothing to do } public SystemPolicy(ClassLoader parent) { @@ -47,18 +48,18 @@ public SystemPolicy(ClassLoader parent) { static ClassLoader createClassLoader(byte type, ClassLoader bootLoader) { switch (type) { - case APP : - if (ClassLoader.getSystemClassLoader() != null) - return ClassLoader.getSystemClassLoader(); - return bootLoader; + case APP: + if (ClassLoader.getSystemClassLoader() != null) + return ClassLoader.getSystemClassLoader(); + return bootLoader; - case BOOT : - return bootLoader; + case BOOT: + return bootLoader; - case EXT : - if (ClassLoader.getSystemClassLoader() != null) - return ClassLoader.getSystemClassLoader().getParent(); - return bootLoader; + case EXT: + if (ClassLoader.getSystemClassLoader() != null) + return ClassLoader.getSystemClassLoader().getParent(); + return bootLoader; } return null; } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/classpath/ClasspathEntry.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/classpath/ClasspathEntry.java index d9361831241..3380aebfd75 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/classpath/ClasspathEntry.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/classpath/ClasspathEntry.java @@ -37,10 +37,11 @@ import org.eclipse.osgi.storage.bundlefile.BundleFile; /** - * A ClasspathEntry contains a single BundleFile which is used as - * a source to load classes and resources from, and a single + * A ClasspathEntry contains a single BundleFile which is used as a + * source to load classes and resources from, and a single * ProtectionDomain which is used as the domain to define classes * loaded from this ClasspathEntry. + * * @since 3.2 */ public class ClasspathEntry { @@ -61,14 +62,16 @@ static final class PDEData { private final List mrBundleFiles; private HashMap userObjects = null; - // TODO Note that PDE has internal dependency on this field type/name (bug 267238) + // TODO Note that PDE has internal dependency on this field type/name (bug + // 267238) @SuppressWarnings("unused") private final PDEData data; /** * Constructs a ClasspathElement with the specified bundlefile and domain + * * @param bundlefile A BundleFile object which acts as a source - * @param domain the protection domain + * @param domain the protection domain */ public ClasspathEntry(BundleFile bundlefile, ProtectionDomain domain, Generation generation) { this.bundlefile = bundlefile; @@ -77,7 +80,8 @@ public ClasspathEntry(BundleFile bundlefile, ProtectionDomain domain, Generation final Manifest manifest = loadManifest(bundlefile, generation); if (manifest != null && generation.getBundleInfo().getStorage().getConfiguration().DEFINE_PACKAGE_ATTRIBUTES) { mainManifestPackageAttributes = manifestPackageAttributesFor(manifest.getMainAttributes(), null); - perPackageManifestAttributes = manifestPackageAttributesMapFor(manifest.getEntries().entrySet(), mainManifestPackageAttributes); + perPackageManifestAttributes = manifestPackageAttributesMapFor(manifest.getEntries().entrySet(), + mainManifestPackageAttributes); } else { mainManifestPackageAttributes = ManifestPackageAttributes.NONE; perPackageManifestAttributes = null; @@ -88,7 +92,9 @@ public ClasspathEntry(BundleFile bundlefile, ProtectionDomain domain, Generation // this is the root bundle file isMRJar = generation.isMRJar(); } else { - isMRJar = manifest != null ? Boolean.parseBoolean(manifest.getMainAttributes().getValue(BundleInfo.MULTI_RELEASE_HEADER)) : false; + isMRJar = manifest != null + ? Boolean.parseBoolean(manifest.getMainAttributes().getValue(BundleInfo.MULTI_RELEASE_HEADER)) + : false; } if (isMRJar) { mrBundleFiles = getMRBundleFiles(bundlefile, generation); @@ -107,13 +113,15 @@ private static List getMRBundleFiles(BundleFile bundlefile, Generati String versionPath = BundleInfo.MULTI_RELEASE_VERSIONS + i + '/'; BundleEntry versionEntry = bundlefile.getEntry(versionPath); if (versionEntry != null) { - mrBundleFiles.add(storage.createNestedBundleFile(versionPath, bundlefile, generation, BundleInfo.MULTI_RELEASE_FILTER_PREFIXES)); + mrBundleFiles.add(storage.createNestedBundleFile(versionPath, bundlefile, generation, + BundleInfo.MULTI_RELEASE_FILTER_PREFIXES)); } } return Collections.unmodifiableList(mrBundleFiles); } - private static ManifestPackageAttributes manifestPackageAttributesFor(Attributes attributes, ManifestPackageAttributes defaultAttributes) { + private static ManifestPackageAttributes manifestPackageAttributesFor(Attributes attributes, + ManifestPackageAttributes defaultAttributes) { return ManifestPackageAttributes.of(attributes.getValue(Attributes.Name.SPECIFICATION_TITLE), // attributes.getValue(Attributes.Name.SPECIFICATION_VERSION), // attributes.getValue(Attributes.Name.SPECIFICATION_VENDOR), // @@ -123,7 +131,8 @@ private static ManifestPackageAttributes manifestPackageAttributesFor(Attributes defaultAttributes); } - private static Map manifestPackageAttributesMapFor(Set> entries, ManifestPackageAttributes defaultAttributes) { + private static Map manifestPackageAttributesMapFor( + Set> entries, ManifestPackageAttributes defaultAttributes) { Map result = null; for (Entry entry : entries) { String name = entry.getKey(); @@ -141,6 +150,7 @@ private static Map manifestPackageAttributesM /** * Returns the source BundleFile for this classpath entry + * * @return the source BundleFile for this classpath entry */ public BundleFile getBundleFile() { @@ -149,6 +159,7 @@ public BundleFile getBundleFile() { /** * Returns the ProtectionDomain for this classpath entry + * * @return the ProtectionDomain for this classpath entry */ public ProtectionDomain getDomain() { @@ -157,6 +168,7 @@ public ProtectionDomain getDomain() { /** * Returns a user object which is keyed by the specified key + * * @param key the key of the user object to get * @return a user object which is keyed by the specified key */ @@ -169,6 +181,7 @@ public synchronized Object getUserObject(Object key) { /** * Adds a user object + * * @param userObject the user object to add */ public synchronized void addUserObject(KeyedElement userObject) { @@ -180,8 +193,9 @@ public synchronized void addUserObject(KeyedElement userObject) { } /** - * Finds the entry with the specified path. - * This handles Multi-Release searching also. + * Finds the entry with the specified path. This handles Multi-Release searching + * also. + * * @param path the path to find * @return the entry with the specified path. */ @@ -196,10 +210,11 @@ public BundleEntry findEntry(String path) { } /** - * Finds the resource wiht the specified name. - * This handles Multi-Release searching also. - * @param name the resource name - * @param m the module this classpath entry is for + * Finds the resource wiht the specified name. This handles Multi-Release + * searching also. + * + * @param name the resource name + * @param m the module this classpath entry is for * @param index the index this classpath entry. * @return the resource URL or {@code null} if the resource does not exist. */ @@ -214,8 +229,9 @@ public URL findResource(String name, Module m, int index) { } /** - * Adds the BundleFile objects for this classpath in the proper order - * for searching for resources. This handles Multi-Release ordering also. + * Adds the BundleFile objects for this classpath in the proper order for + * searching for resources. This handles Multi-Release ordering also. + * * @param bundlefiles */ public void addBundleFiles(List bundlefiles) { @@ -246,7 +262,8 @@ private static Manifest loadManifest(BundleFile cpBundleFile, Generation generat } ManifestPackageAttributes manifestPackageAttributesFor(String packageName) { - ManifestPackageAttributes perPackage = perPackageManifestAttributes == null ? null : perPackageManifestAttributes.get(packageName); + ManifestPackageAttributes perPackage = perPackageManifestAttributes == null ? null + : perPackageManifestAttributes.get(packageName); if (perPackage != null) { return perPackage; } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/classpath/ClasspathManager.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/classpath/ClasspathManager.java index dbaf19969d0..038a0cffe63 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/classpath/ClasspathManager.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/classpath/ClasspathManager.java @@ -51,36 +51,43 @@ import org.osgi.framework.namespace.HostNamespace; /** - * A helper class for {@link ModuleClassLoader} implementations. This class will keep track of - * {@link ClasspathEntry} objects for the host bundle and any attached fragment bundles. This - * class takes care of searching the {@link ClasspathEntry} objects for a module class loader - * implementation. Additional behavior may be added to a classpath manager by configuring a + * A helper class for {@link ModuleClassLoader} implementations. This class will + * keep track of {@link ClasspathEntry} objects for the host bundle and any + * attached fragment bundles. This class takes care of searching the + * {@link ClasspathEntry} objects for a module class loader implementation. + * Additional behavior may be added to a classpath manager by configuring a * {@link ClassLoaderHook}. + * * @see ModuleClassLoader * @see ClassLoaderHook * @since 3.2 */ public class ClasspathManager { private static final FragmentClasspath[] emptyFragments = new FragmentClasspath[0]; - private static final String[] DEFAULT_CLASSPATH = new String[] {"."}; //$NON-NLS-1$ + private static final String[] DEFAULT_CLASSPATH = new String[] { "." }; //$NON-NLS-1$ private final Generation generation; private final ModuleClassLoader classloader; private final HookRegistry hookRegistry; private final Debug debug; - // TODO Note that PDE has internal dependency on this field type/name (bug 267238) + // TODO Note that PDE has internal dependency on this field type/name (bug + // 267238) private final ClasspathEntry[] entries; - // TODO Note that PDE has internal dependency on this field type/name (bug 267238) + // TODO Note that PDE has internal dependency on this field type/name (bug + // 267238) private volatile FragmentClasspath[] fragments; // a Map where "libname" is the key and libpath" is the value private ArrayMap loadedLibraries = null; - // used to detect recusive defineClass calls for the same class on the same class loader (bug 345500) + // used to detect recusive defineClass calls for the same class on the same + // class loader (bug 345500) private ThreadLocal currentDefineContext = new ThreadLocal<>(); /** - * Constructs a classpath manager for the given generation and module class loader - * @param generation the host generation for this classpath manager + * Constructs a classpath manager for the given generation and module class + * loader + * + * @param generation the host generation for this classpath manager * @param classloader the ModuleClassLoader for this classpath manager */ public ClasspathManager(Generation generation, ModuleClassLoader classloader) { @@ -95,9 +102,12 @@ public ClasspathManager(Generation generation, ModuleClassLoader classloader) { } private static String[] getClassPath(ModuleRevision revision) { - List moduleDatas = revision.getModuleCapabilities(EquinoxModuleDataNamespace.MODULE_DATA_NAMESPACE); + List moduleDatas = revision + .getModuleCapabilities(EquinoxModuleDataNamespace.MODULE_DATA_NAMESPACE); @SuppressWarnings("unchecked") - List cp = moduleDatas.isEmpty() ? null : (List) moduleDatas.get(0).getAttributes().get(EquinoxModuleDataNamespace.CAPABILITY_CLASSPATH); + List cp = moduleDatas.isEmpty() ? null + : (List) moduleDatas.get(0).getAttributes() + .get(EquinoxModuleDataNamespace.CAPABILITY_CLASSPATH); return cp == null ? DEFAULT_CLASSPATH : cp.toArray(new String[cp.size()]); } @@ -105,7 +115,8 @@ private FragmentClasspath[] buildFragmentClasspaths(ModuleClassLoader hostloader if (hostloader == null) { return emptyFragments; } - List fragmentWires = hostloader.getBundleLoader().getWiring().getProvidedModuleWires(HostNamespace.HOST_NAMESPACE); + List fragmentWires = hostloader.getBundleLoader().getWiring() + .getProvidedModuleWires(HostNamespace.HOST_NAMESPACE); if (fragmentWires == null || fragmentWires.isEmpty()) { // we don't hold locks while checking the graph, just return if no longer valid return emptyFragments; @@ -148,8 +159,9 @@ public void close() { if (entry != null) { try { entry.close(); - }catch (IOException e) { - generation.getBundleInfo().getStorage().getAdaptor().publishContainerEvent(ContainerEvent.ERROR, generation.getRevision().getRevisions().getModule(), e); + } catch (IOException e) { + generation.getBundleInfo().getStorage().getAdaptor().publishContainerEvent(ContainerEvent.ERROR, + generation.getRevision().getRevisions().getModule(), e); } } } @@ -169,43 +181,55 @@ private ClasspathEntry[] buildClasspath(String[] cp, ClasspathManager hostloader } /** - * Finds all the ClasspathEntry objects for the requested classpath. This method will first call all - * the configured class loading hooks {@link ClassLoaderHook#addClassPathEntry(ArrayList, String, ClasspathManager, Generation)} - * methods. This allows class loading hooks to add additional ClasspathEntry objects to the result for the - * requested classpath. Then the local host classpath entries and attached fragment classpath entries are - * searched. - * @param result a list of ClasspathEntry objects. This list is used to add new ClasspathEntry objects to. - * @param cp the requested classpath. - * @param hostloader the host classpath manager for the classpath + * Finds all the ClasspathEntry objects for the requested classpath. This method + * will first call all the configured class loading hooks + * {@link ClassLoaderHook#addClassPathEntry(ArrayList, String, ClasspathManager, Generation)} + * methods. This allows class loading hooks to add additional ClasspathEntry + * objects to the result for the requested classpath. Then the local host + * classpath entries and attached fragment classpath entries are searched. + * + * @param result a list of ClasspathEntry objects. This list is used + * to add new ClasspathEntry objects to. + * @param cp the requested classpath. + * @param hostloader the host classpath manager for the classpath * @param sourceGeneration the source generation to search for the classpath */ - private void findClassPathEntry(ArrayList result, String cp, ClasspathManager hostloader, Generation sourceGeneration) { + private void findClassPathEntry(ArrayList result, String cp, ClasspathManager hostloader, + Generation sourceGeneration) { List loaderHooks = hookRegistry.getClassLoaderHooks(); boolean hookAdded = false; for (ClassLoaderHook hook : loaderHooks) { hookAdded |= hook.addClassPathEntry(result, cp, hostloader, sourceGeneration); } if (!addClassPathEntry(result, cp, hostloader, sourceGeneration) && !hookAdded) { - BundleException be = new BundleException(NLS.bind(Msg.BUNDLE_CLASSPATH_ENTRY_NOT_FOUND_EXCEPTION, cp, sourceGeneration.getRevision().toString()), BundleException.MANIFEST_ERROR); - sourceGeneration.getBundleInfo().getStorage().getAdaptor().publishContainerEvent(ContainerEvent.INFO, sourceGeneration.getRevision().getRevisions().getModule(), be); + BundleException be = new BundleException(NLS.bind(Msg.BUNDLE_CLASSPATH_ENTRY_NOT_FOUND_EXCEPTION, cp, + sourceGeneration.getRevision().toString()), BundleException.MANIFEST_ERROR); + sourceGeneration.getBundleInfo().getStorage().getAdaptor().publishContainerEvent(ContainerEvent.INFO, + sourceGeneration.getRevision().getRevisions().getModule(), be); } } /** - * Adds a ClasspathEntry for the requested classpath to the result. The local host classpath entries - * are searched first and then attached fragments classpath entries are searched. The search stops once the first - * classpath entry is found. - * @param result a list of ClasspathEntry objects. This list is used to add new ClasspathEntry objects to. - * @param cp the requested classpath. + * Adds a ClasspathEntry for the requested classpath to the result. The local + * host classpath entries are searched first and then attached fragments + * classpath entries are searched. The search stops once the first classpath + * entry is found. + * + * @param result a list of ClasspathEntry objects. This list is used to add + * new ClasspathEntry objects to. + * @param cp the requested classpath. * @param hostManager the host classpath manager for the classpath - * @param source the source generation to search for the classpath + * @param source the source generation to search for the classpath * @return true if a ClasspathEntry was added to the result */ - public boolean addClassPathEntry(ArrayList result, String cp, ClasspathManager hostManager, Generation source) { - return addStandardClassPathEntry(result, cp, hostManager, source) || addEclipseClassPathEntry(result, cp, hostManager, source); + public boolean addClassPathEntry(ArrayList result, String cp, ClasspathManager hostManager, + Generation source) { + return addStandardClassPathEntry(result, cp, hostManager, source) + || addEclipseClassPathEntry(result, cp, hostManager, source); } - public static boolean addStandardClassPathEntry(ArrayList result, String cp, ClasspathManager hostManager, Generation generation) { + public static boolean addStandardClassPathEntry(ArrayList result, String cp, + ClasspathManager hostManager, Generation generation) { if (cp.equals(".")) { //$NON-NLS-1$ result.add(hostManager.createClassPathEntry(generation.getBundleFile(), generation)); return true; @@ -230,7 +254,8 @@ public static boolean addStandardClassPathEntry(ArrayList result return false; } - private boolean addEclipseClassPathEntry(ArrayList result, String cp, ClasspathManager hostManager, Generation source) { + private boolean addEclipseClassPathEntry(ArrayList result, String cp, ClasspathManager hostManager, + Generation source) { String var = hasPrefix(cp); if (var != null) // find internal library using eclipse predefined vars @@ -238,7 +263,8 @@ private boolean addEclipseClassPathEntry(ArrayList result, Strin if (cp.startsWith(NativeCodeFinder.EXTERNAL_LIB_PREFIX)) { cp = cp.substring(NativeCodeFinder.EXTERNAL_LIB_PREFIX.length()); // find external library using system property substitution - ClasspathEntry cpEntry = hostManager.getExternalClassPath(source.getBundleInfo().getStorage().getConfiguration().substituteVars(cp), source); + ClasspathEntry cpEntry = hostManager.getExternalClassPath( + source.getBundleInfo().getStorage().getConfiguration().substituteVars(cp), source); if (cpEntry != null) { result.add(cpEntry); return true; @@ -247,15 +273,19 @@ private boolean addEclipseClassPathEntry(ArrayList result, Strin return false; } - private boolean addInternalClassPath(String var, ArrayList cpEntries, String cp, ClasspathManager hostManager, Generation source) { + private boolean addInternalClassPath(String var, ArrayList cpEntries, String cp, + ClasspathManager hostManager, Generation source) { EquinoxConfiguration configuration = source.getBundleInfo().getStorage().getConfiguration(); if (var.equals("ws")) //$NON-NLS-1$ - return ClasspathManager.addStandardClassPathEntry(cpEntries, "ws/" + configuration.getWS() + cp.substring(4), hostManager, source); //$NON-NLS-1$ + return ClasspathManager.addStandardClassPathEntry(cpEntries, + "ws/" + configuration.getWS() + cp.substring(4), hostManager, source); //$NON-NLS-1$ if (var.equals("os")) //$NON-NLS-1$ - return ClasspathManager.addStandardClassPathEntry(cpEntries, "os/" + configuration.getOS() + cp.substring(4), hostManager, source); //$NON-NLS-1$ + return ClasspathManager.addStandardClassPathEntry(cpEntries, + "os/" + configuration.getOS() + cp.substring(4), hostManager, source); //$NON-NLS-1$ if (var.equals("nl")) { //$NON-NLS-1$ cp = cp.substring(4); - List NL_JAR_VARIANTS = source.getBundleInfo().getStorage().getConfiguration().ECLIPSE_NL_JAR_VARIANTS; + List NL_JAR_VARIANTS = source.getBundleInfo().getStorage() + .getConfiguration().ECLIPSE_NL_JAR_VARIANTS; for (String nlVariant : NL_JAR_VARIANTS) { if (ClasspathManager.addStandardClassPathEntry(cpEntries, "nl/" + nlVariant + cp, hostManager, source)) //$NON-NLS-1$ return true; @@ -264,7 +294,7 @@ private boolean addInternalClassPath(String var, ArrayList cpEnt return false; } - //return a String representing the string found between the $s + // return a String representing the string found between the $s private static String hasPrefix(String libPath) { if (libPath.startsWith("$ws$")) //$NON-NLS-1$ return "ws"; //$NON-NLS-1$ @@ -276,10 +306,13 @@ private static String hasPrefix(String libPath) { } /** - * Creates a new ClasspathEntry object for the requested classpath if the source exists. - * @param cp the requested classpath. + * Creates a new ClasspathEntry object for the requested classpath if the source + * exists. + * + * @param cp the requested classpath. * @param cpGeneration the source generation to search for the classpath - * @return a new ClasspathEntry for the requested classpath or null if the source does not exist. + * @return a new ClasspathEntry for the requested classpath or null if the + * source does not exist. */ public ClasspathEntry getClasspath(String cp, Generation cpGeneration) { BundleFile bundlefile = null; @@ -297,8 +330,10 @@ else if ((file = cpGeneration.getBundleFile().getFile(cp, false)) != null) } /** - * Uses the requested classpath as an absolute path to locate a source for a new ClasspathEntry. - * @param cp the requested classpath + * Uses the requested classpath as an absolute path to locate a source for a new + * ClasspathEntry. + * + * @param cp the requested classpath * @param cpGeneration the source generation to search for the classpath * @return a classpath entry which uses an absolut path as a source */ @@ -330,11 +365,13 @@ private static BundleFile createBundleFile(File content, Generation generation) if (!content.exists()) { return null; } - return generation.getBundleInfo().getStorage().createBundleFile(content, generation, content.isDirectory(), false); + return generation.getBundleInfo().getStorage().createBundleFile(content, generation, content.isDirectory(), + false); } private static BundleFile createBundleFile(String nestedDir, Generation generation) { - return generation.getBundleInfo().getStorage().createNestedBundleFile(nestedDir, generation.getBundleFile(), generation); + return generation.getBundleInfo().getStorage().createNestedBundleFile(nestedDir, generation.getBundleFile(), + generation); } private ClasspathEntry createClassPathEntry(BundleFile bundlefile, Generation source) { @@ -347,11 +384,15 @@ private ClasspathEntry createClassPathEntry(BundleFile bundlefile, Generation so } /** - * Finds a local resource by searching the ClasspathEntry objects of the classpath manager. - * This method will first call all the configured class loading hooks - * {@link ClassLoaderHook#preFindLocalResource(String, ClasspathManager)} methods. Then it - * will search for the resource. Finally it will call all the configured class loading hooks - * {@link ClassLoaderHook#postFindLocalResource(String, URL, ClasspathManager)} methods. + * Finds a local resource by searching the ClasspathEntry objects of the + * classpath manager. This method will first call all the configured class + * loading hooks + * {@link ClassLoaderHook#preFindLocalResource(String, ClasspathManager)} + * methods. Then it will search for the resource. Finally it will call all the + * configured class loading hooks + * {@link ClassLoaderHook#postFindLocalResource(String, URL, ClasspathManager)} + * methods. + * * @param resource the requested resource name. * @return the requested resource URL or null if the resource does not exist */ @@ -386,7 +427,7 @@ public URL findLocalResource(String resource) { private URL findLocalResourceImpl(String resource, int classPathIndex) { Module m = generation.getRevision().getRevisions().getModule(); URL result = null; - int[] curIndex = {0}; + int[] curIndex = { 0 }; // look in hook specific entries if any for (ClassLoaderHook hook : hookRegistry.getClassLoaderHooks()) { @@ -414,7 +455,8 @@ private URL findLocalResourceImpl(String resource, int classPathIndex) { return null; } - private URL findLocalResourceImpl(String resource, ClasspathEntry[] cpEntries, Module m, int classPathIndex, int[] curIndex) { + private URL findLocalResourceImpl(String resource, ClasspathEntry[] cpEntries, Module m, int classPathIndex, + int[] curIndex) { URL result; for (ClasspathEntry cpEntry : cpEntries) { if (cpEntry != null) { @@ -429,14 +471,16 @@ private URL findLocalResourceImpl(String resource, ClasspathEntry[] cpEntries, M } /** - * Finds the local resources by searching the ClasspathEntry objects of the classpath manager. + * Finds the local resources by searching the ClasspathEntry objects of the + * classpath manager. + * * @param resource the requested resource name. * @return an enumeration of the the requested resources */ public Enumeration findLocalResources(String resource) { Module m = generation.getRevision().getRevisions().getModule(); List resources = new ArrayList<>(6); - int[] classPathIndex = {0}; + int[] classPathIndex = { 0 }; // look in hook specific entries if any for (ClassLoaderHook hook : hookRegistry.getClassLoaderHooks()) { @@ -460,7 +504,8 @@ public Enumeration findLocalResources(String resource) { return Collections.emptyEnumeration(); } - private void findLocalResources(String resource, ClasspathEntry[] cpEntries, Module m, int[] classPathIndex, List resources) { + private void findLocalResources(String resource, ClasspathEntry[] cpEntries, Module m, int[] classPathIndex, + List resources) { for (ClasspathEntry cpEntry : cpEntries) { if (cpEntry != null) { URL url = cpEntry.findResource(resource, m, classPathIndex[0]); @@ -473,7 +518,9 @@ private void findLocalResources(String resource, ClasspathEntry[] cpEntries, Mod } /** - * Finds a local entry by searching the ClasspathEntry objects of the classpath manager. + * Finds a local entry by searching the ClasspathEntry objects of the classpath + * manager. + * * @param path the requested entry path. * @return the requested entry or null if the entry does not exist */ @@ -482,15 +529,16 @@ public BundleEntry findLocalEntry(String path) { } /** - * Finds a local entry by searching the ClasspathEntry with the specified - * class path index. - * @param path the requested entry path. + * Finds a local entry by searching the ClasspathEntry with the specified class + * path index. + * + * @param path the requested entry path. * @param classPathIndex the index of the ClasspathEntry to search * @return the requested entry or null if the entry does not exist */ public BundleEntry findLocalEntry(String path, int classPathIndex) { BundleEntry result = null; - int[] curIndex = {0}; + int[] curIndex = { 0 }; // look in hook specific entries if any for (ClassLoaderHook hook : hookRegistry.getClassLoaderHooks()) { @@ -534,24 +582,27 @@ private BundleEntry findLocalEntry(String path, ClasspathEntry[] cpEntries, int } /** - * Finds a local class by searching the ClasspathEntry objects of the classpath manager. - * This method will first call all the configured class loader hooks - * {@link ClassLoaderHook#preFindLocalClass(String, ClasspathManager)} methods. Then it - * will search for the class. If a class is found then + * Finds a local class by searching the ClasspathEntry objects of the classpath + * manager. This method will first call all the configured class loader hooks + * {@link ClassLoaderHook#preFindLocalClass(String, ClasspathManager)} methods. + * Then it will search for the class. If a class is found then *
    - *
  1. All configured class loader hooks - * {@link ClassLoaderHook#processClass(String, byte[], ClasspathEntry, BundleEntry, ClasspathManager)} - * methods will be called.
  2. - *
  3. The class is then defined.
  4. - *
  5. Finally, all configured class loading - * stats hooks {@link ClassLoaderHook#recordClassDefine(String, Class, byte[], ClasspathEntry, BundleEntry, ClasspathManager)} - * methods are called.
  6. + *
  7. All configured class loader hooks + * {@link ClassLoaderHook#processClass(String, byte[], ClasspathEntry, BundleEntry, ClasspathManager)} + * methods will be called.
  8. + *
  9. The class is then defined.
  10. + *
  11. Finally, all configured class loading stats hooks + * {@link ClassLoaderHook#recordClassDefine(String, Class, byte[], ClasspathEntry, BundleEntry, ClasspathManager)} + * methods are called.
  12. *
* Finally all the configured class loading hooks - * {@link ClassLoaderHook#postFindLocalClass(String, Class, ClasspathManager)} methods are called. + * {@link ClassLoaderHook#postFindLocalClass(String, Class, ClasspathManager)} + * methods are called. + * * @param classname the requested class name. * @return the requested class or null if the class does not exist - * @throws ClassNotFoundException if a ClassLoaderHook prevents the requested class from loading + * @throws ClassNotFoundException if a ClassLoaderHook prevents the requested + * class from loading */ public Class findLocalClass(String classname) throws ClassNotFoundException { Class result = null; @@ -615,7 +666,8 @@ private Class findLocalClassImpl(String classname, ClasspathEntry[] cpEntries private Class findClassImpl(String name, ClasspathEntry classpathEntry, List hooks) { if (debug.DEBUG_LOADER) - Debug.println("ModuleClassLoader[" + classloader.getBundleLoader() + " - " + classpathEntry.getBundleFile() + "].findClassImpl(" + name + ")"); //$NON-NLS-1$ //$NON-NLS-2$//$NON-NLS-3$ //$NON-NLS-4$ + Debug.println("ModuleClassLoader[" + classloader.getBundleLoader() + " - " + classpathEntry.getBundleFile() //$NON-NLS-1$ //$NON-NLS-2$ + + "].findClassImpl(" + name + ")"); //$NON-NLS-1$ //$NON-NLS-2$ String filename = name.replace('.', '/').concat(".class"); //$NON-NLS-1$ BundleEntry entry = classpathEntry.findEntry(filename); @@ -631,7 +683,8 @@ private Class findClassImpl(String name, ClasspathEntry classpathEntry, List< throw (LinkageError) new LinkageError("Error reading class bytes: " + name).initCause(e); //$NON-NLS-1$ } if (debug.DEBUG_LOADER) { - Debug.println(" read " + classbytes.length + " bytes from " + classpathEntry.getBundleFile() + "!/" + filename); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + Debug.println( + " read " + classbytes.length + " bytes from " + classpathEntry.getBundleFile() + "!/" + filename); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ Debug.println(" defining class " + name); //$NON-NLS-1$ } @@ -650,21 +703,26 @@ static class DefineContext { } /** - * Defines the specified class. This method will first call all the configured class loader hooks + * Defines the specified class. This method will first call all the configured + * class loader hooks * {@link ClassLoadingHook#processClass(String, byte[], ClasspathEntry, BundleEntry, ClasspathManager)} - * methods. If any hook modifies the bytes the all configured hook + * methods. If any hook modifies the bytes the all configured hook * {@link ClassLoaderHook#rejectTransformation(String, byte[], ClasspathEntry, BundleEntry, ClasspathManager)} - * methods are called. Then it will call the {@link ModuleClassLoader#defineClass(String, byte[], ClasspathEntry, BundleEntry)} - * method to define the class. After that, the class loader hooks are called to announce the class - * definition by calling {@link ClassLoaderHook#recordClassDefine(String, Class, byte[], ClasspathEntry, BundleEntry, ClasspathManager)}. - * @param name the name of the class to define - * @param classbytes the class bytes + * methods are called. Then it will call the + * {@link ModuleClassLoader#defineClass(String, byte[], ClasspathEntry, BundleEntry)} + * method to define the class. After that, the class loader hooks are called to + * announce the class definition by calling + * {@link ClassLoaderHook#recordClassDefine(String, Class, byte[], ClasspathEntry, BundleEntry, ClasspathManager)}. + * + * @param name the name of the class to define + * @param classbytes the class bytes * @param classpathEntry the classpath entry used to load the class bytes - * @param entry the BundleEntry used to load the class bytes - * @param hooks the class loader hooks + * @param entry the BundleEntry used to load the class bytes + * @param hooks the class loader hooks * @return the defined class */ - private Class defineClass(String name, byte[] classbytes, ClasspathEntry classpathEntry, BundleEntry entry, List hooks) { + private Class defineClass(String name, byte[] classbytes, ClasspathEntry classpathEntry, BundleEntry entry, + List hooks) { DefineClassResult result = null; boolean recursionDetected = false; try { @@ -701,7 +759,8 @@ private Class defineClass(String name, byte[] classbytes, ClasspathEntry clas // Now call the hooks that do support recursion without the check. for (ClassLoaderHook hook : hooks) { if (hook.isProcessClassRecursionSupported()) { - // Note if the hooks don't take protective measures for a recursive class load here + // Note if the hooks don't take protective measures for a recursive class load + // here // it will result in a stack overflow. classbytes = processClass(hook, name, classbytes, classpathEntry, entry, this, hooks); } @@ -731,10 +790,12 @@ private Class defineClass(String name, byte[] classbytes, ClasspathEntry clas return result == null ? null : result.clazz; } - private byte[] processClass(ClassLoaderHook hook, String name, byte[] classbytes, ClasspathEntry classpathEntry, BundleEntry entry, ClasspathManager classpathManager, List hooks) { + private byte[] processClass(ClassLoaderHook hook, String name, byte[] classbytes, ClasspathEntry classpathEntry, + BundleEntry entry, ClasspathManager classpathManager, List hooks) { byte[] modifiedBytes = hook.processClass(name, classbytes, classpathEntry, entry, this); if (modifiedBytes != null) { - // the WeavingHookConfigurator already calls the rejectTransformation method; avoid calling it again. + // the WeavingHookConfigurator already calls the rejectTransformation method; + // avoid calling it again. if (!(hook instanceof WeavingHookConfigurator)) { for (ClassLoaderHook rejectHook : hooks) { if (rejectHook.rejectTransformation(name, modifiedBytes, classpathEntry, entry, this)) { @@ -763,10 +824,12 @@ private void definePackage(String name, ClasspathEntry classpathEntry) { } // get info about the package from the classpath entry's manifest. - String specTitle = null, specVersion = null, specVendor = null, implTitle = null, implVersion = null, implVendor = null; + String specTitle = null, specVersion = null, specVendor = null, implTitle = null, implVersion = null, + implVendor = null; if (generation.getBundleInfo().getStorage().getConfiguration().DEFINE_PACKAGE_ATTRIBUTES) { - ManifestPackageAttributes manifestPackageAttributes = classpathEntry.manifestPackageAttributesFor(packageName); + ManifestPackageAttributes manifestPackageAttributes = classpathEntry + .manifestPackageAttributesFor(packageName); TitleVersionVendor specification = manifestPackageAttributes.getSpecification(); TitleVersionVendor implementation = manifestPackageAttributes.getImplementation(); specTitle = specification.getTitle(); @@ -779,11 +842,13 @@ private void definePackage(String name, ClasspathEntry classpathEntry) { // The package is not defined yet define it before we define the class. // TODO still need to seal packages. - classloader.publicDefinePackage(packageName, specTitle, specVersion, specVendor, implTitle, implVersion, implVendor, null); + classloader.publicDefinePackage(packageName, specTitle, specVersion, specVendor, implTitle, implVersion, + implVendor, null); } /** * Returns the fragment classpaths of this classpath manager + * * @return the fragment classpaths of this classpath manager */ public FragmentClasspath[] getFragmentClasspaths() { @@ -792,6 +857,7 @@ public FragmentClasspath[] getFragmentClasspaths() { /** * Returns the host classpath entries for this classpath manager + * * @return the host classpath entries for this classpath manager */ public ClasspathEntry[] getHostClasspathEntries() { @@ -800,6 +866,7 @@ public ClasspathEntry[] getHostClasspathEntries() { /** * Finds a library for the bundle represented by this class path manager + * * @param libname the library name * @return The absolution path to the library or null if not found */ @@ -810,7 +877,8 @@ public String findLibrary(String libname) { } synchronized (loadedLibraries) { // we assume that each classloader will load a small number of of libraries - // instead of wasting space with a map we iterate over our collection of found libraries + // instead of wasting space with a map we iterate over our collection of found + // libraries // each element is a String[2], each array is {"libname", "libpath"} String libpath = loadedLibraries.get(libname); if (libpath != null) diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/classpath/FragmentClasspath.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/classpath/FragmentClasspath.java index b640e5162c3..6003ee4dfe5 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/classpath/FragmentClasspath.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/classpath/FragmentClasspath.java @@ -19,8 +19,9 @@ import org.eclipse.osgi.storage.BundleInfo.Generation; /** - * A FragmentClasspath contains all the ClasspathEntry objects for a fragment - * BaseData. + * A FragmentClasspath contains all the ClasspathEntry objects for + * a fragment BaseData. + * * @since 3.2 */ public class FragmentClasspath { @@ -35,6 +36,7 @@ public FragmentClasspath(Generation generation, ClasspathEntry[] entries) { /** * Returns the fragment Generation for this FragmentClasspath + * * @return the fragment Generation for this FragmentClasspath */ public Generation getGeneration() { @@ -43,6 +45,7 @@ public Generation getGeneration() { /** * Returns the fragment classpath entries for this FragmentClasspath + * * @return the fragment classpath entries for this FragmentClasspath */ public ClasspathEntry[] getEntries() { @@ -57,8 +60,9 @@ public void close() { for (ClasspathEntry entry : entries) { try { entry.close(); - }catch (IOException e) { - generation.getBundleInfo().getStorage().getAdaptor().publishContainerEvent(ContainerEvent.ERROR, generation.getRevision().getRevisions().getModule(), e); + } catch (IOException e) { + generation.getBundleInfo().getStorage().getAdaptor().publishContainerEvent(ContainerEvent.ERROR, + generation.getRevision().getRevisions().getModule(), e); } } } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/classpath/ManifestPackageAttributes.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/classpath/ManifestPackageAttributes.java index 9dec7ab2f76..6b4acc7d725 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/classpath/ManifestPackageAttributes.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/classpath/ManifestPackageAttributes.java @@ -14,19 +14,23 @@ package org.eclipse.osgi.internal.loader.classpath; /** - * Stores a pair of {@link TitleVersionVendor} package attributes for the Implementation- and Specification- entries. + * Stores a pair of {@link TitleVersionVendor} package attributes for the + * Implementation- and Specification- entries. */ class ManifestPackageAttributes { /** - * Constant used when no titles, versions or vendors are specified for the package. + * Constant used when no titles, versions or vendors are specified for the + * package. */ - static final ManifestPackageAttributes NONE = new ManifestPackageAttributes(TitleVersionVendor.NONE, TitleVersionVendor.NONE); + static final ManifestPackageAttributes NONE = new ManifestPackageAttributes(TitleVersionVendor.NONE, + TitleVersionVendor.NONE); private final TitleVersionVendor implementation; private final TitleVersionVendor specification; /** * Utility method to return the first version, or the second if it is null - * @param first the string to return if not null + * + * @param first the string to return if not null * @param second the fallback value if the first is null * @return the first value, or the second value if the first is null */ @@ -35,21 +39,26 @@ private static String or(String first, String second) { } /** - * Factory method for creating ManifestPackageAttributes. If any of the given title, - * version, or vendor values are null then the defaultAttributes will be - * used. If the defaultAttributes is null or returns all null values then - * null values will be used. If null values are used for all of the - * versions, titles, and vendors then {@link #NONE} is returned. - * @param specificationTitle the package specification title - * @param specificationVersion the package specification version - * @param specificationVendor the package specification vendor - * @param implementationTitle the package implementation title + * Factory method for creating ManifestPackageAttributes. If any of the given + * title, version, or vendor values are null then the + * defaultAttributes will be used. If the defaultAttributes is null or returns + * all null values then null values will be used. If + * null values are used for all of the versions, titles, and + * vendors then {@link #NONE} is returned. + * + * @param specificationTitle the package specification title + * @param specificationVersion the package specification version + * @param specificationVendor the package specification vendor + * @param implementationTitle the package implementation title * @param implementationVersion the package implementation version - * @param implementationVendor the package implementation vendor - * @param defaultAttributes the default attributes to use when the specified title, version or vendor is null. + * @param implementationVendor the package implementation vendor + * @param defaultAttributes the default attributes to use when the specified + * title, version or vendor is null. * @return */ - static ManifestPackageAttributes of(String specificationTitle, String specificationVersion, String specificationVendor, String implementationTitle, String implementationVersion, String implementationVendor, ManifestPackageAttributes defaultAttributes) { + static ManifestPackageAttributes of(String specificationTitle, String specificationVersion, + String specificationVendor, String implementationTitle, String implementationVersion, + String implementationVendor, ManifestPackageAttributes defaultAttributes) { if (defaultAttributes == null) { defaultAttributes = NONE; } @@ -63,9 +72,13 @@ static ManifestPackageAttributes of(String specificationTitle, String specificat ); } - private static ManifestPackageAttributes of(String specificationTitle, String specificationVersion, String specificationVendor, String implementationTitle, String implementationVersion, String implementationVendor) { - TitleVersionVendor specification = TitleVersionVendor.of(specificationTitle, specificationVersion, specificationVendor); - TitleVersionVendor implementation = TitleVersionVendor.of(implementationTitle, implementationVersion, implementationVendor); + private static ManifestPackageAttributes of(String specificationTitle, String specificationVersion, + String specificationVendor, String implementationTitle, String implementationVersion, + String implementationVendor) { + TitleVersionVendor specification = TitleVersionVendor.of(specificationTitle, specificationVersion, + specificationVendor); + TitleVersionVendor implementation = TitleVersionVendor.of(implementationTitle, implementationVersion, + implementationVendor); if (specification == TitleVersionVendor.NONE && implementation == TitleVersionVendor.NONE) { return NONE; } @@ -82,6 +95,7 @@ private ManifestPackageAttributes(TitleVersionVendor implementation, TitleVersio /** * Returns the title, version and vendor for the package implementation. + * * @return the title, version and vendor for the package implemetnation. */ TitleVersionVendor getImplementation() { @@ -90,6 +104,7 @@ TitleVersionVendor getImplementation() { /** * Returns the title, version and vendor for the package specification. + * * @return the title, version and vendor for the package specification. */ TitleVersionVendor getSpecification() { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/classpath/TitleVersionVendor.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/classpath/TitleVersionVendor.java index 1a754a7a87b..20f8984037c 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/classpath/TitleVersionVendor.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/classpath/TitleVersionVendor.java @@ -15,11 +15,13 @@ package org.eclipse.osgi.internal.loader.classpath; /** - * Stores a (title,version,vendor) triple for Specification-* or Implementation-* + * Stores a (title,version,vendor) triple for Specification-* or + * Implementation-* */ class TitleVersionVendor { /** - * Constant value when no title, version or vendor are specified for the package. + * Constant value when no title, version or vendor are specified for the + * package. */ static final TitleVersionVendor NONE = new TitleVersionVendor(null, null, null); private final String title; @@ -27,8 +29,9 @@ class TitleVersionVendor { private final String vendor; /** - * Factory for creating TitleVersionVendor objects. If the given title, version and - * vendor are null then {@link #NONE} is returned. + * Factory for creating TitleVersionVendor objects. If the given title, version + * and vendor are null then {@link #NONE} is returned. + * * @param title * @param version * @param vendor @@ -49,6 +52,7 @@ private TitleVersionVendor(String title, String version, String vendor) { /** * Returns the title + * * @return the title */ String getTitle() { @@ -57,6 +61,7 @@ String getTitle() { /** * returns the version + * * @return the version */ String getVersion() { @@ -65,6 +70,7 @@ String getVersion() { /** * returns the vendor + * * @return the vendor */ String getVendor() { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/sources/NullPackageSource.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/sources/NullPackageSource.java index 3525cb4afee..8b44c63e0f4 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/sources/NullPackageSource.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/sources/NullPackageSource.java @@ -21,10 +21,10 @@ import java.util.Map; /** - * This class is used to optimize finding provided-packages for a bundle. - * If the package cannot be found in a list of required bundles then this class - * is used to cache a null package source so that the search does not need to - * be done again. + * This class is used to optimize finding provided-packages for a bundle. If the + * package cannot be found in a list of required bundles then this class is used + * to cache a null package source so that the search does not need to be done + * again. */ public class NullPackageSource extends PackageSource { static Map sources = new HashMap<>(); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/sources/PackageSource.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/sources/PackageSource.java index 59a744abc8f..0b3541574eb 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/sources/PackageSource.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/sources/PackageSource.java @@ -58,8 +58,10 @@ public boolean isNullSource() { public abstract Enumeration getResources(String name) throws IOException; - // This is intentionally lenient; we don't force all suppliers to match (only one) - // it is better to get class cast exceptions in split package cases than miss an event + // This is intentionally lenient; we don't force all suppliers to match (only + // one) + // it is better to get class cast exceptions in split package cases than miss an + // event public boolean hasCommonSource(PackageSource other) { if (other == null) return false; @@ -104,11 +106,12 @@ public String toString() { /** * Used by ServiceReferenceImpl for isAssignableTo - * @param registrant Bundle registering service - * @param client Bundle desiring to use service - * @param className class name to use + * + * @param registrant Bundle registering service + * @param client Bundle desiring to use service + * @param className class name to use * @param serviceClass class of original service object - * @param container the equinox container + * @param container the equinox container * @return true if assignable given package wiring */ public static boolean isServiceAssignableTo(Bundle registrant, Bundle client, String className, @@ -131,9 +134,9 @@ public static boolean isServiceAssignableTo(Bundle registrant, Bundle client, St if (consumerBL == null) { return false; } - // 3) for the specified bundle, find the wiring for the package. If no wiring is found return true - PackageSource consumerSource = getSourceFromLoader(consumerBL, pkgName, className, checkInternal, - container); + // 3) for the specified bundle, find the wiring for the package. If no wiring is + // found return true + PackageSource consumerSource = getSourceFromLoader(consumerBL, pkgName, className, checkInternal, container); if (consumerSource == null) { // confirmed no source for consumer return true; @@ -144,8 +147,7 @@ public static boolean isServiceAssignableTo(Bundle registrant, Bundle client, St } // 4) For the registrant bundle, find the wiring for the package. - PackageSource producerSource = getSourceFromLoader(producerBL, pkgName, className, checkInternal, - container); + PackageSource producerSource = getSourceFromLoader(producerBL, pkgName, className, checkInternal, container); if (producerSource == null) { // confirmed no local class either; now check service object if (serviceClass != null && ServiceFactory.class.isAssignableFrom(serviceClass)) { @@ -160,13 +162,13 @@ public static boolean isServiceAssignableTo(Bundle registrant, Bundle client, St } // 5) If no wiring is found for the registrant bundle then find the wiring for // the classloader of the service object. If no wiring is found return false. - producerSource = getPackageSource(serviceClass, pkgName, className, checkInternal, - container); + producerSource = getPackageSource(serviceClass, pkgName, className, checkInternal, container); if (producerSource == null) { return false; } } - // 6) If the two wirings found are equal then return true; otherwise return false. + // 6) If the two wirings found are equal then return true; otherwise return + // false. return producerSource.hasCommonSource(consumerSource); } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/sources/SingleSourcePackage.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/sources/SingleSourcePackage.java index 204e9797a94..9129f6ac4fd 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/sources/SingleSourcePackage.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/loader/sources/SingleSourcePackage.java @@ -29,7 +29,7 @@ public SingleSourcePackage(String id, BundleLoader supplier) { @Override public SingleSourcePackage[] getSuppliers() { - return new SingleSourcePackage[] {this}; + return new SingleSourcePackage[] { this }; } public BundleLoader getLoader() { @@ -58,7 +58,8 @@ public boolean equals(Object source) { if (!(source instanceof SingleSourcePackage)) return false; SingleSourcePackage singleSource = (SingleSourcePackage) source; - // we do an == test on id because the id is interned in the constructor of PackageSource + // we do an == test on id because the id is interned in the constructor of + // PackageSource return supplier == singleSource.supplier && id == singleSource.getId(); } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/location/BasicLocation.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/location/BasicLocation.java index 4430a1a81ff..2c52c946431 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/location/BasicLocation.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/location/BasicLocation.java @@ -53,7 +53,8 @@ public class BasicLocation implements Location { private ServiceRegistration serviceRegistration; - public BasicLocation(String property, URL defaultValue, boolean isReadOnly, String dataAreaPrefix, ConfigValues configValues, EquinoxContainer container, AtomicBoolean debug) { + public BasicLocation(String property, URL defaultValue, boolean isReadOnly, String dataAreaPrefix, + ConfigValues configValues, EquinoxContainer container, AtomicBoolean debug) { this.property = property; this.defaultValue = defaultValue; this.isReadOnly = isReadOnly; @@ -91,7 +92,9 @@ public synchronized URL getURL() { EquinoxLogServices logServices = container.getLogServices(); // Note that logServices can be null if we are very early in the startup. if (logServices != null) { - logServices.log(EquinoxContainer.NAME, FrameworkLogEntry.INFO, "Called Location.getURL() when it has not been set for: \"" + property + "\"", new RuntimeException("Call stack for Location.getURL()")); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ + logServices.log(EquinoxContainer.NAME, FrameworkLogEntry.INFO, + "Called Location.getURL() when it has not been set for: \"" + property + "\"", //$NON-NLS-1$//$NON-NLS-2$ + new RuntimeException("Call stack for Location.getURL()")); //$NON-NLS-1$ } } setURL(defaultValue, false); @@ -131,7 +134,8 @@ public synchronized boolean set(URL value, boolean lock) throws IllegalStateExce } @Override - public synchronized boolean set(URL value, boolean lock, String lockFilePath) throws IllegalStateException, IOException { + public synchronized boolean set(URL value, boolean lock, String lockFilePath) + throws IllegalStateException, IOException { synchronized (this) { if (location != null) throw new IllegalStateException(Msg.ECLIPSE_CANNOT_CHANGE_LOCATION); @@ -262,7 +266,8 @@ public synchronized void release() { @Override public Location createLocation(Location parentLocation, URL defaultLocation, boolean readonly) { - BasicLocation result = new BasicLocation(null, defaultLocation, readonly, dataAreaPrefix, configValues, container, debug); + BasicLocation result = new BasicLocation(null, defaultLocation, readonly, dataAreaPrefix, configValues, + container, debug); result.setParent(parentLocation); return result; } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/location/EquinoxLocations.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/location/EquinoxLocations.java index 9773a0846f8..580d180239e 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/location/EquinoxLocations.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/location/EquinoxLocations.java @@ -77,7 +77,8 @@ public class EquinoxLocations { private final BasicLocation instanceLocation; private final BasicLocation eclipseHomeLocation; - public EquinoxLocations(ConfigValues equinoxConfig, EquinoxContainer container, AtomicBoolean debugLocations, Map exceptions) { + public EquinoxLocations(ConfigValues equinoxConfig, EquinoxContainer container, AtomicBoolean debugLocations, + Map exceptions) { this.equinoxConfig = equinoxConfig; this.container = container; this.debugLocations = debugLocations; @@ -89,7 +90,8 @@ public EquinoxLocations(ConfigValues equinoxConfig, EquinoxContainer container, if (equinoxConfig.getConfiguration(PROP_CONFIG_AREA) != null) { exceptions.put(new IllegalArgumentException(String.format( // "The property '%s' with the value '%s' is being overriden by the OSGi standard configuration property '%s' with the value '%s'.", //$NON-NLS-1$ - PROP_CONFIG_AREA, equinoxConfig.getConfiguration(PROP_CONFIG_AREA), Constants.FRAMEWORK_STORAGE, osgiStorage)), FrameworkLogEntry.WARNING); + PROP_CONFIG_AREA, equinoxConfig.getConfiguration(PROP_CONFIG_AREA), Constants.FRAMEWORK_STORAGE, + osgiStorage)), FrameworkLogEntry.WARNING); } equinoxConfig.setConfiguration(PROP_CONFIG_AREA, osgiStorage); } @@ -107,23 +109,29 @@ public EquinoxLocations(ConfigValues equinoxConfig, EquinoxContainer container, temp = buildLocation(PROP_INSTANCE_AREA_DEFAULT, null, "", false, false, INSTANCE_DATA_AREA_PREFIX); //$NON-NLS-1$ defaultLocation = temp == null ? null : temp.getURL(); if (defaultLocation == null) - defaultLocation = buildURL(new File(System.getProperty(PROP_USER_DIR), "workspace").getAbsolutePath(), true); //$NON-NLS-1$ - instanceLocation = buildLocation(PROP_INSTANCE_AREA, defaultLocation, "", false, false, INSTANCE_DATA_AREA_PREFIX); //$NON-NLS-1$ + defaultLocation = buildURL(new File(System.getProperty(PROP_USER_DIR), "workspace").getAbsolutePath(), //$NON-NLS-1$ + true); + instanceLocation = buildLocation(PROP_INSTANCE_AREA, defaultLocation, "", false, false, //$NON-NLS-1$ + INSTANCE_DATA_AREA_PREFIX); mungeConfigurationLocation(); - // compute a default but it is very unlikely to be used since main will have computed everything + // compute a default but it is very unlikely to be used since main will have + // computed everything temp = buildLocation(PROP_CONFIG_AREA_DEFAULT, null, "", false, false, null); //$NON-NLS-1$ defaultLocation = temp == null ? null : temp.getURL(); if (defaultLocation == null && equinoxConfig.getConfiguration(PROP_CONFIG_AREA) == null) // only compute the default if the configuration area property is not set defaultLocation = buildURL(computeDefaultConfigurationLocation(), true); configurationLocation = buildLocation(PROP_CONFIG_AREA, defaultLocation, "", false, false, null); //$NON-NLS-1$ - // get the parent location based on the system property. This will have been set on the - // way in either by the caller/user or by main. There will be no parent location if we are not + // get the parent location based on the system property. This will have been set + // on the + // way in either by the caller/user or by main. There will be no parent location + // if we are not // cascaded. URL parentLocation = computeSharedConfigurationLocation(); if (parentLocation != null && !parentLocation.equals(configurationLocation.getURL())) { - Location parent = new BasicLocation(null, parentLocation, true, null, equinoxConfig, container, debugLocations); + Location parent = new BasicLocation(null, parentLocation, true, null, equinoxConfig, container, + debugLocations); ((BasicLocation) configurationLocation).setParent(parent); } @@ -134,14 +142,16 @@ public EquinoxLocations(ConfigValues equinoxConfig, EquinoxContainer container, equinoxConfig.setConfiguration(PROP_HOME_LOCATION_AREA, eclipseHomeLocationPath); } // if eclipse.home.location is not set then default to osgi.install.area - if (equinoxConfig.getConfiguration(PROP_HOME_LOCATION_AREA) == null && equinoxConfig.getConfiguration(PROP_INSTALL_AREA) != null) + if (equinoxConfig.getConfiguration(PROP_HOME_LOCATION_AREA) == null + && equinoxConfig.getConfiguration(PROP_INSTALL_AREA) != null) equinoxConfig.setConfiguration(PROP_HOME_LOCATION_AREA, equinoxConfig.getConfiguration(PROP_INSTALL_AREA)); eclipseHomeLocation = buildLocation(PROP_HOME_LOCATION_AREA, null, "", true, true, null); //$NON-NLS-1$ } /** * Builds a URL with the given specification - * @param spec the URL specification + * + * @param spec the URL specification * @param trailingSlash flag to indicate a trailing slash on the spec * @return a URL */ @@ -189,16 +199,20 @@ private BasicLocation buildLocation(String property, URL defaultLocation, String String location = equinoxConfig.clearConfiguration(property); // the user/product may specify a non-default readOnly setting String userReadOnlySetting = equinoxConfig.getConfiguration(property + READ_ONLY_AREA_SUFFIX); - boolean readOnly = (userReadOnlySetting == null ? readOnlyDefault : Boolean.valueOf(userReadOnlySetting).booleanValue()); + boolean readOnly = (userReadOnlySetting == null ? readOnlyDefault + : Boolean.valueOf(userReadOnlySetting).booleanValue()); // 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(property, defaultLocation, userReadOnlySetting != null || !computeReadOnly ? readOnly : !canWrite(defaultLocation), dataAreaPrefix, equinoxConfig, container, debugLocations); + return new BasicLocation(property, defaultLocation, + userReadOnlySetting != null || !computeReadOnly ? readOnly : !canWrite(defaultLocation), + dataAreaPrefix, equinoxConfig, container, debugLocations); String trimmedLocation = location.trim(); if (trimmedLocation.equalsIgnoreCase(NONE)) return null; if (trimmedLocation.equalsIgnoreCase(NO_DEFAULT)) - return new BasicLocation(property, null, readOnly, dataAreaPrefix, equinoxConfig, container, debugLocations); + return new BasicLocation(property, null, readOnly, dataAreaPrefix, equinoxConfig, container, + debugLocations); if (trimmedLocation.startsWith(USER_HOME)) { String base = substituteVar(location, USER_HOME, PROP_USER_HOME); location = new File(base, userDefaultAppendage).getAbsolutePath(); @@ -208,14 +222,18 @@ private BasicLocation buildLocation(String property, URL defaultLocation, String } int idx = location.indexOf(INSTALL_HASH_PLACEHOLDER); if (idx == 0) { - throw new RuntimeException("The location cannot start with '" + INSTALL_HASH_PLACEHOLDER + "': " + location); //$NON-NLS-1$ //$NON-NLS-2$ + throw new RuntimeException( + "The location cannot start with '" + INSTALL_HASH_PLACEHOLDER + "': " + location); //$NON-NLS-1$ //$NON-NLS-2$ } else if (idx > 0) { - location = location.substring(0, idx) + getInstallDirHash() + location.substring(idx + INSTALL_HASH_PLACEHOLDER.length()); + location = location.substring(0, idx) + getInstallDirHash() + + location.substring(idx + INSTALL_HASH_PLACEHOLDER.length()); } URL url = buildURL(location, true); BasicLocation result = null; if (url != null) { - result = new BasicLocation(property, null, userReadOnlySetting != null || !computeReadOnly ? readOnly : !canWrite(url), dataAreaPrefix, equinoxConfig, container, debugLocations); + result = new BasicLocation(property, null, + userReadOnlySetting != null || !computeReadOnly ? readOnly : !canWrite(url), dataAreaPrefix, + equinoxConfig, container, debugLocations); result.setURL(url, false); } return result; @@ -259,10 +277,11 @@ private URL computeSharedConfigurationLocation() { private String computeDefaultConfigurationLocation() { // 1) We store the config state relative to the 'eclipse' directory if possible // 2) If this directory is read-only - // we store the state in /.eclipse/_ where - // is unique for each local user, and is the one - // defined in .eclipseproduct marker file. If .eclipseproduct does not - // exist, use "eclipse" as the application-id. + // we store the state in /.eclipse/_ where + // + // is unique for each local user, and is the one + // defined in .eclipseproduct marker file. If .eclipseproduct does not + // exist, use "eclipse" as the application-id. URL installURL = computeInstallConfigurationLocation(); if (installURL != null && "file".equals(installURL.getProtocol())) { //$NON-NLS-1$ @@ -273,7 +292,8 @@ private String computeDefaultConfigurationLocation() { if (defaultConfigDir.exists() && StorageUtil.canWrite(defaultConfigDir)) return defaultConfigDir.getAbsolutePath(); } - // We can't write in the eclipse install dir so try for some place in the user's home dir + // We can't write in the eclipse install dir so try for some place in the user's + // home dir return computeDefaultUserAreaLocation(CONFIG_DIR); } @@ -289,10 +309,11 @@ private static boolean canWrite(URL location) { } private String computeDefaultUserAreaLocation(String pathAppendage) { - // we store the state in /.eclipse/_ where - // is unique for each local user, and is the one - // defined in .eclipseproduct marker file. If .eclipseproduct does not - // exist, use "eclipse" as the application-id. + // we store the state in /.eclipse/_ where + // + // is unique for each local user, and is the one + // defined in .eclipseproduct marker file. If .eclipseproduct does not + // exist, use "eclipse" as the application-id. String installProperty = equinoxConfig.getConfiguration(PROP_INSTALL_AREA); URL installURL = buildURL(installProperty, true); if (installURL == null) @@ -314,7 +335,7 @@ private String computeDefaultUserAreaLocation(String pathAppendage) { appVersion = ""; //$NON-NLS-1$ appName += File.separator + appId + "_" + appVersion + "_" + installDirHash; //$NON-NLS-1$ //$NON-NLS-2$ } catch (IOException e) { - // Do nothing if we get an exception. We will default to a standard location + // Do nothing if we get an exception. We will default to a standard location // in the user's home dir. // add the hash to help prevent collisions appName += File.separator + installDirHash; @@ -329,10 +350,12 @@ private String computeDefaultUserAreaLocation(String pathAppendage) { /** * Return hash code identifying an absolute installation path + * * @return hash code as String */ private String getInstallDirHash() { - // compute an install dir hash to prevent configuration area collisions with other eclipse installs + // compute an install dir hash to prevent configuration area collisions with + // other eclipse installs String installProperty = equinoxConfig.getConfiguration(PROP_INSTALL_AREA); URL installURL = buildURL(installProperty, true); if (installURL == null) @@ -353,6 +376,7 @@ private String getInstallDirHash() { /** * Returns the user Location object + * * @return the user Location object */ public BasicLocation getUserLocation() { @@ -361,6 +385,7 @@ public BasicLocation getUserLocation() { /** * Returns the configuration Location object + * * @return the configuration Location object */ public BasicLocation getConfigurationLocation() { @@ -369,6 +394,7 @@ public BasicLocation getConfigurationLocation() { /** * Returns the install Location object + * * @return the install Location object */ public BasicLocation getInstallLocation() { @@ -377,6 +403,7 @@ public BasicLocation getInstallLocation() { /** * Returns the instance Location object + * * @return the instance Location object */ public BasicLocation getInstanceLocation() { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/Arguments.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/Arguments.java index 1cf1d62fc64..d9da3c37ed2 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/Arguments.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/Arguments.java @@ -37,7 +37,8 @@ public Arguments(Object... arguments) { } if (arguments.length > 1) { object = arguments[arguments.length - 2]; - if ((object instanceof ServiceReference && context == null) || (object instanceof Throwable && exception == null)) { + if ((object instanceof ServiceReference && context == null) + || (object instanceof Throwable && exception == null)) { length--; if (object instanceof Throwable) { exception = (Throwable) object; diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/ConfigAdminListener.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/ConfigAdminListener.java index d3a15018ddd..809f650240a 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/ConfigAdminListener.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/ConfigAdminListener.java @@ -83,7 +83,8 @@ private ServiceRegistration registerConfigurationListener(ServiceReference } } - private ServiceRegistration registerProxyConfigListener(ServiceReference configRef, Class listenerClass) throws ClassNotFoundException, NoSuchMethodException { + private ServiceRegistration registerProxyConfigListener(ServiceReference configRef, Class listenerClass) + throws ClassNotFoundException, NoSuchMethodException { LoggerContextConfiguration loggerConfiguration = new LoggerContextConfiguration(listenerClass, configRef); return loggerConfiguration.register(); } @@ -123,8 +124,9 @@ class LoggerContextConfiguration implements InvocationHandler { private final Method getEventReference; private final Method getEventType; - public LoggerContextConfiguration(Class listenerClass, ServiceReference ref) throws ClassNotFoundException, NoSuchMethodException { - listenerProxy = Proxy.newProxyInstance(listenerClass.getClassLoader(), new Class[] {listenerClass}, this); + public LoggerContextConfiguration(Class listenerClass, ServiceReference ref) + throws ClassNotFoundException, NoSuchMethodException { + listenerProxy = Proxy.newProxyInstance(listenerClass.getClassLoader(), new Class[] { listenerClass }, this); configAdminRef = ref; ClassLoader cl = listenerClass.getClassLoader(); @@ -134,7 +136,8 @@ public LoggerContextConfiguration(Class listenerClass, ServiceReference re getConfigPid = configClass.getMethod(METHOD_CONFIG_GET_PID); configAdminClass = cl.loadClass(CLASS_CONFIG_ADMIN); - getConfiguration = configAdminClass.getMethod(METHOD_CONFIG_ADMIN_GET_CONFIGURATION, String.class, String.class); + getConfiguration = configAdminClass.getMethod(METHOD_CONFIG_ADMIN_GET_CONFIGURATION, String.class, + String.class); listConfigurations = configAdminClass.getMethod(METHOD_CONFIG_ADMIN_LIST_CONFIGURATIONS, String.class); configEventClass = cl.loadClass(CLASS_CONFIG_EVENT); @@ -154,7 +157,8 @@ public ServiceRegistration register() { // seems the bundle has stopped! return null; } - ServiceRegistration registration = configContext.registerService(CLASS_SYNC_CONFIG_LISTENER, listenerProxy, null); + ServiceRegistration registration = configContext.registerService(CLASS_SYNC_CONFIG_LISTENER, + listenerProxy, null); try { Object[] configs = (Object[]) listConfigurations.invoke(configAdmin, PID_FILTER); @@ -167,7 +171,8 @@ public ServiceRegistration register() { String pid = (String) getConfigPid.invoke(config); String contextName = getContextName(pid); @SuppressWarnings("unchecked") - Dictionary configDictionary = (Dictionary) getConfigProperties.invoke(config); + Dictionary configDictionary = (Dictionary) getConfigProperties + .invoke(config); if (configDictionary != null) { setLogLevels(contextName, getLogLevels(configDictionary)); } @@ -181,7 +186,8 @@ public ServiceRegistration register() { @Override public Object invoke(Object proxy, Method method, Object[] event) throws Throwable { - // There is only one method on ConfigurationListener, no need to check the method type + // There is only one method on ConfigurationListener, no need to check the + // method type // ConfigurationListener::configurationEvent(ConfigurationEvent) if (!configAdminRef.equals(getReference(event))) { // ignore other config admin events diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/EquinoxLogFactory.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/EquinoxLogFactory.java index 99a0d0aae7f..cd14ea6ad93 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/EquinoxLogFactory.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/EquinoxLogFactory.java @@ -42,7 +42,8 @@ public FrameworkLog getService(final Bundle bundle, ServiceRegistration regist @SuppressWarnings("deprecation") static int convertLevel(FrameworkLogEntry logEntry) { switch (logEntry.getSeverity()) { - case FrameworkLogEntry.ERROR : - return LogService.LOG_ERROR; - case FrameworkLogEntry.WARNING : - return LogService.LOG_WARNING; - case FrameworkLogEntry.INFO : - return LogService.LOG_INFO; - case FrameworkLogEntry.OK : - return LogService.LOG_DEBUG; - case FrameworkLogEntry.CANCEL : - default : - return 32; // unknown + case FrameworkLogEntry.ERROR: + return LogService.LOG_ERROR; + case FrameworkLogEntry.WARNING: + return LogService.LOG_WARNING; + case FrameworkLogEntry.INFO: + return LogService.LOG_INFO; + case FrameworkLogEntry.OK: + return LogService.LOG_DEBUG; + case FrameworkLogEntry.CANCEL: + default: + return 32; // unknown } } } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/EquinoxLogServices.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/EquinoxLogServices.java index 2efb30678a5..45086b85572 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/EquinoxLogServices.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/EquinoxLogServices.java @@ -98,11 +98,13 @@ public EquinoxLogServices(EquinoxConfiguration environmentInfo) { defaultLevel = LogLevel.valueOf(defaultLevelConfig); } } catch (IllegalArgumentException e) { - //ignore and use LogLevel.WARN + // ignore and use LogLevel.WARN } - boolean captureLogEntryLocation = "true".equals(environmentInfo.getConfiguration(EquinoxConfiguration.PROP_LOG_CAPTURE_ENTRY_LOCATION, "true")); //$NON-NLS-1$ //$NON-NLS-2$ - logServiceManager = new LogServiceManager(logHistoryMax, defaultLevel, captureLogEntryLocation, logWriter, perfWriter); + boolean captureLogEntryLocation = "true" //$NON-NLS-1$ + .equals(environmentInfo.getConfiguration(EquinoxConfiguration.PROP_LOG_CAPTURE_ENTRY_LOCATION, "true")); //$NON-NLS-1$ + logServiceManager = new LogServiceManager(logHistoryMax, defaultLevel, captureLogEntryLocation, logWriter, + perfWriter); eclipseLogFactory = new EquinoxLogFactory(logWriter, logServiceManager); rootFrameworkLog = eclipseLogFactory.createFrameworkLog(null, logWriter); @@ -141,7 +143,8 @@ private ServiceRegistration registerPerformanceLog(BundleContext context) { Dictionary serviceProperties = new Hashtable<>(); serviceProperties.put(Constants.SERVICE_RANKING, Integer.valueOf(Integer.MIN_VALUE)); - serviceProperties.put(Constants.SERVICE_PID, context.getBundle().getBundleId() + '.' + service.getClass().getName()); + serviceProperties.put(Constants.SERVICE_PID, + context.getBundle().getBundleId() + '.' + service.getClass().getName()); serviceProperties.put(FrameworkLog.SERVICE_PERFORMANCE, Boolean.TRUE.toString()); return context.registerService(serviceName, service, serviceProperties); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/EquinoxLogWriter.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/EquinoxLogWriter.java index b0aee6d42f5..6babf37dd77 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/EquinoxLogWriter.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/EquinoxLogWriter.java @@ -63,7 +63,7 @@ class EquinoxLogWriter implements SynchronousLogListener, LogFilter { LINE_SEPARATOR = s == null ? "\n" : s; //$NON-NLS-1$ } - //Constants for rotating log file + // Constants for rotating log file /** The default size a log file can grow before it is rotated */ private static final int DEFAULT_LOG_SIZE = 1000; /** The default number of backup log files */ @@ -73,23 +73,35 @@ class EquinoxLogWriter implements SynchronousLogListener, LogFilter { /** The system property used to specify the log level */ private static final String PROP_LOG_LEVEL = "eclipse.log.level"; //$NON-NLS-1$ - /** The system property used to specify size a log file can grow before it is rotated */ + /** + * The system property used to specify size a log file can grow before it is + * rotated + */ private static final String PROP_LOG_SIZE_MAX = "eclipse.log.size.max"; //$NON-NLS-1$ - /** The system property used to specify the maximim number of backup log files to use */ + /** + * The system property used to specify the maximim number of backup log files to + * use + */ private static final String PROP_LOG_FILE_MAX = "eclipse.log.backup.max"; //$NON-NLS-1$ /** The extension used for log files */ private static final String LOG_EXT = ".log"; //$NON-NLS-1$ - /** The extension markup to use for backup log files*/ + /** The extension markup to use for backup log files */ private static final String BACKUP_MARK = ".bak_"; //$NON-NLS-1$ - /** The system property used to specify command line args should be omitted from the log */ + /** + * The system property used to specify command line args should be omitted from + * the log + */ private static final String PROP_LOG_INCLUDE_COMMAND_LINE = "eclipse.log.include.commandline"; //$NON-NLS-1$ - /** Indicates if the console messages should be printed to the console (System.out) */ + /** + * Indicates if the console messages should be printed to the console + * (System.out) + */ private boolean consoleLog = false; /** Indicates if the next log message is part of a new session */ private boolean newSession = true; /** - * The File object to store messages. This value may be null. + * The File object to store messages. This value may be null. */ private File outFile; @@ -113,6 +125,7 @@ class EquinoxLogWriter implements SynchronousLogListener, LogFilter { /** * Constructs an EclipseLog which uses the specified File to log messages to + * * @param outFile a file to log messages to */ public EquinoxLogWriter(File outFile, String loggerName, boolean enabled, EquinoxConfiguration environmentInfo) { @@ -126,6 +139,7 @@ public EquinoxLogWriter(File outFile, String loggerName, boolean enabled, Equino /** * Constructs an EclipseLog which uses the specified Writer to log messages to + * * @param writer a writer to log messages to */ public EquinoxLogWriter(Writer writer, String loggerName, boolean enabled, EquinoxConfiguration environmentInfo) { @@ -157,15 +171,16 @@ private Throwable getRoot(Throwable t) { /** * Helper method for writing out argument arrays. + * * @param header the header - * @param args the list of arguments + * @param args the list of arguments */ private void writeArgs(String header, String[] args) throws IOException { if (args == null || args.length == 0) return; write(header); for (int i = 0; i < args.length; i++) { - //mask out the password argument for security + // mask out the password argument for security if (i > 0 && PASSWORD.equals(args[i - 1])) write(" (omitted)"); //$NON-NLS-1$ else @@ -175,7 +190,8 @@ private void writeArgs(String header, String[] args) throws IOException { } /** - * Returns the session timestamp. This is the time the platform was started + * Returns the session timestamp. This is the time the platform was started + * * @return the session timestamp */ private String getSessionTimestamp() { @@ -194,6 +210,7 @@ private String getSessionTimestamp() { /** * Writes the session + * * @throws IOException if an error occurs writing to the log */ private void writeSession() throws IOException { @@ -254,8 +271,8 @@ public void close() { } /** - * If a File is used to log messages to then the File opened and a Writer is created - * to log messages to. + * If a File is used to log messages to then the File opened and a Writer is + * created to log messages to. */ private void openFile() { if (writer == null) { @@ -307,7 +324,7 @@ private synchronized void log(FrameworkLogEntry logEntry) { System.err.println("An exception occurred while writing to the platform log:");//$NON-NLS-1$ e.printStackTrace(System.err); System.err.println("Logging to the console instead.");//$NON-NLS-1$ - //we failed to write, so dump log entry to console instead + // we failed to write, so dump log entry to console instead try { writer = logForErrorStream(); writeLog(0, logEntry); @@ -395,6 +412,7 @@ private void copyReader(Reader reader, Writer aWriter) throws IOException { /** * Returns a date string using the correct format for the log. + * * @param date the Date to format * @return a date string. */ @@ -429,6 +447,7 @@ private StringBuilder appendPaddedInt(int value, int pad, StringBuilder buffer) /** * Returns a stacktrace string using the correct format for the log + * * @param t the Throwable to get the stacktrace for * @return a stacktrace string */ @@ -451,6 +470,7 @@ private String getStackTrace(Throwable t) { /** * Returns a Writer for the given OutputStream + * * @param output an OutputStream to use for the Writer * @return a Writer for the given OutputStream */ @@ -466,9 +486,10 @@ private Writer logForErrorStream() { } /** - * Writes the log entry to the log using the specified depth. A depth value of 0 - * indicates that the log entry is the root entry. Any value greater than 0 indicates - * a sub-entry. + * Writes the log entry to the log using the specified depth. A depth value of 0 + * indicates that the log entry is the root entry. Any value greater than 0 + * indicates a sub-entry. + * * @param depth the depth of th entry * @param entry the entry to log * @throws IOException if any error occurs writing to the log @@ -487,9 +508,10 @@ private void writeLog(int depth, FrameworkLogEntry entry) throws IOException { } /** - * Writes the ENTRY or SUBENTRY header for an entry. A depth value of 0 - * indicates that the log entry is the root entry. Any value greater than 0 indicates - * a sub-entry. + * Writes the ENTRY or SUBENTRY header for an entry. A depth value of 0 + * indicates that the log entry is the root entry. Any value greater than 0 + * indicates a sub-entry. + * * @param depth the depth of th entry * @param entry the entry to write the header for * @throws IOException if any error occurs writing to the log @@ -516,6 +538,7 @@ private void writeEntry(int depth, FrameworkLogEntry entry) throws IOException { /** * Writes the MESSAGE header to the log for the given entry. + * * @param entry the entry to write the message for * @throws IOException if any error occurs writing to the log */ @@ -527,6 +550,7 @@ private void writeMessage(FrameworkLogEntry entry) throws IOException { /** * Writes the STACK header to the log for the given entry. + * * @param entry the entry to write the stacktrace for * @throws IOException if any error occurs writing to the log */ @@ -544,6 +568,7 @@ private void writeStack(FrameworkLogEntry entry) throws IOException { /** * Writes the given message to the log. + * * @param message the message * @throws IOException if any error occurs writing to the log */ @@ -557,6 +582,7 @@ private void write(String message) throws IOException { /** * Writes the given message to the log and a newline. + * * @param s the message * @throws IOException if any error occurs writing to the log */ @@ -567,6 +593,7 @@ private void writeln(String s) throws IOException { /** * Writes a newline log. + * * @throws IOException if any error occurs writing to the log */ private void writeln() throws IOException { @@ -575,6 +602,7 @@ private void writeln() throws IOException { /** * Writes a space to the log. + * * @throws IOException if any error occurs writing to the log */ private void writeSpace() throws IOException { @@ -582,8 +610,9 @@ private void writeSpace() throws IOException { } /** - * Checks the log file size. If the log file size reaches the limit then the log + * Checks the log file size. If the log file size reaches the limit then the log * is rotated + * * @return false if an error occured trying to rotate the log */ private boolean checkLogFileSize() { @@ -592,13 +621,15 @@ private boolean checkLogFileSize() { boolean isBackupOK = true; if (outFile != null) { - if ((ExtendedLogServiceFactory.secureAction.length(outFile) >> 10) > maxLogSize) { // Use KB as file size unit. + if ((ExtendedLogServiceFactory.secureAction.length(outFile) >> 10) > maxLogSize) { // Use KB as file size + // unit. String logFilename = outFile.getAbsolutePath(); // Delete old backup file that will be replaced. String backupFilename = ""; //$NON-NLS-1$ if (logFilename.toLowerCase().endsWith(LOG_EXT)) { - backupFilename = logFilename.substring(0, logFilename.length() - LOG_EXT.length()) + BACKUP_MARK + backupIdx + LOG_EXT; + backupFilename = logFilename.substring(0, logFilename.length() - LOG_EXT.length()) + BACKUP_MARK + + backupIdx + LOG_EXT; } else { backupFilename = logFilename + BACKUP_MARK + backupIdx; } @@ -672,7 +703,8 @@ private void readLogProperties() { else if (newLogLevel.equals("WARNING")) //$NON-NLS-1$ logLevel = FrameworkLogEntry.ERROR | FrameworkLogEntry.WARNING; else if (newLogLevel.equals("INFO")) //$NON-NLS-1$ - logLevel = FrameworkLogEntry.INFO | FrameworkLogEntry.ERROR | FrameworkLogEntry.WARNING | FrameworkLogEntry.CANCEL; + logLevel = FrameworkLogEntry.INFO | FrameworkLogEntry.ERROR | FrameworkLogEntry.WARNING + | FrameworkLogEntry.CANCEL; else logLevel = FrameworkLogEntry.OK; // OK (0) means log everything } @@ -747,8 +779,10 @@ public void logged(LogEntry entry) { log((FrameworkLogEntry) context); return; } - // OK we are now in a case where someone logged a normal entry to the real LogService - log(new FrameworkLogEntry(getFwkEntryTag(entry), convertSeverity(entry.getLevel()), 0, entry.getMessage(), 0, entry.getException(), null)); + // OK we are now in a case where someone logged a normal entry to the real + // LogService + log(new FrameworkLogEntry(getFwkEntryTag(entry), convertSeverity(entry.getLevel()), 0, entry.getMessage(), 0, + entry.getException(), null)); } private static String getFwkEntryTag(LogEntry entry) { @@ -761,16 +795,16 @@ private static String getFwkEntryTag(LogEntry entry) { @SuppressWarnings("deprecation") private static int convertSeverity(int entryLevel) { switch (entryLevel) { - case LogService.LOG_ERROR : - return FrameworkLogEntry.ERROR; - case LogService.LOG_WARNING : - return FrameworkLogEntry.WARNING; - case LogService.LOG_INFO : - return FrameworkLogEntry.INFO; - case LogService.LOG_DEBUG : - return FrameworkLogEntry.OK; - default : - return 32; // unknown + case LogService.LOG_ERROR: + return FrameworkLogEntry.ERROR; + case LogService.LOG_WARNING: + return FrameworkLogEntry.WARNING; + case LogService.LOG_INFO: + return FrameworkLogEntry.INFO; + case LogService.LOG_DEBUG: + return FrameworkLogEntry.OK; + default: + return 32; // unknown } } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/EventAdminAdapter.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/EventAdminAdapter.java index 7ff945e6b1a..97a6bae24f2 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/EventAdminAdapter.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/EventAdminAdapter.java @@ -24,7 +24,10 @@ public class EventAdminAdapter implements ServiceTrackerCustomizer { public static final String EVENT_TOPIC = "event.topics"; //$NON-NLS-1$ - private static final String[] LOG_TOPICS_ARRAY = {"*", "org/*", "org/osgi/*", "org/osgi/service/*", "org/osgi/service/log/*", "org/osgi/service/log/LogEntry/*", "org/osgi/service/log/LogEntry/LOG_ERROR", "org/osgi/service/log/LogEntry/LOG_WARNING", "org/osgi/service/log/LogEntry/LOG_INFO", "org/osgi/service/log/LogEntry/LOG_DEBUG", "org/osgi/service/log/LogEntry/LOG_OTHER"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$//$NON-NLS-10$ //$NON-NLS-11$ + private static final String[] LOG_TOPICS_ARRAY = { "*", "org/*", "org/osgi/*", "org/osgi/service/*", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + "org/osgi/service/log/*", "org/osgi/service/log/LogEntry/*", "org/osgi/service/log/LogEntry/LOG_ERROR", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + "org/osgi/service/log/LogEntry/LOG_WARNING", "org/osgi/service/log/LogEntry/LOG_INFO", //$NON-NLS-1$ //$NON-NLS-2$ + "org/osgi/service/log/LogEntry/LOG_DEBUG", "org/osgi/service/log/LogEntry/LOG_OTHER" }; //$NON-NLS-1$ //$NON-NLS-2$ private static final Object LOG_TOPIC_TOKEN = new Object(); private static Collection logTopics = new HashSet<>(Arrays.asList(LOG_TOPICS_ARRAY)); private static Collection eventAdminObjectClass = Arrays.asList("org.osgi.service.event.EventAdmin"); //$NON-NLS-1$ diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/EventAdminLogListener.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/EventAdminLogListener.java index 05c6eea8227..f78d96e8c79 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/EventAdminLogListener.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/EventAdminLogListener.java @@ -91,24 +91,25 @@ public void logged(final LogEntry entry) { } @SuppressWarnings("deprecation") - Object convertEvent(LogEntry entry) throws InstantiationException, IllegalAccessException, InvocationTargetException { + Object convertEvent(LogEntry entry) + throws InstantiationException, IllegalAccessException, InvocationTargetException { String topic = TOPIC; int level = entry.getLevel(); switch (level) { - case LogService.LOG_ERROR : - topic += TOPIC_SEPARATOR + LOG_ERROR; - break; - case LogService.LOG_WARNING : - topic += TOPIC_SEPARATOR + LOG_WARNING; - break; - case LogService.LOG_INFO : - topic += TOPIC_SEPARATOR + LOG_INFO; - break; - case LogService.LOG_DEBUG : - topic += TOPIC_SEPARATOR + LOG_DEBUG; - break; - default : // other log levels are represented by LOG_OTHER - topic += TOPIC_SEPARATOR + LOG_OTHER; + case LogService.LOG_ERROR: + topic += TOPIC_SEPARATOR + LOG_ERROR; + break; + case LogService.LOG_WARNING: + topic += TOPIC_SEPARATOR + LOG_WARNING; + break; + case LogService.LOG_INFO: + topic += TOPIC_SEPARATOR + LOG_INFO; + break; + case LogService.LOG_DEBUG: + topic += TOPIC_SEPARATOR + LOG_DEBUG; + break; + default: // other log levels are represented by LOG_OTHER + topic += TOPIC_SEPARATOR + LOG_OTHER; } Hashtable properties = new Hashtable<>(); Bundle bundle = entry.getBundle(); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/ExtendedLogEntryImpl.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/ExtendedLogEntryImpl.java index b01dc35df9b..2ba71383979 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/ExtendedLogEntryImpl.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/ExtendedLogEntryImpl.java @@ -59,7 +59,9 @@ private static long getId(Thread thread) { return threadId.longValue(); } - public ExtendedLogEntryImpl(Bundle bundle, String loggerName, StackTraceElement stackTraceElement, Object contextObject, LogLevel logLevelEnum, int level, String message, ServiceReference ref, Throwable throwable) { + public ExtendedLogEntryImpl(Bundle bundle, String loggerName, StackTraceElement stackTraceElement, + Object contextObject, LogLevel logLevelEnum, int level, String message, ServiceReference ref, + Throwable throwable) { this.time = System.currentTimeMillis(); this.loggerName = loggerName; this.bundle = bundle; diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/ExtendedLogReaderServiceFactory.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/ExtendedLogReaderServiceFactory.java index bb2e6a98ae3..e05025688b4 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/ExtendedLogReaderServiceFactory.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/ExtendedLogReaderServiceFactory.java @@ -84,7 +84,8 @@ static boolean safeIsLoggable(LogFilter filter, Bundle bundle, String name, int } catch (RuntimeException | LinkageError e) { // "listener.logged" calls user code and might throw an unchecked exception // we catch the error here to gather information on where the problem occurred. - // Catch linkage errors as these are generally recoverable but let other Errors propagate (see bug 222001) + // Catch linkage errors as these are generally recoverable but let other Errors + // propagate (see bug 222001) getErrorStream().println("LogFilter.isLoggable threw a non-fatal unchecked exception as follows:"); //$NON-NLS-1$ e.printStackTrace(getErrorStream()); } @@ -108,7 +109,8 @@ static void safeLogged(LogListener listener, LogEntry logEntry) { } catch (RuntimeException | LinkageError e) { // "listener.logged" calls user code and might throw an unchecked exception // we catch the error here to gather information on where the problem occurred. - // Catch linkage errors as these are generally recoverable but let other Errors propagate (see bug 222001) + // Catch linkage errors as these are generally recoverable but let other Errors + // propagate (see bug 222001) getErrorStream().println("LogListener.logged threw a non-fatal unchecked exception as follows:"); //$NON-NLS-1$ e.printStackTrace(getErrorStream()); } @@ -137,12 +139,14 @@ public LogLevel getDefaultLogLevel() { } @Override - public ExtendedLogReaderServiceImpl getService(Bundle bundle, ServiceRegistration registration) { + public ExtendedLogReaderServiceImpl getService(Bundle bundle, + ServiceRegistration registration) { return new ExtendedLogReaderServiceImpl(this); } @Override - public void ungetService(Bundle bundle, ServiceRegistration registration, ExtendedLogReaderServiceImpl service) { + public void ungetService(Bundle bundle, ServiceRegistration registration, + ExtendedLogReaderServiceImpl service) { service.shutdown(); } @@ -203,18 +207,21 @@ private void decrementNestedCount() { private int[] getCount() { int[] count = nestedCallCount.get(); if (count == null) { - count = new int[] {0}; + count = new int[] { 0 }; nestedCallCount.set(count); } return count; } - void log(final Bundle bundle, final String name, final StackTraceElement stackTraceElement, final Object context, final LogLevel logLevelEnum, final int level, final String message, final ServiceReference ref, final Throwable exception) { + void log(final Bundle bundle, final String name, final StackTraceElement stackTraceElement, final Object context, + final LogLevel logLevelEnum, final int level, final String message, final ServiceReference ref, + final Throwable exception) { if (System.getSecurityManager() != null) { AccessController.doPrivileged(new PrivilegedAction() { @Override public Void run() { - logPrivileged(bundle, name, stackTraceElement, context, logLevelEnum, level, message, ref, exception); + logPrivileged(bundle, name, stackTraceElement, context, logLevelEnum, level, message, ref, + exception); return null; } }); @@ -223,8 +230,10 @@ public Void run() { } } - void logPrivileged(Bundle bundle, String name, StackTraceElement stackTraceElement, Object context, LogLevel logLevelEnum, int level, String message, ServiceReference ref, Throwable exception) { - LogEntry logEntry = new ExtendedLogEntryImpl(bundle, name, stackTraceElement, context, logLevelEnum, level, message, ref, exception); + void logPrivileged(Bundle bundle, String name, StackTraceElement stackTraceElement, Object context, + LogLevel logLevelEnum, int level, String message, ServiceReference ref, Throwable exception) { + LogEntry logEntry = new ExtendedLogEntryImpl(bundle, name, stackTraceElement, context, logLevelEnum, level, + message, ref, exception); storeEntry(logEntry); ArrayMap listenersCopy; listenersLock.readLock().lock(); @@ -274,8 +283,9 @@ void addLogListener(LogListener listener, LogFilter filter) { Object[] listenerObjects = listenersCopy.get(listener); if (listenerObjects == null) { // Only create a task queue for non-SynchronousLogListeners - OrderedTaskQueue taskQueue = (listener instanceof SynchronousLogListener) ? null : executor.createQueue(); - listenerObjects = new Object[] {filter, taskQueue}; + OrderedTaskQueue taskQueue = (listener instanceof SynchronousLogListener) ? null + : executor.createQueue(); + listenerObjects = new Object[] { filter, taskQueue }; } else if (filter != listenerObjects[0]) { // update the filter listenerObjects[0] = filter; @@ -331,8 +341,8 @@ Enumeration getLog() { } /** -* This Executor uses OrderedTaskQueue to execute tasks in a FIFO order. -*/ + * This Executor uses OrderedTaskQueue to execute tasks in a FIFO order. + */ class OrderedExecutor implements ThreadFactory { private final int nThreads = Math.min(Runtime.getRuntime().availableProcessors(), 10); private final String logThreadName; @@ -400,13 +410,13 @@ void executeNextTask(OrderedTaskQueue taskQueue) { /** * Keeps an list of ordered tasks and guarantees the tasks are run in the order - * they are queued. Tasks executed with this queue will always be run - * in FIFO order and will never run in parallel to guarantee events are - * received in the proper order by the listener. Each log listener - * has its own ordered task queue. + * they are queued. Tasks executed with this queue will always be run in FIFO + * order and will never run in parallel to guarantee events are received in the + * proper order by the listener. Each log listener has its own ordered task + * queue. *

- * Note that only the execute method is thread safe. All other methods - * must be guarded by the OrderedExecutor monitor. + * Note that only the execute method is thread safe. All other methods must be + * guarded by the OrderedExecutor monitor. */ class OrderedTaskQueue { private final Queue dependencyQueue = new LinkedList<>(); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/ExtendedLogServiceFactory.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/ExtendedLogServiceFactory.java index ff7249cf1d5..487bd6cb42a 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/ExtendedLogServiceFactory.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/ExtendedLogServiceFactory.java @@ -39,7 +39,8 @@ public class ExtendedLogServiceFactory implements ServiceFactory registration, ExtendedLogService service) { + public void ungetService(Bundle bundle, ServiceRegistration registration, + ExtendedLogService service) { // do nothing - // Notice that we do not remove the the LogService impl for the bundle because other bundles + // Notice that we do not remove the the LogService impl for the bundle because + // other bundles // still need to be able to get the cached loggers for a bundle. } @@ -98,8 +101,10 @@ boolean isLoggable(Bundle bundle, String name, int level) { return logReaderServiceFactory.isLoggable(bundle, name, level); } - void log(Bundle bundle, String name, StackTraceElement stackTraceElement, Object context, LogLevel logLevelEnum, int level, String message, ServiceReference ref, Throwable exception) { - logReaderServiceFactory.log(bundle, name, stackTraceElement, context, logLevelEnum, level, message, ref, exception); + void log(Bundle bundle, String name, StackTraceElement stackTraceElement, Object context, LogLevel logLevelEnum, + int level, String message, ServiceReference ref, Throwable exception) { + logReaderServiceFactory.log(bundle, name, stackTraceElement, context, logLevelEnum, level, message, ref, + exception); } void checkLogPermission() throws SecurityException { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/LogServiceManager.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/LogServiceManager.java index 45f16b29560..9b11db65785 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/LogServiceManager.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/LogServiceManager.java @@ -49,8 +49,10 @@ public class LogServiceManager implements SynchronousBundleListener, FrameworkLi private static final String LOGGER_BUNDLE_EVENT = "Events.Bundle"; //$NON-NLS-1$ private static final String LOGGER_SERVICE_EVENT = "Events.Service"; //$NON-NLS-1$ - private static final String[] LOGSERVICE_CLASSES = {LogService.class.getName(), LoggerFactory.class.getName(), ExtendedLogService.class.getName()}; - private static final String[] LOGREADERSERVICE_CLASSES = {LogReaderService.class.getName(), ExtendedLogReaderService.class.getName()}; + private static final String[] LOGSERVICE_CLASSES = { LogService.class.getName(), LoggerFactory.class.getName(), + ExtendedLogService.class.getName() }; + private static final String[] LOGREADERSERVICE_CLASSES = { LogReaderService.class.getName(), + ExtendedLogReaderService.class.getName() }; private ServiceRegistration logReaderServiceRegistration; private ServiceRegistration logServiceRegistration; @@ -61,7 +63,8 @@ public class LogServiceManager implements SynchronousBundleListener, FrameworkLi private EventAdminAdapter eventAdminAdapter; private ConfigAdminListener configAdminListener; - public LogServiceManager(int maxHistory, LogLevel defaultLevel, boolean captureLogEntryLocation, LogListener... systemListeners) { + public LogServiceManager(int maxHistory, LogLevel defaultLevel, boolean captureLogEntryLocation, + LogListener... systemListeners) { logReaderServiceFactory = new ExtendedLogReaderServiceFactory(maxHistory, defaultLevel); logServiceFactory = new ExtendedLogServiceFactory(logReaderServiceFactory, captureLogEntryLocation); systemBundleLog = logServiceFactory.getLogService(new MockSystemBundle()); @@ -86,8 +89,10 @@ public void start(BundleContext context) { logServiceRegistration = context.registerService(LOGSERVICE_CLASSES, logServiceFactory, null); Hashtable loggerAdminProps = new Hashtable<>(); // TODO the constant for log service id will like be defined - loggerAdminProps.put("osgi.log.service.id", logServiceRegistration.getReference().getProperty(Constants.SERVICE_ID)); //$NON-NLS-1$ - loggerAdminRegistration = context.registerService(LoggerAdmin.class, logServiceFactory.getLoggerAdmin(), loggerAdminProps); + loggerAdminProps.put("osgi.log.service.id", //$NON-NLS-1$ + logServiceRegistration.getReference().getProperty(Constants.SERVICE_ID)); + loggerAdminRegistration = context.registerService(LoggerAdmin.class, logServiceFactory.getLoggerAdmin(), + loggerAdminProps); eventAdminAdapter = new EventAdminAdapter(context, logReaderServiceFactory); eventAdminAdapter.start(); @@ -168,15 +173,15 @@ public void frameworkEvent(FrameworkEvent event) { int eventType = event.getType(); int logType; switch (eventType) { - case FrameworkEvent.ERROR : - logType = LogService.LOG_ERROR; - break; - case FrameworkEvent.WARNING : - logType = LogService.LOG_WARNING; - break; - default : - logType = LogService.LOG_INFO; - break; + case FrameworkEvent.ERROR: + logType = LogService.LOG_ERROR; + break; + case FrameworkEvent.WARNING: + logType = LogService.LOG_WARNING; + break; + default: + logType = LogService.LOG_INFO; + break; } String bsn = (bundle == null) ? null : bundle.getSymbolicName(); String loggerName = (bsn == null) ? LOGGER_FRAMEWORK_EVENT : LOGGER_FRAMEWORK_EVENT + "." + bsn; //$NON-NLS-1$ @@ -192,35 +197,35 @@ public void frameworkEvent(FrameworkEvent event) { */ private static String getBundleEventTypeName(int type) { switch (type) { - case BundleEvent.INSTALLED : - return ("BundleEvent INSTALLED"); //$NON-NLS-1$ + case BundleEvent.INSTALLED: + return ("BundleEvent INSTALLED"); //$NON-NLS-1$ - case BundleEvent.RESOLVED : - return ("BundleEvent RESOLVED"); //$NON-NLS-1$ + case BundleEvent.RESOLVED: + return ("BundleEvent RESOLVED"); //$NON-NLS-1$ - case BundleEvent.STARTED : - return ("BundleEvent STARTED"); //$NON-NLS-1$ + case BundleEvent.STARTED: + return ("BundleEvent STARTED"); //$NON-NLS-1$ - case BundleEvent.STARTING : - return ("BundleEvent STARTING"); //$NON-NLS-1$ + case BundleEvent.STARTING: + return ("BundleEvent STARTING"); //$NON-NLS-1$ - case BundleEvent.STOPPED : - return ("BundleEvent STOPPED"); //$NON-NLS-1$ + case BundleEvent.STOPPED: + return ("BundleEvent STOPPED"); //$NON-NLS-1$ - case BundleEvent.STOPPING : - return ("BundleEvent STOPPING"); //$NON-NLS-1$ + case BundleEvent.STOPPING: + return ("BundleEvent STOPPING"); //$NON-NLS-1$ - case BundleEvent.UNINSTALLED : - return ("BundleEvent UNINSTALLED"); //$NON-NLS-1$ + case BundleEvent.UNINSTALLED: + return ("BundleEvent UNINSTALLED"); //$NON-NLS-1$ - case BundleEvent.UNRESOLVED : - return ("BundleEvent UNRESOLVED"); //$NON-NLS-1$ + case BundleEvent.UNRESOLVED: + return ("BundleEvent UNRESOLVED"); //$NON-NLS-1$ - case BundleEvent.UPDATED : - return ("BundleEvent UPDATED"); //$NON-NLS-1$ + case BundleEvent.UPDATED: + return ("BundleEvent UPDATED"); //$NON-NLS-1$ - default : - return ("BundleEvent " + Integer.toHexString(type)); //$NON-NLS-1$ + default: + return ("BundleEvent " + Integer.toHexString(type)); //$NON-NLS-1$ } } @@ -230,17 +235,17 @@ private static String getBundleEventTypeName(int type) { */ private static String getServiceEventTypeName(int type) { switch (type) { - case ServiceEvent.REGISTERED : - return ("ServiceEvent REGISTERED"); //$NON-NLS-1$ + case ServiceEvent.REGISTERED: + return ("ServiceEvent REGISTERED"); //$NON-NLS-1$ - case ServiceEvent.MODIFIED : - return ("ServiceEvent MODIFIED"); //$NON-NLS-1$ + case ServiceEvent.MODIFIED: + return ("ServiceEvent MODIFIED"); //$NON-NLS-1$ - case ServiceEvent.UNREGISTERING : - return ("ServiceEvent UNREGISTERING"); //$NON-NLS-1$ + case ServiceEvent.UNREGISTERING: + return ("ServiceEvent UNREGISTERING"); //$NON-NLS-1$ - default : - return ("ServiceEvent " + Integer.toHexString(type)); //$NON-NLS-1$ + default: + return ("ServiceEvent " + Integer.toHexString(type)); //$NON-NLS-1$ } } @@ -250,26 +255,26 @@ private static String getServiceEventTypeName(int type) { */ private static String getFrameworkEventTypeName(int type) { switch (type) { - case FrameworkEvent.ERROR : - return ("FrameworkEvent ERROR"); //$NON-NLS-1$ + case FrameworkEvent.ERROR: + return ("FrameworkEvent ERROR"); //$NON-NLS-1$ - case FrameworkEvent.INFO : - return ("FrameworkEvent INFO"); //$NON-NLS-1$ + case FrameworkEvent.INFO: + return ("FrameworkEvent INFO"); //$NON-NLS-1$ - case FrameworkEvent.PACKAGES_REFRESHED : - return ("FrameworkEvent PACKAGES REFRESHED"); //$NON-NLS-1$ + case FrameworkEvent.PACKAGES_REFRESHED: + return ("FrameworkEvent PACKAGES REFRESHED"); //$NON-NLS-1$ - case FrameworkEvent.STARTED : - return ("FrameworkEvent STARTED"); //$NON-NLS-1$ + case FrameworkEvent.STARTED: + return ("FrameworkEvent STARTED"); //$NON-NLS-1$ - case FrameworkEvent.STARTLEVEL_CHANGED : - return ("FrameworkEvent STARTLEVEL CHANGED"); //$NON-NLS-1$ + case FrameworkEvent.STARTLEVEL_CHANGED: + return ("FrameworkEvent STARTLEVEL CHANGED"); //$NON-NLS-1$ - case FrameworkEvent.WARNING : - return ("FrameworkEvent WARNING"); //$NON-NLS-1$ + case FrameworkEvent.WARNING: + return ("FrameworkEvent WARNING"); //$NON-NLS-1$ - default : - return ("FrameworkEvent " + Integer.toHexString(type)); //$NON-NLS-1$ + default: + return ("FrameworkEvent " + Integer.toHexString(type)); //$NON-NLS-1$ } } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/LoggerImpl.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/LoggerImpl.java index 710d5ee098a..cde7b707bdd 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/LoggerImpl.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/log/LoggerImpl.java @@ -21,7 +21,8 @@ import org.osgi.service.log.admin.LoggerContext; public class LoggerImpl implements Logger { - static final String THIS_PACKAGE_NAME = LoggerImpl.class.getName().substring(0, LoggerImpl.class.getName().length() - LoggerImpl.class.getSimpleName().length()); + static final String THIS_PACKAGE_NAME = LoggerImpl.class.getName().substring(0, + LoggerImpl.class.getName().length() - LoggerImpl.class.getSimpleName().length()); static final Object[] EMPTY = new Object[0]; protected final ExtendedLogServiceImpl logServiceImpl; protected final String name; @@ -76,32 +77,35 @@ public void log(Object context, int level, String message, Throwable exception) log(context, null, level, message, null, exception); } - private void log(Object context, LogLevel logLevelEnum, int level, String message, ServiceReference ref, Throwable exception) { + private void log(Object context, LogLevel logLevelEnum, int level, String message, ServiceReference ref, + Throwable exception) { log(logServiceImpl.getBundle(), context, logLevelEnum, level, message, ref, exception); } - void log(Bundle entryBundle, Object context, LogLevel logLevelEnum, int level, String message, ServiceReference ref, Throwable exception) { + void log(Bundle entryBundle, Object context, LogLevel logLevelEnum, int level, String message, + ServiceReference ref, Throwable exception) { if (logLevelEnum == null) { logLevelEnum = getLogLevel(level); } if (enabledLevel.implies(logLevelEnum)) { - logServiceImpl.getFactory().log(entryBundle, name, getLocation(), context, logLevelEnum, level, message, ref, exception); + logServiceImpl.getFactory().log(entryBundle, name, getLocation(), context, logLevelEnum, level, message, + ref, exception); } } @SuppressWarnings("deprecation") private LogLevel getLogLevel(int level) { switch (level) { - case LogService.LOG_DEBUG : - return LogLevel.DEBUG; - case LogService.LOG_ERROR : - return LogLevel.ERROR; - case LogService.LOG_INFO : - return LogLevel.INFO; - case LogService.LOG_WARNING : - return LogLevel.WARN; - default : - return LogLevel.TRACE; + case LogService.LOG_DEBUG: + return LogLevel.DEBUG; + case LogService.LOG_ERROR: + return LogLevel.ERROR; + case LogService.LOG_INFO: + return LogLevel.INFO; + case LogService.LOG_WARNING: + return LogLevel.WARN; + default: + return LogLevel.TRACE; } } @@ -117,12 +121,12 @@ public void trace(String message) { @Override public void trace(String format, Object arg) { - trace(format, new Object[] {arg}); + trace(format, new Object[] { arg }); } @Override public void trace(String format, Object arg1, Object arg2) { - trace(format, new Object[] {arg1, arg2}); + trace(format, new Object[] { arg1, arg2 }); } @Override @@ -142,12 +146,12 @@ public void debug(String message) { @Override public void debug(String format, Object arg) { - debug(format, new Object[] {arg}); + debug(format, new Object[] { arg }); } @Override public void debug(String format, Object arg1, Object arg2) { - debug(format, new Object[] {arg1, arg2}); + debug(format, new Object[] { arg1, arg2 }); } @Override @@ -167,12 +171,12 @@ public void info(String message) { @Override public void info(String format, Object arg) { - info(format, new Object[] {arg}); + info(format, new Object[] { arg }); } @Override public void info(String format, Object arg1, Object arg2) { - info(format, new Object[] {arg1, arg2}); + info(format, new Object[] { arg1, arg2 }); } @Override @@ -192,12 +196,12 @@ public void warn(String message) { @Override public void warn(String format, Object arg) { - warn(format, new Object[] {arg}); + warn(format, new Object[] { arg }); } @Override public void warn(String format, Object arg1, Object arg2) { - warn(format, new Object[] {arg1, arg2}); + warn(format, new Object[] { arg1, arg2 }); } @Override @@ -217,12 +221,12 @@ public void error(String message) { @Override public void error(String format, Object arg) { - error(format, new Object[] {arg}); + error(format, new Object[] { arg }); } @Override public void error(String format, Object arg1, Object arg2) { - error(format, new Object[] {arg1, arg2}); + error(format, new Object[] { arg1, arg2 }); } @Override @@ -237,12 +241,12 @@ public void audit(String message) { @Override public void audit(String format, Object arg) { - audit(format, new Object[] {arg}); + audit(format, new Object[] { arg }); } @Override public void audit(String format, Object arg1, Object arg2) { - audit(format, new Object[] {arg1, arg2}); + audit(format, new Object[] { arg1, arg2 }); } @Override @@ -294,7 +298,9 @@ private void log(LogLevel level, String format, Object... arguments) { StackTraceElement location = getLocation(); Arguments processedArguments = new Arguments(arguments); String message = processedArguments.isEmpty() ? format : formatMessage(format, processedArguments); - logServiceImpl.getFactory().log(logServiceImpl.getBundle(), name, location, processedArguments.serviceReference(), level, level.ordinal(), message.toString(), processedArguments.serviceReference(), processedArguments.throwable()); + logServiceImpl.getFactory().log(logServiceImpl.getBundle(), name, location, + processedArguments.serviceReference(), level, level.ordinal(), message.toString(), + processedArguments.serviceReference(), processedArguments.throwable()); } private StackTraceElement getLocation() { @@ -319,8 +325,10 @@ String formatMessage(String format, Arguments processedArguments) { int offset = 0; StringBuilder message = new StringBuilder(format.length() * 2); for (Object argument : processedArguments.arguments()) { - // By design, the message will continue to be formatted for as long as arguments remain. - // Once all arguments have been processed, formatting stops. This means some escape characters + // By design, the message will continue to be formatted for as long as arguments + // remain. + // Once all arguments have been processed, formatting stops. This means some + // escape characters // and place holders may remain unconsumed. This matches SLF4J behavior. while (matcher.find()) { if (matcher.group(2).isEmpty()) { @@ -342,7 +350,8 @@ String formatMessage(String format, Arguments processedArguments) { return message.toString(); } - private static int append(StringBuilder builder, Matcher matcher, char[] chars, int offset, int length, Object argument) { + private static int append(StringBuilder builder, Matcher matcher, char[] chars, int offset, int length, + Object argument) { builder.append(chars, offset, length); builder.append(argument); return matcher.end(3); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/permadmin/BundlePermissions.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/permadmin/BundlePermissions.java index fd7d2a72265..c854995a165 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/permadmin/BundlePermissions.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/permadmin/BundlePermissions.java @@ -30,7 +30,8 @@ public final class BundlePermissions extends PermissionCollection { private final PermissionInfoCollection restrictedPermissions; private final Permissions wovenPermissions; - public BundlePermissions(Bundle bundle, SecurityAdmin securityAdmin, PermissionInfoCollection impliedPermissions, PermissionInfoCollection restrictedPermissions) { + public BundlePermissions(Bundle bundle, SecurityAdmin securityAdmin, PermissionInfoCollection impliedPermissions, + PermissionInfoCollection restrictedPermissions) { this.bundle = bundle; this.securityAdmin = securityAdmin; this.impliedPermissions = impliedPermissions; @@ -51,8 +52,8 @@ public void add(Permission permission) { * woven by weaving hooks. * * @param permission The package permission to add to this woven bundle. - * @throws SecurityException If the permission - * does not have an action of {@link PackagePermission#IMPORT}. + * @throws SecurityException If the permission does not have an + * action of {@link PackagePermission#IMPORT}. */ public void addWovenPermission(PackagePermission permission) { if (!permission.getActions().equals(PackagePermission.IMPORT)) @@ -63,7 +64,8 @@ public void addWovenPermission(PackagePermission permission) { @Override public Enumeration elements() { // TODO return an empty enumeration for now; - // It does not seem possible to do this properly with multiple exports and conditional permissions. + // It does not seem possible to do this properly with multiple exports and + // conditional permissions. return Collections.emptyEnumeration(); } @@ -77,7 +79,8 @@ public boolean implies(Permission permission) { if (wovenPermissions.implies(permission)) return true; - // We must be allowed by the restricted permissions to have any hope of passing the check + // We must be allowed by the restricted permissions to have any hope of passing + // the check if ((restrictedPermissions != null) && !restrictedPermissions.implies(permission)) return false; diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/permadmin/EquinoxSecurityManager.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/permadmin/EquinoxSecurityManager.java index fed8442028a..fe81a570f36 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/permadmin/EquinoxSecurityManager.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/permadmin/EquinoxSecurityManager.java @@ -28,7 +28,8 @@ public class EquinoxSecurityManager extends SecurityManager { /* * This is super goofy, but we need to make sure that the CheckContext and - * CheckPermissionAction classes load early. Otherwise, we run into problems later. + * CheckPermissionAction classes load early. Otherwise, we run into problems + * later. */ static { Class c; @@ -94,13 +95,14 @@ public void checkPermission(Permission perm, Object context) { } /** - * Gets the AccessControlContext currently being evaluated by - * the SecurityManager. + * Gets the AccessControlContext currently being evaluated by the + * SecurityManager. * - * @return the AccessControlContext currently being evaluated by the SecurityManager, or - * null if no AccessControlContext is being evaluated. Note: this method will - * return null if the permission check is being done directly on the AccessControlContext - * rather than the SecurityManager. + * @return the AccessControlContext currently being evaluated by the + * SecurityManager, or null if no AccessControlContext is being + * evaluated. Note: this method will return null if the permission check + * is being done directly on the AccessControlContext rather than the + * SecurityManager. */ public AccessControlContext getContextToBeChecked() { CheckContext cc = localCheckContext.get(); @@ -124,7 +126,8 @@ void internalCheckPermission(Permission perm, Object context) { List conditionSets = cc.depthCondSets.get(cc.getDepth()); if (conditionSets == null) return; - // TODO the spec seems impossible to implement just doing the simple thing for now + // TODO the spec seems impossible to implement just doing the simple thing for + // now Map, Dictionary> conditionDictionaries = new HashMap<>(); for (Decision[] domainDecisions : conditionSets) { boolean grant = false; @@ -161,7 +164,8 @@ void internalCheckPermission(Permission perm, Object context) { } } - private int getPostponedDecision(Decision decision, Map, Dictionary> conditionDictionaries, CheckContext cc) { + private int getPostponedDecision(Decision decision, + Map, Dictionary> conditionDictionaries, CheckContext cc) { Condition[] postponed = decision.postponed; for (Condition postponedCond : postponed) { Dictionary condContext = conditionDictionaries.get(postponedCond.getClass()); @@ -179,7 +183,7 @@ private int getPostponedDecision(Decision decision, Map twoStringClassArray[] = new Class[] {String.class, String.class}; - static private final Class oneStringClassArray[] = new Class[] {String.class}; + static private final Class twoStringClassArray[] = new Class[] { String.class, String.class }; + static private final Class oneStringClassArray[] = new Class[] { String.class }; static private final Class noArgClassArray[] = new Class[] {}; - static private final Class[][] permClassArrayArgs = new Class[][] {noArgClassArray, oneStringClassArray, twoStringClassArray}; + static private final Class[][] permClassArrayArgs = new Class[][] { noArgClassArray, oneStringClassArray, + twoStringClassArray }; static private final String ALL_PERMISSION_NAME = AllPermission.class.getName(); static final String FILE_PERMISSION_NAME = FilePermission.class.getName(); static final String ALL_FILES = "<>"; //$NON-NLS-1$ @@ -84,7 +85,8 @@ boolean implies(final BundlePermissions bundlePermissions, Permission perm) { return true; final Class permClass = perm.getClass(); PermissionCollection collection = getCachedCollection(bundlePermissions, permClass); - // must populate the collection outside of the lock to prevent class loader deadlock + // must populate the collection outside of the lock to prevent class loader + // deadlock if (collection == null) { collection = perm.newPermissionCollection(); if (collection == null) { @@ -108,20 +110,25 @@ boolean implies(final BundlePermissions bundlePermissions, Permission perm) { return collection.implies(perm); } - PermissionCollection getCachedCollection(BundlePermissions bundlePermissions, Class permClass) { + PermissionCollection getCachedCollection(BundlePermissions bundlePermissions, + Class permClass) { synchronized (cachedPermissionCollections) { - if (bundlePermissions != null && cachedRelativeFilePermissionCollections != null && FILE_PERMISSION_NAME.equals(permClass.getName())) { + if (bundlePermissions != null && cachedRelativeFilePermissionCollections != null + && FILE_PERMISSION_NAME.equals(permClass.getName())) { return cachedRelativeFilePermissionCollections.get(bundlePermissions); } return cachedPermissionCollections.get(permClass); } } - private PermissionCollection cacheCollection(BundlePermissions bundlePermissions, Class permClass, PermissionCollection collection) { + private PermissionCollection cacheCollection(BundlePermissions bundlePermissions, + Class permClass, PermissionCollection collection) { synchronized (cachedPermissionCollections) { // check to see if another thread beat this thread at adding the collection - boolean relativeFiles = bundlePermissions != null && cachedRelativeFilePermissionCollections != null && FILE_PERMISSION_NAME.equals(permClass.getName()); - PermissionCollection exists = relativeFiles ? cachedRelativeFilePermissionCollections.get(bundlePermissions) : cachedPermissionCollections.get(permClass); + boolean relativeFiles = bundlePermissions != null && cachedRelativeFilePermissionCollections != null + && FILE_PERMISSION_NAME.equals(permClass.getName()); + PermissionCollection exists = relativeFiles ? cachedRelativeFilePermissionCollections.get(bundlePermissions) + : cachedPermissionCollections.get(permClass); if (exists != null) { collection = exists; } else { @@ -139,7 +146,8 @@ PermissionInfo[] getPermissionInfos() { return permInfos; } - void addPermissions(BundlePermissions bundlePermissions, PermissionCollection collection, Class permClass) throws Exception { + void addPermissions(BundlePermissions bundlePermissions, PermissionCollection collection, + Class permClass) throws Exception { String permClassName = permClass.getName(); Constructor constructor = null; int numArgs = -1; @@ -156,7 +164,8 @@ void addPermissions(BundlePermissions bundlePermissions, PermissionCollection co throw new NoSuchMethodException(permClass.getName() + ".()"); //$NON-NLS-1$ } /* - * TODO: We need to cache the permission constructors to enhance performance (see bug 118813). + * TODO: We need to cache the permission constructors to enhance performance + * (see bug 118813). */ for (PermissionInfo permInfo : permInfos) { if (permInfo.getType().equals(permClassName)) { @@ -172,7 +181,8 @@ void addPermissions(BundlePermissions bundlePermissions, PermissionCollection co if (!args[0].equals(ALL_FILES)) { File file = new File(args[0]); if (!file.isAbsolute()) { // relative name - File target = bundlePermissions == null ? null : bundlePermissions.getBundle().getDataFile(permInfo.getName()); + File target = bundlePermissions == null ? null + : bundlePermissions.getBundle().getDataFile(permInfo.getName()); if (target == null) { // ignore if we cannot find the data area continue; diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/permadmin/PermissionsHash.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/permadmin/PermissionsHash.java index bdc384a22a5..062eedeefb3 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/permadmin/PermissionsHash.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/permadmin/PermissionsHash.java @@ -21,16 +21,14 @@ /** * A simple Hashtable based collection of Permission objects. *

- * The class' .implies method simply scans each permission - * individually and asks if the permission should be granted. - * No addition semantics is provided by the collection, so it is - * not possible to grant permissions whose "grantedness" is + * The class' .implies method simply scans each permission individually and asks + * if the permission should be granted. No addition semantics is provided by the + * collection, so it is not possible to grant permissions whose "grantedness" is * split across multiple stored Permissions. *

- * Instances of this class can be used to store heterogeneous - * collections of permissions, as long as it is not necessary - * to remember when multiple occurances of .equal permissions - * are added. + * Instances of this class can be used to store heterogeneous collections of + * permissions, as long as it is not necessary to remember when multiple + * occurances of .equal permissions are added. * */ class PermissionsHash extends PermissionCollection { @@ -51,10 +49,8 @@ public PermissionsHash() { /** * Adds the argument to the collection. * - * @param perm java.security.Permission - * the permission to add to the collection. - * @exception IllegalStateException - * if the collection is read only. + * @param perm java.security.Permission the permission to add to the collection. + * @exception IllegalStateException if the collection is read only. */ @Override public void add(Permission perm) { @@ -66,11 +62,9 @@ public void add(Permission perm) { } /** - * Answers an enumeration of the permissions - * in the receiver. + * Answers an enumeration of the permissions in the receiver. * - * @return Enumeration - * the permissions in the receiver. + * @return Enumeration the permissions in the receiver. */ @Override public Enumeration elements() { @@ -78,15 +72,12 @@ public Enumeration elements() { } /** - * Indicates whether the argument permission is implied - * by the permissions contained in the receiver. + * Indicates whether the argument permission is implied by the permissions + * contained in the receiver. * - * @return boolean - * true if the argument permission - * is implied by the permissions in the receiver, - * and false if it is not. - * @param perm java.security.Permission - * the permission to check + * @return boolean true if the argument permission is implied by + * the permissions in the receiver, and false if it is not. + * @param perm java.security.Permission the permission to check */ @Override public boolean implies(Permission perm) { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/permadmin/SecurityRow.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/permadmin/SecurityRow.java index af9efdae4ec..637d4aa9926 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/permadmin/SecurityRow.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/permadmin/SecurityRow.java @@ -31,7 +31,7 @@ public final class SecurityRow implements ConditionalPermissionInfo { /* Used to find condition constructors getConditions */ - static final Class[] conditionMethodArgs = new Class[] {Bundle.class, ConditionInfo.class}; + static final Class[] conditionMethodArgs = new Class[] { Bundle.class, ConditionInfo.class }; static Condition[] ABSTAIN_LIST = new Condition[0]; static Condition[] SATISFIED_LIST = new Condition[0]; static final Decision DECISION_ABSTAIN = new Decision(SecurityTable.ABSTAIN, null, null, null); @@ -47,7 +47,8 @@ public final class SecurityRow implements ConditionalPermissionInfo { final Map bundleConditions; final Object bundleConditionsLock = new Object(); - public SecurityRow(SecurityAdmin securityAdmin, String name, ConditionInfo[] conditionInfos, PermissionInfo[] permissionInfos, String decision) { + public SecurityRow(SecurityAdmin securityAdmin, String name, ConditionInfo[] conditionInfos, + PermissionInfo[] permissionInfos, String decision) { if (permissionInfos == null || permissionInfos.length == 0) throw new IllegalArgumentException("It is invalid to have empty permissionInfos"); //$NON-NLS-1$ this.securityAdmin = securityAdmin; @@ -74,7 +75,8 @@ static SecurityRow createSecurityRow(SecurityAdmin securityAdmin, String encoded return (SecurityRow) createConditionalPermissionInfo(securityAdmin, encoded); } - private static ConditionalPermissionInfo createConditionalPermissionInfo(SecurityAdmin securityAdmin, String encoded) { + private static ConditionalPermissionInfo createConditionalPermissionInfo(SecurityAdmin securityAdmin, + String encoded) { encoded = encoded.trim(); if (encoded.length() == 0) throw new IllegalArgumentException("Empty encoded string is invalid"); //$NON-NLS-1$ @@ -113,7 +115,8 @@ private static ConditionalPermissionInfo createConditionalPermissionInfo(Securit String decision = encoded.substring(0, start); decision = decision.trim(); - if (decision.length() == 0 || (!ConditionalPermissionInfo.DENY.equalsIgnoreCase(decision) && !ConditionalPermissionInfo.ALLOW.equalsIgnoreCase(decision))) + if (decision.length() == 0 || (!ConditionalPermissionInfo.DENY.equalsIgnoreCase(decision) + && !ConditionalPermissionInfo.ALLOW.equalsIgnoreCase(decision))) throw new IllegalArgumentException(encoded); List condList = new ArrayList<>(); @@ -167,20 +170,20 @@ private static void escapeString(String str, StringBuilder output) { for (int i = 0; i < len; i++) { char c = str.charAt(i); switch (c) { - case '"' : - case '\\' : - output.append('\\'); - output.append(c); - break; - case '\r' : - output.append("\\r"); //$NON-NLS-1$ - break; - case '\n' : - output.append("\\n"); //$NON-NLS-1$ - break; - default : - output.append(c); - break; + case '"': + case '\\': + output.append('\\'); + output.append(c); + break; + case '\r': + output.append("\\r"); //$NON-NLS-1$ + break; + case '\n': + output.append("\\n"); //$NON-NLS-1$ + break; + default: + output.append(c); + break; } } } @@ -195,19 +198,19 @@ private static String unescapeString(String str) { if (i < end) { c = str.charAt(i); switch (c) { - case '"' : - case '\\' : - break; - case 'r' : - c = '\r'; - break; - case 'n' : - c = '\n'; - break; - default : - c = '\\'; - i--; - break; + case '"': + case '\\': + break; + case 'r': + c = '\r'; + break; + case 'n': + c = '\n'; + break; + default: + c = '\\'; + i--; + break; } } } @@ -285,7 +288,7 @@ Condition[] getConditions(BundlePermissions bundlePermissions) { } } - Object[] args = {bundlePermissions.getBundle(), conditionInfos[i]}; + Object[] args = { bundlePermissions.getBundle(), conditionInfos[i] }; try { if (method != null) conditions[i] = (Condition) method.invoke(null, args); @@ -354,14 +357,16 @@ Decision evaluate(BundlePermissions bundlePermissions, Permission permission) { if (condition == null) continue; // this condition must have been satisfied && !mutable in a previous check if (!isPostponed(condition)) { - // must call isMutable before calling isSatisfied according to the specification. + // must call isMutable before calling isSatisfied according to the + // specification. boolean mutable = condition.isMutable(); if (condition.isSatisfied()) { if (!mutable) conditions[i] = null; // ignore this condition for future checks } else { if (!mutable) - // this will cause the row to always abstain; mark this to be ignored in future checks + // this will cause the row to always abstain; mark this to be ignored in future + // checks synchronized (bundleConditionsLock) { bundleConditions.put(bundlePermissions, ABSTAIN_LIST); } @@ -373,7 +378,8 @@ Decision evaluate(BundlePermissions bundlePermissions, Permission permission) { postponedPermCheck = evaluatePermission(bundlePermissions, permission); if (postponedPermCheck == DECISION_ABSTAIN) return postponedPermCheck; // no need to postpone the condition if the row abstains - // this row will deny or allow the permission; must queue the postponed condition + // this row will deny or allow the permission; must queue the postponed + // condition if (postponedConditions == null) postponedConditions = new ArrayList<>(1); postponedConditions.add(condition); @@ -386,7 +392,8 @@ Decision evaluate(BundlePermissions bundlePermissions, Permission permission) { } } if (postponedPermCheck != null) - return new Decision(postponedPermCheck.decision | SecurityTable.POSTPONED, postponedConditions.toArray(new Condition[postponedConditions.size()]), this, bundlePermissions); + return new Decision(postponedPermCheck.decision | SecurityTable.POSTPONED, + postponedConditions.toArray(new Condition[postponedConditions.size()]), this, bundlePermissions); return evaluatePermission(bundlePermissions, permission); } @@ -396,7 +403,9 @@ private boolean isPostponed(Condition condition) { } private Decision evaluatePermission(BundlePermissions bundlePermissions, Permission permission) { - return permissionInfoCollection.implies(bundlePermissions, permission) ? (deny ? DECISION_DENIED : DECISION_GRANTED) : DECISION_ABSTAIN; + return permissionInfoCollection.implies(bundlePermissions, permission) + ? (deny ? DECISION_DENIED : DECISION_GRANTED) + : DECISION_ABSTAIN; } @Override @@ -438,7 +447,8 @@ static int getHashCode(String name, ConditionInfo[] conds, PermissionInfo[] perm return h; } - static String getEncoded(String name, ConditionInfo[] conditionInfos, PermissionInfo[] permissionInfos, boolean deny) { + static String getEncoded(String name, ConditionInfo[] conditionInfos, PermissionInfo[] permissionInfos, + boolean deny) { StringBuilder result = new StringBuilder(); if (deny) result.append(ConditionalPermissionInfo.DENY); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/permadmin/SecurityRowSnapShot.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/permadmin/SecurityRowSnapShot.java index b2b415c82cd..d2f5815a057 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/permadmin/SecurityRowSnapShot.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/permadmin/SecurityRowSnapShot.java @@ -24,7 +24,8 @@ public class SecurityRowSnapShot implements ConditionalPermissionInfo { private final PermissionInfo[] permissionInfos; private final String decision; - public SecurityRowSnapShot(String name, ConditionInfo[] conditionInfos, PermissionInfo[] permissionInfos, String decision) { + public SecurityRowSnapShot(String name, ConditionInfo[] conditionInfos, PermissionInfo[] permissionInfos, + String decision) { if (permissionInfos == null || permissionInfos.length == 0) throw new IllegalArgumentException("It is invalid to have empty permissionInfos"); //$NON-NLS-1$ decision = decision.toLowerCase(); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/permadmin/SecurityTable.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/permadmin/SecurityTable.java index 55abf9ade3a..63b4469287d 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/permadmin/SecurityTable.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/permadmin/SecurityTable.java @@ -61,7 +61,7 @@ int evaluate(BundlePermissions bundlePermissions, Permission permission) { return ABSTAIN; } - //can't short-circuit early, so try cache + // can't short-circuit early, so try cache Integer result = evaluationCache.get(evaluationCacheKey); boolean hasMutable = false; if (result != null) { @@ -70,14 +70,14 @@ int evaluate(BundlePermissions bundlePermissions, Permission permission) { return result; } } - //cache miss or has mutable rows + // cache miss or has mutable rows boolean postponed = false; Decision[] results = new Decision[rows.length]; int immediateDecisionIdx = -1; // evaluate each row for (int i = 0; i < rows.length && immediateDecisionIdx == -1; i++) { if (result == null) { - //check all conditions for any that are mutable, this will turn off the cache + // check all conditions for any that are mutable, this will turn off the cache hasMutable |= checkMutable(bundlePermissions, evaluationCacheKey, rows[i]); } try { @@ -104,7 +104,8 @@ int evaluate(BundlePermissions bundlePermissions, Permission permission) { // no need to process the rest of the rows immediateDecisionIdx = i; } - Integer immediateDecision = handlePostponedConditions(evaluationCacheKey, hasMutable, postponed, results, immediateDecisionIdx); + Integer immediateDecision = handlePostponedConditions(evaluationCacheKey, hasMutable, postponed, results, + immediateDecisionIdx); if (immediateDecision != null) return immediateDecision; int finalDecision = postponed ? POSTPONED : ABSTAIN; @@ -114,7 +115,8 @@ int evaluate(BundlePermissions bundlePermissions, Permission permission) { return finalDecision; } - private boolean checkMutable(BundlePermissions bundlePermissions, EvaluationCacheKey evaluationCacheKey, SecurityRow row) { + private boolean checkMutable(BundlePermissions bundlePermissions, EvaluationCacheKey evaluationCacheKey, + SecurityRow row) { Condition[] conditions = row.getConditions(bundlePermissions); if (conditions != null) { for (Condition condition : conditions) { @@ -127,11 +129,13 @@ private boolean checkMutable(BundlePermissions bundlePermissions, EvaluationCach return false; } - private Integer handlePostponedConditions(EvaluationCacheKey evaluationCacheKey, boolean hasMutable, boolean postponed, Decision[] results, int immediateDecisionIdx) { + private Integer handlePostponedConditions(EvaluationCacheKey evaluationCacheKey, boolean hasMutable, + boolean postponed, Decision[] results, int immediateDecisionIdx) { if (postponed) { int immediateDecision = immediateDecisionIdx < 0 ? DENIED : results[immediateDecisionIdx].decision; // iterate over all postponed conditions; - // if they all provide the same decision as the immediate decision then return the immediate decision + // if they all provide the same decision as the immediate decision then return + // the immediate decision boolean allSameDecision = true; int i = immediateDecisionIdx < 0 ? results.length - 1 : immediateDecisionIdx - 1; for (; i >= 0 && allSameDecision; i--) { @@ -139,7 +143,8 @@ private Integer handlePostponedConditions(EvaluationCacheKey evaluationCacheKey, if ((results[i].decision & immediateDecision) == 0) allSameDecision = false; else - results[i] = SecurityRow.DECISION_ABSTAIN; // we can clear postpones with the same decision as the immediate + results[i] = SecurityRow.DECISION_ABSTAIN; // we can clear postpones with the same decision as + // the immediate } } if (allSameDecision) { @@ -149,12 +154,14 @@ private Integer handlePostponedConditions(EvaluationCacheKey evaluationCacheKey, return immediateDecision; } - // we now are forced to postpone; we need to also remember the postponed decisions and + // we now are forced to postpone; we need to also remember the postponed + // decisions and // the immediate decision if there is one. EquinoxSecurityManager equinoxManager = securityAdmin.getSupportedSecurityManager(); if (equinoxManager == null) { // TODO this is really an error condition. - // This should never happen. We checked for a supported manager when the row was postponed + // This should never happen. We checked for a supported manager when the row was + // postponed if (!hasMutable) { evaluationCache.put(evaluationCacheKey, ABSTAIN); } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/permadmin/SecurityTableUpdate.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/permadmin/SecurityTableUpdate.java index e99eafb6410..a3532e76abc 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/permadmin/SecurityTableUpdate.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/permadmin/SecurityTableUpdate.java @@ -32,7 +32,8 @@ public SecurityTableUpdate(SecurityAdmin securityAdmin, SecurityRow[] rows, long for (SecurityRow row : rows) { // Use SecurityRowSnapShot to prevent modification before commit // and to throw exceptions from delete - this.rows.add(new SecurityRowSnapShot(row.getName(), row.internalGetConditionInfos(), row.internalGetPermissionInfos(), row.getAccessDecision())); + this.rows.add(new SecurityRowSnapShot(row.getName(), row.internalGetConditionInfos(), + row.internalGetPermissionInfos(), row.getAccessDecision())); } } @@ -43,7 +44,8 @@ public boolean commit() { @Override public List getConditionalPermissionInfos() { - // it is fine to return the internal list; it is a snap shot and we allow clients to modify it. + // it is fine to return the internal list; it is a snap shot and we allow + // clients to modify it. return rows; } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/provisional/service/security/AuthorizationEngine.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/provisional/service/security/AuthorizationEngine.java index b57c3929722..0aa09c6c44d 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/provisional/service/security/AuthorizationEngine.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/provisional/service/security/AuthorizationEngine.java @@ -21,9 +21,10 @@ import org.osgi.util.tracker.ServiceTracker; /** - * An authorization engine is used to grant authorization to {@link SignedContent}. - * For example, an engine could determine if SignedContent is authorized - * to enable code from a signed bundle. + * An authorization engine is used to grant authorization to + * {@link SignedContent}. For example, an engine could determine if + * SignedContent is authorized to enable code from a signed bundle. + * * @since 3.4 */ public abstract class AuthorizationEngine { @@ -38,12 +39,14 @@ public AuthorizationEngine(BundleContext context) { } /** - * Authorizes a SignedContent object. The engine determines if the - * signed content authorization should be granted. The context is the entity - * associated with the signed content. For example, signed content - * for a bundle will have a Bundle object as the context. + * Authorizes a SignedContent object. The engine determines if the + * signed content authorization should be granted. The context is the entity + * associated with the signed content. For example, signed content for a bundle + * will have a Bundle object as the context. + * * @param content the signed content. The value may be null. - * @param context the context associated with the signed content. The value may be null. + * @param context the context associated with the signed content. The value may + * be null. */ public final void authorize(SignedContent content, Object context) { fireEvent(doAuthorize(content, context)); @@ -65,19 +68,22 @@ private void fireEvent(AuthorizationEvent event) { } /** - * Authorizes a SignedContent object. The engine determines if the + * Authorizes a SignedContent object. The engine determines if the * signed content authorization should be granted. + * * @param content * @param context the context associated with the signed content - * @return an authorization event which will be fired. A value of null - * may be returned; in this case no authorization event will be fired. + * @return an authorization event which will be fired. A value of + * null may be returned; in this case no authorization + * event will be fired. */ protected abstract AuthorizationEvent doAuthorize(SignedContent content, Object context); /** * Return the current status of the Authorization system. * - * @return A value of {@link AuthorizationStatus#OK} or {@link AuthorizationStatus#ERROR} + * @return A value of {@link AuthorizationStatus#OK} or + * {@link AuthorizationStatus#ERROR} * @see AuthorizationStatus#OK * @see AuthorizationStatus#ERROR */ @@ -85,7 +91,8 @@ private void fireEvent(AuthorizationEvent event) { class AuthEventDispatcher implements EventDispatcher { @Override - public void dispatchEvent(AuthorizationListener eventListener, Object listenerObject, int eventAction, AuthorizationEvent eventObject) { + public void dispatchEvent(AuthorizationListener eventListener, Object listenerObject, int eventAction, + AuthorizationEvent eventObject) { eventListener.authorizationEvent(eventObject); } } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/provisional/service/security/AuthorizationEvent.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/provisional/service/security/AuthorizationEvent.java index 3798cb6b8ab..1db7d144679 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/provisional/service/security/AuthorizationEvent.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/provisional/service/security/AuthorizationEvent.java @@ -16,8 +16,9 @@ import org.eclipse.osgi.signedcontent.SignedContent; /** - * An event that is fired when an AuthorizationEngine implementation makes - * a decision. + * An event that is fired when an AuthorizationEngine implementation makes a + * decision. + * * @since 3.4 */ public class AuthorizationEvent { @@ -39,9 +40,10 @@ public class AuthorizationEvent { /** * Create a new AuthorizationEvent - * @param result - the result code - * @param content - the signed content - * @param context - operation specific context + * + * @param result - the result code + * @param content - the signed content + * @param context - operation specific context * @param severity - severity code */ public AuthorizationEvent(int result, SignedContent content, Object context, int severity) { @@ -53,6 +55,7 @@ public AuthorizationEvent(int result, SignedContent content, Object context, int /** * Get the result code + * * @return - the result code */ public int getResult() { @@ -61,6 +64,7 @@ public int getResult() { /** * get the severity + * * @return - the severity */ public int getSeverity() { @@ -69,6 +73,7 @@ public int getSeverity() { /** * Get the SignedContent object being evaluated + * * @return - SignedContent */ public SignedContent getSignedContent() { @@ -77,6 +82,7 @@ public SignedContent getSignedContent() { /** * Get the operation specific context + * * @return - context */ public Object getContext() { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/provisional/service/security/AuthorizationListener.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/provisional/service/security/AuthorizationListener.java index 4284fff2400..562127572d1 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/provisional/service/security/AuthorizationListener.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/provisional/service/security/AuthorizationListener.java @@ -16,8 +16,9 @@ import java.util.EventListener; /** - * A Listener interface for an authorization handler. Implementors - * should register as an OSGI service. + * A Listener interface for an authorization handler. Implementors should + * register as an OSGI service. + * * @since 3.4 */ public interface AuthorizationListener extends EventListener { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/provisional/service/security/AuthorizationStatus.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/provisional/service/security/AuthorizationStatus.java index b06088847b2..1fa4c8934cc 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/provisional/service/security/AuthorizationStatus.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/provisional/service/security/AuthorizationStatus.java @@ -24,14 +24,14 @@ public class AuthorizationStatus { /** - * This code means that the system is functioning normally - no bundles - * are currently experiencing authorization problems. + * This code means that the system is functioning normally - no bundles are + * currently experiencing authorization problems. */ public static final int OK = 0x00; /** - * This code means that there are bundles in the system that are being - * disabled due to authorization constraints. + * This code means that there are bundles in the system that are being disabled + * due to authorization constraints. */ public static final int ERROR = 0x01; diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/provisional/verifier/CertificateChain.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/provisional/verifier/CertificateChain.java index f4a9d562ee1..2b76cb419cf 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/provisional/verifier/CertificateChain.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/provisional/verifier/CertificateChain.java @@ -19,41 +19,47 @@ /** * This class represents a chain of certificates. *

- * EXPERIMENTAL. This class or interface has been added as - * part of a work in progress. There is no guarantee that this API will - * work or that it will remain the same. Please do not use this API without - * consulting with the equinox team. + * EXPERIMENTAL. This class or interface has been added as part + * of a work in progress. There is no guarantee that this API will work or that + * it will remain the same. Please do not use this API without consulting with + * the equinox team. *

*/ public interface CertificateChain { /** - * Returns the list of X500 distinguished names that make up the certificate chain. Each - * distinguished name is separated by a ';'. The first distinguished name is the signer - * and the last is the root Certificate Authority. - * @return the list of X500 distinguished names that make up the certificate chain + * Returns the list of X500 distinguished names that make up the certificate + * chain. Each distinguished name is separated by a ';'. The first distinguished + * name is the signer and the last is the root Certificate Authority. + * + * @return the list of X500 distinguished names that make up the certificate + * chain */ public String getChain(); /** * Retruns all certificates in this certificate chain + * * @return all certificates in this certificate chain */ public Certificate[] getCertificates(); /** * Returns the first certificate of the certificate chain + * * @return the first certificate of the certificate chain */ public Certificate getSigner(); /** * Returns the root certificate of the certificate chain + * * @return the foot certificate of the certificate chain */ public Certificate getRoot(); /** * Returns true if this certificate chain is trusted + * * @return true if this certificate chain is trusted */ boolean isTrusted(); @@ -61,7 +67,7 @@ public interface CertificateChain { /** * Return the signing time for this signer. * - * @return null if there is a signing time for this signer null otherwise + * @return null if there is a signing time for this signer null otherwise */ public Date getSigningTime(); } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/provisional/verifier/CertificateTrustAuthority.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/provisional/verifier/CertificateTrustAuthority.java index ec126b74730..6a307e95c85 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/provisional/verifier/CertificateTrustAuthority.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/provisional/verifier/CertificateTrustAuthority.java @@ -18,14 +18,17 @@ import java.security.cert.CertificateException; /** - * A CertificateTrustAuthority is used to check if certificate chains are trusted. + * A CertificateTrustAuthority is used to check if certificate chains are + * trusted. * */ public interface CertificateTrustAuthority { /** - * Determines if the certificates are trusted. This method will throw a - * CertificateException if the specified certificate chain is not trusted. + * Determines if the certificates are trusted. This method will throw a + * CertificateException if the specified certificate chain is not + * trusted. + * * @param certChain a chain of certificates * @throws CertificateException if the certficates are not trusted */ diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/provisional/verifier/CertificateVerifier.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/provisional/verifier/CertificateVerifier.java index b8170bce2e8..494dace9547 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/provisional/verifier/CertificateVerifier.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/provisional/verifier/CertificateVerifier.java @@ -18,13 +18,13 @@ /** * A certificate verifier is used to verify the authenticity of a signed - * repository. A certificate verifier is created using a + * repository. A certificate verifier is created using a * {@link CertificateVerifierFactory}. *

- * EXPERIMENTAL. This class or interface has been added as - * part of a work in progress. There is no guarantee that this API will - * work or that it will remain the same. Please do not use this API without - * consulting with the equinox team. + * EXPERIMENTAL. This class or interface has been added as part + * of a work in progress. There is no guarantee that this API will work or that + * it will remain the same. Please do not use this API without consulting with + * the equinox team. *

*/ public interface CertificateVerifier { @@ -39,23 +39,27 @@ public interface CertificateVerifier { public void checkContent() throws CertificateException, CertificateExpiredException, SignatureException; /** - * Verifies the content of the repository. An array is returned with the entry names - * which are corrupt. If no entries are corrupt then an empty array is returned. - * @return An array of entry names which are corrupt. An empty array is returned if the - * repository is not corrupt or if the repository is not signed. + * Verifies the content of the repository. An array is returned with the entry + * names which are corrupt. If no entries are corrupt then an empty array is + * returned. + * + * @return An array of entry names which are corrupt. An empty array is returned + * if the repository is not corrupt or if the repository is not signed. */ public String[] verifyContent(); /** * Returns true if the repository is signed + * * @return true if the repository is signed */ public boolean isSigned(); /** - * Returns all certificate chains of the repository. All certificate chains - * are returned whether they are trusted or not. If the repository is not signed + * Returns all certificate chains of the repository. All certificate chains are + * returned whether they are trusted or not. If the repository is not signed * then an empty array is returned. + * * @return all certificate chains of the repository */ public CertificateChain[] getChains(); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/provisional/verifier/CertificateVerifierFactory.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/provisional/verifier/CertificateVerifierFactory.java index c03e470930b..cccfa4a662e 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/provisional/verifier/CertificateVerifierFactory.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/provisional/verifier/CertificateVerifierFactory.java @@ -20,15 +20,16 @@ /** * A factory used to create certificate verifiers. *

- * EXPERIMENTAL. This class or interface has been added as - * part of a work in progress. There is no guarantee that this API will - * work or that it will remain the same. Please do not use this API without - * consulting with the equinox team. + * EXPERIMENTAL. This class or interface has been added as part + * of a work in progress. There is no guarantee that this API will work or that + * it will remain the same. Please do not use this API without consulting with + * the equinox team. *

*/ public interface CertificateVerifierFactory { /** * Creates a certificate verifier for the specified content of a repository + * * @param content the content of the repository * @return a certificate verifier for the specified content of a repository * @throws IOException if an IO exception occurs while reading the repository @@ -37,9 +38,11 @@ public interface CertificateVerifierFactory { /** * Returns a certificate verifier for the specified bundle. + * * @param bundle the bundle to get a verifier for * @return a certificate verifier for the specified bundle. - * @throws IOException if an IO exception occurs while reading the bundle content + * @throws IOException if an IO exception occurs while reading the bundle + * content */ public CertificateVerifier getVerifier(Bundle bundle) throws IOException; } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/service/security/KeyStoreTrustEngine.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/service/security/KeyStoreTrustEngine.java index 47764b5ac0c..2d15b6368ca 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/service/security/KeyStoreTrustEngine.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/service/security/KeyStoreTrustEngine.java @@ -47,11 +47,13 @@ public class KeyStoreTrustEngine extends TrustEngine { /** * Create a new KeyStoreTrustEngine that is backed by a KeyStore - * @param path - path to the keystore - * @param type - the type of keystore at the path location + * + * @param path - path to the keystore + * @param type - the type of keystore at the path location * @param password - the password required to unlock the keystore */ - public KeyStoreTrustEngine(String path, String type, char[] password, String name, SignedBundleHook signedBundleHook) { //TODO: This should be a *CallbackHandler* + public KeyStoreTrustEngine(String path, String type, char[] password, String name, + SignedBundleHook signedBundleHook) { // TODO: This should be a *CallbackHandler* this.path = path; this.type = type; this.password = password; @@ -61,6 +63,7 @@ public KeyStoreTrustEngine(String path, String type, char[] password, String nam /** * Return the type + * * @return type - the type for the KeyStore being managed */ private String getType() { @@ -69,6 +72,7 @@ private String getType() { /** * Return the path + * * @return - the path for the KeyStore being managed */ private String getPath() { @@ -77,6 +81,7 @@ private String getPath() { /** * Return the password + * * @return password - the password as a char[] */ private char[] getPassword() { @@ -85,6 +90,7 @@ private char[] getPassword() { /** * Return the KeyStore managed + * * @return The KeyStore instance, initialized and loaded * @throws KeyStoreException */ @@ -98,7 +104,7 @@ private synchronized KeyStore getKeyStore() throws IOException, GeneralSecurityE try { in.close(); } catch (IOException e) { - //ignore secondary failure + // ignore secondary failure } } } @@ -146,9 +152,11 @@ else if (rootCert != certChain[i]) { if (alias != null) return store.getCertificate(alias); } - // if we have reached the end and the last cert is not found to be a valid root CA + // if we have reached the end and the last cert is not found to be a valid root + // CA // then we need to back off the root CA and try to find an alternative - if (certChain.length > 1 && i == certChain.length - 1 && certChain[i - 1] instanceof X509Certificate) + if (certChain.length > 1 && i == certChain.length - 1 + && certChain[i - 1] instanceof X509Certificate) return findAlternativeRoot((X509Certificate) certChain[i - 1], store); } } @@ -163,11 +171,14 @@ else if (rootCert != certChain[i]) { return null; } - private Certificate findAlternativeRoot(X509Certificate cert, KeyStore store) throws InvalidKeyException, KeyStoreException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException, CertificateException { + private Certificate findAlternativeRoot(X509Certificate cert, KeyStore store) + throws InvalidKeyException, KeyStoreException, NoSuchAlgorithmException, NoSuchProviderException, + SignatureException, CertificateException { synchronized (store) { for (Enumeration e = store.aliases(); e.hasMoreElements();) { Certificate nextCert = store.getCertificate(e.nextElement()); - if (nextCert instanceof X509Certificate && ((X509Certificate) nextCert).getSubjectDN().equals(cert.getIssuerDN())) { + if (nextCert instanceof X509Certificate + && ((X509Certificate) nextCert).getSubjectDN().equals(cert.getIssuerDN())) { cert.verify(nextCert.getPublicKey()); return nextCert; } @@ -304,21 +315,22 @@ private void saveStore(KeyStore store, OutputStream os) throws IOException, Gene } /** - * Closes a stream and ignores any resulting exception. This is useful - * when doing stream cleanup in a finally block where secondary exceptions - * are not worth logging. + * Closes a stream and ignores any resulting exception. This is useful when + * doing stream cleanup in a finally block where secondary exceptions are not + * worth logging. */ private void safeClose(OutputStream out) { try { if (out != null) out.close(); } catch (IOException e) { - //ignore + // ignore } } /** * Get an input stream for the KeyStore managed + * * @return inputstream - the stream * @throws KeyStoreException */ @@ -328,6 +340,7 @@ private InputStream getInputStream() throws IOException { /** * Get an output stream for the KeyStore managed + * * @return outputstream - the stream * @throws KeyStoreException */ diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/FilteredServiceListener.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/FilteredServiceListener.java index 88614f84c03..8dd8bd4126d 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/FilteredServiceListener.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/FilteredServiceListener.java @@ -50,25 +50,29 @@ class FilteredServiceListener implements ServiceListener, ListenerHook.ListenerI /** * Constructor. * - * @param context The bundle context of the bundle which added the specified service listener. - * @param filterstring The filter string specified when this service listener was added. - * @param listener The service listener object. + * @param context The bundle context of the bundle which added the + * specified service listener. + * @param filterstring The filter string specified when this service listener + * was added. + * @param listener The service listener object. * @exception InvalidSyntaxException if the filter is invalid. */ - FilteredServiceListener(final BundleContextImpl context, final ServiceListener listener, final String filterstring) throws InvalidSyntaxException { + FilteredServiceListener(final BundleContextImpl context, final ServiceListener listener, final String filterstring) + throws InvalidSyntaxException { this.debug = context.getContainer().getConfiguration().getDebug(); this.unfiltered = (listener instanceof UnfilteredServiceListener); if (filterstring == null) { this.filter = null; this.objectClass = null; } else { - FilterImpl filterImpl = FilterImpl.newInstance(filterstring, context.getContainer().getConfiguration().getDebug().DEBUG_FILTER); + FilterImpl filterImpl = FilterImpl.newInstance(filterstring, + context.getContainer().getConfiguration().getDebug().DEBUG_FILTER); String clazz = filterImpl.getRequiredObjectClass(); if (unfiltered || (clazz == null)) { this.objectClass = null; this.filter = filterImpl; } else { - this.objectClass = clazz.intern(); /*intern the name for future identity comparison */ + this.objectClass = clazz.intern(); /* intern the name for future identity comparison */ // a filter with no children and non-null requiredObjectClass is a simple // filter; // e.g. (objectClass=SomeService) @@ -90,24 +94,29 @@ class FilteredServiceListener implements ServiceListener, ListenerHook.ListenerI public void serviceChanged(ServiceEvent event) { ServiceReferenceImpl reference = (ServiceReferenceImpl) event.getServiceReference(); - // first check if we can short circuit the filter match if the required objectClass does not match the event + // first check if we can short circuit the filter match if the required + // objectClass does not match the event objectClassCheck: if (objectClass != null) { String[] classes = reference.getClasses(); int size = classes.length; for (int i = 0; i < size; i++) { - if (classes[i] == objectClass) // objectClass strings have previously been interned for identity comparison + if (classes[i] == objectClass) // objectClass strings have previously been interned for identity + // comparison break objectClassCheck; } - return; // no class in this event matches a required part of the filter; we do not need to deliver this event + return; // no class in this event matches a required part of the filter; we do not need + // to deliver this event } - // TODO could short circuit service.id filters as well since the id is constant for a registration. + // TODO could short circuit service.id filters as well since the id is constant + // for a registration. if (!ServiceRegistry.hasListenServicePermission(event, context)) return; if (debug.DEBUG_EVENTS) { String listenerName = this.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(this)); //$NON-NLS-1$ - Debug.println("filterServiceEvent(" + listenerName + ", \"" + getFilter() + "\", " + reference.getRegistration().getProperties() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + Debug.println("filterServiceEvent(" + listenerName + ", \"" + getFilter() + "\", " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + + reference.getRegistration().getProperties() + ")"); //$NON-NLS-1$ } event = filterMatch(event); @@ -116,7 +125,8 @@ public void serviceChanged(ServiceEvent event) { } if (allservices || ServiceRegistry.isAssignableTo(context, objectClass, reference)) { if (debug.DEBUG_EVENTS) { - String listenerName = listener.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(listener)); //$NON-NLS-1$ + String listenerName = listener.getClass().getName() + "@" //$NON-NLS-1$ + + Integer.toHexString(System.identityHashCode(listener)); Debug.println("dispatchFilteredServiceEvent(" + listenerName + ")"); //$NON-NLS-1$ //$NON-NLS-2$ } @@ -125,11 +135,13 @@ public void serviceChanged(ServiceEvent event) { } /** - * Returns a service event that should be delivered to the listener based on the filter evaluation. - * This may result in a service event of type MODIFIED_ENDMATCH. + * Returns a service event that should be delivered to the listener based on the + * filter evaluation. This may result in a service event of type + * MODIFIED_ENDMATCH. * * @param delivered The service event delivered by the framework. - * @return The event to be delivered or null if no event is to be delivered to the listener. + * @return The event to be delivered or null if no event is to be delivered to + * the listener. */ private ServiceEvent filterMatch(ServiceEvent delivered) { boolean modified = delivered.getType() == ServiceEvent.MODIFIED; @@ -162,11 +174,13 @@ public String toString() { if (filterString == null) { filterString = ""; //$NON-NLS-1$ } - return listener.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(listener)) + filterString; //$NON-NLS-1$ + return listener.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(listener)) //$NON-NLS-1$ + + filterString; } /** * Return the bundle context for the ListenerHook. + * * @return The context of the bundle which added the service listener. * @see org.osgi.framework.hooks.service.ListenerHook.ListenerInfo#getBundleContext() */ @@ -177,8 +191,9 @@ public BundleContext getBundleContext() { /** * Return the filter string for the ListenerHook. - * @return The filter string with which the listener was added. This may - * be null if the listener was added without a filter. + * + * @return The filter string with which the listener was added. This may be + * null if the listener was added without a filter. * @see org.osgi.framework.hooks.service.ListenerHook.ListenerInfo#getFilter() */ @Override @@ -190,11 +205,10 @@ public String getFilter() { } /** - * Return the state of the listener for this addition and removal life - * cycle. Initially this method will return false - * indicating the listener has been added but has not been removed. - * After the listener has been removed, this method must always return - * true. + * Return the state of the listener for this addition and removal life cycle. + * Initially this method will return false indicating the listener + * has been added but has not been removed. After the listener has been removed, + * this method must always return true. * * @return false if the listener has not been been removed, * true otherwise. @@ -213,8 +227,9 @@ void markRemoved() { /** * Returns an objectClass filter string for the specified class name. - * @return A filter string for the specified class name or null if the - * specified class name is null. + * + * @return A filter string for the specified class name or null if + * the specified class name is null. */ private static String getObjectClassFilterString(String className) { if (className == null) { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/HookContext.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/HookContext.java index de045bd59b5..6dcbad30584 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/HookContext.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/HookContext.java @@ -18,9 +18,9 @@ /** * A callable hook that contains the context for call a collection of hooks. - * This is effectively a "closure" for calling each hook. The hook context - * must know the type of the hook object, the method to call on the hook - * as well as all the parameters which need to be passed to the hook method. + * This is effectively a "closure" for calling each hook. The hook context must + * know the type of the hook object, the method to call on the hook as well as + * all the parameters which need to be passed to the hook method. * */ @FunctionalInterface @@ -29,9 +29,9 @@ public interface HookContext { /** * Call the specified hook. * - * @param hook The hook object to call. The hook object must be of the type - * supported by this hook context. If it is not, then this method will - * simply return. + * @param hook The hook object to call. The hook object must be of + * the type supported by this hook context. If it is + * not, then this method will simply return. * @param hookRegistration the registration for the hook object * @throws Exception An exception thrown by the hook object. */ @@ -39,6 +39,7 @@ public interface HookContext { /** * Returns true if the given registration should be skipped. + * * @param hookRegistration the registration to check * @return true if the given registration should be skipped. */ diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ModifiedServiceEvent.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ModifiedServiceEvent.java index 4ae46dc54d5..d66b244e22a 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ModifiedServiceEvent.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ModifiedServiceEvent.java @@ -28,9 +28,10 @@ class ModifiedServiceEvent extends ServiceEvent { private final Map previousProperties; /** - * Create a ServiceEvent containing the service properties prior to modification. + * Create a ServiceEvent containing the service properties prior to + * modification. * - * @param reference Reference to service with modified properties. + * @param reference Reference to service with modified properties. * @param previousProperties Service properties prior to modification. */ ModifiedServiceEvent(ServiceReference reference, Map previousProperties) { @@ -59,16 +60,15 @@ ServiceEvent getModifiedEndMatchEvent() { } /** - * Return if the specified filter matches the previous service - * properties. + * Return if the specified filter matches the previous service properties. * - * @param filter The filer to evaluate using the previous service - * properties. + * @param filter The filer to evaluate using the previous service properties. * @return True is the filter matches the previous service properties. */ boolean matchPreviousProperties(Filter filter) { - /* We use matches here since ServiceProperties already - * does case insensitive lookup. + /* + * We use matches here since ServiceProperties already does case insensitive + * lookup. */ return filter.matches(previousProperties); } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/PrototypeServiceFactoryUse.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/PrototypeServiceFactoryUse.java index 3a7fc06f45d..732213fca3f 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/PrototypeServiceFactoryUse.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/PrototypeServiceFactoryUse.java @@ -26,8 +26,8 @@ import org.osgi.framework.ServiceRegistration; /** - * This class represents the use of a service by a bundle. One is created for each - * service acquired by a bundle. + * This class represents the use of a service by a bundle. One is created for + * each service acquired by a bundle. * *

* This class manages a prototype service factory. @@ -35,15 +35,18 @@ * @ThreadSafe */ public class PrototypeServiceFactoryUse extends ServiceFactoryUse { - /** Service objects returned by PrototypeServiceFactory.getService() and their use count. */ + /** + * Service objects returned by PrototypeServiceFactory.getService() and their + * use count. + */ /* @GuardedBy("getLock()") */ private final Map serviceObjects; /** * Constructs a service use encapsulating the service object. * - * @param context bundle getting the service - * @param registration ServiceRegistration of the service + * @param context bundle getting the service + * @param registration ServiceRegistration of the service */ PrototypeServiceFactoryUse(BundleContextImpl context, ServiceRegistrationImpl registration) { super(context, registration); @@ -86,8 +89,8 @@ S newServiceObject() { * * @param service The service object to release. * @return true if the service was released; otherwise false. - * @throws IllegalArgumentException If the specified service was not - * provided by this object. + * @throws IllegalArgumentException If the specified service was not provided by + * this object. */ /* @GuardedBy("getLock()") */ @Override @@ -99,7 +102,7 @@ boolean releaseServiceObject(final S service) { if (debug.DEBUG_SERVICES) { Debug.println( '[' + Thread.currentThread().getName() + "] ungetService[PSfactory=" + registration.getBundle() //$NON-NLS-1$ - + "](" + context.getBundleImpl() + "," + registration + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + + "](" + context.getBundleImpl() + "," + registration + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } AtomicInteger useCount = serviceObjects.get(service); if (useCount.decrementAndGet() < 1) { @@ -114,8 +117,9 @@ boolean releaseServiceObject(final S service) { * *

    *
  1. The bundle's use count for this service is set to zero. - *
  2. The {@link PrototypeServiceFactory#ungetService(Bundle, ServiceRegistration, Object)} method - * is called to release the service object for the bundle. + *
  3. The + * {@link PrototypeServiceFactory#ungetService(Bundle, ServiceRegistration, Object)} + * method is called to release the service object for the bundle. *
*/ /* @GuardedBy("getLock()") */ @@ -135,7 +139,8 @@ void release() { /** * Is this service use using any services? * - * @return true if no services are being used and this service use can be discarded. + * @return true if no services are being used and this service use can be + * discarded. */ /* @GuardedBy("getLock()") */ @Override diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ServiceConsumer.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ServiceConsumer.java index 1e62ea934d5..221a80c648b 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ServiceConsumer.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ServiceConsumer.java @@ -17,8 +17,8 @@ /** * Closure to allow sharing the same code for getting and ungetting a service. * The {@link #prototypeConsumer} closure must be used for calls from - * ServiceObjects and the {@link #singletonConsumer} closure must be used - * for calls from BundleContext. + * ServiceObjects and the {@link #singletonConsumer} closure must be used for + * calls from BundleContext. * * The closure instance calls the correct method on the specified ServiceUse * object for the current service consumer type. @@ -65,7 +65,7 @@ public boolean ungetService(ServiceUse use, S service) { /** * Unget the service for the consumer. * - * @param use Service Use object to unget the service from. + * @param use Service Use object to unget the service from. * @param service The Service to unget. * @return true if the service was ungotten, false otherwise. */ diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ServiceFactoryUse.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ServiceFactoryUse.java index 45055c740f5..1f7faa43ed9 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ServiceFactoryUse.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ServiceFactoryUse.java @@ -27,8 +27,8 @@ import org.osgi.framework.ServiceRegistration; /** - * This class represents the use of a service by a bundle. One is created for each - * service acquired by a bundle. + * This class represents the use of a service by a bundle. One is created for + * each service acquired by a bundle. * *

* This class manages a service factory. @@ -36,21 +36,24 @@ * @ThreadSafe */ public class ServiceFactoryUse extends ServiceUse { - /** ServiceFactory object */ + /** ServiceFactory object */ final ServiceFactory factory; /** Service object returned by ServiceFactory.getService() */ /* @GuardedBy("getLock()") */ private S cachedService; - /** true if we are calling the factory getService method. Used to detect recursion. */ + /** + * true if we are calling the factory getService method. Used to detect + * recursion. + */ /* @GuardedBy("getLock()") */ private boolean factoryInUse; /** * Constructs a service use encapsulating the service factory. * - * @param context bundle getting the service - * @param registration ServiceRegistration of the service + * @param context bundle getting the service + * @param registration ServiceRegistration of the service */ ServiceFactoryUse(BundleContextImpl context, ServiceRegistrationImpl registration) { super(context, registration); @@ -64,22 +67,20 @@ public class ServiceFactoryUse extends ServiceUse { /** * Get a service's service object and increment the use count. * - *

The following steps are followed to get the service object: + *

+ * The following steps are followed to get the service object: *

    *
  1. The use count is incremented by one. - *
  2. If the use count is now one, - * the {@link ServiceFactory#getService(Bundle, ServiceRegistration)} method - * is called to create a service object for the context bundle. - * This service object is cached. - * While the use count is greater than zero, - * subsequent calls to get the service object - * will return the cached service object. - *
    If the service object returned by the {@link ServiceFactory} - * is not an instanceof - * all the classes named when the service was registered or - * the {@link ServiceFactory} throws an exception, - * null is returned and a - * {@link FrameworkEvent} of type {@link FrameworkEvent#ERROR} is broadcast. + *
  3. If the use count is now one, the + * {@link ServiceFactory#getService(Bundle, ServiceRegistration)} method is + * called to create a service object for the context bundle. This service object + * is cached. While the use count is greater than zero, subsequent calls to get + * the service object will return the cached service object.
    + * If the service object returned by the {@link ServiceFactory} is not an + * instanceof all the classes named when the service was registered + * or the {@link ServiceFactory} throws an exception, null is + * returned and a {@link FrameworkEvent} of type {@link FrameworkEvent#ERROR} is + * broadcast. *
  4. The service object is returned. *
* @@ -104,8 +105,11 @@ S getService() { Debug.println(factory + ".getService() recursively called."); //$NON-NLS-1$ } - ServiceException se = new ServiceException(NLS.bind(Msg.SERVICE_FACTORY_RECURSION, factory.getClass().getName(), "getService"), ServiceException.FACTORY_RECURSION); //$NON-NLS-1$ - context.getContainer().getEventPublisher().publishFrameworkEvent(FrameworkEvent.WARNING, registration.getBundle(), se); + ServiceException se = new ServiceException( + NLS.bind(Msg.SERVICE_FACTORY_RECURSION, factory.getClass().getName(), "getService"), //$NON-NLS-1$ + ServiceException.FACTORY_RECURSION); + context.getContainer().getEventPublisher().publishFrameworkEvent(FrameworkEvent.WARNING, + registration.getBundle(), se); return null; } factoryInUse = true; @@ -131,14 +135,17 @@ S getService() { *

* Decrements the use count if the service was being used. * - *

The following steps are followed to unget the service object: + *

+ * The following steps are followed to unget the service object: *

    *
  1. If the use count is zero, return. *
  2. The use count is decremented by one. *
  3. If the use count is non zero, return. - *
  4. The {@link ServiceFactory#ungetService(Bundle, ServiceRegistration, Object)} method - * is called to release the service object for the context bundle. + *
  5. The + * {@link ServiceFactory#ungetService(Bundle, ServiceRegistration, Object)} + * method is called to release the service object for the context bundle. *
+ * * @return true if the service was ungotten; otherwise false. */ /* @GuardedBy("getLock()") */ @@ -170,8 +177,9 @@ boolean ungetService() { * *
    *
  1. The bundle's use count for this service is set to zero. - *
  2. The {@link ServiceFactory#ungetService(Bundle, ServiceRegistration, Object)} method - * is called to release the service object for the bundle. + *
  3. The + * {@link ServiceFactory#ungetService(Bundle, ServiceRegistration, Object)} + * method is called to release the service object for the bundle. *
*/ /* @GuardedBy("getLock()") */ @@ -204,7 +212,7 @@ S getCachedService() { } /** - * Call the service factory to get the service. + * Call the service factory to get the service. * * @return The service returned by the factory or null if there was an error. */ @@ -225,8 +233,11 @@ public S run() { } // allow the adaptor to handle this unexpected error context.getContainer().handleRuntimeError(t); - ServiceException se = new ServiceException(NLS.bind(Msg.SERVICE_FACTORY_EXCEPTION, factory.getClass().getName(), "getService"), ServiceException.FACTORY_EXCEPTION, t); //$NON-NLS-1$ - context.getContainer().getEventPublisher().publishFrameworkEvent(FrameworkEvent.ERROR, registration.getBundle(), se); + ServiceException se = new ServiceException( + NLS.bind(Msg.SERVICE_FACTORY_EXCEPTION, factory.getClass().getName(), "getService"), //$NON-NLS-1$ + ServiceException.FACTORY_EXCEPTION, t); + context.getContainer().getEventPublisher().publishFrameworkEvent(FrameworkEvent.ERROR, + registration.getBundle(), se); return null; } @@ -235,8 +246,11 @@ public S run() { Debug.println(factory + ".getService() returned null."); //$NON-NLS-1$ } - ServiceException se = new ServiceException(NLS.bind(Msg.SERVICE_OBJECT_NULL_EXCEPTION, factory.getClass().getName()), ServiceException.FACTORY_ERROR); - context.getContainer().getEventPublisher().publishFrameworkEvent(FrameworkEvent.WARNING, registration.getBundle(), se); + ServiceException se = new ServiceException( + NLS.bind(Msg.SERVICE_OBJECT_NULL_EXCEPTION, factory.getClass().getName()), + ServiceException.FACTORY_ERROR); + context.getContainer().getEventPublisher().publishFrameworkEvent(FrameworkEvent.WARNING, + registration.getBundle(), se); return null; } @@ -246,21 +260,20 @@ public S run() { if (debug.DEBUG_SERVICES) { Debug.println("Service object is not an instanceof " + invalidService); //$NON-NLS-1$ } - ServiceException se = new ServiceException( - NLS.bind(Msg.SERVICE_FACTORY_NOT_INSTANCEOF_CLASS_EXCEPTION, - new Object[] { factory.getClass().getName(), service.getClass().getName(), - invalidService }), + ServiceException se = new ServiceException(NLS.bind(Msg.SERVICE_FACTORY_NOT_INSTANCEOF_CLASS_EXCEPTION, + new Object[] { factory.getClass().getName(), service.getClass().getName(), invalidService }), ServiceException.FACTORY_ERROR); - context.getContainer().getEventPublisher().publishFrameworkEvent(FrameworkEvent.ERROR, registration.getBundle(), se); + context.getContainer().getEventPublisher().publishFrameworkEvent(FrameworkEvent.ERROR, + registration.getBundle(), se); return null; } return service; } /** - * Call the service factory to unget the service. + * Call the service factory to unget the service. * - * @param service The service object to pass to the factory. + * @param service The service object to pass to the factory. */ /* @GuardedBy("getLock()") */ void factoryUngetService(final S service) { @@ -278,8 +291,11 @@ public Void run() { Debug.printStackTrace(t); } - ServiceException se = new ServiceException(NLS.bind(Msg.SERVICE_FACTORY_EXCEPTION, factory.getClass().getName(), "ungetService"), ServiceException.FACTORY_EXCEPTION, t); //$NON-NLS-1$ - context.getContainer().getEventPublisher().publishFrameworkEvent(FrameworkEvent.ERROR, registration.getBundle(), se); + ServiceException se = new ServiceException( + NLS.bind(Msg.SERVICE_FACTORY_EXCEPTION, factory.getClass().getName(), "ungetService"), //$NON-NLS-1$ + ServiceException.FACTORY_EXCEPTION, t); + context.getContainer().getEventPublisher().publishFrameworkEvent(FrameworkEvent.ERROR, + registration.getBundle(), se); } } } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ServiceObjectsImpl.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ServiceObjectsImpl.java index 6b924272d75..f71a9aab389 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ServiceObjectsImpl.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ServiceObjectsImpl.java @@ -32,8 +32,8 @@ public class ServiceObjectsImpl implements ServiceObjects { /** * Constructs a service objects encapsulating the service object. * - * @param user bundle getting the service - * @param registration ServiceRegistration of the service + * @param user bundle getting the service + * @param registration ServiceRegistration of the service */ ServiceObjectsImpl(BundleContextImpl user, ServiceRegistrationImpl registration) { this.registration = registration; @@ -42,26 +42,26 @@ public class ServiceObjectsImpl implements ServiceObjects { } /** - * Returns a service object for the {@link #getServiceReference() - * referenced} service. + * Returns a service object for the {@link #getServiceReference() referenced} + * service. * *

* This {@code ServiceObjects} object can be used to obtain multiple service * objects for the referenced service if the service has - * {@link Constants#SCOPE_PROTOTYPE prototype} scope. If the referenced - * service has {@link Constants#SCOPE_SINGLETON singleton} or - * {@link Constants#SCOPE_BUNDLE bundle} scope, this method behaves the same - * as calling the {@link BundleContext#getService(ServiceReference)} method - * for the referenced service. That is, only one, use-counted service object - * is available from this {@link ServiceObjects} object. + * {@link Constants#SCOPE_PROTOTYPE prototype} scope. If the referenced service + * has {@link Constants#SCOPE_SINGLETON singleton} or + * {@link Constants#SCOPE_BUNDLE bundle} scope, this method behaves the same as + * calling the {@link BundleContext#getService(ServiceReference)} method for the + * referenced service. That is, only one, use-counted service object is + * available from this {@link ServiceObjects} object. * *

- * This method will always return {@code null} when the referenced service - * has been unregistered. + * This method will always return {@code null} when the referenced service has + * been unregistered. * *

- * For a prototype scope service, the following steps are required to get - * the service object: + * For a prototype scope service, the following steps are required to get the + * service object: *

    *
  1. If the referenced service has been unregistered, {@code null} is * returned.
  2. @@ -69,21 +69,21 @@ public class ServiceObjectsImpl implements ServiceObjects { * {@link PrototypeServiceFactory#getService(Bundle, ServiceRegistration)} * method is called to create a service object for the caller. *
  3. If the service object returned by the {@code PrototypeServiceFactory} - * object is {@code null}, not an {@code instanceof} all the classes named - * when the service was registered or the {@code PrototypeServiceFactory} - * object throws an exception, {@code null} is returned and a Framework - * event of type {@link FrameworkEvent#ERROR} containing a - * {@link ServiceException} describing the error is fired.
  4. + * object is {@code null}, not an {@code instanceof} all the classes named when + * the service was registered or the {@code PrototypeServiceFactory} object + * throws an exception, {@code null} is returned and a Framework event of type + * {@link FrameworkEvent#ERROR} containing a {@link ServiceException} describing + * the error is fired. *
  5. The service object is returned.
  6. *
* - * @return A service object for the referenced service or {@code null} if - * the service is not registered, the service object returned by a - * {@code ServiceFactory} does not implement the classes under which - * it was registered or the {@code ServiceFactory} threw an - * exception. + * @return A service object for the referenced service or {@code null} if the + * service is not registered, the service object returned by a + * {@code ServiceFactory} does not implement the classes under which it + * was registered or the {@code ServiceFactory} threw an exception. * @throws IllegalStateException If the BundleContext used to create this - * {@code ServiceObjects} object is no longer valid. + * {@code ServiceObjects} object is no longer + * valid. * @see #ungetService(Object) */ @Override @@ -93,22 +93,22 @@ public S getService() { } /** - * Releases a service object for the {@link #getServiceReference() - * referenced} service. + * Releases a service object for the {@link #getServiceReference() referenced} + * service. * *

* This {@code ServiceObjects} object can be used to obtain multiple service * objects for the referenced service if the service has - * {@link Constants#SCOPE_PROTOTYPE prototype} scope. If the referenced - * service has {@link Constants#SCOPE_SINGLETON singleton} or - * {@link Constants#SCOPE_BUNDLE bundle} scope, this method behaves the same - * as calling the {@link BundleContext#ungetService(ServiceReference)} - * method for the referenced service. That is, only one, use-counted service - * object is available from this {@link ServiceObjects} object. + * {@link Constants#SCOPE_PROTOTYPE prototype} scope. If the referenced service + * has {@link Constants#SCOPE_SINGLETON singleton} or + * {@link Constants#SCOPE_BUNDLE bundle} scope, this method behaves the same as + * calling the {@link BundleContext#ungetService(ServiceReference)} method for + * the referenced service. That is, only one, use-counted service object is + * available from this {@link ServiceObjects} object. * *

- * For a prototype scope service, the following steps are required to - * release the service object: + * For a prototype scope service, the following steps are required to release + * the service object: *

    *
  1. If the referenced service has been unregistered, this method returns * without doing anything.
  2. @@ -118,15 +118,16 @@ public S getService() { *
* *

- * The specified service object must no longer be used and all references to - * it should be destroyed after calling this method. + * The specified service object must no longer be used and all references to it + * should be destroyed after calling this method. * * @param service A service object previously provided by this - * {@code ServiceObjects} object. - * @throws IllegalStateException If the BundleContext used to create this - * {@code ServiceObjects} object is no longer valid. - * @throws IllegalArgumentException If the specified service was not - * provided by this {@code ServiceObjects} object. + * {@code ServiceObjects} object. + * @throws IllegalStateException If the BundleContext used to create this + * {@code ServiceObjects} object is no longer + * valid. + * @throws IllegalArgumentException If the specified service was not provided by + * this {@code ServiceObjects} object. * @see #getService() */ @Override diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ServiceProperties.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ServiceProperties.java index da04440cf26..6a2ce6c50af 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ServiceProperties.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ServiceProperties.java @@ -31,8 +31,8 @@ class ServiceProperties extends CaseInsensitiveDictionaryMap { * Create a properties object from a Dictionary. * * @param props The properties for this service. - * @throws IllegalArgumentException If a case-variants of a key are - * in the props parameter. + * @throws IllegalArgumentException If a case-variants of a key are in the props + * parameter. */ ServiceProperties(Dictionary props) { this(props, 0); @@ -43,8 +43,8 @@ class ServiceProperties extends CaseInsensitiveDictionaryMap { * * @param props The properties for this service. * @param extra Extra capacity in the map. - * @throws IllegalArgumentException If a case-variants of a key are - * in the props parameter. + * @throws IllegalArgumentException If a case-variants of a key are in the props + * parameter. */ ServiceProperties(Dictionary props, int extra) { super(initialCapacity((props == null) ? extra : props.size() + extra)); @@ -70,8 +70,8 @@ class ServiceProperties extends CaseInsensitiveDictionaryMap { * Create a properties object from a Map. * * @param props The properties for this service. - * @throws IllegalArgumentException If a case-variants of a key are - * in the props parameter. + * @throws IllegalArgumentException If a case-variants of a key are in the props + * parameter. */ ServiceProperties(Map props) { super(initialCapacity((props == null) ? 0 : props.size())); @@ -95,9 +95,8 @@ class ServiceProperties extends CaseInsensitiveDictionaryMap { /** * Attempt to clone the value if necessary and possible. * - * For some strange reason, you can test to see if an Object is - * Cloneable but you can't call the clone method since it is - * protected on Object! + * For some strange reason, you can test to see if an Object is Cloneable but + * you can't call the clone method since it is protected on Object! * * @param value object to be cloned. * @return cloned object or original object if we didn't clone it. diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ServiceReferenceImpl.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ServiceReferenceImpl.java index f04cf4270da..f0a39b1fa76 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ServiceReferenceImpl.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ServiceReferenceImpl.java @@ -32,8 +32,8 @@ * BundleContext.getServiceReference and * BundleContext.getServiceReferences methods. *

- * A ServiceReference object may be shared between bundles and - * can be used to examine the properties of the service and to get the service + * A ServiceReference object may be shared between bundles and can + * be used to examine the properties of the service and to get the service * object. *

* Every service registered in the Framework has a unique @@ -63,16 +63,16 @@ public class ServiceReferenceImpl implements ServiceReference { */ ServiceReferenceImpl(ServiceRegistrationImpl registration) { this.registration = registration; - /* We must not dereference registration in the constructor - * since it is "leaked" to us in the ServiceRegistrationImpl - * constructor. + /* + * We must not dereference registration in the constructor since it is "leaked" + * to us in the ServiceRegistrationImpl constructor. */ } /** - * Returns the property value to which the specified property key is mapped - * in the properties Dictionary object of the service - * referenced by this ServiceReference object. + * Returns the property value to which the specified property key is mapped in + * the properties Dictionary object of the service referenced by + * this ServiceReference object. * *

* Property keys are case-insensitive. @@ -80,12 +80,12 @@ public class ServiceReferenceImpl implements ServiceReference { *

* This method must continue to return property values after the service has * been unregistered. This is so references to unregistered services (for - * example, ServiceReference objects stored in the log) can - * still be interrogated. + * example, ServiceReference objects stored in the log) can still + * be interrogated. * * @param key The property key. - * @return The property value to which the key is mapped; null - * if there is no property named after the key. + * @return The property value to which the key is mapped; null if + * there is no property named after the key. */ @Override public Object getProperty(String key) { @@ -93,15 +93,14 @@ public Object getProperty(String key) { } /** - * Returns an array of the keys in the properties Dictionary - * object of the service referenced by this ServiceReference - * object. + * Returns an array of the keys in the properties Dictionary object + * of the service referenced by this ServiceReference object. * *

* This method will continue to return the keys after the service has been - * unregistered. This is so references to unregistered services (for - * example, ServiceReference objects stored in the log) can - * still be interrogated. + * unregistered. This is so references to unregistered services (for example, + * ServiceReference objects stored in the log) can still be + * interrogated. * *

* This method is case-preserving ; this means that every key in the @@ -127,8 +126,8 @@ public String[] getPropertyKeys() { * unregistered. * * @return The bundle that registered the service referenced by this - * ServiceReference object; null if - * that service has already been unregistered. + * ServiceReference object; null if that + * service has already been unregistered. * @see BundleContext#registerService(String[],Object,java.util.Dictionary) */ @Override @@ -138,13 +137,12 @@ public Bundle getBundle() { /** * Returns the bundles that are using the service referenced by this - * ServiceReference object. Specifically, this method returns - * the bundles whose usage count for that service is greater than zero. + * ServiceReference object. Specifically, this method returns the + * bundles whose usage count for that service is greater than zero. * - * @return An array of bundles whose usage count for the service referenced - * by this ServiceReference object is greater than - * zero; null if no bundles are currently using that - * service. + * @return An array of bundles whose usage count for the service referenced by + * this ServiceReference object is greater than zero; + * null if no bundles are currently using that service. * * @since 1.1 */ @@ -155,28 +153,28 @@ public Bundle[] getUsingBundles() { /** * Tests if the bundle that registered the service referenced by this - * ServiceReference and the specified bundle use the same - * source for the package of the specified class name. + * ServiceReference and the specified bundle use the same source + * for the package of the specified class name. *

* This method performs the following checks: *

    *
  1. Get the package name from the specified class name.
  2. *
  3. For the bundle that registered the service referenced by this - * ServiceReference (registrant bundle); find the source for - * the package. If no source is found then return true if the + * ServiceReference (registrant bundle); find the source for the + * package. If no source is found then return true if the * registrant bundle is equal to the specified bundle; otherwise return * false.
  4. - *
  5. If the package source of the registrant bundle is equal to the - * package source of the specified bundle then return true; - * otherwise return false.
  6. + *
  7. If the package source of the registrant bundle is equal to the package + * source of the specified bundle then return true; otherwise + * return false.
  8. *
* - * @param bundle The Bundle object to check. + * @param bundle The Bundle object to check. * @param className The class name to check. * @return true if the bundle which registered the service - * referenced by this ServiceReference and the - * specified bundle use the same source for the package of the - * specified class name. Otherwise false is returned. + * referenced by this ServiceReference and the specified + * bundle use the same source for the package of the specified class + * name. Otherwise false is returned. * * @since 1.3 */ @@ -191,23 +189,21 @@ public boolean isAssignableTo(Bundle bundle, String className) { * *

* If this ServiceReference and the specified - * ServiceReference have the same - * {@link Constants#SERVICE_ID service id} they are equal. This - * ServiceReference is less than the specified - * ServiceReference if it has a lower + * ServiceReference have the same {@link Constants#SERVICE_ID + * service id} they are equal. This ServiceReference is less than + * the specified ServiceReference if it has a lower * {@link Constants#SERVICE_RANKING service ranking} and greater if it has a - * higher service ranking. Otherwise, if this ServiceReference - * and the specified ServiceReference have the same + * higher service ranking. Otherwise, if this ServiceReference and + * the specified ServiceReference have the same * {@link Constants#SERVICE_RANKING service ranking}, this * ServiceReference is less than the specified - * ServiceReference if it has a higher - * {@link Constants#SERVICE_ID service id} and greater if it has a lower - * service id. + * ServiceReference if it has a higher {@link Constants#SERVICE_ID + * service id} and greater if it has a lower service id. * * @param object The ServiceReference to be compared. * @return Returns a negative integer, zero, or a positive integer if this - * ServiceReference is less than, equal to, or - * greater than the specified ServiceReference. + * ServiceReference is less than, equal to, or greater than + * the specified ServiceReference. * @since 1.4 */ @Override @@ -236,7 +232,7 @@ public int compareTo(Object object) { /** * Returns a hash code value for the object. * - * @return a hash code value for this object. + * @return a hash code value for this object. */ @Override public int hashCode() { @@ -246,9 +242,9 @@ public int hashCode() { /** * Indicates whether some other object is "equal to" this one. * - * @param obj the reference object with which to compare. - * @return true if this object is the same as the obj - * argument; false otherwise. + * @param obj the reference object with which to compare. + * @return true if this object is the same as the obj argument; + * false otherwise. */ @Override public boolean equals(Object obj) { @@ -297,22 +293,22 @@ String[] getClasses() { * Returns a copy of the properties of the service referenced by this * {@code ServiceReference} object. *

- * This method will continue to return the properties after the service has - * been unregistered. This is so references to unregistered services (for - * example, {@code ServiceReference} objects stored in the log) can still be + * This method will continue to return the properties after the service has been + * unregistered. This is so references to unregistered services (for example, + * {@code ServiceReference} objects stored in the log) can still be * interrogated. *

* The returned {@code Dictionary} object: *

    - *
  • Must map property values by using property keys in a - * case-insensitive manner.
  • - *
  • Must return property keys is a case-preserving manner. This - * means that the keys must have the same case as the corresponding key in - * the properties {@code Dictionary} that was passed to the + *
  • Must map property values by using property keys in a case-insensitive + * manner.
  • + *
  • Must return property keys is a case-preserving manner. This means + * that the keys must have the same case as the corresponding key in the + * properties {@code Dictionary} that was passed to the * {@link BundleContext#registerService(String[],Object,Dictionary)} or * {@link ServiceRegistration#setProperties(Dictionary)} methods.
  • - *
  • Is the property of the caller and can be modified by the caller but - * any changes are not reflected in the properties of the service. + *
  • Is the property of the caller and can be modified by the caller but any + * changes are not reflected in the properties of the service. * {@link ServiceRegistration#setProperties(Dictionary)} must be called to * modify the properties of the service.
  • *
@@ -341,6 +337,7 @@ private void checkAdaptPermission(Class adapterType) { if (sm == null) { return; } - sm.checkPermission(new AdaptPermission(adapterType.getName(), registration.getRegisteringBundle(), AdaptPermission.ADAPT)); + sm.checkPermission( + new AdaptPermission(adapterType.getName(), registration.getRegisteringBundle(), AdaptPermission.ADAPT)); } } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ServiceRegistrationImpl.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ServiceRegistrationImpl.java index f67041c6333..34c357032cd 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ServiceRegistrationImpl.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ServiceRegistrationImpl.java @@ -39,16 +39,18 @@ * A registered service. * * The framework returns a ServiceRegistration object when a - * {@link BundleContextImpl#registerService(String, Object, Dictionary) BundleContext.registerService} - * method is successful. This object is for the private use of - * the registering bundle and should not be shared with other bundles. - *

The ServiceRegistration object may be used to update the properties - * for the service or to unregister the service. + * {@link BundleContextImpl#registerService(String, Object, Dictionary) + * BundleContext.registerService} method is successful. This object is for the + * private use of the registering bundle and should not be shared with other + * bundles. + *

+ * The ServiceRegistration object may be used to update the properties for the + * service or to unregister the service. * - *

If the ServiceRegistration is garbage collected the framework may remove - * the service. This implies that if a - * bundle wants to keep its service registered, it should keep the - * ServiceRegistration object referenced. + *

+ * If the ServiceRegistration is garbage collected the framework may remove the + * service. This implies that if a bundle wants to keep its service registered, + * it should keep the ServiceRegistration object referenced. * * @ThreadSafe */ @@ -71,9 +73,9 @@ public class ServiceRegistrationImpl implements ServiceRegistration, Compa /* @GuardedBy("registrationLock") */ private ServiceReferenceImpl reference; - /** List of contexts using the service. - * List<BundleContextImpl>. - * */ + /** + * List of contexts using the service. List<BundleContextImpl>. + */ /* @GuardedBy("registrationLock") */ private final List contextsUsing; @@ -99,8 +101,8 @@ public class ServiceRegistrationImpl implements ServiceRegistration, Compa private static final int UNREGISTERED = 0x02; /** - * Construct a ServiceRegistration and register the service - * in the framework's service registry. + * Construct a ServiceRegistration and register the service in the framework's + * service registry. * */ ServiceRegistrationImpl(ServiceRegistry registry, BundleContextImpl context, String[] clazzes, S service) { @@ -114,10 +116,10 @@ public class ServiceRegistrationImpl implements ServiceRegistration, Compa synchronized (registrationLock) { this.state = REGISTERED; - /* We leak this from the constructor here, but it is ok - * because the ServiceReferenceImpl constructor only - * stores the value in a final field without - * otherwise using it. + /* + * We leak this from the constructor here, but it is ok because the + * ServiceReferenceImpl constructor only stores the value in a final field + * without otherwise using it. */ this.reference = new ServiceReferenceImpl<>(this); } @@ -147,24 +149,27 @@ void register(Dictionary props) { /** * Update the properties associated with this service. * - *

The key "objectClass" cannot be modified by this method. It's - * value is set when the service is registered. + *

+ * The key "objectClass" cannot be modified by this method. It's value is set + * when the service is registered. * - *

The following steps are followed to modify a service's properties: + *

+ * The following steps are followed to modify a service's properties: *

    *
  1. The service's properties are replaced with the provided properties. - *
  2. A {@link ServiceEvent} of type {@link ServiceEvent#MODIFIED} - * is synchronously sent. + *
  3. A {@link ServiceEvent} of type {@link ServiceEvent#MODIFIED} is + * synchronously sent. *
* - * @param props The properties for this service. - * Changes should not be made to this object after calling this method. - * To update the service's properties this method should be called again. - * @exception java.lang.IllegalStateException If - * this ServiceRegistration has already been unregistered. + * @param props The properties for this service. Changes should not be made to + * this object after calling this method. To update the service's + * properties this method should be called again. + * @exception java.lang.IllegalStateException If this ServiceRegistration has + * already been unregistered. * - * @exception IllegalArgumentException If the properties - * parameter contains case variants of the same key name. + * @exception IllegalArgumentException If the properties + * parameter contains case variants + * of the same key name. */ @Override public void setProperties(Dictionary props) { @@ -189,33 +194,30 @@ public void setProperties(Dictionary props) { } /** - * Unregister the service. - * Remove a service registration from the framework's service - * registry. - * All {@link ServiceReferenceImpl} objects for this registration - * can no longer be used to interact with the service. + * Unregister the service. Remove a service registration from the framework's + * service registry. All {@link ServiceReferenceImpl} objects for this + * registration can no longer be used to interact with the service. * - *

The following steps are followed to unregister a service: + *

+ * The following steps are followed to unregister a service: *

    - *
  1. The service is removed from the framework's service - * registry so that it may no longer be used. - * {@link ServiceReferenceImpl}s for the service may no longer be used - * to get a service object for the service. - *
  2. A {@link ServiceEvent} of type {@link ServiceEvent#UNREGISTERING} - * is synchronously sent so that bundles using this service - * may release their use of the service. - *
  3. For each bundle whose use count for this service is greater - * than zero: + *
  4. The service is removed from the framework's service registry so that it + * may no longer be used. {@link ServiceReferenceImpl}s for the service may no + * longer be used to get a service object for the service. + *
  5. A {@link ServiceEvent} of type {@link ServiceEvent#UNREGISTERING} is + * synchronously sent so that bundles using this service may release their use + * of the service. + *
  6. For each bundle whose use count for this service is greater than zero: *
      *
    1. The bundle's use count for this service is set to zero. - *
    2. If the service was registered with a {@link ServiceFactory}, - * the {@link ServiceFactory#ungetService ServiceFactory.ungetService} method - * is called to release the service object for the bundle. + *
    3. If the service was registered with a {@link ServiceFactory}, the + * {@link ServiceFactory#ungetService ServiceFactory.ungetService} method is + * called to release the service object for the bundle. *
    *
* - * @exception java.lang.IllegalStateException If - * this ServiceRegistration has already been unregistered. + * @exception java.lang.IllegalStateException If this ServiceRegistration has + * already been unregistered. * @see BundleContextImpl#ungetService */ @Override @@ -247,7 +249,9 @@ public void unregister() { BundleContextImpl[] users = null; synchronized (registrationLock) { - /* we have published the ServiceEvent, now mark the service fully unregistered */ + /* + * we have published the ServiceEvent, now mark the service fully unregistered + */ state = UNREGISTERED; size = contextsUsing.size(); @@ -285,11 +289,11 @@ boolean isUnregistered() { } /** - * Returns a {@link ServiceReferenceImpl} object for this registration. - * The {@link ServiceReferenceImpl} object may be shared with other bundles. + * Returns a {@link ServiceReferenceImpl} object for this registration. The + * {@link ServiceReferenceImpl} object may be shared with other bundles. * - * @exception java.lang.IllegalStateException If - * this ServiceRegistration has already been unregistered. + * @exception java.lang.IllegalStateException If this ServiceRegistration has + * already been unregistered. * @return A {@link ServiceReferenceImpl} object. */ @Override @@ -310,10 +314,11 @@ void ungetHookInstance() { } ServiceReferenceImpl getReferenceImpl() { - /* use reference instead of unregistered so that ServiceFactorys, called - * by releaseService after the registration is unregistered, can - * get the ServiceReference. Note this technically may violate the spec - * but makes more sense. + /* + * use reference instead of unregistered so that ServiceFactorys, called by + * releaseService after the registration is unregistered, can get the + * ServiceReference. Note this technically may violate the spec but makes more + * sense. */ synchronized (registrationLock) { if (reference == null) { @@ -325,14 +330,14 @@ ServiceReferenceImpl getReferenceImpl() { } /** - * Count of service properties set by framework for each - * service registration. + * Count of service properties set by framework for each service registration. *
    *
  • Constants.OBJECTCLASS
  • *
  • Constants.SERVICE_ID
  • *
  • Constants.SERVICE_BUNDLEID
  • *
  • Constants.SERVICE_SCOPE
  • *
+ * * @see #createProperties(Dictionary) */ private static final int FRAMEWORK_SET_SERVICE_PROPERTIES_COUNT = 4; @@ -370,7 +375,9 @@ private Map createProperties(Dictionary p) { } else { serviceranking = 0; if (ranking != null) { - registry.getContainer().getEventPublisher().publishFrameworkEvent(FrameworkEvent.WARNING, getBundle(), new ServiceException("Invalid ranking type: " + ranking.getClass(), ServiceException.UNSPECIFIED)); //$NON-NLS-1$ + registry.getContainer().getEventPublisher().publishFrameworkEvent(FrameworkEvent.WARNING, getBundle(), + new ServiceException("Invalid ranking type: " + ranking.getClass(), //$NON-NLS-1$ + ServiceException.UNSPECIFIED)); } } @@ -379,6 +386,7 @@ private Map createProperties(Dictionary p) { /** * Return the properties object. This is for framework internal use only. + * * @return The service registration's properties. */ public Map getProperties() { @@ -390,14 +398,14 @@ public Map getProperties() { /** * Get the value of a service's property. * - *

This method will continue to return property values after the - * service has been unregistered. This is so that references to - * unregistered service can be interrogated. - * (For example: ServiceReference objects stored in the log.) + *

+ * This method will continue to return property values after the service has + * been unregistered. This is so that references to unregistered service can be + * interrogated. (For example: ServiceReference objects stored in the log.) * * @param key Name of the property. - * @return Value of the property or null if there is - * no property by that name. + * @return Value of the property or null if there is no property by + * that name. */ Object getProperty(String key) { synchronized (registrationLock) { @@ -408,10 +416,10 @@ Object getProperty(String key) { /** * Get the list of key names for the service's properties. * - *

This method will continue to return the keys after the - * service has been unregistered. This is so that references to - * unregistered service can be interrogated. - * (For example: ServiceReference objects stored in the log.) + *

+ * This method will continue to return the keys after the service has been + * unregistered. This is so that references to unregistered service can be + * interrogated. (For example: ServiceReference objects stored in the log.) * * @return The list of property key names. */ @@ -424,10 +432,10 @@ String[] getPropertyKeys() { /** * Get a copy of the service's properties. * - *

This method will continue to return the properties after the - * service has been unregistered. This is so that references to - * unregistered service can be interrogated. - * (For example: ServiceReference objects stored in the log.) + *

+ * This method will continue to return the properties after the service has been + * unregistered. This is so that references to unregistered service can be + * interrogated. (For example: ServiceReference objects stored in the log.) * * @return A copy of the properties. */ @@ -439,6 +447,7 @@ Dictionary getPropertiesCopy() { /** * Return the service id for this service. + * * @return The service id for this service. */ long getId() { @@ -447,6 +456,7 @@ long getId() { /** * Return the service ranking for this service. + * * @return The service ranking for this service. */ int getRanking() { @@ -466,9 +476,10 @@ S getServiceObject() { /** * Return the bundle which registered the service. * - *

This method will always return null when the - * service has been unregistered. This can be used to - * determine if the service has been unregistered. + *

+ * This method will always return null when the service has been + * unregistered. This can be used to determine if the service has been + * unregistered. * * @return The bundle which registered the service. */ @@ -483,10 +494,10 @@ Bundle getBundle() { } /** - * This method returns the bundle which registered the - * service regardless of the registration status of this - * service registration. This is not an OSGi specified - * method. + * This method returns the bundle which registered the service regardless of the + * registration status of this service registration. This is not an OSGi + * specified method. + * * @return The bundle which registered the service. */ public Bundle getRegisteringBundle() { @@ -496,7 +507,7 @@ public Bundle getRegisteringBundle() { /** * Get a service object for the using BundleContext. * - * @param user BundleContext using service. + * @param user BundleContext using service. * @param consumer The closure for the consumer type. * @return Service object */ @@ -523,8 +534,10 @@ S getService(BundleContextImpl user, ServiceConsumer consumer) { @SuppressWarnings("unchecked") ServiceUse u = (ServiceUse) servicesInUse.get(this); if (u == null) { - /* if this is the first use of the service - * optimistically record this service is being used. */ + /* + * if this is the first use of the service optimistically record this service is + * being used. + */ use = newServiceUse(user); added = true; synchronized (registrationLock) { @@ -583,7 +596,6 @@ S getService(BundleContextImpl user, ServiceConsumer consumer) { } } - /** * Create a new ServiceObjects for the requesting bundle. * @@ -621,12 +633,12 @@ private ServiceUse newServiceUse(BundleContextImpl user) { /** * Unget a service for the using BundleContext. * - * @param user BundleContext using service. - * @param consumer The closure for the consumer type. + * @param user BundleContext using service. + * @param consumer The closure for the consumer type. * @param serviceObject The service object to release for prototype consumers. * @return false if the context bundle's use count for the service - * is zero or if the service has been unregistered, - * otherwise true. + * is zero or if the service has been unregistered, otherwise + * true. */ boolean ungetService(BundleContextImpl user, ServiceConsumer consumer, S serviceObject) { if (isUnregistered()) { @@ -768,8 +780,8 @@ public String toString() { * ServiceRegistrationImpl for order. * *

- * This does a reverse comparison so that the highest item is sorted to the left. - * We keep ServiceRegistationImpls in sorted lists such that the highest + * This does a reverse comparison so that the highest item is sorted to the + * left. We keep ServiceRegistationImpls in sorted lists such that the highest * ranked service is at element 0 for quick retrieval. * * @param other The ServiceRegistrationImpl to be compared. diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ServiceRegistry.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ServiceRegistry.java index 20b84db38f0..b248cab0e71 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ServiceRegistry.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ServiceRegistry.java @@ -63,8 +63,8 @@ import org.osgi.framework.hooks.service.ListenerHook.ListenerInfo; /** - * The Service Registry. This class is the main control point for service - * layer operations in the framework. + * The Service Registry. This class is the main control point for service layer + * operations in the framework. * * @ThreadSafe */ @@ -73,26 +73,27 @@ public class ServiceRegistry { static final String listenerHookName = ListenerHook.class.getName(); - - /** Published services by class name. - * The {@literal List>}s are both sorted - * in the natural order of ServiceRegistrationImpl and also are sets in that - * there must be no two entries in a List which are equal. + /** + * Published services by class name. The + * {@literal List>}s are both sorted in the natural + * order of ServiceRegistrationImpl and also are sets in that there must be no + * two entries in a List which are equal. */ /* @GuardedBy("this") */ private final Map>> publishedServicesByClass; - /** All published services. - * The List is both sorted in the natural order of ServiceRegistrationImpl and also is a - * set in that there must be no two entries in the List which are equal. + /** + * All published services. The List is both sorted in the natural order of + * ServiceRegistrationImpl and also is a set in that there must be no two + * entries in the List which are equal. */ /* @GuardedBy("this") */ private final List> allPublishedServices; - /** Published services by BundleContextImpl. - * The {@literal List>}s are NOT sorted - * and also are sets in that - * there must be no two entries in a List which are equal. + /** + * Published services by BundleContextImpl. The + * {@literal List>}s are NOT sorted and also are sets + * in that there must be no two entries in a List which are equal. */ /* @GuardedBy("this") */ private final Map>> publishedServicesByContext; @@ -101,7 +102,8 @@ public class ServiceRegistry { /* @GuardedBy("this") */ private long serviceid; - /** Active Service Listeners. + /** + * Active Service Listeners. * {@literal Map>}. */ /* @GuardedBy("serviceEventListeners") */ @@ -139,14 +141,14 @@ public ServiceRegistry(EquinoxContainer container) { } /** - * Registers the specified service object with the specified properties - * under the specified class names into the Framework. A + * Registers the specified service object with the specified properties under + * the specified class names into the Framework. A * ServiceRegistrationImpl object is returned. The * ServiceRegistrationImpl object is for the private use of the - * bundle registering the service and should not be shared with other - * bundles. The registering bundle is defined to be the context bundle. - * Other bundles can locate the service by using either the - * {@link #getServiceReferences} or {@link #getServiceReference} method. + * bundle registering the service and should not be shared with other bundles. + * The registering bundle is defined to be the context bundle. Other bundles can + * locate the service by using either the {@link #getServiceReferences} or + * {@link #getServiceReference} method. * *

* A bundle can register a service object that implements the @@ -156,66 +158,68 @@ public ServiceRegistry(EquinoxContainer container) { *

* The following steps are required to register a service: *

    - *
  1. If service is not a ServiceFactory, - * an IllegalArgumentException is thrown if - * service is not an instanceof all the - * classes named. + *
  2. If service is not a ServiceFactory, an + * IllegalArgumentException is thrown if service is + * not an instanceof all the classes named. *
  3. The Framework adds these service properties to the specified - * Dictionary (which may be null): a property - * named {@link Constants#SERVICE_ID} identifying the registration number of - * the service and a property named {@link Constants#OBJECTCLASS} containing - * all the specified classes. If any of these properties have already been - * specified by the registering bundle, their values will be overwritten by - * the Framework. - *
  4. The service is added to the Framework service registry and may now - * be used by other bundles. + * Dictionary (which may be null): a property named + * {@link Constants#SERVICE_ID} identifying the registration number of the + * service and a property named {@link Constants#OBJECTCLASS} containing all the + * specified classes. If any of these properties have already been specified by + * the registering bundle, their values will be overwritten by the Framework. + *
  5. The service is added to the Framework service registry and may now be + * used by other bundles. *
  6. A service event of type {@link ServiceEvent#REGISTERED} is fired. *
  7. A ServiceRegistration object for this registration is * returned. *
* - * @param context The BundleContext of the registering bundle. - * @param clazzes The class names under which the service can be located. - * The class names in this array will be stored in the service's - * properties under the key {@link Constants#OBJECTCLASS}. - * @param service The service object or a ServiceFactory - * object. - * @param properties The properties for this service. The keys in the - * properties object must all be String objects. See - * {@link Constants} for a list of standard service property keys. - * Changes should not be made to this object after calling this - * method. To update the service's properties the - * {@link ServiceRegistration#setProperties} method must be called. - * The set of properties may be null if the service - * has no properties. + * @param context The BundleContext of the registering bundle. + * @param clazzes The class names under which the service can be located. The + * class names in this array will be stored in the service's + * properties under the key {@link Constants#OBJECTCLASS}. + * @param service The service object or a ServiceFactory object. + * @param properties The properties for this service. The keys in the properties + * object must all be String objects. See + * {@link Constants} for a list of standard service property + * keys. Changes should not be made to this object after + * calling this method. To update the service's properties the + * {@link ServiceRegistration#setProperties} method must be + * called. The set of properties may be null if + * the service has no properties. * * @return A ServiceRegistrationImpl object for use by the bundle * registering the service to update the service's properties or to * unregister the service. * - * @throws java.lang.IllegalArgumentException If one of the following is - * true: - *
    - *
  • service is null. - *
  • service is not a ServiceFactory - * object and is not an instance of all the named classes in - * clazzes. - *
  • properties contains case variants of the same - * key name. - *
+ * @throws java.lang.IllegalArgumentException If one of the following is true: + *
    + *
  • service is + * null. + *
  • service is not a + * ServiceFactory object + * and is not an instance of all the + * named classes in + * clazzes. + *
  • properties + * contains case variants of the same + * key name. + *
* - * @throws java.lang.SecurityException If the caller does not have the - * ServicePermission to register the service for all - * the named classes and the Java Runtime Environment supports - * permissions. + * @throws java.lang.SecurityException If the caller does not have the + * ServicePermission to + * register the service for all the + * named classes and the Java Runtime + * Environment supports permissions. * - * @throws java.lang.IllegalStateException If this BundleContext is no - * longer valid. + * @throws java.lang.IllegalStateException If this BundleContext is no longer + * valid. * * @see ServiceRegistration * @see ServiceFactory */ - public ServiceRegistrationImpl registerService(BundleContextImpl context, String[] clazzes, Object service, Dictionary properties) { + public ServiceRegistrationImpl registerService(BundleContextImpl context, String[] clazzes, Object service, + Dictionary properties) { if (service == null) { if (debug.DEBUG_SERVICES) { Debug.println("Service object is null"); //$NON-NLS-1$ @@ -259,7 +263,8 @@ public ServiceRegistrationImpl registerService(BundleContextImpl context, Str if (debug.DEBUG_SERVICES) { Debug.println("Service object is not an instanceof " + invalidService); //$NON-NLS-1$ } - throw new IllegalArgumentException(NLS.bind(Msg.SERVICE_NOT_INSTANCEOF_CLASS_EXCEPTION, invalidService)); + throw new IllegalArgumentException( + NLS.bind(Msg.SERVICE_NOT_INSTANCEOF_CLASS_EXCEPTION, invalidService)); } } @@ -314,48 +319,47 @@ private List> addHook(Class hookType, List> hookTypes) { * Returns an array of ServiceReferenceImpl objects. The returned * array of ServiceReferenceImpl objects contains services that * were registered under the specified class, match the specified filter - * criteria, and the packages for the class names under which the services - * were registered match the context bundle's packages as defined in + * criteria, and the packages for the class names under which the services were + * registered match the context bundle's packages as defined in * {@link ServiceReference#isAssignableTo(Bundle, String)}. * *

- * The list is valid at the time of the call to this method, however since - * the Framework is a very dynamic environment, services can be modified or + * The list is valid at the time of the call to this method, however since the + * Framework is a very dynamic environment, services can be modified or * unregistered at anytime. * *

- * filter is used to select the registered service whose - * properties objects contain keys and values which satisfy the filter. See - * {@link Filter} for a description of the filter string syntax. + * filter is used to select the registered service whose properties + * objects contain keys and values which satisfy the filter. See {@link Filter} + * for a description of the filter string syntax. * *

- * If filter is null, all registered services - * are considered to match the filter. If filter cannot be - * parsed, an {@link InvalidSyntaxException} will be thrown with a human - * readable message where the filter became unparsable. + * If filter is null, all registered services are + * considered to match the filter. If filter cannot be parsed, an + * {@link InvalidSyntaxException} will be thrown with a human readable message + * where the filter became unparsable. * *

* The following steps are required to select a set of * ServiceReferenceImpl objects: *

    - *
  1. If the filter string is not null, the filter string - * is parsed and the set ServiceReferenceImpl objects of - * registered services that satisfy the filter is produced. If the filter - * string is null, then all registered services are - * considered to satisfy the filter. + *
  2. If the filter string is not null, the filter string is + * parsed and the set ServiceReferenceImpl objects of registered + * services that satisfy the filter is produced. If the filter string is + * null, then all registered services are considered to satisfy the + * filter. *
  3. If the Java Runtime Environment supports permissions, the set of * ServiceReferenceImpl objects produced by the previous step is - * reduced by checking that the caller has the - * ServicePermission to get at least one of the class names - * under which the service was registered. If the caller does not have the - * correct permission for a particular ServiceReferenceImpl - * object, then it is removed from the set. - *
  4. If clazz is not null, the set is - * further reduced to those services that are an instanceof - * and were registered under the specified class. The complete list of - * classes of which a service is an instance and which were specified when - * the service was registered is available from the service's - * {@link Constants#OBJECTCLASS} property. + * reduced by checking that the caller has the ServicePermission to + * get at least one of the class names under which the service was registered. + * If the caller does not have the correct permission for a particular + * ServiceReferenceImpl object, then it is removed from the set. + *
  5. If clazz is not null, the set is further + * reduced to those services that are an instanceof and were + * registered under the specified class. The complete list of classes of which a + * service is an instance and which were specified when the service was + * registered is available from the service's {@link Constants#OBJECTCLASS} + * property. *
  6. The set is reduced one final time by cycling through each * ServiceReference object and calling * {@link ServiceReference#isAssignableTo(Bundle, String)} with the context @@ -369,22 +373,25 @@ private List> addHook(Class hookType, List> hookTypes) { * returned. *
* - * @param context The BundleContext of the requesting bundle. - * @param clazz The class name with which the service was registered or - * null for all services. + * @param context The BundleContext of the requesting bundle. + * @param clazz The class name with which the service was registered or + * null for all services. * @param filterstring The filter criteria. - * @param allservices True if the bundle called getAllServiceReferences. + * @param allservices True if the bundle called getAllServiceReferences. * @return An array of ServiceReferenceImpl objects or - * null if no services are registered which satisfy - * the search. - * @throws InvalidSyntaxException If filter contains an - * invalid filter string that cannot be parsed. - * @throws java.lang.IllegalStateException If this BundleContext is no - * longer valid. + * null if no services are registered which satisfy the + * search. + * @throws InvalidSyntaxException If filter contains an + * invalid filter string that cannot be + * parsed. + * @throws java.lang.IllegalStateException If this BundleContext is no longer + * valid. */ - public ServiceReferenceImpl[] getServiceReferences(final BundleContextImpl context, final String clazz, final String filterstring, final boolean allservices) throws InvalidSyntaxException { + public ServiceReferenceImpl[] getServiceReferences(final BundleContextImpl context, final String clazz, + final String filterstring, final boolean allservices) throws InvalidSyntaxException { if (debug.DEBUG_SERVICES) { - Debug.println((allservices ? "getAllServiceReferences(" : "getServiceReferences(") + clazz + ", \"" + filterstring + "\")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + Debug.println((allservices ? "getAllServiceReferences(" : "getServiceReferences(") + clazz + ", \"" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + + filterstring + "\")"); //$NON-NLS-1$ } Filter filter = (filterstring == null) ? null : context.createFilter(filterstring); List> registrations = lookupServiceRegistrations(clazz, filter); @@ -425,34 +432,33 @@ public ServiceReferenceImpl[] getServiceReferences(final BundleContextImpl co } /** - * Returns a ServiceReference object for a service that - * implements and was registered under the specified class. + * Returns a ServiceReference object for a service that implements + * and was registered under the specified class. * *

- * This ServiceReference object is valid at the time of the - * call to this method, however as the Framework is a very dynamic - * environment, services can be modified or unregistered at anytime. + * This ServiceReference object is valid at the time of the call to + * this method, however as the Framework is a very dynamic environment, services + * can be modified or unregistered at anytime. * *

* This method is the same as calling * {@link BundleContext#getServiceReferences(String, String)} with a - * null filter string. It is provided as a convenience for - * when the caller is interested in any service that implements the - * specified class. + * null filter string. It is provided as a convenience for when the + * caller is interested in any service that implements the specified class. *

* If multiple such services exist, the service with the highest ranking (as * specified in its {@link Constants#SERVICE_RANKING} property) is returned. *

* If there is a tie in ranking, the service with the lowest service ID (as - * specified in its {@link Constants#SERVICE_ID} property); that is, the - * service that was registered first is returned. + * specified in its {@link Constants#SERVICE_ID} property); that is, the service + * that was registered first is returned. * * @param context The BundleContext of the requesting bundle. - * @param clazz The class name with which the service was registered. - * @return A ServiceReference object, or null - * if no services are registered which implement the named class. - * @throws java.lang.IllegalStateException If this BundleContext is no - * longer valid. + * @param clazz The class name with which the service was registered. + * @return A ServiceReference object, or null if no + * services are registered which implement the named class. + * @throws java.lang.IllegalStateException If this BundleContext is no longer + * valid. */ public ServiceReferenceImpl getServiceReference(BundleContextImpl context, String clazz) { if (debug.DEBUG_SERVICES) { @@ -463,7 +469,8 @@ public ServiceReferenceImpl getServiceReference(BundleContextImpl context, St ServiceReferenceImpl[] references = getServiceReferences(context, clazz, null, false); if (references != null) { - // Since we maintain the registrations in a sorted List, the first element is always the + // Since we maintain the registrations in a sorted List, the first element is + // always the // correct one to return. return references[0]; } @@ -482,57 +489,57 @@ public ServiceReferenceImpl getServiceReference(BundleContextImpl context, St *

* A bundle's use of a service is tracked by the bundle's use count of that * service. Each time a service's service object is returned by - * {@link #getService(BundleContextImpl, ServiceReferenceImpl)} the context bundle's use count for - * that service is incremented by one. Each time the service is released by - * {@link #ungetService(BundleContextImpl, ServiceReferenceImpl)} the context bundle's use count - * for that service is decremented by one. + * {@link #getService(BundleContextImpl, ServiceReferenceImpl)} the context + * bundle's use count for that service is incremented by one. Each time the + * service is released by + * {@link #ungetService(BundleContextImpl, ServiceReferenceImpl)} the context + * bundle's use count for that service is decremented by one. *

- * When a bundle's use count for a service drops to zero, the bundle should - * no longer use that service. + * When a bundle's use count for a service drops to zero, the bundle should no + * longer use that service. * *

- * This method will always return null when the service - * associated with this reference has been unregistered. + * This method will always return null when the service associated + * with this reference has been unregistered. * *

* The following steps are required to get the service object: *

    - *
  1. If the service has been unregistered, null is - * returned. - *
  2. The context bundle's use count for this service is incremented by - * one. - *
  3. If the context bundle's use count for the service is currently one - * and the service was registered with an object implementing the + *
  4. If the service has been unregistered, null is returned. + *
  5. The context bundle's use count for this service is incremented by one. + *
  6. If the context bundle's use count for the service is currently one and + * the service was registered with an object implementing the * ServiceFactory interface, the * {@link ServiceFactory#getService(Bundle, ServiceRegistration)} method is - * called to create a service object for the context bundle. This service - * object is cached by the Framework. While the context bundle's use count - * for the service is greater than zero, subsequent calls to get the - * services's service object for the context bundle will return the cached - * service object.
    - * If the service object returned by the ServiceFactory - * object is not an instanceof all the classes named when the - * service was registered or the ServiceFactory object throws - * an exception, null is returned and a Framework event of - * type {@link FrameworkEvent#ERROR} containing a {@link ServiceException} - * describing the error is fired. + * called to create a service object for the context bundle. This service object + * is cached by the Framework. While the context bundle's use count for the + * service is greater than zero, subsequent calls to get the services's service + * object for the context bundle will return the cached service object.
    + * If the service object returned by the ServiceFactory object is + * not an instanceof all the classes named when the service was + * registered or the ServiceFactory object throws an exception, + * null is returned and a Framework event of type + * {@link FrameworkEvent#ERROR} containing a {@link ServiceException} describing + * the error is fired. *
  7. The service object for the service is returned. *
* - * @param context The BundleContext of the requesting bundle. + * @param context The BundleContext of the requesting bundle. * @param reference A reference to the service. * @return A service object for the service associated with - * reference or null if the service is - * not registered, the service object returned by a - * ServiceFactory does not implement the classes - * under which it was registered or the ServiceFactory - * threw an exception. - * @throws java.lang.SecurityException If the caller does not have the - * ServicePermission to get the service using at - * least one of the named classes the service was registered under - * and the Java Runtime Environment supports permissions. - * @throws java.lang.IllegalStateException If this BundleContext is no - * longer valid. + * reference or null if the service is not + * registered, the service object returned by a + * ServiceFactory does not implement the classes under + * which it was registered or the ServiceFactory threw an + * exception. + * @throws java.lang.SecurityException If the caller does not have the + * ServicePermission to get + * the service using at least one of the + * named classes the service was + * registered under and the Java Runtime + * Environment supports permissions. + * @throws java.lang.IllegalStateException If this BundleContext is no longer + * valid. * @see #ungetService(BundleContextImpl, ServiceReferenceImpl) * @see ServiceFactory */ @@ -543,35 +550,36 @@ public S getService(BundleContextImpl context, ServiceReferenceImpl refer } /** - * Returns the {@link ServiceObjects} object for the service referenced by - * the specified {@code ServiceReference} object. + * Returns the {@link ServiceObjects} object for the service referenced by the + * specified {@code ServiceReference} object. * *

- * The {@link ServiceObjects} object can be used to obtain multiple - * service objects for services with {@link Constants#SCOPE_PROTOTYPE - * prototype} scope. For services with {@link Constants#SCOPE_SINGLETON - * singleton} or {@link Constants#SCOPE_BUNDLE bundle} scope, the + * The {@link ServiceObjects} object can be used to obtain multiple service + * objects for services with {@link Constants#SCOPE_PROTOTYPE prototype} scope. + * For services with {@link Constants#SCOPE_SINGLETON singleton} or + * {@link Constants#SCOPE_BUNDLE bundle} scope, the * {@link ServiceObjects#getService()} method behaves the same as the * {@link BundleContext#getService(ServiceReference)} method and the - * {@link ServiceObjects#ungetService(Object)} method behaves the same as - * the {@link BundleContext#ungetService(ServiceReference)} method. That is, only one, - * use-counted service object is available from the {@link ServiceObjects} + * {@link ServiceObjects#ungetService(Object)} method behaves the same as the + * {@link BundleContext#ungetService(ServiceReference)} method. That is, only + * one, use-counted service object is available from the {@link ServiceObjects} * object. * *

- * This method will always return {@code null} when the service associated - * with the specified {@code reference} has been unregistered. + * This method will always return {@code null} when the service associated with + * the specified {@code reference} has been unregistered. * - * @param Type of Service. - * @param context The BundleContext of the requesting bundle. + * @param Type of Service. + * @param context The BundleContext of the requesting bundle. * @param reference A reference to the service. - * @return A {@link ServiceObjects} object for the service associated with - * the specified {@code reference} or {@code null} if the service is - * not registered. + * @return A {@link ServiceObjects} object for the service associated with the + * specified {@code reference} or {@code null} if the service is not + * registered. * @throws SecurityException If the caller does not have the - * {@code ServicePermission} to get the service using at least one - * of the named classes the service was registered under and the - * Java Runtime Environment supports permissions. + * {@code ServicePermission} to get the service using + * at least one of the named classes the service was + * registered under and the Java Runtime Environment + * supports permissions. */ public ServiceObjectsImpl getServiceObjects(BundleContextImpl context, ServiceReferenceImpl reference) { checkGetServicePermission(reference); @@ -580,38 +588,35 @@ public ServiceObjectsImpl getServiceObjects(BundleContextImpl context, Se /** * Releases the service object referenced by the specified - * ServiceReference object. If the context bundle's use count - * for the service is zero, this method returns false. - * Otherwise, the context bundle's use count for the service is decremented - * by one. + * ServiceReference object. If the context bundle's use count for + * the service is zero, this method returns false. Otherwise, the + * context bundle's use count for the service is decremented by one. * *

- * The service's service object should no longer be used and all references - * to it should be destroyed when a bundle's use count for the service drops - * to zero. + * The service's service object should no longer be used and all references to + * it should be destroyed when a bundle's use count for the service drops to + * zero. * *

* The following steps are required to unget the service object: *

    - *
  1. If the context bundle's use count for the service is zero or the - * service has been unregistered, false is returned. - *
  2. The context bundle's use count for this service is decremented by - * one. - *
  3. If the context bundle's use count for the service is currently zero - * and the service was registered with a ServiceFactory - * object, the + *
  4. If the context bundle's use count for the service is zero or the service + * has been unregistered, false is returned. + *
  5. The context bundle's use count for this service is decremented by one. + *
  6. If the context bundle's use count for the service is currently zero and + * the service was registered with a ServiceFactory object, the * {@link ServiceFactory#ungetService(Bundle, ServiceRegistration, Object)} * method is called to release the service object for the context bundle. *
  7. true is returned. *
* - * @param context The BundleContext of the requesting bundle. + * @param context The BundleContext of the requesting bundle. * @param reference A reference to the service to be released. - * @return false if the context bundle's use count for the - * service is zero or if the service has been unregistered; - * true otherwise. - * @throws java.lang.IllegalStateException If this BundleContext is no - * longer valid. + * @return false if the context bundle's use count for the service + * is zero or if the service has been unregistered; true + * otherwise. + * @throws java.lang.IllegalStateException If this BundleContext is no longer + * valid. * @see #getService * @see ServiceFactory */ @@ -622,15 +627,15 @@ public boolean ungetService(BundleContextImpl context, ServiceReferenceImpl r } /** - * Returns this bundle's ServiceReference list for all - * services it has registered or null if this bundle has no - * registered services. + * Returns this bundle's ServiceReference list for all services it + * has registered or null if this bundle has no registered + * services. * *

* If the Java runtime supports permissions, a ServiceReference - * object to a service is included in the returned list only if the caller - * has the ServicePermission to get the service using at - * least one of the named classes the service was registered under. + * object to a service is included in the returned list only if the caller has + * the ServicePermission to get the service using at least one of + * the named classes the service was registered under. * *

* The list is valid at the time of the call to this method, however, as the @@ -640,8 +645,7 @@ public boolean ungetService(BundleContextImpl context, ServiceReferenceImpl r * @param context The BundleContext of the requesting bundle. * @return An array of ServiceReference objects or * null. - * @throws java.lang.IllegalStateException If this bundle has been - * uninstalled. + * @throws java.lang.IllegalStateException If this bundle has been uninstalled. * @see ServiceRegistration * @see ServiceReference * @see ServicePermission @@ -673,17 +677,17 @@ public ServiceReferenceImpl[] getRegisteredServices(BundleContextImpl context } /** - * Returns this bundle's ServiceReference list for all - * services it is using or returns null if this bundle is not - * using any services. A bundle is considered to be using a service if its - * use count for that service is greater than zero. + * Returns this bundle's ServiceReference list for all services it + * is using or returns null if this bundle is not using any + * services. A bundle is considered to be using a service if its use count for + * that service is greater than zero. * *

* If the Java Runtime Environment supports permissions, a - * ServiceReference object to a service is included in the - * returned list only if the caller has the ServicePermission - * to get the service using at least one of the named classes the service - * was registered under. + * ServiceReference object to a service is included in the returned + * list only if the caller has the ServicePermission to get the + * service using at least one of the named classes the service was registered + * under. *

* The list is valid at the time of the call to this method, however, as the * Framework is a very dynamic environment, services can be modified or @@ -692,8 +696,7 @@ public ServiceReferenceImpl[] getRegisteredServices(BundleContextImpl context * @param context The BundleContext of the requesting bundle. * @return An array of ServiceReference objects or * null. - * @throws java.lang.IllegalStateException If this bundle has been - * uninstalled. + * @throws java.lang.IllegalStateException If this bundle has been uninstalled. * @see ServiceReference * @see ServicePermission */ @@ -735,8 +738,8 @@ public ServiceReferenceImpl[] getServicesInUse(BundleContextImpl context) { } /** - * Called when the BundleContext is closing to unregister all services - * currently registered by the bundle. + * Called when the BundleContext is closing to unregister all services currently + * registered by the bundle. * * @param context The BundleContext of the closing bundle. */ @@ -752,8 +755,8 @@ public void unregisterServices(BundleContextImpl context) { } /** - * Called when the BundleContext is closing to unget all services - * currently used by the bundle. + * Called when the BundleContext is closing to unget all services currently used + * by the bundle. * * @param context The BundleContext of the closing bundle. */ @@ -780,21 +783,25 @@ public void releaseServicesInUse(BundleContextImpl context) { /** * Add a new Service Listener for a bundle. * - * @param context Context of bundle adding listener. + * @param context Context of bundle adding listener. * @param listener Service Listener to be added. - * @param filter Filter string for listener or null. + * @param filter Filter string for listener or null. * @throws InvalidSyntaxException If the filter string is invalid. */ - public void addServiceListener(BundleContextImpl context, ServiceListener listener, String filter) throws InvalidSyntaxException { + public void addServiceListener(BundleContextImpl context, ServiceListener listener, String filter) + throws InvalidSyntaxException { if (debug.DEBUG_EVENTS) { - String listenerName = listener.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(listener)); //$NON-NLS-1$ - Debug.println("addServiceListener[" + context.getBundleImpl() + "](" + listenerName + ", \"" + filter + "\")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + String listenerName = listener.getClass().getName() + "@" //$NON-NLS-1$ + + Integer.toHexString(System.identityHashCode(listener)); + Debug.println( + "addServiceListener[" + context.getBundleImpl() + "](" + listenerName + ", \"" + filter + "\")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } FilteredServiceListener filteredListener = new FilteredServiceListener(context, listener, filter); FilteredServiceListener oldFilteredListener; synchronized (serviceEventListeners) { - CopyOnWriteIdentityMap listeners = serviceEventListeners.get(context); + CopyOnWriteIdentityMap listeners = serviceEventListeners + .get(context); if (listeners == null) { listeners = new CopyOnWriteIdentityMap<>(); serviceEventListeners.put(context, listeners); @@ -815,12 +822,13 @@ public void addServiceListener(BundleContextImpl context, ServiceListener listen /** * Remove a Service Listener for a bundle. * - * @param context Context of bundle removing listener. + * @param context Context of bundle removing listener. * @param listener Service Listener to be removed. */ public void removeServiceListener(BundleContextImpl context, ServiceListener listener) { if (debug.DEBUG_EVENTS) { - String listenerName = listener.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(listener)); //$NON-NLS-1$ + String listenerName = listener.getClass().getName() + "@" //$NON-NLS-1$ + + Integer.toHexString(System.identityHashCode(listener)); Debug.println("removeServiceListener[" + context.getBundleImpl() + "](" + listenerName + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } @@ -862,8 +870,9 @@ public void removeAllServiceListeners(BundleContextImpl context) { } /** - * Coerce the generic type of a collection from Collection - * to Collection + * Coerce the generic type of a collection from + * Collection to Collection + * * @param c Collection to be coerced. * @return c coerced to Collection */ @@ -898,7 +907,8 @@ void publishServiceEventPrivileged(final ServiceEvent event) { BundleContextImpl systemContext = null; synchronized (serviceEventListeners) { listenerSnapshot = new LinkedHashMap<>(serviceEventListeners.size()); - for (Map.Entry> entry : serviceEventListeners.entrySet()) { + for (Map.Entry> entry : serviceEventListeners + .entrySet()) { Map listeners = entry.getValue(); if (!listeners.isEmpty()) { if (entry.getKey().getBundleImpl().getBundleId() == 0) { @@ -911,10 +921,10 @@ void publishServiceEventPrivileged(final ServiceEvent event) { } } - /* shrink the snapshot. - * keySet returns a Collection which cannot be added to and - * removals from that collection will result in removals of the - * entry from the snapshot. + /* + * shrink the snapshot. keySet returns a Collection which cannot be added to and + * removals from that collection will result in removals of the entry from the + * snapshot. */ Collection contexts = asBundleContexts(listenerSnapshot.keySet()); notifyEventHooksPrivileged(event, contexts); @@ -936,9 +946,11 @@ void publishServiceEventPrivileged(final ServiceEvent event) { /* deliver the event to the snapshot */ ListenerQueue queue = container.newListenerQueue(); - for (Map.Entry>> entry : listenerSnapshot.entrySet()) { - @SuppressWarnings({"unchecked", "rawtypes"}) - EventDispatcher dispatcher = (EventDispatcher) entry.getKey(); + for (Map.Entry>> entry : listenerSnapshot + .entrySet()) { + @SuppressWarnings({ "unchecked", "rawtypes" }) + EventDispatcher dispatcher = (EventDispatcher) entry + .getKey(); Set> listenerSet = entry.getValue(); queue.queueListeners(listenerSet, dispatcher); } @@ -946,8 +958,9 @@ void publishServiceEventPrivileged(final ServiceEvent event) { } /** - * Coerce the generic type of a collection from Collection - * to Collection + * Coerce the generic type of a collection from Collection to + * Collection + * * @param c Collection to be coerced. * @return c coerced to Collection */ @@ -970,13 +983,14 @@ synchronized long getNextServiceId() { /** * Add the ServiceRegistrationImpl to the data structure. * - * @param context The BundleContext of the bundle registering the service. + * @param context The BundleContext of the bundle registering the service. * @param registration The new ServiceRegistration. */ /* @GuardedBy("this") */ void addServiceRegistration(BundleContextImpl context, ServiceRegistrationImpl registration) { assert Thread.holdsLock(this); - // Add the ServiceRegistrationImpl to the list of Services published by BundleContextImpl. + // Add the ServiceRegistrationImpl to the list of Services published by + // BundleContextImpl. List> contextServices = publishedServicesByContext.get(context); if (contextServices == null) { contextServices = new ArrayList<>(initialSubCapacity); @@ -985,7 +999,8 @@ void addServiceRegistration(BundleContextImpl context, ServiceRegistrationImpl> services = publishedServicesByClass.get(clazz); @@ -1009,7 +1024,7 @@ void addServiceRegistration(BundleContextImpl context, ServiceRegistrationImpl registration) { assert Thread.holdsLock(this); - // Remove the ServiceRegistrationImpl from the list of Services published by BundleContextImpl. + // Remove the ServiceRegistrationImpl from the list of Services published by + // BundleContextImpl. List> contextServices = publishedServicesByContext.get(context); if (contextServices != null) { contextServices.remove(registration); } - // Remove the ServiceRegistrationImpl from the list of Services published by Class Name. + // Remove the ServiceRegistrationImpl from the list of Services published by + // Class Name. for (String clazz : registration.getClasses()) { List> services = publishedServicesByClass.get(clazz); services.remove(registration); @@ -1073,8 +1090,8 @@ void removeServiceRegistration(BundleContextImpl context, ServiceRegistrationImp /** * Lookup Service Registrations in the data structure by class name and filter. * - * @param clazz The class name with which the service was registered or - * null for all services. + * @param clazz The class name with which the service was registered or + * null for all services. * @param filter The filter criteria. * @return List */ @@ -1093,7 +1110,7 @@ private List> lookupServiceRegistrations(String clazz filter = null; } } else { - result = allPublishedServices; + result = allPublishedServices; } } else { // have to check all services @@ -1200,7 +1217,8 @@ static boolean hasListenServicePermission(ServiceEvent event, BundleContextImpl /** * Return the name of the class that is not satisfied by the service object. - * @param clazzes Array of class names. + * + * @param clazzes Array of class names. * @param serviceObject Service object. * @return The name of the class that is not satisfied by the service object. */ @@ -1217,7 +1235,7 @@ public ClassLoader run() { if (!serviceClazz.isInstance(serviceObject)) return element; } catch (ClassNotFoundException e) { - //This check is rarely done + // This check is rarely done if (extensiveCheckServiceClass(element, serviceObject.getClass())) return element; } @@ -1249,17 +1267,20 @@ static boolean isAssignableTo(BundleContextImpl context, String clazz, ServiceRe } /** - * Call the registered FindHook services to allow them to inspect and possibly shrink the result. - * The FindHook must be called in order: descending by service.ranking, then ascending by service.id. - * This is the natural order for ServiceReference. + * Call the registered FindHook services to allow them to inspect and possibly + * shrink the result. The FindHook must be called in order: descending by + * service.ranking, then ascending by service.id. This is the natural order for + * ServiceReference. * - * @param context The context of the bundle getting the service references. - * @param clazz The class name used to search for the service references. + * @param context The context of the bundle getting the service references. + * @param clazz The class name used to search for the service references. * @param filterstring The filter used to search for the service references. - * @param allservices True if getAllServiceReferences called. - * @param result The result to return to the caller which may have been shrunk by the FindHooks. + * @param allservices True if getAllServiceReferences called. + * @param result The result to return to the caller which may have been + * shrunk by the FindHooks. */ - private void notifyFindHooks(final BundleContextImpl context, final String clazz, final String filterstring, final boolean allservices, final Collection> result) { + private void notifyFindHooks(final BundleContextImpl context, final String clazz, final String filterstring, + final boolean allservices, final Collection> result) { if (System.getSecurityManager() == null) { notifyFindHooksPrivileged(context, clazz, filterstring, allservices, result); } else { @@ -1273,42 +1294,51 @@ public Void run() { } } - void notifyFindHooksPrivileged(final BundleContextImpl context, final String clazz, final String filterstring, final boolean allservices, final Collection> result) { + void notifyFindHooksPrivileged(final BundleContextImpl context, final String clazz, final String filterstring, + final boolean allservices, final Collection> result) { if (debug.DEBUG_HOOKS) { - Debug.println("notifyServiceFindHooks(" + context.getBundleImpl() + "," + clazz + "," + filterstring + "," + allservices + "," + result + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ + Debug.println("notifyServiceFindHooks(" + context.getBundleImpl() + "," + clazz + "," + filterstring + "," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + + allservices + "," + result + ")"); //$NON-NLS-1$ //$NON-NLS-2$ } notifyHooksPrivileged(FindHook.class, "find", //$NON-NLS-1$ (hook, hookRegistration) -> hook.find(context, clazz, filterstring, allservices, result)); } /** - * Call the registered EventHook services to allow them to inspect and possibly shrink the result. - * The EventHooks must be called in order: descending by service.ranking, then ascending by service.id. - * This is the natural order for ServiceReference. + * Call the registered EventHook services to allow them to inspect and possibly + * shrink the result. The EventHooks must be called in order: descending by + * service.ranking, then ascending by service.id. This is the natural order for + * ServiceReference. * - * @param event The service event to be delivered. - * @param result The result to return to the caller which may have been shrunk by the EventHooks. + * @param event The service event to be delivered. + * @param result The result to return to the caller which may have been shrunk + * by the EventHooks. */ @SuppressWarnings("deprecation") private void notifyEventHooksPrivileged(final ServiceEvent event, final Collection result) { if (debug.DEBUG_HOOKS) { - Debug.println("notifyServiceEventHooks(" + event.getType() + ":" + event.getServiceReference() + "," + result + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + Debug.println("notifyServiceEventHooks(" + event.getType() + ":" + event.getServiceReference() + "," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + + result + ")"); //$NON-NLS-1$ } notifyHooksPrivileged(org.osgi.framework.hooks.service.EventHook.class, "event", //$NON-NLS-1$ (hook, hookRegistration) -> hook.event(event, result)); } /** - * Call the registered EventListenerHook services to allow them to inspect and possibly shrink the result. - * The EventListenerHooks must be called in order: descending by service.ranking, then ascending by service.id. - * This is the natural order for ServiceReference. + * Call the registered EventListenerHook services to allow them to inspect and + * possibly shrink the result. The EventListenerHooks must be called in order: + * descending by service.ranking, then ascending by service.id. This is the + * natural order for ServiceReference. * - * @param event The service event to be delivered. - * @param result The result to return to the caller which may have been shrunk by the EventListenerHooks. + * @param event The service event to be delivered. + * @param result The result to return to the caller which may have been shrunk + * by the EventListenerHooks. */ - private void notifyEventListenerHooksPrivileged(final ServiceEvent event, final Map> result) { + private void notifyEventListenerHooksPrivileged(final ServiceEvent event, + final Map> result) { if (debug.DEBUG_HOOKS) { - Debug.println("notifyServiceEventListenerHooks(" + event.getType() + ":" + event.getServiceReference() + "," + result + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + Debug.println("notifyServiceEventListenerHooks(" + event.getType() + ":" + event.getServiceReference() + "," //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + + result + ")"); //$NON-NLS-1$ } notifyHooksPrivileged(EventListenerHook.class, "event", (hook, r) -> hook.event(event, result)); //$NON-NLS-1$ } @@ -1323,7 +1353,8 @@ private void notifyEventListenerHooksPrivileged(final ServiceEvent event, final @SuppressWarnings("unchecked") public void notifyHooksPrivileged(Class hookType, String serviceMethod, HookContext hookContext) { List> hooks = lookupServiceRegistrations(hookType.getName(), null); - // Since the list is already sorted, we don't need to sort the list to call the hooks + // Since the list is already sorted, we don't need to sort the list to call the + // hooks // in the proper order. for (ServiceRegistrationImpl registration : hooks) { @@ -1369,8 +1400,8 @@ private void notifyHookPrivileged(BundleContextImpl context, ServiceRegistra } /** - * Call a newly registered ListenerHook service to provide the current collection of - * service listeners. + * Call a newly registered ListenerHook service to provide the current + * collection of service listeners. * * @param registration The newly registered ListenerHook service. */ @@ -1397,7 +1428,8 @@ void notifyNewListenerHookPrivileged(ServiceRegistrationImpl registration) { // snapshot the listeners Collection addedListeners = new ArrayList<>(initialCapacity); synchronized (serviceEventListeners) { - for (CopyOnWriteIdentityMap listeners : serviceEventListeners.values()) { + for (CopyOnWriteIdentityMap listeners : serviceEventListeners + .values()) { if (!listeners.isEmpty()) { addedListeners.addAll(listeners.values()); } @@ -1413,14 +1445,16 @@ void notifyNewListenerHookPrivileged(ServiceRegistrationImpl registration) { } /** - * Call the registered ListenerHook services to notify them of newly added or removed service listeners. - * The ListenerHook must be called in order: descending by service.ranking, then ascending by service.id. - * This is the natural order for ServiceReference. + * Call the registered ListenerHook services to notify them of newly added or + * removed service listeners. The ListenerHook must be called in order: + * descending by service.ranking, then ascending by service.id. This is the + * natural order for ServiceReference. * - * @param listeners A non-empty, unmodifiable collection of ListenerInfo objects. - * All elements in the list must be for the same bundle. - * @param added true if the specified listeners are being added. false - * if they are being removed. + * @param listeners A non-empty, unmodifiable collection of ListenerInfo + * objects. All elements in the list must be for the same + * bundle. + * @param added true if the specified listeners are being + * added. false if they are being removed. */ private void notifyListenerHooks(final Collection listeners, final boolean added) { if (System.getSecurityManager() == null) { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ServiceUse.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ServiceUse.java index f2ce1914ad4..50dbb3512a0 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ServiceUse.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ServiceUse.java @@ -26,9 +26,10 @@ import org.eclipse.osgi.internal.messages.Msg; import org.eclipse.osgi.util.NLS; import org.osgi.framework.ServiceException; + /** - * This class represents the use of a service by a bundle. One is created for each - * service acquired by a bundle. + * This class represents the use of a service by a bundle. One is created for + * each service acquired by a bundle. * *

* This class manages a singleton service. @@ -63,8 +64,8 @@ public class ServiceUse { /** * Constructs a service use encapsulating the service object. * - * @param context bundle getting the service - * @param registration ServiceRegistration of the service + * @param context bundle getting the service + * @param registration ServiceRegistration of the service */ ServiceUse(BundleContextImpl context, ServiceRegistrationImpl registration) { this.useCount = 0; @@ -143,8 +144,8 @@ S newServiceObject() { * * @param service The service object to release. * @return true if the service was released; otherwise false. - * @throws IllegalArgumentException If the specified service was not - * provided by this object. + * @throws IllegalArgumentException If the specified service was not provided by + * this object. */ /* @GuardedBy("getLock()") */ boolean releaseServiceObject(final S service) { @@ -170,7 +171,8 @@ void release() { /** * Is this service use using any services? * - * @return true if no services are being used and this service use can be discarded. + * @return true if no services are being used and this service use can be + * discarded. */ /* @GuardedBy("getLock()") */ boolean isEmpty() { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ShrinkableCollection.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ShrinkableCollection.java index 728bcfbd988..e5e8d11c59f 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ShrinkableCollection.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ShrinkableCollection.java @@ -21,18 +21,18 @@ import java.util.List; /** - * A Shrinkable Collection. This class provides a wrapper for a list of collections - * that allows items to be removed from the wrapped collections (shrinking) but - * does not allow items to be added to the wrapped collections. + * A Shrinkable Collection. This class provides a wrapper for a list of + * collections that allows items to be removed from the wrapped collections + * (shrinking) but does not allow items to be added to the wrapped collections. * *

- * The collections must act as sets in that each collection in the list - * must not have two entries which are equal. + * The collections must act as sets in that each collection in the list must not + * have two entries which are equal. * *

- * All the optional Collection operations except - * add and addAll are supported. Attempting to add to the - * collection will result in an UnsupportedOperationException. + * All the optional Collection operations except add + * and addAll are supported. Attempting to add to the collection + * will result in an UnsupportedOperationException. * */ @@ -143,18 +143,18 @@ public Iterator iterator() { return new Iterator() { private E last; - @Override + @Override public boolean hasNext() { return iter.hasNext(); } - @Override + @Override public E next() { last = iter.next(); return last; } - @Override + @Override public void remove() { iter.remove(); for (Collection c : collections) { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ShrinkableValueCollectionMap.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ShrinkableValueCollectionMap.java index 34b337dfd58..a263336329d 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ShrinkableValueCollectionMap.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/serviceregistry/ShrinkableValueCollectionMap.java @@ -43,9 +43,10 @@ public boolean containsKey(Object key) { @Override public boolean containsValue(Object value) { - /* Since values are collections and the collection has identity equality, - * there is no way any value could be contained in this map unless that - * value has already been gotten from this map. + /* + * Since values are collections and the collection has identity equality, there + * is no way any value could be contained in this map unless that value has + * already been gotten from this map. */ if (values == null) { return false; diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/signedcontent/SignedBundleHook.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/signedcontent/SignedBundleHook.java index 684e2a75dc7..e0a7a92c4dd 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/signedcontent/SignedBundleHook.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/signedcontent/SignedBundleHook.java @@ -62,8 +62,9 @@ public class SignedBundleHook implements ActivatorHookFactory, HookConfigurator, SignedContentFactory { static final SecureAction secureAction = AccessController.doPrivileged(SecureAction.createSecureAction()); - //TODO: comes from configuration!; - private final static String CACERTS_PATH = System.getProperty("java.home") + File.separatorChar + "lib" + File.separatorChar + "security" + File.separatorChar + "cacerts"; //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$//$NON-NLS-4$ + // TODO: comes from configuration!; + private final static String CACERTS_PATH = System.getProperty("java.home") + File.separatorChar + "lib" //$NON-NLS-1$//$NON-NLS-2$ + + File.separatorChar + "security" + File.separatorChar + "cacerts"; //$NON-NLS-1$//$NON-NLS-2$ private final static String CACERTS_TYPE = "JKS"; //$NON-NLS-1$ private final static String OSGI_KEYSTORE = "osgi.framework.keystore"; //$NON-NLS-1$ private int supportSignedBundles; @@ -99,14 +100,17 @@ BundleContext getContext() { void frameworkStart(BundleContext bc) { this.context = bc; if ((supportSignedBundles & EquinoxConfiguration.SIGNED_CONTENT_VERIFY_TRUST) != 0) - // initialize the trust engine listener only if trust is being established with a trust engine + // initialize the trust engine listener only if trust is being established with + // a trust engine trustEngineListener = new TrustEngineListener(context, this); // always register the trust engine Dictionary trustEngineProps = new Hashtable<>(7); trustEngineProps.put(Constants.SERVICE_RANKING, Integer.valueOf(Integer.MIN_VALUE)); trustEngineProps.put(SignedContentConstants.TRUST_ENGINE, SignedContentConstants.DEFAULT_TRUST_ENGINE); - KeyStoreTrustEngine systemTrustEngine = new KeyStoreTrustEngine(CACERTS_PATH, CACERTS_TYPE, null, "System", this); //$NON-NLS-1$ - systemTrustEngineReg = context.registerService(TrustEngine.class.getName(), systemTrustEngine, trustEngineProps); + KeyStoreTrustEngine systemTrustEngine = new KeyStoreTrustEngine(CACERTS_PATH, CACERTS_TYPE, null, "System", //$NON-NLS-1$ + this); + systemTrustEngineReg = context.registerService(TrustEngine.class.getName(), systemTrustEngine, + trustEngineProps); String osgiTrustPath = context.getProperty(OSGI_KEYSTORE); if (osgiTrustPath != null) { try { @@ -115,7 +119,8 @@ void frameworkStart(BundleContext bc) { trustEngineProps.put(SignedContentConstants.TRUST_ENGINE, OSGI_KEYSTORE); String path = url.getPath(); osgiTrustEngineReg = new ArrayList<>(1); - osgiTrustEngineReg.add(context.registerService(TrustEngine.class.getName(), new KeyStoreTrustEngine(path, CACERTS_TYPE, null, OSGI_KEYSTORE, this), trustEngineProps)); + osgiTrustEngineReg.add(context.registerService(TrustEngine.class.getName(), + new KeyStoreTrustEngine(path, CACERTS_TYPE, null, OSGI_KEYSTORE, this), trustEngineProps)); } } catch (MalformedURLException e) { log("Invalid setting for " + OSGI_KEYSTORE, FrameworkLogEntry.WARNING, e); //$NON-NLS-1$ @@ -128,7 +133,9 @@ void frameworkStart(BundleContext bc) { osgiTrustEngineReg = new ArrayList<>(1); while (st.hasMoreTokens()) { String trustRepoPath = st.nextToken(); - osgiTrustEngineReg.add(context.registerService(TrustEngine.class.getName(), new KeyStoreTrustEngine(trustRepoPath, CACERTS_TYPE, null, OSGI_KEYSTORE, this), trustEngineProps)); + osgiTrustEngineReg.add(context.registerService(TrustEngine.class.getName(), + new KeyStoreTrustEngine(trustRepoPath, CACERTS_TYPE, null, OSGI_KEYSTORE, this), + trustEngineProps)); } } } @@ -165,7 +172,8 @@ public void addHooks(HookRegistry hookRegistry) { } @Override - public SignedContent getSignedContent(File content) throws IOException, InvalidKeyException, SignatureException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException { + public SignedContent getSignedContent(File content) throws IOException, InvalidKeyException, SignatureException, + CertificateException, NoSuchAlgorithmException, NoSuchProviderException { SignedContentFromBundleFile signedContent = new SignedContentFromBundleFile(content, container.getConfiguration().getDebug()); determineTrust(signedContent, EquinoxConfiguration.SIGNED_CONTENT_VERIFY_TRUST); @@ -173,7 +181,8 @@ public SignedContent getSignedContent(File content) throws IOException, InvalidK } @Override - public SignedContent getSignedContent(Bundle bundle) throws IOException, InvalidKeyException, SignatureException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException { + public SignedContent getSignedContent(Bundle bundle) throws IOException, InvalidKeyException, SignatureException, + CertificateException, NoSuchAlgorithmException, NoSuchProviderException { Generation generation = (Generation) ((EquinoxBundle) bundle).getModule().getCurrentRevision() .getRevisionInfo(); SignedContentFromBundleFile signedContent = new SignedContentFromBundleFile(generation.getBundleFile()); @@ -194,14 +203,16 @@ private TrustEngine[] getTrustEngines() { Filter filter = null; if (trustEngineNameProp != null) try { - filter = context.createFilter("(&(" + Constants.OBJECTCLASS + "=" + TrustEngine.class.getName() + ")(" + SignedContentConstants.TRUST_ENGINE + "=" + trustEngineNameProp + "))"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$//$NON-NLS-5$ + filter = context.createFilter("(&(" + Constants.OBJECTCLASS + "=" + TrustEngine.class.getName() //$NON-NLS-1$ //$NON-NLS-2$ + + ")(" + SignedContentConstants.TRUST_ENGINE + "=" + trustEngineNameProp + "))"); //$NON-NLS-1$ //$NON-NLS-2$//$NON-NLS-3$ } catch (InvalidSyntaxException e) { log("Invalid trust engine filter", FrameworkLogEntry.WARNING, e); //$NON-NLS-1$ } if (filter != null) { trustEngineTracker = new ServiceTracker<>(context, filter, new TrustEngineCustomizer()); } else - trustEngineTracker = new ServiceTracker<>(context, TrustEngine.class.getName(), new TrustEngineCustomizer()); + trustEngineTracker = new ServiceTracker<>(context, TrustEngine.class.getName(), + new TrustEngineCustomizer()); trustEngineTracker.open(); } Object[] services = trustEngineTracker.getServices(); @@ -267,19 +278,20 @@ void determineTrust(SignedContentFromBundleFile trustedContent, int supportFlags private Certificate findTrustAnchor(Certificate[] certs, TrustEngine[] engines, int supportFlags) { if ((supportFlags & EquinoxConfiguration.SIGNED_CONTENT_VERIFY_TRUST) == 0) - // we are not searching the engines; in this case we just assume the root cert is trusted + // we are not searching the engines; in this case we just assume the root cert + // is trusted return certs != null && certs.length > 0 ? certs[certs.length - 1] : null; - for (TrustEngine engine : engines) { - try { - Certificate anchor = engine.findTrustAnchor(certs); - if (anchor != null) - // found an anchor - return anchor; - } catch (IOException e) { - // log the exception and continue - log("TrustEngine failure: " + engine.getName(), FrameworkLogEntry.WARNING, e); //$NON-NLS-1$ - } + for (TrustEngine engine : engines) { + try { + Certificate anchor = engine.findTrustAnchor(certs); + if (anchor != null) + // found an anchor + return anchor; + } catch (IOException e) { + // log the exception and continue + log("TrustEngine failure: " + engine.getName(), FrameworkLogEntry.WARNING, e); //$NON-NLS-1$ } - return null; + } + return null; } } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/signedcontent/SignedContentConstants.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/signedcontent/SignedContentConstants.java index 3847cfdfea1..4edcc2f28f8 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/signedcontent/SignedContentConstants.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/signedcontent/SignedContentConstants.java @@ -43,29 +43,29 @@ public interface SignedContentConstants { public static final String digestManifestSearch = "-Digest-Manifest: "; //$NON-NLS-1$ public static final int digestManifestSearchLen = digestManifestSearch.length(); - public static final int SIGNEDDATA_OID[] = {1, 2, 840, 113549, 1, 7, 2}; - public static final int MD5_OID[] = {1, 2, 840, 113549, 2, 5}; - public static final int MD2_OID[] = {1, 2, 840, 113549, 2, 2}; + public static final int SIGNEDDATA_OID[] = { 1, 2, 840, 113549, 1, 7, 2 }; + public static final int MD5_OID[] = { 1, 2, 840, 113549, 2, 5 }; + public static final int MD2_OID[] = { 1, 2, 840, 113549, 2, 2 }; - public static final int SHA1_OID[] = {1, 3, 14, 3, 2, 26}; + public static final int SHA1_OID[] = { 1, 3, 14, 3, 2, 26 }; - public static final int SHA256_OID[] = {2, 16, 840, 1, 101, 3, 4, 2, 1}; - public static final int SHA384_OID[] = {2, 16, 840, 1, 101, 3, 4, 2, 2}; - public static final int SHA512_OID[] = {2, 16, 840, 1, 101, 3, 4, 2, 3}; - public static final int SHA224_OID[] = {2, 16, 840, 1, 101, 3, 4, 2, 4}; - public static final int SHA512_224_OID[] = {2, 16, 840, 1, 101, 3, 4, 2, 5}; - public static final int SHA512_256_OID[] = {2, 16, 840, 1, 101, 3, 4, 2, 6}; + public static final int SHA256_OID[] = { 2, 16, 840, 1, 101, 3, 4, 2, 1 }; + public static final int SHA384_OID[] = { 2, 16, 840, 1, 101, 3, 4, 2, 2 }; + public static final int SHA512_OID[] = { 2, 16, 840, 1, 101, 3, 4, 2, 3 }; + public static final int SHA224_OID[] = { 2, 16, 840, 1, 101, 3, 4, 2, 4 }; + public static final int SHA512_224_OID[] = { 2, 16, 840, 1, 101, 3, 4, 2, 5 }; + public static final int SHA512_256_OID[] = { 2, 16, 840, 1, 101, 3, 4, 2, 6 }; - public static final int DSA_OID[] = {1, 2, 840, 10040, 4, 1}; - public static final int RSA_OID[] = {1, 2, 840, 113549, 1, 1, 1}; + public static final int DSA_OID[] = { 1, 2, 840, 10040, 4, 1 }; + public static final int RSA_OID[] = { 1, 2, 840, 113549, 1, 1, 1 }; // constant for trust engine service public static final String TRUST_ENGINE = "osgi.signedcontent.trust.engine"; //$NON-NLS-1$ public static final Object DEFAULT_TRUST_ENGINE = "org.eclipse.osgi"; //$NON-NLS-1$ // constant for the timestamp related - public static final int TIMESTAMP_OID[] = {1, 2, 840, 113549, 1, 9, 16, 2, 14}; - public static final int TIMESTAMP_TST_OID[] = {1, 2, 840, 113549, 1, 9, 16, 1, 4}; - public static final int SIGNING_TIME[] = {1, 2, 840, 113549, 1, 9, 5}; + public static final int TIMESTAMP_OID[] = { 1, 2, 840, 113549, 1, 9, 16, 2, 14 }; + public static final int TIMESTAMP_TST_OID[] = { 1, 2, 840, 113549, 1, 9, 16, 1, 4 }; + public static final int SIGNING_TIME[] = { 1, 2, 840, 113549, 1, 9, 5 }; } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/signedcontent/SignedContentFromBundleFile.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/signedcontent/SignedContentFromBundleFile.java index 833eeff2bae..ec1d2fb787a 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/signedcontent/SignedContentFromBundleFile.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/signedcontent/SignedContentFromBundleFile.java @@ -47,6 +47,7 @@ public class SignedContentFromBundleFile implements SignedContent { static abstract class BaseSignerInfo implements SignerInfo { private volatile Certificate trustAnchor = null; + @Override public Certificate getTrustAnchor() { return trustAnchor; diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/url/ContentHandlerFactoryImpl.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/url/ContentHandlerFactoryImpl.java index f6d2fbb6b6f..93c0815fa3d 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/url/ContentHandlerFactoryImpl.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/url/ContentHandlerFactoryImpl.java @@ -32,11 +32,12 @@ import org.osgi.util.tracker.ServiceTracker; /** - * The ContentHandlerFactory is registered with the JVM to provide content handlers - * to requestors. The ContentHandlerFactory will first look for built-in content handlers. - * If a built in handler exists, this factory will return null. Otherwise, this ContentHandlerFactory - * will search the service registry for a maching Content-Handler and, if found, return a - * proxy for that content handler. + * The ContentHandlerFactory is registered with the JVM to provide content + * handlers to requestors. The ContentHandlerFactory will first look for + * built-in content handlers. If a built in handler exists, this factory will + * return null. Otherwise, this ContentHandlerFactory will search the service + * registry for a maching Content-Handler and, if found, return a proxy for that + * content handler. */ public class ContentHandlerFactoryImpl extends MultiplexingFactory implements java.net.ContentHandlerFactory { private ServiceTracker contentHandlerTracker; @@ -45,7 +46,8 @@ public class ContentHandlerFactoryImpl extends MultiplexingFactory implements ja private static final String CONTENT_HANDLER_PKGS = "java.content.handler.pkgs"; //$NON-NLS-1$ private static final String DEFAULT_VM_CONTENT_HANDLERS = "sun.net.www.content|sun.awt.www.content"; //$NON-NLS-1$ - private static final List> ignoredClasses = Arrays.asList(new Class[] {MultiplexingContentHandler.class, ContentHandlerFactoryImpl.class, URLConnection.class}); + private static final List> ignoredClasses = Arrays.asList( + new Class[] { MultiplexingContentHandler.class, ContentHandlerFactoryImpl.class, URLConnection.class }); private Map proxies; private java.net.ContentHandlerFactory parentFactory; @@ -55,7 +57,7 @@ public ContentHandlerFactoryImpl(BundleContext context, EquinoxContainer contain proxies = new Hashtable<>(5); - //We need to track content handler registrations + // We need to track content handler registrations contentHandlerTracker = new ServiceTracker<>(context, contentHandlerClazz, null); contentHandlerTracker.open(); } @@ -63,17 +65,19 @@ public ContentHandlerFactoryImpl(BundleContext context, EquinoxContainer contain /** * @see java.net.ContentHandlerFactory#createContentHandler(String) */ - //TODO method is too long... consider reducing indentation (returning quickly) and moving complex steps to private methods + // TODO method is too long... consider reducing indentation (returning quickly) + // and moving complex steps to private methods @Override public ContentHandler createContentHandler(String contentType) { - //first, we check to see if there exists a built in content handler for - //this content type. we can not overwrite built in ContentHandlers + // first, we check to see if there exists a built in content handler for + // this content type. we can not overwrite built in ContentHandlers String builtInHandlers = URLStreamHandlerFactoryImpl.secureAction.getProperty(CONTENT_HANDLER_PKGS); - builtInHandlers = builtInHandlers == null ? DEFAULT_VM_CONTENT_HANDLERS : DEFAULT_VM_CONTENT_HANDLERS + '|' + builtInHandlers; + builtInHandlers = builtInHandlers == null ? DEFAULT_VM_CONTENT_HANDLERS + : DEFAULT_VM_CONTENT_HANDLERS + '|' + builtInHandlers; Class clazz = null; if (builtInHandlers != null) { - //replace '/' with a '.' and all characters not allowed in a java class name - //with a '_'. + // replace '/' with a '.' and all characters not allowed in a java class name + // with a '_'. // find all characters not allowed in java names String convertedContentType = contentType.replace('.', '_'); @@ -88,10 +92,10 @@ public ContentHandler createContentHandler(String contentType) { try { clazz = URLStreamHandlerFactoryImpl.secureAction.loadSystemClass(name.toString()); if (clazz != null) { - return (null); //this class exists, it is a built in handler, let the JVM handle it + return (null); // this class exists, it is a built in handler, let the JVM handle it } } catch (ClassNotFoundException ex) { - //keep looking + // keep looking } } } @@ -103,7 +107,7 @@ public ContentHandler createContentHandler(String contentType) { } public ContentHandler createInternalContentHandler(String contentType) { - //first check to see if the handler is in the cache + // first check to see if the handler is in the cache ContentHandlerProxy proxy = proxies.get(contentType); if (proxy != null) { return (proxy); @@ -113,9 +117,10 @@ public ContentHandler createInternalContentHandler(String contentType) { for (ServiceReference serviceReference : serviceReferences) { Object prop = serviceReference.getProperty(URLConstants.URL_CONTENT_MIMETYPE); if (prop instanceof String) - prop = new String[] {(String) prop}; // TODO should this be a warning? + prop = new String[] { (String) prop }; // TODO should this be a warning? if (!(prop instanceof String[])) { - String message = NLS.bind(Msg.URL_HANDLER_INCORRECT_TYPE, new Object[]{URLConstants.URL_CONTENT_MIMETYPE, contentHandlerClazz, serviceReference.getBundle()}); + String message = NLS.bind(Msg.URL_HANDLER_INCORRECT_TYPE, new Object[] { + URLConstants.URL_CONTENT_MIMETYPE, contentHandlerClazz, serviceReference.getBundle() }); container.getLogServices().log(EquinoxContainer.NAME, FrameworkLogEntry.WARNING, message, null); continue; } @@ -135,8 +140,10 @@ public ContentHandler createInternalContentHandler(String contentType) { if (parentHandler != null) return parentHandler; } - //If we can't find the content handler in the service registry, return Proxy with DefaultContentHandler set. - //We need to do this because if we return null, we won't get called again for this content type. + // If we can't find the content handler in the service registry, return Proxy + // with DefaultContentHandler set. + // We need to do this because if we return null, we won't get called again for + // this content type. proxy = new ContentHandlerProxy(contentType, null, context); proxies.put(contentType, proxy); return (proxy); @@ -151,10 +158,12 @@ public synchronized ContentHandler findAuthorizedContentHandler(String contentTy return createInternalContentHandler(contentType); try { - Method createInternalContentHandlerMethod = factory.getClass().getMethod("createInternalContentHandler", new Class[] {String.class}); //$NON-NLS-1$ - return (ContentHandler) createInternalContentHandlerMethod.invoke(factory, new Object[] {contentType}); + Method createInternalContentHandlerMethod = factory.getClass().getMethod("createInternalContentHandler", //$NON-NLS-1$ + new Class[] { String.class }); + return (ContentHandler) createInternalContentHandlerMethod.invoke(factory, new Object[] { contentType }); } catch (Exception e) { - container.getLogServices().log(ContentHandlerFactoryImpl.class.getName(), FrameworkLogEntry.ERROR, "findAuthorizedContentHandler-loop", e); //$NON-NLS-1$ + container.getLogServices().log(ContentHandlerFactoryImpl.class.getName(), FrameworkLogEntry.ERROR, + "findAuthorizedContentHandler-loop", e); //$NON-NLS-1$ throw new RuntimeException(e.getMessage(), e); } } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/url/ContentHandlerProxy.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/url/ContentHandlerProxy.java index f182360e71c..ca830cb4ec2 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/url/ContentHandlerProxy.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/url/ContentHandlerProxy.java @@ -23,17 +23,20 @@ import org.osgi.util.tracker.ServiceTrackerCustomizer; /** - * The ContentHandlerProxy is a ContentHandler that acts as a proxy for registered ContentHandlers. - * When a ContentHandler is requested from the ContentHandlerFactory and it exists in the service - * registry, a ContentHandlerProxy is created which will pass all the requests from the requestor to - * the real ContentHandler. We can't return the real ContentHandler from the ContentHandlerFactory - * because the JVM caches ContentHandlers and therefore would not support a dynamic environment of - * ContentHandlers being registered and unregistered. + * The ContentHandlerProxy is a ContentHandler that acts as a proxy for + * registered ContentHandlers. When a ContentHandler is requested from the + * ContentHandlerFactory and it exists in the service registry, a + * ContentHandlerProxy is created which will pass all the requests from the + * requestor to the real ContentHandler. We can't return the real ContentHandler + * from the ContentHandlerFactory because the JVM caches ContentHandlers and + * therefore would not support a dynamic environment of ContentHandlers being + * registered and unregistered. */ -public class ContentHandlerProxy extends ContentHandler implements ServiceTrackerCustomizer> { +public class ContentHandlerProxy extends ContentHandler + implements ServiceTrackerCustomizer> { protected ContentHandler realHandler; - //TODO avoid type-based names + // TODO avoid type-based names protected ServiceTracker> contentHandlerServiceTracker; protected BundleContext context; @@ -47,7 +50,8 @@ public ContentHandlerProxy(String contentType, ServiceReference this.context = context; this.contentType = contentType; - // In case the reference == null, the proxy is constructed with DefaultContentHandler for a Content Handler + // In case the reference == null, the proxy is constructed with + // DefaultContentHandler for a Content Handler // until a real ContentHandler for this mime-type is registered setNewHandler(reference, getRank(reference)); @@ -73,10 +77,10 @@ private void setNewHandler(ServiceReference reference, int rank) */ @Override public ServiceReference addingService(ServiceReference reference) { - //check to see if our contentType is being registered by another service + // check to see if our contentType is being registered by another service Object prop = reference.getProperty(URLConstants.URL_CONTENT_MIMETYPE); if (prop instanceof String) { - prop = new String[] {(String) prop}; + prop = new String[] { (String) prop }; } if (!(prop instanceof String[])) { return null; @@ -84,7 +88,8 @@ public ServiceReference addingService(ServiceReference ranking || contentHandlerServiceReference == null) setNewHandler(reference, newServiceRanking); @@ -92,12 +97,14 @@ public ServiceReference addingService(ServiceReference reference, ServiceR int newrank = getRank(reference); if (reference == contentHandlerServiceReference) { if (newrank < ranking) { - // The ContentHandler we are currently using has dropped it's ranking below a ContentHandler - // registered for the same protocol. We need to swap out ContentHandlers. + // The ContentHandler we are currently using has dropped it's ranking below a + // ContentHandler + // registered for the same protocol. We need to swap out ContentHandlers. // this should get us the highest ranked service, if available ServiceReference newReference = contentHandlerServiceTracker.getServiceReference(); if (newReference != contentHandlerServiceReference && newReference != null) { - setNewHandler(newReference, ((Integer) newReference.getProperty(Constants.SERVICE_RANKING)).intValue()); + setNewHandler(newReference, + ((Integer) newReference.getProperty(Constants.SERVICE_RANKING)).intValue()); } } } else if (newrank > ranking) { @@ -121,11 +130,12 @@ public void modifiedService(ServiceReference reference, ServiceR } /** - * @see org.osgi.util.tracker.ServiceTrackerCustomizer#removedService(ServiceReference, Object) + * @see org.osgi.util.tracker.ServiceTrackerCustomizer#removedService(ServiceReference, + * Object) */ @Override public void removedService(ServiceReference reference, ServiceReference service) { - //check to see if our URLStreamHandler was unregistered. + // check to see if our URLStreamHandler was unregistered. if (reference != contentHandlerServiceReference) return; // If so, look for a lower ranking URLHandler diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/url/EquinoxFactoryManager.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/url/EquinoxFactoryManager.java index 677d96ddfb8..4b2142cd875 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/url/EquinoxFactoryManager.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/url/EquinoxFactoryManager.java @@ -70,13 +70,14 @@ private static void forceURLStreamHandlerFactory(URLStreamHandlerFactoryImpl shf Object lock = getURLStreamHandlerFactoryLock(); synchronized (lock) { URLStreamHandlerFactory factory = (URLStreamHandlerFactory) factoryField.get(null); - // doing a null check here just in case, but it would be really strange if it was null, + // doing a null check here just in case, but it would be really strange if it + // was null, // because we failed to set the factory normally!! if (factory != null) { try { factory.getClass().getMethod("isMultiplexing", (Class[]) null); //$NON-NLS-1$ - Method register = factory.getClass().getMethod("register", new Class[] {Object.class}); //$NON-NLS-1$ - register.invoke(factory, new Object[] {shf}); + Method register = factory.getClass().getMethod("register", new Class[] { Object.class }); //$NON-NLS-1$ + register.invoke(factory, new Object[] { shf }); } catch (NoSuchMethodException e) { // current factory does not support multiplexing, ok we'll wrap it shf.setParentFactory(factory); @@ -139,14 +140,15 @@ private static void forceContentHandlerFactory(ContentHandlerFactoryImpl chf) th throw new Exception("Could not find ContentHandlerFactory field"); //$NON-NLS-1$ synchronized (URLConnection.class) { java.net.ContentHandlerFactory factory = (java.net.ContentHandlerFactory) factoryField.get(null); - // doing a null check here just in case, but it would be really strange if it was null, + // doing a null check here just in case, but it would be really strange if it + // was null, // because we failed to set the factory normally!! if (factory != null) { try { factory.getClass().getMethod("isMultiplexing", (Class[]) null); //$NON-NLS-1$ - Method register = factory.getClass().getMethod("register", new Class[] {Object.class}); //$NON-NLS-1$ - register.invoke(factory, new Object[] {chf}); + Method register = factory.getClass().getMethod("register", new Class[] { Object.class }); //$NON-NLS-1$ + register.invoke(factory, new Object[] { chf }); } catch (NoSuchMethodException e) { // current factory does not support multiplexing, ok we'll wrap it chf.setParentFactory(factory); @@ -191,8 +193,8 @@ private void uninstallURLStreamHandlerFactory() { if (factory == urlStreamHandlerFactory) { factory = (URLStreamHandlerFactory) urlStreamHandlerFactory.designateSuccessor(); } else { - Method unregister = factory.getClass().getMethod("unregister", new Class[] {Object.class}); //$NON-NLS-1$ - unregister.invoke(factory, new Object[] {urlStreamHandlerFactory}); + Method unregister = factory.getClass().getMethod("unregister", new Class[] { Object.class }); //$NON-NLS-1$ + unregister.invoke(factory, new Object[] { urlStreamHandlerFactory }); } factoryField.set(null, null); // always attempt to clear the handlers cache @@ -223,8 +225,8 @@ private void uninstallContentHandlerFactory() { if (factory == contentHandlerFactory) { factory = (java.net.ContentHandlerFactory) contentHandlerFactory.designateSuccessor(); } else { - Method unregister = factory.getClass().getMethod("unregister", new Class[] {Object.class}); //$NON-NLS-1$ - unregister.invoke(factory, new Object[] {contentHandlerFactory}); + Method unregister = factory.getClass().getMethod("unregister", new Class[] { Object.class }); //$NON-NLS-1$ + unregister.invoke(factory, new Object[] { contentHandlerFactory }); } // null out the field so that we can successfully call setContentHandlerFactory factoryField.set(null, null); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/url/MultiplexingFactory.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/url/MultiplexingFactory.java index 402375fdefe..fafd5a36453 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/url/MultiplexingFactory.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/url/MultiplexingFactory.java @@ -40,17 +40,18 @@ public abstract class MultiplexingFactory { /** * As a short-term (hopefully) solution we use a special class which is defined - * using the Unsafe class from the VM. This class is an implementation of + * using the Unsafe class from the VM. This class is an implementation of * Collection simply to provide a method add(AccessibleObject) * which turns around and calls AccessibleObject.setAccessible(true). *

- * The reason this is needed is to hack into the VM to get deep reflective access to - * the java.net package for the various hacks we have to do to multiplex the - * URL and Content handlers. Note that on Java 9 deep reflection is not possible - * by default on the java.net package. + * The reason this is needed is to hack into the VM to get deep reflective + * access to the java.net package for the various hacks we have to do to + * multiplex the URL and Content handlers. Note that on Java 9 deep reflection + * is not possible by default on the java.net package. *

* The setAccessible class will be defined in the java.base module which grants - * it the ability to call setAccessible(true) on other types from the java.base module + * it the ability to call setAccessible(true) on other types from the java.base + * module */ public static final Collection setAccessible; static final Collection systemLoaders; @@ -65,11 +66,14 @@ public abstract class MultiplexingFactory { theUnsafe.setAccessible(true); Object unsafe = theUnsafe.get(null); - // The SetAccessible bytes stored in a resource to avoid real loading of it (see SetAccessible.java.src for source). - byte[] bytes = StorageUtil.getBytes(MultiplexingFactory.class.getResource("SetAccessible.bytes").openStream(), -1, 4000); //$NON-NLS-1$ + // The SetAccessible bytes stored in a resource to avoid real loading of it (see + // SetAccessible.java.src for source). + byte[] bytes = StorageUtil + .getBytes(MultiplexingFactory.class.getResource("SetAccessible.bytes").openStream(), -1, 4000); //$NON-NLS-1$ Class> collectionClass = null; - // using defineAnonymousClass here because it seems more simple to get what we need + // using defineAnonymousClass here because it seems more simple to get what we + // need try { Method defineAnonymousClass = unsafeClass.getMethod("defineAnonymousClass", Class.class, byte[].class, //$NON-NLS-1$ Object[].class); @@ -147,8 +151,8 @@ public void register(Object factory) { // set parent for each factory so they can do proper delegation try { Class clazz = factory.getClass(); - Method setParentFactory = clazz.getMethod("setParentFactory", new Class[] {Object.class}); //$NON-NLS-1$ - setParentFactory.invoke(factory, new Object[] {getParentFactory()}); + Method setParentFactory = clazz.getMethod("setParentFactory", new Class[] { Object.class }); //$NON-NLS-1$ + setParentFactory.invoke(factory, new Object[] { getParentFactory() }); } catch (Exception e) { container.getLogServices().log(MultiplexingFactory.class.getName(), FrameworkLogEntry.ERROR, "register", e); //$NON-NLS-1$ // just return and not have it registered @@ -161,12 +165,15 @@ public void unregister(Object factory) { removeFactory(factory); // close the service tracker try { - // this is brittle; if class does not directly extend MultplexingFactory then this method will not exist, but we do not want a public method here - Method closeTracker = factory.getClass().getSuperclass().getDeclaredMethod("closePackageAdminTracker", (Class[]) null); //$NON-NLS-1$ + // this is brittle; if class does not directly extend MultplexingFactory then + // this method will not exist, but we do not want a public method here + Method closeTracker = factory.getClass().getSuperclass().getDeclaredMethod("closePackageAdminTracker", //$NON-NLS-1$ + (Class[]) null); closeTracker.setAccessible(true); // its a private method closeTracker.invoke(factory, (Object[]) null); } catch (Exception e) { - container.getLogServices().log(MultiplexingFactory.class.getName(), FrameworkLogEntry.ERROR, "unregister", e); //$NON-NLS-1$ + container.getLogServices().log(MultiplexingFactory.class.getName(), FrameworkLogEntry.ERROR, "unregister", //$NON-NLS-1$ + e); // just return without blowing up here } } @@ -176,7 +183,7 @@ public Object designateSuccessor() { // Note that we do this outside of the sync block above. // This is only possible because we do additional locking outside of // this class to ensure no other threads are trying to manipulate the - // list of registered factories. See Framework class the following methods: + // list of registered factories. See Framework class the following methods: // Framework.installURLStreamHandlerFactory(BundleContext, FrameworkAdaptor) // Framework.installContentHandlerFactory(BundleContext, FrameworkAdaptor) // Framework.uninstallURLStreamHandlerFactory @@ -186,12 +193,13 @@ public Object designateSuccessor() { Object successor = released.remove(0); try { Class clazz = successor.getClass(); - Method register = clazz.getMethod("register", new Class[] {Object.class}); //$NON-NLS-1$ + Method register = clazz.getMethod("register", new Class[] { Object.class }); //$NON-NLS-1$ for (Object r : released) { - register.invoke(successor, new Object[] {r}); + register.invoke(successor, new Object[] { r }); } } catch (Exception e) { - container.getLogServices().log(MultiplexingFactory.class.getName(), FrameworkLogEntry.ERROR, "designateSuccessor", e); //$NON-NLS-1$ + container.getLogServices().log(MultiplexingFactory.class.getName(), FrameworkLogEntry.ERROR, + "designateSuccessor", e); //$NON-NLS-1$ throw new RuntimeException(e.getMessage(), e); } closePackageAdminTracker(); // close tracker @@ -206,7 +214,8 @@ public Object findAuthorizedFactory(List> ignoredClasses) { List current = getFactories(); Class[] classStack = internalSecurityManager.getClassContext(); for (Class clazz : classStack) { - if (clazz == InternalSecurityManager.class || clazz == MultiplexingFactory.class || ignoredClasses.contains(clazz) || isSystemClass(clazz)) + if (clazz == InternalSecurityManager.class || clazz == MultiplexingFactory.class + || ignoredClasses.contains(clazz) || isSystemClass(clazz)) continue; if (hasAuthority(clazz)) return this; @@ -214,12 +223,14 @@ public Object findAuthorizedFactory(List> ignoredClasses) { continue; for (Object factory : current) { try { - Method hasAuthorityMethod = factory.getClass().getMethod("hasAuthority", new Class[] {Class.class}); //$NON-NLS-1$ - if (((Boolean) hasAuthorityMethod.invoke(factory, new Object[] {clazz})).booleanValue()) { + Method hasAuthorityMethod = factory.getClass().getMethod("hasAuthority", //$NON-NLS-1$ + new Class[] { Class.class }); + if (((Boolean) hasAuthorityMethod.invoke(factory, new Object[] { clazz })).booleanValue()) { return factory; } } catch (Exception e) { - container.getLogServices().log(MultiplexingFactory.class.getName(), FrameworkLogEntry.ERROR, "findAuthorizedURLStreamHandler-loop", e); //$NON-NLS-1$ + container.getLogServices().log(MultiplexingFactory.class.getName(), FrameworkLogEntry.ERROR, + "findAuthorizedURLStreamHandler-loop", e); //$NON-NLS-1$ // we continue to the next factory here instead of failing } } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/url/MultiplexingURLStreamHandler.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/url/MultiplexingURLStreamHandler.java index 4ce1cb4338e..621bb05b1cc 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/url/MultiplexingURLStreamHandler.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/url/MultiplexingURLStreamHandler.java @@ -40,37 +40,44 @@ private static synchronized void initializeMethods(URLStreamHandlerFactoryImpl f if (methodsInitialized) return; try { - openConnectionMethod = URLStreamHandler.class.getDeclaredMethod("openConnection", new Class[] {URL.class}); //$NON-NLS-1$ + openConnectionMethod = URLStreamHandler.class.getDeclaredMethod("openConnection", //$NON-NLS-1$ + new Class[] { URL.class }); MultiplexingFactory.setAccessible(openConnectionMethod); - openConnectionProxyMethod = URLStreamHandler.class.getDeclaredMethod("openConnection", new Class[] {URL.class, Proxy.class}); //$NON-NLS-1$ + openConnectionProxyMethod = URLStreamHandler.class.getDeclaredMethod("openConnection", //$NON-NLS-1$ + new Class[] { URL.class, Proxy.class }); MultiplexingFactory.setAccessible(openConnectionProxyMethod); - equalsMethod = URLStreamHandler.class.getDeclaredMethod("equals", new Class[] {URL.class, URL.class}); //$NON-NLS-1$ + equalsMethod = URLStreamHandler.class.getDeclaredMethod("equals", new Class[] { URL.class, URL.class }); //$NON-NLS-1$ MultiplexingFactory.setAccessible(equalsMethod); getDefaultPortMethod = URLStreamHandler.class.getDeclaredMethod("getDefaultPort", (Class[]) null); //$NON-NLS-1$ MultiplexingFactory.setAccessible(getDefaultPortMethod); - getHostAddressMethod = URLStreamHandler.class.getDeclaredMethod("getHostAddress", new Class[] {URL.class}); //$NON-NLS-1$ + getHostAddressMethod = URLStreamHandler.class.getDeclaredMethod("getHostAddress", //$NON-NLS-1$ + new Class[] { URL.class }); MultiplexingFactory.setAccessible(getHostAddressMethod); - hashCodeMethod = URLStreamHandler.class.getDeclaredMethod("hashCode", new Class[] {URL.class}); //$NON-NLS-1$ + hashCodeMethod = URLStreamHandler.class.getDeclaredMethod("hashCode", new Class[] { URL.class }); //$NON-NLS-1$ MultiplexingFactory.setAccessible(hashCodeMethod); - hostsEqualMethod = URLStreamHandler.class.getDeclaredMethod("hostsEqual", new Class[] {URL.class, URL.class}); //$NON-NLS-1$ + hostsEqualMethod = URLStreamHandler.class.getDeclaredMethod("hostsEqual", //$NON-NLS-1$ + new Class[] { URL.class, URL.class }); MultiplexingFactory.setAccessible(hostsEqualMethod); - parseURLMethod = URLStreamHandler.class.getDeclaredMethod("parseURL", new Class[] {URL.class, String.class, Integer.TYPE, Integer.TYPE}); //$NON-NLS-1$ + parseURLMethod = URLStreamHandler.class.getDeclaredMethod("parseURL", //$NON-NLS-1$ + new Class[] { URL.class, String.class, Integer.TYPE, Integer.TYPE }); MultiplexingFactory.setAccessible(parseURLMethod); - sameFileMethod = URLStreamHandler.class.getDeclaredMethod("sameFile", new Class[] {URL.class, URL.class}); //$NON-NLS-1$ + sameFileMethod = URLStreamHandler.class.getDeclaredMethod("sameFile", new Class[] { URL.class, URL.class }); //$NON-NLS-1$ MultiplexingFactory.setAccessible(sameFileMethod); - setURLMethod = URLStreamHandler.class.getDeclaredMethod("setURL", new Class[] {URL.class, String.class, String.class, Integer.TYPE, String.class, String.class, String.class, String.class, String.class}); //$NON-NLS-1$ + setURLMethod = URLStreamHandler.class.getDeclaredMethod("setURL", new Class[] { URL.class, String.class, //$NON-NLS-1$ + String.class, Integer.TYPE, String.class, String.class, String.class, String.class, String.class }); MultiplexingFactory.setAccessible(setURLMethod); - toExternalFormMethod = URLStreamHandler.class.getDeclaredMethod("toExternalForm", new Class[] {URL.class}); //$NON-NLS-1$ + toExternalFormMethod = URLStreamHandler.class.getDeclaredMethod("toExternalForm", //$NON-NLS-1$ + new Class[] { URL.class }); MultiplexingFactory.setAccessible(toExternalFormMethod); try { @@ -82,13 +89,15 @@ private static synchronized void initializeMethods(URLStreamHandlerFactoryImpl f } MultiplexingFactory.setAccessible(handlerField); } catch (Exception e) { - factory.container.getLogServices().log(MultiplexingURLStreamHandler.class.getName(), FrameworkLogEntry.ERROR, "initializeMethods", e); //$NON-NLS-1$ + factory.container.getLogServices().log(MultiplexingURLStreamHandler.class.getName(), + FrameworkLogEntry.ERROR, "initializeMethods", e); //$NON-NLS-1$ throw new RuntimeException(e.getMessage(), e); } methodsInitialized = true; } - public MultiplexingURLStreamHandler(String protocol, URLStreamHandlerFactoryImpl factory, URLStreamHandler authorized) { + public MultiplexingURLStreamHandler(String protocol, URLStreamHandlerFactoryImpl factory, + URLStreamHandler authorized) { this.protocol = protocol; this.factory = factory; this.authorized = authorized; @@ -100,13 +109,14 @@ protected URLConnection openConnection(URL url) throws IOException { URLStreamHandler handler = findAuthorizedURLStreamHandler(protocol); if (handler != null) { try { - return (URLConnection) openConnectionMethod.invoke(handler, new Object[] {url}); + return (URLConnection) openConnectionMethod.invoke(handler, new Object[] { url }); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof IOException) throw (IOException) e.getTargetException(); throw (RuntimeException) e.getTargetException(); } catch (Exception e) { - factory.container.getLogServices().log(MultiplexingURLStreamHandler.class.getName(), FrameworkLogEntry.ERROR, "openConnection", e); //$NON-NLS-1$ + factory.container.getLogServices().log(MultiplexingURLStreamHandler.class.getName(), + FrameworkLogEntry.ERROR, "openConnection", e); //$NON-NLS-1$ throw new RuntimeException(e.getMessage(), e); } } @@ -118,13 +128,14 @@ protected URLConnection openConnection(URL url, Proxy proxy) throws IOException URLStreamHandler handler = findAuthorizedURLStreamHandler(protocol); if (handler != null) { try { - return (URLConnection) openConnectionProxyMethod.invoke(handler, new Object[] {url, proxy}); + return (URLConnection) openConnectionProxyMethod.invoke(handler, new Object[] { url, proxy }); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof IOException) throw (IOException) e.getTargetException(); throw (RuntimeException) e.getTargetException(); } catch (Exception e) { - factory.container.getLogServices().log(MultiplexingURLStreamHandler.class.getName(), FrameworkLogEntry.ERROR, "openConnection", e); //$NON-NLS-1$ + factory.container.getLogServices().log(MultiplexingURLStreamHandler.class.getName(), + FrameworkLogEntry.ERROR, "openConnection", e); //$NON-NLS-1$ throw new RuntimeException(e.getMessage(), e); } } @@ -136,11 +147,12 @@ protected boolean equals(URL url1, URL url2) { URLStreamHandler handler = findAuthorizedURLStreamHandler(protocol); if (handler != null) { try { - return ((Boolean) equalsMethod.invoke(handler, new Object[] {url1, url2})).booleanValue(); + return ((Boolean) equalsMethod.invoke(handler, new Object[] { url1, url2 })).booleanValue(); } catch (InvocationTargetException e) { throw (RuntimeException) e.getTargetException(); } catch (Exception e) { - factory.container.getLogServices().log(MultiplexingURLStreamHandler.class.getName(), FrameworkLogEntry.ERROR, "equals", e); //$NON-NLS-1$ + factory.container.getLogServices().log(MultiplexingURLStreamHandler.class.getName(), + FrameworkLogEntry.ERROR, "equals", e); //$NON-NLS-1$ throw new RuntimeException(e.getMessage(), e); } } @@ -156,7 +168,8 @@ protected int getDefaultPort() { } catch (InvocationTargetException e) { throw (RuntimeException) e.getTargetException(); } catch (Exception e) { - factory.container.getLogServices().log(MultiplexingURLStreamHandler.class.getName(), FrameworkLogEntry.ERROR, "getDefaultPort", e); //$NON-NLS-1$ + factory.container.getLogServices().log(MultiplexingURLStreamHandler.class.getName(), + FrameworkLogEntry.ERROR, "getDefaultPort", e); //$NON-NLS-1$ throw new RuntimeException(e.getMessage(), e); } } @@ -168,11 +181,12 @@ protected InetAddress getHostAddress(URL url) { URLStreamHandler handler = findAuthorizedURLStreamHandler(protocol); if (handler != null) { try { - return (InetAddress) getHostAddressMethod.invoke(handler, new Object[] {url}); + return (InetAddress) getHostAddressMethod.invoke(handler, new Object[] { url }); } catch (InvocationTargetException e) { throw (RuntimeException) e.getTargetException(); } catch (Exception e) { - factory.container.getLogServices().log(MultiplexingURLStreamHandler.class.getName(), FrameworkLogEntry.ERROR, "hashCode", e); //$NON-NLS-1$ + factory.container.getLogServices().log(MultiplexingURLStreamHandler.class.getName(), + FrameworkLogEntry.ERROR, "hashCode", e); //$NON-NLS-1$ throw new RuntimeException(e.getMessage(), e); } } @@ -184,11 +198,12 @@ protected int hashCode(URL url) { URLStreamHandler handler = findAuthorizedURLStreamHandler(protocol); if (handler != null) { try { - return ((Integer) hashCodeMethod.invoke(handler, new Object[] {url})).intValue(); + return ((Integer) hashCodeMethod.invoke(handler, new Object[] { url })).intValue(); } catch (InvocationTargetException e) { throw (RuntimeException) e.getTargetException(); } catch (Exception e) { - factory.container.getLogServices().log(MultiplexingURLStreamHandler.class.getName(), FrameworkLogEntry.ERROR, "hashCode", e); //$NON-NLS-1$ + factory.container.getLogServices().log(MultiplexingURLStreamHandler.class.getName(), + FrameworkLogEntry.ERROR, "hashCode", e); //$NON-NLS-1$ throw new RuntimeException(e.getMessage(), e); } } @@ -200,11 +215,12 @@ protected boolean hostsEqual(URL url1, URL url2) { URLStreamHandler handler = findAuthorizedURLStreamHandler(protocol); if (handler != null) { try { - return ((Boolean) hostsEqualMethod.invoke(handler, new Object[] {url1, url2})).booleanValue(); + return ((Boolean) hostsEqualMethod.invoke(handler, new Object[] { url1, url2 })).booleanValue(); } catch (InvocationTargetException e) { throw (RuntimeException) e.getTargetException(); } catch (Exception e) { - factory.container.getLogServices().log(MultiplexingURLStreamHandler.class.getName(), FrameworkLogEntry.ERROR, "hostsEqual", e); //$NON-NLS-1$ + factory.container.getLogServices().log(MultiplexingURLStreamHandler.class.getName(), + FrameworkLogEntry.ERROR, "hostsEqual", e); //$NON-NLS-1$ throw new RuntimeException(e.getMessage(), e); } } @@ -218,12 +234,14 @@ protected void parseURL(URL arg0, String arg1, int arg2, int arg3) { try { // set the real handler for the URL handlerField.set(arg0, handler); - parseURLMethod.invoke(handler, new Object[] {arg0, arg1, Integer.valueOf(arg2), Integer.valueOf(arg3)}); + parseURLMethod.invoke(handler, + new Object[] { arg0, arg1, Integer.valueOf(arg2), Integer.valueOf(arg3) }); return; } catch (InvocationTargetException e) { throw (RuntimeException) e.getTargetException(); } catch (Exception e) { - factory.container.getLogServices().log(MultiplexingURLStreamHandler.class.getName(), FrameworkLogEntry.ERROR, "parseURL", e); //$NON-NLS-1$ + factory.container.getLogServices().log(MultiplexingURLStreamHandler.class.getName(), + FrameworkLogEntry.ERROR, "parseURL", e); //$NON-NLS-1$ throw new RuntimeException(e.getMessage(), e); } } @@ -235,11 +253,12 @@ protected boolean sameFile(URL url1, URL url2) { URLStreamHandler handler = findAuthorizedURLStreamHandler(protocol); if (handler != null) { try { - return ((Boolean) sameFileMethod.invoke(handler, new Object[] {url1, url2})).booleanValue(); + return ((Boolean) sameFileMethod.invoke(handler, new Object[] { url1, url2 })).booleanValue(); } catch (InvocationTargetException e) { throw (RuntimeException) e.getTargetException(); } catch (Exception e) { - factory.container.getLogServices().log(MultiplexingURLStreamHandler.class.getName(), FrameworkLogEntry.ERROR, "sameFile", e); //$NON-NLS-1$ + factory.container.getLogServices().log(MultiplexingURLStreamHandler.class.getName(), + FrameworkLogEntry.ERROR, "sameFile", e); //$NON-NLS-1$ throw new RuntimeException(e.getMessage(), e); } } @@ -247,18 +266,21 @@ protected boolean sameFile(URL url1, URL url2) { } @Override - protected void setURL(URL arg0, String arg1, String arg2, int arg3, String arg4, String arg5, String arg6, String arg7, String arg8) { + protected void setURL(URL arg0, String arg1, String arg2, int arg3, String arg4, String arg5, String arg6, + String arg7, String arg8) { URLStreamHandler handler = findAuthorizedURLStreamHandler(protocol); if (handler != null) { try { // set the real handler for the URL handlerField.set(arg0, handler); - setURLMethod.invoke(handler, new Object[] {arg0, arg1, arg2, Integer.valueOf(arg3), arg4, arg5, arg6, arg7, arg8}); + setURLMethod.invoke(handler, + new Object[] { arg0, arg1, arg2, Integer.valueOf(arg3), arg4, arg5, arg6, arg7, arg8 }); return; } catch (InvocationTargetException e) { throw (RuntimeException) e.getTargetException(); } catch (Exception e) { - factory.container.getLogServices().log(MultiplexingURLStreamHandler.class.getName(), FrameworkLogEntry.ERROR, "setURL", e); //$NON-NLS-1$ + factory.container.getLogServices().log(MultiplexingURLStreamHandler.class.getName(), + FrameworkLogEntry.ERROR, "setURL", e); //$NON-NLS-1$ throw new RuntimeException(e.getMessage(), e); } } @@ -270,11 +292,12 @@ protected String toExternalForm(URL url) { URLStreamHandler handler = findAuthorizedURLStreamHandler(protocol); if (handler != null) { try { - return (String) toExternalFormMethod.invoke(handler, new Object[] {url}); + return (String) toExternalFormMethod.invoke(handler, new Object[] { url }); } catch (InvocationTargetException e) { throw (RuntimeException) e.getTargetException(); } catch (Exception e) { - factory.container.getLogServices().log(MultiplexingURLStreamHandler.class.getName(), FrameworkLogEntry.ERROR, "toExternalForm", e); //$NON-NLS-1$ + factory.container.getLogServices().log(MultiplexingURLStreamHandler.class.getName(), + FrameworkLogEntry.ERROR, "toExternalForm", e); //$NON-NLS-1$ throw new RuntimeException(e.getMessage(), e); } } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/url/NullURLStreamHandlerService.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/url/NullURLStreamHandlerService.java index 6e828d6b77a..ab305282679 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/url/NullURLStreamHandlerService.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/url/NullURLStreamHandlerService.java @@ -20,12 +20,13 @@ import org.osgi.service.url.URLStreamHandlerSetter; /** - * The NullURLStreamService is created when a registered URLStreamHandler service - * with an associated URLStreamHandlerProxy becomes unregistered. The associated - * URLStreamHandlerProxy must still handle all future requests for the now unregistered - * scheme (the JVM caches URLStreamHandlers making up impossible to "unregister" them). - * When requests come in for an unregistered URLStreamHandlerService, the - * NullURLStreamHandlerService is used in it's place. + * The NullURLStreamService is created when a registered URLStreamHandler + * service with an associated URLStreamHandlerProxy becomes unregistered. The + * associated URLStreamHandlerProxy must still handle all future requests for + * the now unregistered scheme (the JVM caches URLStreamHandlers making up + * impossible to "unregister" them). When requests come in for an unregistered + * URLStreamHandlerService, the NullURLStreamHandlerService is used in it's + * place. */ public class NullURLStreamHandlerService implements URLStreamHandlerService { @@ -65,7 +66,8 @@ public boolean sameFile(URL url1, URL url2) { throw new IllegalStateException(); } - public void setURL(URL u, String protocol, String host, int port, String authority, String userInfo, String file, String query, String ref) { + public void setURL(URL u, String protocol, String host, int port, String authority, String userInfo, String file, + String query, String ref) { throw new IllegalStateException(); } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/url/URLStreamHandlerFactoryImpl.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/url/URLStreamHandlerFactoryImpl.java index 0a0b9c2d693..68f63e86c7d 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/url/URLStreamHandlerFactoryImpl.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/url/URLStreamHandlerFactoryImpl.java @@ -41,7 +41,8 @@ public class URLStreamHandlerFactoryImpl extends MultiplexingFactory implements public static final String PROTOCOL_REFERENCE = "reference"; //$NON-NLS-1$ static final SecureAction secureAction = AccessController.doPrivileged(SecureAction.createSecureAction()); - private static final List> ignoredClasses = Arrays.asList(new Class[] {MultiplexingURLStreamHandler.class, URLStreamHandlerFactoryImpl.class, URL.class}); + private static final List> ignoredClasses = Arrays.asList( + new Class[] { MultiplexingURLStreamHandler.class, URLStreamHandlerFactoryImpl.class, URL.class }); private Map proxies; private URLStreamHandlerFactory parentFactory; private ThreadLocal> creatingProtocols = new ThreadLocal<>(); @@ -70,7 +71,7 @@ private Class getBuiltIn(String protocol, String builtInHandlers) { try { clazz = secureAction.loadSystemClass(name.toString()); if (clazz != null) - return clazz; //this class exists, it is a built in handler + return clazz; // this class exists, it is a built in handler } catch (ClassNotFoundException ex) { // keep looking } @@ -79,8 +80,7 @@ private Class getBuiltIn(String protocol, String builtInHandlers) { } /** - * Creates a new URLStreamHandler instance for the specified - * protocol. + * Creates a new URLStreamHandler instance for the specified protocol. * * @param protocol The desired protocol * @return a URLStreamHandler for the specific protocol. @@ -91,7 +91,7 @@ public URLStreamHandler createURLStreamHandler(String protocol) { if (isRecursive(protocol)) return null; try { - //first check for built in handlers + // first check for built in handlers String builtInHandlers = secureAction.getProperty(PROTOCOL_HANDLER_PKGS); Class clazz = getBuiltIn(protocol, builtInHandlers); if (clazz != null) @@ -107,9 +107,10 @@ public URLStreamHandler createURLStreamHandler(String protocol) { // if parent is present do parent lookup if (result == null && parentFactory != null) result = parentFactory.createURLStreamHandler(protocol); - return result; //result may be null; let the VM handle it (consider sun.net.protocol.www.*) + return result; // result may be null; let the VM handle it (consider sun.net.protocol.www.*) } catch (Throwable t) { - container.getLogServices().log(URLStreamHandlerFactoryImpl.class.getName(), FrameworkLogEntry.ERROR, "Unexpected error in factory.", t); //$NON-NLS-1$ + container.getLogServices().log(URLStreamHandlerFactoryImpl.class.getName(), FrameworkLogEntry.ERROR, + "Unexpected error in factory.", t); //$NON-NLS-1$ return null; } finally { releaseRecursive(protocol); @@ -135,22 +136,25 @@ private void releaseRecursive(String protocol) { private URLStreamHandler getFrameworkHandler(String protocol) { if (BundleResourceHandler.OSGI_ENTRY_URL_PROTOCOL.equals(protocol)) { - return new org.eclipse.osgi.storage.url.bundleentry.Handler(container.getStorage().getModuleContainer(), null); + return new org.eclipse.osgi.storage.url.bundleentry.Handler(container.getStorage().getModuleContainer(), + null); } else if (BundleResourceHandler.OSGI_RESOURCE_URL_PROTOCOL.equals(protocol)) { - return new org.eclipse.osgi.storage.url.bundleresource.Handler(container.getStorage().getModuleContainer(), null); + return new org.eclipse.osgi.storage.url.bundleresource.Handler(container.getStorage().getModuleContainer(), + null); } else if (PROTOCOL_REFERENCE.equals(protocol)) { - return new org.eclipse.osgi.storage.url.reference.Handler(container.getConfiguration().getConfiguration(EquinoxLocations.PROP_INSTALL_AREA)); + return new org.eclipse.osgi.storage.url.reference.Handler( + container.getConfiguration().getConfiguration(EquinoxLocations.PROP_INSTALL_AREA)); } return null; } public URLStreamHandler createInternalURLStreamHandler(String protocol) { - //internal protocol handlers + // internal protocol handlers URLStreamHandler frameworkHandler = getFrameworkHandler(protocol); if (frameworkHandler != null) { return frameworkHandler; } - //Now we check the service registry + // Now we check the service registry URLStreamHandlerProxy handler = proxies.computeIfAbsent(protocol, p -> new URLStreamHandlerProxy(p, context)); if (handler.isActive()) { return handler; @@ -168,10 +172,12 @@ protected URLStreamHandler findAuthorizedURLStreamHandler(String protocol) { return createInternalURLStreamHandler(protocol); try { - Method createInternalURLStreamHandlerMethod = factory.getClass().getMethod("createInternalURLStreamHandler", new Class[] {String.class}); //$NON-NLS-1$ - return (URLStreamHandler) createInternalURLStreamHandlerMethod.invoke(factory, new Object[] {protocol}); + Method createInternalURLStreamHandlerMethod = factory.getClass().getMethod("createInternalURLStreamHandler", //$NON-NLS-1$ + new Class[] { String.class }); + return (URLStreamHandler) createInternalURLStreamHandlerMethod.invoke(factory, new Object[] { protocol }); } catch (Exception e) { - container.getLogServices().log(URLStreamHandlerFactoryImpl.class.getName(), FrameworkLogEntry.ERROR, "findAuthorizedURLStreamHandler-loop", e); //$NON-NLS-1$ + container.getLogServices().log(URLStreamHandlerFactoryImpl.class.getName(), FrameworkLogEntry.ERROR, + "findAuthorizedURLStreamHandler-loop", e); //$NON-NLS-1$ throw new RuntimeException(e.getMessage(), e); } } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/url/URLStreamHandlerProxy.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/url/URLStreamHandlerProxy.java index a37feaf287f..4c145ee3498 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/url/URLStreamHandlerProxy.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/url/URLStreamHandlerProxy.java @@ -70,7 +70,8 @@ public URLStreamHandlerProxy(String protocol, BundleContext context) { new ServiceTrackerCustomizer() { @Override - public LazyURLStreamHandlerService addingService(ServiceReference reference) { + public LazyURLStreamHandlerService addingService( + ServiceReference reference) { return new LazyURLStreamHandlerService(context, reference); } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/url/URLStreamHandlerSetter.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/url/URLStreamHandlerSetter.java index 263a39c49eb..d619903ad9b 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/url/URLStreamHandlerSetter.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/url/URLStreamHandlerSetter.java @@ -25,7 +25,8 @@ public URLStreamHandlerSetter(URLStreamHandlerProxy handler) { } /** - * @see org.osgi.service.url.URLStreamHandlerSetter#setURL(URL, String, String, int, String, String) + * @see org.osgi.service.url.URLStreamHandlerSetter#setURL(URL, String, String, + * int, String, String) * @deprecated */ @Override @@ -34,10 +35,12 @@ public void setURL(URL url, String protocol, String host, int port, String file, } /** - * @see org.osgi.service.url.URLStreamHandlerSetter#setURL(URL, String, String, int, String, String, String, String, String) + * @see org.osgi.service.url.URLStreamHandlerSetter#setURL(URL, String, String, + * int, String, String, String, String, String) */ @Override - public void setURL(URL url, String protocol, String host, int port, String authority, String userInfo, String path, String query, String ref) { + public void setURL(URL url, String protocol, String host, int port, String authority, String userInfo, String path, + String query, String ref) { handlerProxy.setURL(url, protocol, host, port, authority, userInfo, path, query, ref); } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/weaving/WeavingHookConfigurator.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/weaving/WeavingHookConfigurator.java index 8e2adaf8b01..2feade8407a 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/weaving/WeavingHookConfigurator.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/weaving/WeavingHookConfigurator.java @@ -54,10 +54,12 @@ private ServiceRegistry getRegistry() { } @Override - public byte[] processClass(String name, byte[] classbytes, ClasspathEntry classpathEntry, BundleEntry entry, ClasspathManager manager) { + public byte[] processClass(String name, byte[] classbytes, ClasspathEntry classpathEntry, BundleEntry entry, + ClasspathManager manager) { ServiceRegistry registry = getRegistry(); if (registry == null) - return null; // no registry somehow we are loading classes before the registry has been created + return null; // no registry somehow we are loading classes before the registry has been + // created ModuleClassLoader classLoader = manager.getClassLoader(); BundleLoader loader = classLoader.getBundleLoader(); // create a woven class object and add it to the thread local stack @@ -80,7 +82,8 @@ public byte[] processClass(String name, byte[] classbytes, ClasspathEntry classp return wovenClass.callHooks(); } catch (Throwable t) { ServiceRegistration errorHook = wovenClass.getErrorHook(); - Bundle errorBundle = errorHook != null ? errorHook.getReference().getBundle() : manager.getGeneration().getRevision().getBundle(); + Bundle errorBundle = errorHook != null ? errorHook.getReference().getBundle() + : manager.getGeneration().getRevision().getBundle(); container.getEventPublisher().publishFrameworkEvent(FrameworkEvent.ERROR, errorBundle, t); // fail hard with a class loading error ClassFormatError error = new ClassFormatError("Unexpected error from weaving hook."); //$NON-NLS-1$ @@ -94,8 +97,10 @@ public byte[] processClass(String name, byte[] classbytes, ClasspathEntry classp } @Override - public void recordClassDefine(String name, Class clazz, byte[] classbytes, ClasspathEntry classpathEntry, BundleEntry entry, ClasspathManager manager) { - // here we assume the stack contans a woven class with the same name as the class we are defining. + public void recordClassDefine(String name, Class clazz, byte[] classbytes, ClasspathEntry classpathEntry, + BundleEntry entry, ClasspathManager manager) { + // here we assume the stack contans a woven class with the same name as the + // class we are defining. WovenClassContext context = wovenClassContext.get(); if (context == null || context.wovenClassStack.size() == 0) return; diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/weaving/WovenClassImpl.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/weaving/WovenClassImpl.java index 6230f70e885..bd4628b0d0a 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/weaving/WovenClassImpl.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/internal/weaving/WovenClassImpl.java @@ -64,7 +64,8 @@ public final class WovenClassImpl implements WovenClass, HookContext, Boolean> deniedHooks) { + public WovenClassImpl(String className, byte[] bytes, BundleEntry entry, ClasspathEntry classpathEntry, + BundleLoader loader, EquinoxContainer container, Map, Boolean> deniedHooks) { super(); this.className = className; this.validBytes = this.resultBytes = bytes; @@ -259,8 +260,10 @@ byte[] callHooks() throws Throwable { } } finally { if ((hookFlags & FLAG_HOOKCALLED) != 0) { - for (ClassLoaderHook classLoaderHook : container.getConfiguration().getHookRegistry().getClassLoaderHooks()) { - rejected |= classLoaderHook.rejectTransformation(className, resultBytes, classpathEntry, entry, loader.getModuleClassLoader().getClasspathManager()); + for (ClassLoaderHook classLoaderHook : container.getConfiguration().getHookRegistry() + .getClassLoaderHooks()) { + rejected |= classLoaderHook.rejectTransformation(className, resultBytes, classpathEntry, entry, + loader.getModuleClassLoader().getClasspathManager()); } if (!rejected) { wovenBytes = resultBytes; @@ -300,12 +303,14 @@ byte[] callHooks() throws Throwable { } private void addImpliedImportPackagePermissions(ManifestElement[] importElements) { - ProtectionDomain wovenDomain = ((Generation) ((ModuleRevision) getBundleWiring().getRevision()).getRevisionInfo()).getDomain(); + ProtectionDomain wovenDomain = ((Generation) ((ModuleRevision) getBundleWiring().getRevision()) + .getRevisionInfo()).getDomain(); if (wovenDomain != null) { // security is enabled; add the permissions for (ManifestElement clause : importElements) for (String pkg : clause.getValueComponents()) - ((BundlePermissions) wovenDomain.getPermissions()).addWovenPermission(new PackagePermission(pkg, PackagePermission.IMPORT)); + ((BundlePermissions) wovenDomain.getPermissions()) + .addWovenPermission(new PackagePermission(pkg, PackagePermission.IMPORT)); } } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/launch/EquinoxFactory.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/launch/EquinoxFactory.java index fd1ad8a5dd7..d901d015eea 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/launch/EquinoxFactory.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/launch/EquinoxFactory.java @@ -21,6 +21,7 @@ /** * The framework factory implementation for the Equinox framework. + * * @since 3.5 */ public class EquinoxFactory implements FrameworkFactory, ConnectFrameworkFactory { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/pluginconversion/PluginConversionException.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/pluginconversion/PluginConversionException.java index 178da0925c2..08fcc8b473f 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/pluginconversion/PluginConversionException.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/pluginconversion/PluginConversionException.java @@ -46,7 +46,7 @@ public PluginConversionException(String message) { * Create a new exception with the given message and nested exception. * * @param message the message for the exception - * @param cause the nested exception + * @param cause the nested exception */ public PluginConversionException(String message, Throwable cause) { super(message); @@ -63,8 +63,8 @@ public PluginConversionException(Throwable cause) { } /** - * Return the nested exception for this exception or null - * if there is none. + * Return the nested exception for this exception or null if there + * is none. * * @return the nested exception or null */ diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/pluginconversion/PluginConverter.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/pluginconversion/PluginConverter.java index c8681083576..e7efd373019 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/pluginconversion/PluginConverter.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/pluginconversion/PluginConverter.java @@ -17,8 +17,9 @@ import java.util.Dictionary; /** - * A plug-in convertor is able to convert plug-in manifest files (plugin.xml) and - * fragment manifest files (fragment.xml) to bundle manifest files (MANIFEST.MF). + * A plug-in convertor is able to convert plug-in manifest files + * (plugin.xml) and fragment manifest files (fragment.xml) to + * bundle manifest files (MANIFEST.MF). *

* This interface is not intended to be implemented by clients. *

@@ -27,57 +28,88 @@ */ public interface PluginConverter { /** - * Converts a plug-in/fragment manifest at the given source base location (a directory or jar file) and - * generates a corresponding bundle manifest at the given default target location (a file). + * Converts a plug-in/fragment manifest at the given source base location (a + * directory or jar file) and generates a corresponding bundle manifest at the + * given default target location (a file). * - * @param pluginBaseLocation the base location for the plug-in/fragment manifest to be converted - * (a directory or jar file, e.g. the plug-in install location) - * @param bundleManifestLocation the location for the bundle manifest to be generated - * (including the file name). - * @param compatibilityManifest a boolean indicating if the manifest should contain headers to run - * in backward compatibility - * @param target a string indicating the version of the runtime for which the manifest generated is targeted - * @param analyseJars a boolean indicating if the code jars of the given plugin must be analysed. When set to false the Export-Package header will not be set in the bundle manifest. - * @param devProperties a dictionary of development time classpath properties. The dictionary contains a mapping from plugin id to development - * time classpath. A value of null indicates that the default development time classpath properties will be used. - * @return the generated manifest file location, if a bundle manifest was successfully - * generated (or already existed), null otherwise. - * @throws PluginConversionException if an error occurs while converting the manifest + * @param pluginBaseLocation the base location for the plug-in/fragment + * manifest to be converted (a directory or jar + * file, e.g. the plug-in install location) + * @param bundleManifestLocation the location for the bundle manifest to be + * generated (including the file name). + * @param compatibilityManifest a boolean indicating if the manifest should + * contain headers to run in backward + * compatibility + * @param target a string indicating the version of the runtime + * for which the manifest generated is targeted + * @param analyseJars a boolean indicating if the code jars of the + * given plugin must be analysed. When set to + * false the Export-Package header will not be set + * in the bundle manifest. + * @param devProperties a dictionary of development time classpath + * properties. The dictionary contains a mapping + * from plugin id to development time classpath. A + * value of null indicates that the + * default development time classpath properties + * will be used. + * @return the generated manifest file location, if a bundle manifest was + * successfully generated (or already existed), null + * otherwise. + * @throws PluginConversionException if an error occurs while converting the + * manifest */ - public File convertManifest(File pluginBaseLocation, File bundleManifestLocation, boolean compatibilityManifest, String target, boolean analyseJars, Dictionary devProperties) throws PluginConversionException; + public File convertManifest(File pluginBaseLocation, File bundleManifestLocation, boolean compatibilityManifest, + String target, boolean analyseJars, Dictionary devProperties) + throws PluginConversionException; /** - * Converts a plug-in/fragment manifest at the given source base location (a directory or jar file) and - * generates a corresponding bundle manifest returned as a dictionary. + * Converts a plug-in/fragment manifest at the given source base location (a + * directory or jar file) and generates a corresponding bundle manifest returned + * as a dictionary. * - * @param pluginBaseLocation the base location for the plug-in/fragment manifest to be converted - * (a directory or jar file, e.g. the plug-in install location) - * @param compatibility a boolean indicating if the manifest should contain headers to run - * in backward compatibility - * @param target a string indicating the version of the runtime for which the manifest generated is targeted - * @param analyseJars a boolean indicating if the code jars of the given plugin must be analysed. When set to false the Export-Package header will not be set in the bundle manifest. - * @param devProperties a dictionary of development time classpath properties. The dictionary contains a mapping from plugin id to development - * time classpath. A value of null indicates that the default development time classpath properties will be used. - * @return the generated manifest as a dictionary, if a bundle manifest was successfully - * generated, null otherwise - * @throws PluginConversionException if an error occurs while converting the manifest + * @param pluginBaseLocation the base location for the plug-in/fragment manifest + * to be converted (a directory or jar file, e.g. the + * plug-in install location) + * @param compatibility a boolean indicating if the manifest should contain + * headers to run in backward compatibility + * @param target a string indicating the version of the runtime for + * which the manifest generated is targeted + * @param analyseJars a boolean indicating if the code jars of the given + * plugin must be analysed. When set to false the + * Export-Package header will not be set in the bundle + * manifest. + * @param devProperties a dictionary of development time classpath + * properties. The dictionary contains a mapping from + * plugin id to development time classpath. A value of + * null indicates that the default + * development time classpath properties will be used. + * @return the generated manifest as a dictionary, if a bundle manifest was + * successfully generated, null otherwise + * @throws PluginConversionException if an error occurs while converting the + * manifest */ - public Dictionary convertManifest(File pluginBaseLocation, boolean compatibility, String target, boolean analyseJars, Dictionary devProperties) throws PluginConversionException; + public Dictionary convertManifest(File pluginBaseLocation, boolean compatibility, String target, + boolean analyseJars, Dictionary devProperties) throws PluginConversionException; /** - * Construct a bundle manifest file from the given dictionary and write it out to the - * specified location in the file system. + * Construct a bundle manifest file from the given dictionary and write it out + * to the specified location in the file system. *

* If the compatibilityManifest parameter is true then - * the generated manifest will include the necessary headers to all the manifest to be - * run in backwards compatibility mode. + * the generated manifest will include the necessary headers to all the manifest + * to be run in backwards compatibility mode. *

* - * @param generationLocation the location for the bundle manifest to be written - * @param manifestToWrite the dictionary to write into generationLocation file - * @param compatibilityManifest a boolean indicating if the file should contain headers to allow - * running in backward compatibility mode - * @throws PluginConversionException if an error occurs while writing the given manifest + * @param generationLocation the location for the bundle manifest to be + * written + * @param manifestToWrite the dictionary to write into generationLocation + * file + * @param compatibilityManifest a boolean indicating if the file should contain + * headers to allow running in backward + * compatibility mode + * @throws PluginConversionException if an error occurs while writing the given + * manifest */ - public void writeManifest(File generationLocation, Dictionary manifestToWrite, boolean compatibilityManifest) throws PluginConversionException; + public void writeManifest(File generationLocation, Dictionary manifestToWrite, + boolean compatibilityManifest) throws PluginConversionException; } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/BaseDescription.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/BaseDescription.java index 5112ca1cebb..40b2ed9ae91 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/BaseDescription.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/BaseDescription.java @@ -18,81 +18,85 @@ import org.osgi.framework.wiring.BundleCapability; /** - * This class represents a base description object for a state. All description + * This class represents a base description object for a state. All description * objects in a state have a name and a version. *

- * This interface is not intended to be implemented by clients. The + * This interface is not intended to be implemented by clients. The * {@link StateObjectFactory} should be used to construct instances. *

+ * * @since 3.1 * @noimplement This interface is not intended to be implemented by clients. */ public interface BaseDescription { /** * Returns the name. + * * @return the name */ public String getName(); /** * Returns the version. + * * @return the version */ public Version getVersion(); /** * Returns the bundle which supplies this base description + * * @return the bundle which supplies this base description * @since 3.2 */ public BundleDescription getSupplier(); /** - * Returns the directives declared with the description. - * This will return all known directives for the type of description. - * The set of directives differs for each description type. + * Returns the directives declared with the description. This will return all + * known directives for the type of description. The set of directives differs + * for each description type. + * * @return the known directives declared with the description * @since 3.7 */ public Map getDeclaredDirectives(); /** - * Returns the attributes declared with the description. - * This will return all known attributes for the type of description. - * The set of attributes differs for each description type. + * Returns the attributes declared with the description. This will return all + * known attributes for the type of description. The set of attributes differs + * for each description type. + * * @return the attributes declared with the description * @since 3.7 */ public Map getDeclaredAttributes(); /** - * Returns the capability represented by this description. - * Some descriptions types may not be able to represent - * a capability. In such cases null is - * returned. + * Returns the capability represented by this description. Some descriptions + * types may not be able to represent a capability. In such cases + * null is returned. + * * @return the capability represented by this base description * @since 3.7 */ public BundleCapability getCapability(); /** - * Returns the user object associated to this description, or - * null if none exists. + * Returns the user object associated to this description, or null + * if none exists. * - * @return the user object associated to this description, - * or null + * @return the user object associated to this description, or null * @since 3.8 */ public Object getUserObject(); /** - * Associates a user-provided object to this description, or - * removes an existing association, if null is provided. The - * provided object is not interpreted in any ways by this - * description. + * Associates a user-provided object to this description, or removes an existing + * association, if null is provided. The provided object is not + * interpreted in any ways by this description. * * @param userObject an arbitrary object provided by the user, or - * null + * null * @since 3.8 */ public void setUserObject(Object userObject); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/BundleDelta.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/BundleDelta.java index 8aa3dac9ed0..dd75eb4de45 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/BundleDelta.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/BundleDelta.java @@ -14,115 +14,124 @@ package org.eclipse.osgi.service.resolver; /** - * BundleDeltas represent the changes related to an individual bundle between two - * states. + * BundleDeltas represent the changes related to an individual bundle between + * two states. *

- * This interface is not intended to be implemented by clients. The + * This interface is not intended to be implemented by clients. The * {@link StateObjectFactory} should be used to construct instances. *

+ * * @since 3.1 * @noimplement This interface is not intended to be implemented by clients. */ public interface BundleDelta extends Comparable { /** - * Delta type constant (bit mask) indicating that the bundle has been added - * to the new state. + * Delta type constant (bit mask) indicating that the bundle has been added to + * the new state. + * * @see BundleDelta#getType */ public static final int ADDED = 0x1; /** - * Delta type constant (bit mask) indicating that the bundle is no longer present in - * the new state. + * Delta type constant (bit mask) indicating that the bundle is no longer + * present in the new state. + * * @see BundleDelta#getType */ public static final int REMOVED = 0x2; /** * Delta type constant (bit mask) indicating that the bundle has been updated - * between the old and new state. Note that an update delta may in fact represent - * a downgrading of the bundle to a previous version. + * between the old and new state. Note that an update delta may in fact + * represent a downgrading of the bundle to a previous version. + * * @see BundleDelta#getType */ public static final int UPDATED = 0x4; /** * Delta type constant (bit mask) indicating that the bundle has become resolved * in the new state. + * * @see BundleDelta#getType */ public static final int RESOLVED = 0x8; /** - * Delta type constant (bit mask) indicating that the bundle has become unresolved - * in the new state. Note that newly added bundles are unresolved by default and - * as such, do not transition to unresolved state so this flag is not set. + * Delta type constant (bit mask) indicating that the bundle has become + * unresolved in the new state. Note that newly added bundles are unresolved by + * default and as such, do not transition to unresolved state so this flag is + * not set. + * * @see BundleDelta#getType */ public static final int UNRESOLVED = 0x10; /** - * Delta type constant (bit mask) indicating that the bundles and packages which this - * bundle requires/imports (respectively) have changed in the new state. + * Delta type constant (bit mask) indicating that the bundles and packages which + * this bundle requires/imports (respectively) have changed in the new state. + * * @see BundleDelta#getType * @deprecated this type is no longer valid */ public static final int LINKAGE_CHANGED = 0x20; /** - * Delta type constant (bit mask) indicating that the bundles which this - * bundle optionally requires have changed in the new state. + * Delta type constant (bit mask) indicating that the bundles which this bundle + * optionally requires have changed in the new state. + * * @see BundleDelta#getType * @deprecated this type is no longer valid */ public static final int OPTIONAL_LINKAGE_CHANGED = 0x40; /** - * Delta type constant (bit mask) indicating that the this bundle is - * pending a removal. Note that bundles with this flag set will also - * have the {@link BundleDelta#REMOVED} flag set. A bundle will have - * this flag set if it has been removed from the state but has other - * existing bundles in the state that depend on it. + * Delta type constant (bit mask) indicating that the this bundle is pending a + * removal. Note that bundles with this flag set will also have the + * {@link BundleDelta#REMOVED} flag set. A bundle will have this flag set if it + * has been removed from the state but has other existing bundles in the state + * that depend on it. + * * @see BundleDelta#getType */ public static final int REMOVAL_PENDING = 0x80; /** - * Delta type constant (bit mask) indicating that the this bundle has - * completed a pending removal. A bundle will complete a pending removal only - * after it has been re-resolved by the resolver. + * Delta type constant (bit mask) indicating that the this bundle has completed + * a pending removal. A bundle will complete a pending removal only after it has + * been re-resolved by the resolver. */ public static final int REMOVAL_COMPLETE = 0x100; /** * Returns the BundleDescription that this bundle delta is for. + * * @return the BundleDescription that this bundle delta is for. */ public BundleDescription getBundle(); /** - * Returns the type of change which occured. The return value is composed - * of by bit-wise masking the relevant flags from the set ADDED, REMOVED, - * UPDATED, RESOLVED, UNRESOLVED, LINKAGE_CHANGED, REMOVAL_PENDING, REMOVAL_COMPLETE. - * Note that bundle start and stop state changes are not captured in the - * delta as they do not represent structural changes but rather transient - * runtime states. + * Returns the type of change which occured. The return value is composed of by + * bit-wise masking the relevant flags from the set ADDED, REMOVED, UPDATED, + * RESOLVED, UNRESOLVED, LINKAGE_CHANGED, REMOVAL_PENDING, REMOVAL_COMPLETE. + * Note that bundle start and stop state changes are not captured in the delta + * as they do not represent structural changes but rather transient runtime + * states. + * * @return the type of change which occured */ public int getType(); /** - * Answers an integer indicating the relative positions of the receiver and - * the argument in the natural order of elements of the receiver's class. + * Answers an integer indicating the relative positions of the receiver and the + * argument in the natural order of elements of the receiver's class. *

* The natural order of elements is determined by the bundle id of the * BundleDescription that this bundle delta is for. * * @return int which should be <0 if the receiver should sort before the - * argument, 0 if the receiver should sort in the same position as - * the argument, and >0 if the receiver should sort after the - * argument. - * @param obj - * another BundleDelta an object to compare the receiver to - * @exception ClassCastException - * if the argument can not be converted into something - * comparable with the receiver. + * argument, 0 if the receiver should sort in the same position as the + * argument, and >0 if the receiver should sort after the argument. + * @param obj another BundleDelta an object to compare the receiver to + * @exception ClassCastException if the argument can not be converted into + * something comparable with the receiver. * @since 3.7 */ @Override diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/BundleDescription.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/BundleDescription.java index dc4bd5c74e3..0e26341a591 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/BundleDescription.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/BundleDescription.java @@ -19,25 +19,28 @@ /** * This class represents a specific version of a bundle in the system. *

- * This interface is not intended to be implemented by clients. The + * This interface is not intended to be implemented by clients. The * {@link StateObjectFactory} should be used to construct instances. *

+ * * @since 3.1 * @noimplement This interface is not intended to be implemented by clients. */ public interface BundleDescription extends BaseDescription, BundleRevision { /** - * Gets the Bundle-SymbolicName of this BundleDescription. - * Same as calling {@link BaseDescription#getName()}. - * @return The bundle symbolic name or null if the bundle - * does not have a symbolic name. + * Gets the Bundle-SymbolicName of this BundleDescription. Same as calling + * {@link BaseDescription#getName()}. + * + * @return The bundle symbolic name or null if the bundle does not have a + * symbolic name. */ @Override public String getSymbolicName(); /** * Returns the arbitrary attributes for this bundle description. + * * @return the arbitrary attributes for this bundle description * @since 3.7 */ @@ -45,8 +48,9 @@ public interface BundleDescription extends BaseDescription, BundleRevision { /** * The location string for this bundle. - * @return The bundle location or null if the bundle description - * does not have a location + * + * @return The bundle location or null if the bundle description does not have a + * location */ public String getLocation(); @@ -59,31 +63,37 @@ public interface BundleDescription extends BaseDescription, BundleRevision { public BundleSpecification[] getRequiredBundles(); /** - * Returns an array of export package descriptions defined by the Export-Package clauses. - * All export package descriptions are returned even if they have not been selected by - * the resolver as an exporter of the package. + * Returns an array of export package descriptions defined by the Export-Package + * clauses. All export package descriptions are returned even if they have not + * been selected by the resolver as an exporter of the package. * * @return an array of export package descriptions */ public ExportPackageDescription[] getExportPackages(); /** - * Returns an array of import package specifications defined by the Import-Package clause. + * Returns an array of import package specifications defined by the + * Import-Package clause. + * * @return an array of import package specifications */ public ImportPackageSpecification[] getImportPackages(); /** - * Returns an array of dynamic import package specifications that have been added - * dynamically to this bundle description. + * Returns an array of dynamic import package specifications that have been + * added dynamically to this bundle description. + * * @return an array of dynamic import package specifications - * @see State#addDynamicImportPackages(BundleDescription, ImportPackageSpecification[]) + * @see State#addDynamicImportPackages(BundleDescription, + * ImportPackageSpecification[]) * @since 3.7 */ public ImportPackageSpecification[] getAddedDynamicImportPackages(); /** - * Returns an array of generic specifications constraints required by this bundle. + * Returns an array of generic specifications constraints required by this + * bundle. + * * @return an array of generic specifications * @since 3.2 */ @@ -91,6 +101,7 @@ public interface BundleDescription extends BaseDescription, BundleRevision { /** * Returns an array of generic descriptions for the capabilities of this bundle. + * * @return an array of generic descriptions * @since 3.2 */ @@ -98,53 +109,63 @@ public interface BundleDescription extends BaseDescription, BundleRevision { /** * Returns true if this bundle has one or more dynamically imported packages. + * * @return true if this bundle has one or more dynamically imported packages. */ public boolean hasDynamicImports(); /** * Returns all the exported packages from this bundle that have been selected by - * the resolver. The returned list will include the ExportPackageDescriptions - * returned by {@link #getExportPackages()} that have been selected by the resolver and - * packages which are propagated by this bundle. - * @return the selected list of packages that this bundle exports. If the bundle is - * unresolved or has no shared packages then an empty array is returned. + * the resolver. The returned list will include the ExportPackageDescriptions + * returned by {@link #getExportPackages()} that have been selected by the + * resolver and packages which are propagated by this bundle. + * + * @return the selected list of packages that this bundle exports. If the bundle + * is unresolved or has no shared packages then an empty array is + * returned. */ public ExportPackageDescription[] getSelectedExports(); /** - * Returns all the capabilities provided by ths bundle that have been selected by - * the resolver. The returned list will include the capabilities - * returned by {@link #getGenericCapabilities()} that have been selected by the - * resolver and any capabilities provided by fragments attached to this bundle. - * @return the selected capabilities that this bundle provides. If the bundle is - * unresolved or has no capabilities then an empty array is returned. + * Returns all the capabilities provided by ths bundle that have been selected + * by the resolver. The returned list will include the capabilities returned by + * {@link #getGenericCapabilities()} that have been selected by the resolver and + * any capabilities provided by fragments attached to this bundle. + * + * @return the selected capabilities that this bundle provides. If the bundle is + * unresolved or has no capabilities then an empty array is returned. * @since 3.7 */ public GenericDescription[] getSelectedGenericCapabilities(); /** - * Returns all the bundle descriptions that satisfy all the require bundles for this bundle. - * If the bundle is not resolved or the bundle does not require any bundles then an empty array is - * returned. - * @return the bundles descriptions that satisfy all the require bundles for this bundle. + * Returns all the bundle descriptions that satisfy all the require bundles for + * this bundle. If the bundle is not resolved or the bundle does not require any + * bundles then an empty array is returned. + * + * @return the bundles descriptions that satisfy all the require bundles for + * this bundle. */ public BundleDescription[] getResolvedRequires(); /** - * Returns all the export packages that satisfy all the imported packages for this bundle. - * If the bundle is not resolved or the bundle does not import any packages then an empty array is - * returned. - * @return the exported packages that satisfy all the imported packages for this bundle. + * Returns all the export packages that satisfy all the imported packages for + * this bundle. If the bundle is not resolved or the bundle does not import any + * packages then an empty array is returned. + * + * @return the exported packages that satisfy all the imported packages for this + * bundle. */ public ExportPackageDescription[] getResolvedImports(); /** - * Returns all the capabilities that satisfy all the capability requirements for this - * bundle. This includes any capabilities required by fragments attached to this bundle. - * @return the capabilities that satisfy all the capability requirements for this bundle. - * If the bundle is unresolved or has no capability requirements then an empty array is - * returned. + * Returns all the capabilities that satisfy all the capability requirements for + * this bundle. This includes any capabilities required by fragments attached to + * this bundle. + * + * @return the capabilities that satisfy all the capability requirements for + * this bundle. If the bundle is unresolved or has no capability + * requirements then an empty array is returned. * @since 3.7 */ public GenericDescription[] getResolvedGenericRequires(); @@ -157,8 +178,8 @@ public interface BundleDescription extends BaseDescription, BundleRevision { public boolean isResolved(); /** - * Returns the state object which hosts this bundle. null is returned if - * this bundle is not currently in a state. + * Returns the state object which hosts this bundle. null is returned if this + * bundle is not currently in a state. * * @return the state object which hosts this bundle. */ @@ -173,17 +194,18 @@ public interface BundleDescription extends BaseDescription, BundleRevision { public String toString(); /** - * Returns the host for this bundle. null is returned if this bundle is not - * a fragment. + * Returns the host for this bundle. null is returned if this bundle is not a + * fragment. * * @return the host for this bundle. */ public HostSpecification getHost(); /** - * Returns the numeric id of this bundle. Typically a bundle description - * will only have a numeric id if it represents a bundle that is installed in a - * framework as the framework assigns the ids. -1 is returned if the id is not known. + * Returns the numeric id of this bundle. Typically a bundle description will + * only have a numeric id if it represents a bundle that is installed in a + * framework as the framework assigns the ids. -1 is returned if the id is not + * known. * * @return the numeric id of this bundle description */ @@ -197,78 +219,84 @@ public interface BundleDescription extends BaseDescription, BundleRevision { public BundleDescription[] getFragments(); /** - * Returns whether this bundle is a singleton. Singleton bundles require - * that at most one single version of the bundle can be resolved at a time. + * Returns whether this bundle is a singleton. Singleton bundles require that at + * most one single version of the bundle can be resolved at a time. *

- * The existence of a single bundle marked as singleton causes all bundles - * with the same symbolic name to be treated as singletons as well. + * The existence of a single bundle marked as singleton causes all bundles with + * the same symbolic name to be treated as singletons as well. *

* - * @return true, if this bundle is a singleton, - * false otherwise + * @return true, if this bundle is a singleton, false + * otherwise */ public boolean isSingleton(); /** - * Returns whether this bundle is pending a removal. A bundle is pending - * removal if it has been removed from the state but other bundles in - * the state currently depend on it. + * Returns whether this bundle is pending a removal. A bundle is pending removal + * if it has been removed from the state but other bundles in the state + * currently depend on it. + * * @return true, if this bundle is pending a removal, - * false otherwise + * false otherwise */ public boolean isRemovalPending(); /** - * Returns all bundles which depend on this bundle. A bundle depends on - * another bundle if it requires the bundle, imports a package which is - * exported by the bundle, is a fragment to the bundle or is the host - * of the bundle. + * Returns all bundles which depend on this bundle. A bundle depends on another + * bundle if it requires the bundle, imports a package which is exported by the + * bundle, is a fragment to the bundle or is the host of the bundle. + * * @return all bundles which depend on this bundle. */ public BundleDescription[] getDependents(); /** * Returns the platform filter in the form of an LDAP filter + * * @return the platfomr filter in the form of an LDAP filter */ public String getPlatformFilter(); /** * Returns true if this bundle allows fragments to attach + * * @return true if this bundle allows fragments to attach */ public boolean attachFragments(); /** - * Returns true if this bundle allows fragments to attach dynamically - * after it has been resolved. + * Returns true if this bundle allows fragments to attach dynamically after it + * has been resolved. + * * @return true if this bundle allows fragments to attach dynamically */ public boolean dynamicFragments(); /** - * Returns the list of execution environments that are required by - * this bundle. Any one of the listed execution environments will - * allow this bundle to be resolved. + * Returns the list of execution environments that are required by this bundle. + * Any one of the listed execution environments will allow this bundle to be + * resolved. + * * @since 3.2 * @return the list of execution environments that are required. */ public String[] getExecutionEnvironments(); /** - * Returns the native code specification for this bundle. A value - * of null is returned if there is no native code - * specification. + * Returns the native code specification for this bundle. A value of + * null is returned if there is no native code specification. + * * @return the native code specification. * @since 3.4 */ public NativeCodeSpecification getNativeCodeSpecification(); /** - * Returns the export packages that satisfy imported packages for this bundle description - * and substitute one of the exports for this bundle description. If the bundle is not resolved - * or the bundle does not have substituted exports then an empty array is - * returned. + * Returns the export packages that satisfy imported packages for this bundle + * description and substitute one of the exports for this bundle description. If + * the bundle is not resolved or the bundle does not have substituted exports + * then an empty array is returned. + * * @return all substituted exports for this bundle description * @since 3.4 */ diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/BundleSpecification.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/BundleSpecification.java index 18c6151f7a9..b9d05d4da0b 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/BundleSpecification.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/BundleSpecification.java @@ -14,12 +14,13 @@ package org.eclipse.osgi.service.resolver; /** - * A representation of one bundle import constraint as seen in a - * bundle manifest and managed by a state and resolver. + * A representation of one bundle import constraint as seen in a bundle manifest + * and managed by a state and resolver. *

- * This interface is not intended to be implemented by clients. The + * This interface is not intended to be implemented by clients. The * {@link StateObjectFactory} should be used to construct instances. *

+ * * @since 3.1 * @noimplement This interface is not intended to be implemented by clients. */ diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/DisabledInfo.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/DisabledInfo.java index d79a6b33911..23ce21f2888 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/DisabledInfo.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/DisabledInfo.java @@ -14,16 +14,20 @@ package org.eclipse.osgi.service.resolver; /** - * A disabled info represents a policy decision to disable a bundle which exists in a {@link State}. - * Bundles may be disabled by adding disabled info with the {@link State#addDisabledInfo(DisabledInfo)} - * method and enabled by removing disabled info with the {@link State#removeDisabledInfo(DisabledInfo)} method. - * A bundle is not considered to be enabled unless there are no disabled info objects for the bundle. + * A disabled info represents a policy decision to disable a bundle which exists + * in a {@link State}. Bundles may be disabled by adding disabled info with the + * {@link State#addDisabledInfo(DisabledInfo)} method and enabled by removing + * disabled info with the {@link State#removeDisabledInfo(DisabledInfo)} method. + * A bundle is not considered to be enabled unless there are no disabled info + * objects for the bundle. *

- * While resolving the bundle if the {@link Resolver} encounters a {@link BundleDescription} which - * has disabled info returned by {@link State#getDisabledInfos(BundleDescription)} then the bundle - * must not be allowed to resolve and a ResolverError of type {@link ResolverError#DISABLED_BUNDLE} - * must be added to the state. + * While resolving the bundle if the {@link Resolver} encounters a + * {@link BundleDescription} which has disabled info returned by + * {@link State#getDisabledInfos(BundleDescription)} then the bundle must not be + * allowed to resolve and a ResolverError of type + * {@link ResolverError#DISABLED_BUNDLE} must be added to the state. *

+ * * @see State * @since 3.4 */ @@ -34,9 +38,10 @@ public final class DisabledInfo { /** * DisabledInfo constructor. + * * @param policyName the name of the policy - * @param message the message, may be null - * @param bundle the bundle + * @param message the message, may be null + * @param bundle the bundle */ public DisabledInfo(String policyName, String message, BundleDescription bundle) { if (policyName == null || bundle == null) @@ -48,6 +53,7 @@ public DisabledInfo(String policyName, String message, BundleDescription bundle) /** * Returns the name of the policy which disabled the bundle. + * * @return the name of the policy */ public String getPolicyName() { @@ -56,6 +62,7 @@ public String getPolicyName() { /** * Returns the message describing the reason the bundle is disabled. + * * @return the message */ public String getMessage() { @@ -64,6 +71,7 @@ public String getMessage() { /** * Returns the bundle which is disabled + * * @return the bundle which is disabled */ public BundleDescription getBundle() { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/ExportPackageDescription.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/ExportPackageDescription.java index 09fa8eb712a..5f4745477f8 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/ExportPackageDescription.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/ExportPackageDescription.java @@ -16,40 +16,46 @@ import java.util.Map; /** - * This class represents a specific version of an exported package in the system. + * This class represents a specific version of an exported package in the + * system. *

- * This interface is not intended to be implemented by clients. The + * This interface is not intended to be implemented by clients. The * {@link StateObjectFactory} should be used to construct instances. *

+ * * @since 3.1 * @noimplement This interface is not intended to be implemented by clients. */ public interface ExportPackageDescription extends BaseDescription { /** - * Returns true if the export package is a root package; false otherwise. - * A ExportPackageDescription is not a root package the exporting bundle - * is re-exporting the package using the Reexport-Package header. + * Returns true if the export package is a root package; false otherwise. A + * ExportPackageDescription is not a root package the exporting bundle is + * re-exporting the package using the Reexport-Package header. + * * @return true if the export package is a root package; false otherwise - * @deprecated all export package descriptions are roots. The Reexport-Package header - * never became API. + * @deprecated all export package descriptions are roots. The Reexport-Package + * header never became API. */ public boolean isRoot(); /** * Returns the arbitrary attributes for this package. + * * @return the arbitrary attributes for this package */ public Map getAttributes(); /** * Returns the directives for this package. + * * @return the directives for this package */ public Map getDirectives(); /** * Returns the specified directive for this package. + * * @param key the directive to fetch * @return the specified directive for this package */ @@ -57,6 +63,7 @@ public interface ExportPackageDescription extends BaseDescription { /** * Returns the exporter of this package. + * * @return the exporter of this package. */ public BundleDescription getExporter(); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/GenericDescription.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/GenericDescription.java index 236f3eeafec..e6593dbd5b3 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/GenericDescription.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/GenericDescription.java @@ -18,6 +18,7 @@ /** * A description of a generic capability. + * * @since 3.2 * @noimplement This interface is not intended to be implemented by clients. */ @@ -29,40 +30,38 @@ public interface GenericDescription extends BaseDescription { /** * Returns the arbitrary attributes for this description + * * @return the arbitrary attributes for this description */ public Dictionary getAttributes(); /** * Returns the type of generic description capability + * * @return the type of generic description capability */ public String getType(); /** - * This method is deprecated. Capabilities do not always have a - * name associated with them. All matching attributes associated - * with a capability are available in the attributes of a - * capability. This method will return the value of the - * attribute with the same key as this capabilities type. - * If this attribute's value is not a String then null is - * returned. - * @deprecated matching should only be done against a capability's - * attributes. + * This method is deprecated. Capabilities do not always have a name associated + * with them. All matching attributes associated with a capability are available + * in the attributes of a capability. This method will return the value of the + * attribute with the same key as this capabilities type. If this attribute's + * value is not a String then null is returned. + * + * @deprecated matching should only be done against a capability's attributes. */ @Override public String getName(); /** - * This method is deprecated. Capabilities do not always have a - * version associated with them. All matching attributes associated - * with a capability are available in the attributes of a - * capability. This method will return the value of the - * attribute with the key "version". - * If this attribute's value is not a {@link Version} then null is - * returned. - * @deprecated matching should only be done against a capability's - * attributes. + * This method is deprecated. Capabilities do not always have a version + * associated with them. All matching attributes associated with a capability + * are available in the attributes of a capability. This method will return the + * value of the attribute with the key "version". If this + * attribute's value is not a {@link Version} then null is returned. + * + * @deprecated matching should only be done against a capability's attributes. */ @Override public Version getVersion(); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/GenericSpecification.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/GenericSpecification.java index a02d1f4f89a..7f30f8a16dc 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/GenericSpecification.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/GenericSpecification.java @@ -15,45 +15,51 @@ /** * A specification which depends on a generic capability + * * @since 3.2 * @noimplement This interface is not intended to be implemented by clients. */ public interface GenericSpecification extends VersionConstraint { /** * The optional resolution type + * * @see #getResolution() */ public static final int RESOLUTION_OPTIONAL = 0x01; /** * The multiple resolution type + * * @see #getResolution() */ public static final int RESOLUTION_MULTIPLE = 0x02; /** * Returns a matching filter used to match with a suppliers attributes + * * @return a matching filter used to match with a suppliers attributes */ public String getMatchingFilter(); /** * Returns the type of generic specification + * * @return the type of generic specification */ public String getType(); /** - * Returns the resolution type of the required capability. The returned - * value is a bit mask that may have the optional bit {@link #RESOLUTION_OPTIONAL} - * and/or the multiple bit {@link #RESOLUTION_MULTIPLE} set. + * Returns the resolution type of the required capability. The returned value is + * a bit mask that may have the optional bit {@link #RESOLUTION_OPTIONAL} and/or + * the multiple bit {@link #RESOLUTION_MULTIPLE} set. * * @return the resolution type of the required capability */ public int getResolution(); /** - * Returns the suppliers of the capability. If the the resolution is multiple then - * more than one supplier may be returned + * Returns the suppliers of the capability. If the the resolution is multiple + * then more than one supplier may be returned + * * @return the suppliers of the capability */ public GenericDescription[] getSuppliers(); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/HostSpecification.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/HostSpecification.java index f7973343924..393eac061a1 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/HostSpecification.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/HostSpecification.java @@ -14,24 +14,29 @@ package org.eclipse.osgi.service.resolver; /** - * A representation of one host bundle constraint as seen in a - * bundle manifest and managed by a state and resolver. + * A representation of one host bundle constraint as seen in a bundle manifest + * and managed by a state and resolver. *

- * This interface is not intended to be implemented by clients. The + * This interface is not intended to be implemented by clients. The * {@link StateObjectFactory} should be used to construct instances. *

+ * * @since 3.1 * @noimplement This interface is not intended to be implemented by clients. */ public interface HostSpecification extends VersionConstraint { /** - * Returns the list of host BundleDescriptions that satisfy this HostSpecification - * @return the list of host BundleDescriptions that satisfy this HostSpecification + * Returns the list of host BundleDescriptions that satisfy this + * HostSpecification + * + * @return the list of host BundleDescriptions that satisfy this + * HostSpecification */ public BundleDescription[] getHosts(); /** * Returns if this HostSpecification is allowed to have multiple hosts + * * @return true if this HostSpecification is allowed to have multiple hosts */ public boolean isMultiHost(); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/ImportPackageSpecification.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/ImportPackageSpecification.java index a2636fc4264..c4e08796e8f 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/ImportPackageSpecification.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/ImportPackageSpecification.java @@ -16,12 +16,13 @@ import java.util.Map; /** - * A representation of one package import constraint as seen in a - * bundle manifest and managed by a state and resolver. + * A representation of one package import constraint as seen in a bundle + * manifest and managed by a state and resolver. *

- * This interface is not intended to be implemented by clients. The + * This interface is not intended to be implemented by clients. The * {@link StateObjectFactory} should be used to construct instances. *

+ * * @since 3.1 * @noimplement This interface is not intended to be implemented by clients. */ @@ -40,32 +41,40 @@ public interface ImportPackageSpecification extends VersionConstraint { public static final String RESOLUTION_DYNAMIC = "dynamic"; //$NON-NLS-1$ /** - * Returns the symbolic name of the bundle this import package must be resolved to. - * @return the symbolic name of the bundle this import pacakge must be resolved to. - * A value of null indicates any symbolic name. + * Returns the symbolic name of the bundle this import package must be resolved + * to. + * + * @return the symbolic name of the bundle this import pacakge must be resolved + * to. A value of null indicates any symbolic name. */ public String getBundleSymbolicName(); /** * Returns the version range which this import package may be resolved to. + * * @return the version range which this import package may be resolved to. */ public VersionRange getBundleVersionRange(); /** - * Returns the arbitrary attributes which this import package may be resolved to. - * @return the arbitrary attributes which this import package may be resolved to. + * Returns the arbitrary attributes which this import package may be resolved + * to. + * + * @return the arbitrary attributes which this import package may be resolved + * to. */ public Map getAttributes(); /** * Returns the directives that control this import package. + * * @return the directives that control this import package. */ public Map getDirectives(); /** * Returns the specified directive that control this import package. + * * @return the specified directive that control this import package. */ public Object getDirective(String key); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/NativeCodeDescription.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/NativeCodeDescription.java index 8cfdf8fa9ea..5b14e970674 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/NativeCodeDescription.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/NativeCodeDescription.java @@ -18,49 +18,56 @@ /** * This class represents a native code description. *

- * This interface is not intended to be implemented by clients. The + * This interface is not intended to be implemented by clients. The * {@link StateObjectFactory} should be used to construct instances. *

+ * * @since 3.4 * @noimplement This interface is not intended to be implemented by clients. */ public interface NativeCodeDescription extends BaseDescription, Comparable { /** * Returns the paths to the native code libraries. + * * @return the paths to the native code libraries. */ public String[] getNativePaths(); /** * Returns the processors supported by the native code. - * @return the processors supported by the native code. An - * empty array is returned if no processors are supported. + * + * @return the processors supported by the native code. An empty array is + * returned if no processors are supported. */ public String[] getProcessors(); /** * Returns the operating system names supported by the native code. - * @return the operating system names supported by the native code. - * An empty array is returned if no operating systems are supported. + * + * @return the operating system names supported by the native code. An empty + * array is returned if no operating systems are supported. */ public String[] getOSNames(); /** * Returns the operating system version ranges supported by the native code. - * @return the operating system version ranges supported by the native code. - * An empty array is returned if all versions are supported. + * + * @return the operating system version ranges supported by the native code. An + * empty array is returned if all versions are supported. */ public VersionRange[] getOSVersions(); /** * Returns the languages supported by the native code. - * @return the languages supported by the native code. An empty array is - * returned if all languages are supported. + * + * @return the languages supported by the native code. An empty array is + * returned if all languages are supported. */ public String[] getLanguages(); /** * Returns the selection filter used to select the native code. + * * @return the selection filter used to select the native code. */ public Filter getFilter(); @@ -69,20 +76,25 @@ public interface NativeCodeDescription extends BaseDescription, Comparable *
  • The minimum version of the os version ranges
  • - *
  • The language
  • + *
  • The language + *
  • * + * * @param other the native code description to be compared - * @return a negative integer, zero, or a positive integer as this natve - * code description is less than, equal to, or greater than the specified object. + * @return a negative integer, zero, or a positive integer as this natve code + * description is less than, equal to, or greater than the specified + * object. * @since 3.7 */ @Override public int compareTo(NativeCodeDescription other); /** - * Indicates if this native code description has invalid native code paths. Native - * code paths are invalid if they can not be found in the bundle content. - * @return true if the native code paths are invalid; otherwise false is returned. + * Indicates if this native code description has invalid native code paths. + * Native code paths are invalid if they can not be found in the bundle content. + * + * @return true if the native code paths are invalid; otherwise false is + * returned. */ public boolean hasInvalidNativePaths(); } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/NativeCodeSpecification.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/NativeCodeSpecification.java index 057cfb64b8b..e28003db0b8 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/NativeCodeSpecification.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/NativeCodeSpecification.java @@ -14,25 +14,26 @@ package org.eclipse.osgi.service.resolver; /** - * This class represents a native code specification. A - * native code specification is different from other - * specification constraints which typically are resolved against - * suppliers provided by other bundles. A native code - * specification supplies it own suppliers which are matched - * against the platform properties at resolve time and the - * supplier with the best match is selected. + * This class represents a native code specification. A native code + * specification is different from other specification constraints which + * typically are resolved against suppliers provided by other bundles. A native + * code specification supplies it own suppliers which are matched against the + * platform properties at resolve time and the supplier with the best match is + * selected. *

    - * This interface is not intended to be implemented by clients. The + * This interface is not intended to be implemented by clients. The * {@link StateObjectFactory} should be used to construct instances. *

    + * * @since 3.4 * @noimplement This interface is not intended to be implemented by clients. */ public interface NativeCodeSpecification extends VersionConstraint { /** - * Returns the list of possible suppliers to this native code specification. When - * this native code specification is resolved one of the possible suppliers + * Returns the list of possible suppliers to this native code specification. + * When this native code specification is resolved one of the possible suppliers * will be selected and returned by {@link VersionConstraint#getSupplier()}. + * * @return the list of possible suppliers. */ public NativeCodeDescription[] getPossibleSuppliers(); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/PlatformAdmin.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/PlatformAdmin.java index 6612cebd4bc..9e50b14f291 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/PlatformAdmin.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/PlatformAdmin.java @@ -18,15 +18,16 @@ /** * Framework service which allows bundle programmers to inspect the bundles and - * packages known to the Framework. The PlatformAdmin service also allows bundles - * with sufficient privileges to update the state of the framework by committing a new - * configuration of bundles and packages. + * packages known to the Framework. The PlatformAdmin service also allows + * bundles with sufficient privileges to update the state of the framework by + * committing a new configuration of bundles and packages. * - * If present, there will only be a single instance of this service - * registered with the Framework. + * If present, there will only be a single instance of this service registered + * with the Framework. *

    * This interface is not intended to be implemented by clients. *

    + * * @since 3.1 * @noimplement This interface is not intended to be implemented by clients. */ @@ -38,32 +39,34 @@ public interface PlatformAdmin { * This is a convenience method, fully equivalent to * getState(true). *

    + * * @return a state representing the current framework. */ public State getState(); /** * Returns a state representing the current system. If there is need to make - * changes to the returned state, a mutable state must be requested. - * Otherwise, an immutable state should be requested. In this case, invoking - * any of the operations that could cause the state to be changed will throw - * an java.lang.UnsupportedOperationException. + * changes to the returned state, a mutable state must be requested. Otherwise, + * an immutable state should be requested. In this case, invoking any of the + * operations that could cause the state to be changed will throw an + * java.lang.UnsupportedOperationException. *

    - * If a mutable state is requested, the resulting state will not - * be resolved and the user objects from the system state bundle descriptions will - * not be copied. + * If a mutable state is requested, the resulting state will + * not be resolved and the user objects from the system state + * bundle descriptions will not be copied. *

    + * * @param mutable whether the returned state should mutable * @return a state representing the current framework. */ public State getState(boolean mutable); /** - * Returns a state helper object. State helpers provide convenience methods - * for manipulating states. + * Returns a state helper object. State helpers provide convenience methods for + * manipulating states. *

    - * A possible implementation for this - * method would provide the same single StateHelper instance to all clients. + * A possible implementation for this method would provide the same single + * StateHelper instance to all clients. *

    * * @return a state helper @@ -72,19 +75,21 @@ public interface PlatformAdmin { public StateHelper getStateHelper(); /** - * Commit the differences between the current state and the given state. - * The given state must return true from State.isResolved() or an exception - * is thrown. The resolved state is committed verbatim, as-is. + * Commit the differences between the current state and the given state. The + * given state must return true from State.isResolved() or an exception is + * thrown. The resolved state is committed verbatim, as-is. * * @param state the future state of the framework - * @throws BundleException if the id of the given state does not match that of the - * current state or if the given state is not resolved. + * @throws BundleException if the id of the given state does not match that of + * the current state or if the given state is not + * resolved. */ public void commit(State state) throws BundleException; /** - * Returns a resolver supplied by the system. The returned resolver - * will not be associated with any state. + * Returns a resolver supplied by the system. The returned resolver will not be + * associated with any state. + * * @return a system resolver * @deprecated in favour of {@link #createResolver()}. */ @@ -92,6 +97,7 @@ public interface PlatformAdmin { /** * Creates a new {@link Resolver} that is not associated with any {@link State}. + * * @return the new Resolver. * @since 3.5 */ @@ -100,23 +106,27 @@ public interface PlatformAdmin { /** * Returns a factory that knows how to create state objects, such as bundle * descriptions and the different types of version constraints. + * * @return a state object factory */ public StateObjectFactory getFactory(); /** - * Adds the disabled info to the state managed by this platform admin. - * If a disable info already exists for the specified policy and the specified bundle - * then it is replaced with the given disabled info. + * Adds the disabled info to the state managed by this platform admin. If a + * disable info already exists for the specified policy and the specified bundle + * then it is replaced with the given disabled info. + * * @param disabledInfo the disabled info to add. * @throws IllegalArgumentException if the BundleDescription for - * the specified disabled info does not exist in the state managed by this platform admin. + * the specified disabled info does not exist + * in the state managed by this platform admin. * @since 3.4 */ public void addDisabledInfo(DisabledInfo disabledInfo); /** * Removes the disabled info from the state managed by this platform admin. + * * @param disabledInfo the disabled info to remove * @since 3.4 */ diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/Resolver.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/Resolver.java index 72059199239..e4a8d2c2bfc 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/Resolver.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/Resolver.java @@ -22,119 +22,136 @@ *

    * Clients may implement this interface. *

    + * * @since 3.1 */ public interface Resolver { /** * Resolves the state associated with this resolver and returns an array of - * bundle deltas describing the changes.. The state and version bindings - * for the various bundles and packages in this state are updated and a - * array containing bundle deltas describing the changes returned. + * bundle deltas describing the changes.. The state and version bindings for the + * various bundles and packages in this state are updated and a array containing + * bundle deltas describing the changes returned. *

    - * This method is intended to be called only by State objects in response - * to a user invocation of State.resolve(). States will typically refuse to - * update their constituents (see State.resolveBundle() and - * State.resolveConstraint()) if their resolve method is not currently - * being invoked. + * This method is intended to be called only by State objects in response to a + * user invocation of State.resolve(). States will typically refuse to update + * their constituents (see State.resolveBundle() and State.resolveConstraint()) + * if their resolve method is not currently being invoked. *

    *

    * Note the given state is destructively modified to reflect the results of * resolution. *

    - * @param discard the list of bundles to discard the resolve status and - * reresolve. A null value indicates that all currently unresolved - * bundles in the state should be resolved. - * @param platformProperties the platform properties used to match platform filters - * against. A null value indicates that the system properties should - * be used to match against + * + * @param discard the list of bundles to discard the resolve status + * and reresolve. A null value indicates + * that all currently unresolved bundles in the state + * should be resolved. + * @param platformProperties the platform properties used to match platform + * filters against. A null value + * indicates that the system properties should be used + * to match against */ public void resolve(BundleDescription[] discard, Dictionary[] platformProperties); /** * Flushes this resolver of any stored/cached data it may be keeping to - * facilitate incremental processing on its associated state. This is - * typicaly used when switching the resolver's state object. + * facilitate incremental processing on its associated state. This is typicaly + * used when switching the resolver's state object. */ public void flush(); /** - * Returns the state associated with this resolver. A state can work with - * at most one resolver at any given time. Similarly, a resolver can work - * with at most one state at a time. + * Returns the state associated with this resolver. A state can work with at + * most one resolver at any given time. Similarly, a resolver can work with at + * most one state at a time. * - * @return the state for this resolver. null is returned if the resolver - * does not have a state + * @return the state for this resolver. null is returned if the resolver does + * not have a state */ public State getState(); /** - * Sets the state associated with this resolver. A state can work with at - * most one resolver at any given time. Similarly, a resolver can work with - * at most one state at a time. + * Sets the state associated with this resolver. A state can work with at most + * one resolver at any given time. Similarly, a resolver can work with at most + * one state at a time. *

    - * To ensure that this resolver and the given state are properly linked, - * the following expression must be included in this method if the given - * state (value) is not identical to the result of this.getState(). + * To ensure that this resolver and the given state are properly linked, the + * following expression must be included in this method if the given state + * (value) is not identical to the result of this.getState(). *

    * *
    -	 *  if (this.getState() != value) value.setResolver(this);
    +	 * if (this.getState() != value)
    +	 * 	value.setResolver(this);
     	 * 
    */ public void setState(State value); /** * Notifies the resolver a bundle has been added to the state. + * * @param bundle the bundle added */ public void bundleAdded(BundleDescription bundle); /** * Notifies the resolver a bundle has been removed from the state. - * @param bundle the bundle description to remove - * @param pending indicates if the bundle to be remove has current dependents and - * will pend complete removal until the bundle has been re-resolved. + * + * @param bundle the bundle description to remove + * @param pending indicates if the bundle to be remove has current dependents + * and will pend complete removal until the bundle has been + * re-resolved. */ public void bundleRemoved(BundleDescription bundle, boolean pending); /** * Notifies the resolver a bundle has been updated in the state. - * @param newDescription the new description + * + * @param newDescription the new description * @param existingDescription the existing description - * @param pending indicates if the bundle to be updated has current dependents and - * will pend complete removal until the bundle has been re-resolved. + * @param pending indicates if the bundle to be updated has current + * dependents and will pend complete removal until + * the bundle has been re-resolved. */ public void bundleUpdated(BundleDescription newDescription, BundleDescription existingDescription, boolean pending); /** - * Attempts to find an ExportPackageDescription that will satisfy a dynamic import - * for the specified requestedPackage for the specified importingBundle. If no - * ExportPackageDescription is available that satisfies a dynamic import for the - * importingBundle then null is returned. - * @param importingBundle the BundleDescription that is requesting a dynamic package + * Attempts to find an ExportPackageDescription that will satisfy a dynamic + * import for the specified requestedPackage for the specified importingBundle. + * If no ExportPackageDescription is available that satisfies a dynamic import + * for the importingBundle then null is returned. + * + * @param importingBundle the BundleDescription that is requesting a dynamic + * package * @param requestedPackage the name of the package that is being requested - * @return the ExportPackageDescription that satisfies the dynamic import request; - * a value of null is returned if none is available. + * @return the ExportPackageDescription that satisfies the dynamic import + * request; a value of null is returned if none is + * available. */ public ExportPackageDescription resolveDynamicImport(BundleDescription importingBundle, String requestedPackage); /** - * Sets the selection policy for this resolver. A selection policy is used to sort - * possible suppliers of a version constraint in descending order. That is an order - * which is from most desired to least desired. The objects passed to the - * selection policy {@link Comparator#compare(Object, Object)} method - * will be of type {@link BaseDescription}. The selection policy should return a - * negative number, zero, or a positive number depending on if the first object is - * more desired, equal amount of desire, or less desired than the second object respectively. + * Sets the selection policy for this resolver. A selection policy is used to + * sort possible suppliers of a version constraint in descending order. That is + * an order which is from most desired to least desired. The objects passed to + * the selection policy {@link Comparator#compare(Object, Object)} method will + * be of type {@link BaseDescription}. The selection policy should return a + * negative number, zero, or a positive number depending on if the first object + * is more desired, equal amount of desire, or less desired than the second + * object respectively. *

    - * If no selection policy is set then a default policy will be used which sorts according - * to the following rules: + * If no selection policy is set then a default policy will be used which sorts + * according to the following rules: *

      - *
    1. The resolution status of the bundle which supplies the base description. Resolved bundles take priority over unresolved ones. - *
    2. The version of the base description. Higher versions take priority over lower versions. - *
    3. The bundle ID which supplies the base description. Lower IDs take priority over higher IDs. + *
    4. The resolution status of the bundle which supplies the base description. + * Resolved bundles take priority over unresolved ones. + *
    5. The version of the base description. Higher versions take priority over + * lower versions. + *
    6. The bundle ID which supplies the base description. Lower IDs take + * priority over higher IDs. *
    + * * @param selectionPolicy the selection policy for this resolver * @since 3.2 */ @@ -142,6 +159,7 @@ public interface Resolver { /** * Returns the selection policy for this resolver or null if it is not set + * * @return the selection policy for this resolver or null if it is not set * @since 3.2 */ diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/ResolverError.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/ResolverError.java index 1455899a72a..2426c0a513d 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/ResolverError.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/ResolverError.java @@ -15,153 +15,174 @@ /** * ResolverErrors represent a single error that prevents a bundle from resolving - * in a State object. - * *

    + * in a State object. * + *

    * This interface is not intended to be implemented by clients. *

    + * * @since 3.2 * @noimplement This interface is not intended to be implemented by clients. */ public interface ResolverError { /** - * Error type constant (bit mask) indicating that an Import-Package could - * not be resolved. + * Error type constant (bit mask) indicating that an Import-Package could not be + * resolved. + * * @see ResolverError#getType() */ public static final int MISSING_IMPORT_PACKAGE = 0x0001; /** - * Error type constant (bit mask) indicating that a Require-Bundle could - * not be resolved. + * Error type constant (bit mask) indicating that a Require-Bundle could not be + * resolved. + * * @see ResolverError#getType() */ public static final int MISSING_REQUIRE_BUNDLE = 0x0002; /** - * Error type constant (bit mask) indicating that a Fragment-Host could - * not be resolved. + * Error type constant (bit mask) indicating that a Fragment-Host could not be + * resolved. + * * @see ResolverError#getType() */ public static final int MISSING_FRAGMENT_HOST = 0x0004; /** - * Error type constant (bit mask) indicating that the bundle could not - * be resolved because another singleton bundle was selected. + * Error type constant (bit mask) indicating that the bundle could not be + * resolved because another singleton bundle was selected. + * * @see ResolverError#getType() */ public static final int SINGLETON_SELECTION = 0x0008; /** - * Error type constant (bit mask) indicating that the bundle fragment - * could not be resolved because a constraint conflict with a host. + * Error type constant (bit mask) indicating that the bundle fragment could not + * be resolved because a constraint conflict with a host. + * * @see ResolverError#getType() */ public static final int FRAGMENT_CONFLICT = 0x0010; /** - * Error type constant (bit mask) indicating that an Import-Package could - * not be resolved because of a uses directive conflict. + * Error type constant (bit mask) indicating that an Import-Package could not be + * resolved because of a uses directive conflict. + * * @see ResolverError#getType() */ public static final int IMPORT_PACKAGE_USES_CONFLICT = 0x0020; /** - * Error type constant (bit mask) indicating that a Require-Bundle could - * not be resolved because of a uses directive conflict. + * Error type constant (bit mask) indicating that a Require-Bundle could not be + * resolved because of a uses directive conflict. + * * @see ResolverError#getType() */ public static final int REQUIRE_BUNDLE_USES_CONFLICT = 0x0040; /** - * Error type constant (bit mask) indicating that an Import-Package could - * not be resolved because the importing bundle does not have the correct - * permissions to import the package. + * Error type constant (bit mask) indicating that an Import-Package could not be + * resolved because the importing bundle does not have the correct permissions + * to import the package. + * * @see ResolverError#getType() */ public static final int IMPORT_PACKAGE_PERMISSION = 0x0080; /** - * Error type constant (bit mask) indicating that an Import-Package could - * not be resolved because no exporting bundle has the correct - * permissions to export the package. + * Error type constant (bit mask) indicating that an Import-Package could not be + * resolved because no exporting bundle has the correct permissions to export + * the package. + * * @see ResolverError#getType() */ public static final int EXPORT_PACKAGE_PERMISSION = 0x0100; /** - * Error type constant (bit mask) indicating that a Require-Bundle could - * not be resolved because the requiring bundle does not have the correct - * permissions to require the bundle. + * Error type constant (bit mask) indicating that a Require-Bundle could not be + * resolved because the requiring bundle does not have the correct permissions + * to require the bundle. + * * @see ResolverError#getType() */ public static final int REQUIRE_BUNDLE_PERMISSION = 0x0200; /** - * Error type constant (bit mask) indicating that a Require-Bundle could - * not be resolved because no bundle with the required symbolic name has - * the correct permissions to provide the required symbolic name. + * Error type constant (bit mask) indicating that a Require-Bundle could not be + * resolved because no bundle with the required symbolic name has the correct + * permissions to provide the required symbolic name. + * * @see ResolverError#getType() */ public static final int PROVIDE_BUNDLE_PERMISSION = 0x0400; /** - * Error type constant (bit mask) indicating that a Fragment-Host could - * not be resolved because no bundle with the required symbolic name has - * the correct permissions to host a fragment. + * Error type constant (bit mask) indicating that a Fragment-Host could not be + * resolved because no bundle with the required symbolic name has the correct + * permissions to host a fragment. + * * @see ResolverError#getType() */ public static final int HOST_BUNDLE_PERMISSION = 0x0800; /** - * Error type constant (bit mask) indicating that a Fragment-Host could - * not be resolved because the fragment bundle does not have the correct - * permissions to be a fragment. + * Error type constant (bit mask) indicating that a Fragment-Host could not be + * resolved because the fragment bundle does not have the correct permissions to + * be a fragment. + * * @see ResolverError#getType() */ public static final int FRAGMENT_BUNDLE_PERMISSION = 0x1000; /** - * Error type constant (bit mask) indicating that a bundle could not be - * resolved because a platform filter did not match the runtime environment. + * Error type constant (bit mask) indicating that a bundle could not be resolved + * because a platform filter did not match the runtime environment. + * * @see ResolverError#getType() */ public static final int PLATFORM_FILTER = 0x2000; /** - * Error type constant (bit mask) indicating that a bundle could not be - * resolved because the required execution enviroment did not match the runtime + * Error type constant (bit mask) indicating that a bundle could not be resolved + * because the required execution enviroment did not match the runtime * environment. + * * @see ResolverError#getType() */ public static final int MISSING_EXECUTION_ENVIRONMENT = 0x4000; /** - * Error type constant (bit mask) indicating that a bundle could not be - * resolved because the required generic capability could not be resolved. + * Error type constant (bit mask) indicating that a bundle could not be resolved + * because the required generic capability could not be resolved. */ public static final int MISSING_GENERIC_CAPABILITY = 0x8000; /** - * Error type constant (bit mask) indicating that a bundle could not be - * resolved because no match was found for the native code specification. + * Error type constant (bit mask) indicating that a bundle could not be resolved + * because no match was found for the native code specification. + * * @since 3.4 */ public static final int NO_NATIVECODE_MATCH = 0x10000; /** - * Error type constant (bit mask) indicating that a bundle could not be - * resolved because the matching native code paths are invalid. + * Error type constant (bit mask) indicating that a bundle could not be resolved + * because the matching native code paths are invalid. + * * @since 3.4 */ public static final int INVALID_NATIVECODE_PATHS = 0x20000; /** - * Error type constant (bit mask) indicating that a bundle could not be - * resolved because the bundle was disabled + * Error type constant (bit mask) indicating that a bundle could not be resolved + * because the bundle was disabled + * * @since 3.4 */ public static final int DISABLED_BUNDLE = 0x40000; /** - * Error type constant (bit mask) indicating that a Require-Capability could - * not be resolved because the requiring bundle does not have the correct + * Error type constant (bit mask) indicating that a Require-Capability could not + * be resolved because the requiring bundle does not have the correct * permissions to require the capability. + * * @see ResolverError#getType() * @since 3.7 */ public static final int REQUIRE_CAPABILITY_PERMISSION = 0x80000; /** - * Error type constant (bit mask) indicating that a Require-Bundle could - * not be resolved because no bundle with the required symbolic name has - * the correct permissions to provide the required symbolic name. + * Error type constant (bit mask) indicating that a Require-Bundle could not be + * resolved because no bundle with the required symbolic name has the correct + * permissions to provide the required symbolic name. + * * @see ResolverError#getType() * @since 3.7 */ @@ -169,28 +190,31 @@ public interface ResolverError { /** * Returns the bundle which this ResolverError is for + * * @return the bundle which this ResolverError is for */ public BundleDescription getBundle(); /** * Returns the type of ResolverError this is + * * @return the type of ResolverError this is */ public int getType(); /** - * Returns non-translatable data associated with this ResolverError. - * For example, the data for a ResolverError of type MISSING_IMPORT_PACKAGE - * could be the Import-Package manifest statement which did not resolve. + * Returns non-translatable data associated with this ResolverError. For + * example, the data for a ResolverError of type MISSING_IMPORT_PACKAGE could be + * the Import-Package manifest statement which did not resolve. + * * @return non-translatable data associated with this ResolverError */ public String getData(); /** - * Returns the unsatisfied constraint if this ResolverError occurred - * because of an unsatisfied constraint; otherwise null - * is returned. + * Returns the unsatisfied constraint if this ResolverError occurred because of + * an unsatisfied constraint; otherwise null is returned. + * * @return the unsatisfied constraint or null. */ public VersionConstraint getUnsatisfiedConstraint(); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/ResolverHookException.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/ResolverHookException.java index 50dd0c2bcc3..1d3e9c0b806 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/ResolverHookException.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/ResolverHookException.java @@ -14,8 +14,9 @@ package org.eclipse.osgi.service.resolver; /** - * A runtime exception thrown by a resolver to indicate that a resolver - * hook threw an unexpected exception and the resolve operation terminated. + * A runtime exception thrown by a resolver to indicate that a resolver hook + * threw an unexpected exception and the resolve operation terminated. + * * @since 3.7 */ public class ResolverHookException extends RuntimeException { @@ -23,8 +24,9 @@ public class ResolverHookException extends RuntimeException { /** * Constructs a new resolver hook exception. + * * @param message the message of the exception - * @param cause the cause of the exception + * @param cause the cause of the exception */ public ResolverHookException(String message, Throwable cause) { super(message, cause); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/State.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/State.java index f5c9ab97249..4738df73a0b 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/State.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/State.java @@ -26,9 +26,10 @@ * presented to the resolver relative to this state (i.e., both resolved and * unresolved). *

    - * This interface is not intended to be implemented by clients. The + * This interface is not intended to be implemented by clients. The * {@link StateObjectFactory} should be used to construct instances. *

    + * * @since 3.1 * @noimplement This interface is not intended to be implemented by clients. */ @@ -36,11 +37,12 @@ public interface State { /** * Adds the given bundle to this state. *

    - * If the bundle already exists in another state then an IllegalStateException - * will be thrown. Note that even if you remove a BundleDescription from - * one State object using {@link State#removeBundle(BundleDescription)} it - * may still be considered as removing pending if other bundles in that state depend on the - * bundle you removed. To complete a pending removal a call must be done to + * If the bundle already exists in another state then an + * IllegalStateException will be thrown. Note that even if you + * remove a BundleDescription from one State object + * using {@link State#removeBundle(BundleDescription)} it may still be + * considered as removing pending if other bundles in that state depend on the + * bundle you removed. To complete a pending removal a call must be done to * {@link State#resolve(BundleDescription[])} with the removed bundle. *

    * @@ -51,12 +53,14 @@ public interface State { public boolean addBundle(BundleDescription description); /** - * Returns a delta describing the differences between this state and the - * given state. The given state is taken as the base so the absence of a bundle - * in this state is reported as a deletion, etc. - *

    Note that the generated StateDelta will contain BundleDeltas with one - *of the following types: BundleDelta.ADDED, BundleDelta.REMOVED and - *BundleDelta.UPDATED

    + * Returns a delta describing the differences between this state and the given + * state. The given state is taken as the base so the absence of a bundle in + * this state is reported as a deletion, etc. + *

    + * Note that the generated StateDelta will contain BundleDeltas with one of the + * following types: BundleDelta.ADDED, BundleDelta.REMOVED and + * BundleDelta.UPDATED + *

    * * @param baseState the base state * @return a delta describing differences between this and the base state state @@ -68,7 +72,7 @@ public interface State { * * @param bundleId the id of the bundle description to be removed * @return the removed bundle description, or null, if a bundle - * with the given id does not exist in this state + * with the given id does not exist in this state */ public BundleDescription removeBundle(long bundleId); @@ -77,7 +81,7 @@ public interface State { * * @param bundle the bundle description to be removed * @return true, if if the bundle description was removed, - * false otherwise + * false otherwise */ public boolean removeBundle(BundleDescription bundle); @@ -86,13 +90,13 @@ public interface State { * * @param newDescription the bundle description to replace an existing one * @return true, if if the bundle description was updated, - * false otherwise + * false otherwise */ public boolean updateBundle(BundleDescription newDescription); /** - * Returns the delta representing the changes from the time this state was - * first captured until now. + * Returns the delta representing the changes from the time this state was first + * captured until now. * * @return the state delta */ @@ -107,8 +111,7 @@ public interface State { /** * Returns the bundle descriptor for the bundle with the given id. - * null is returned if no such bundle is found in - * this state. + * null is returned if no such bundle is found in this state. * * @return the descriptor for the identified bundle * @see BundleDescription#getBundleId() @@ -116,15 +119,14 @@ public interface State { public BundleDescription getBundle(long id); /** - * Returns the bundle descriptor for the bundle with the given name and - * version. A null value is returned if no such bundle is found in this state. - * A resolved bundle is always preferably returned over an unresolved bundle. - * If multiple bundles with the same resolution state are available, the bundle - * with the highest version number is returned if the version is - * null. + * Returns the bundle descriptor for the bundle with the given name and version. + * A null value is returned if no such bundle is found in this state. A resolved + * bundle is always preferably returned over an unresolved bundle. If multiple + * bundles with the same resolution state are available, the bundle with the + * highest version number is returned if the version is null. * * @param symbolicName symbolic name of the bundle to query - * @param version version of the bundle to query. null matches any bundle + * @param version version of the bundle to query. null matches any bundle * @return the descriptor for the identified bundle */ public BundleDescription getBundle(String symbolicName, Version version); @@ -139,11 +141,11 @@ public interface State { public BundleDescription getBundleByLocation(String location); /** - * Returns the timestamp for this state. This - * correlates this timestamp to the system state. For example, if - * the system state timestamp is 4 but then some bundles are installed, - * the system state timestamp is updated. By comparing 4 to the current system - * state timestamp it is possible to detect if the states are out of sync. + * Returns the timestamp for this state. This correlates this timestamp to the + * system state. For example, if the system state timestamp is 4 but then some + * bundles are installed, the system state timestamp is updated. By comparing 4 + * to the current system state timestamp it is possible to detect if the states + * are out of sync. * * @return the timestamp of this state */ @@ -151,13 +153,14 @@ public interface State { /** * Sets the timestamp for this state + * * @param newTimeStamp the new timestamp for this state */ public void setTimeStamp(long newTimeStamp); /** - * Returns true if there have been no modifications to this state since the - * last time resolve() was called. + * Returns true if there have been no modifications to this state since the last + * time resolve() was called. * * @return whether or not this state has changed since last resolved. */ @@ -166,106 +169,147 @@ public interface State { /** * Resolves the given version constraint with the given supplier. The given * constraint object is destructively modified to reflect its new resolved - * state. Note that a constraint can be unresolved by passing null for - * the supplier. + * state. Note that a constraint can be unresolved by passing null for the + * supplier. *

    - * This method is intended to be used by resolvers in the process of - * determining which constraints are satisfied by which components. + * This method is intended to be used by resolvers in the process of determining + * which constraints are satisfied by which components. *

    * * @param constraint the version constraint to update - * @param supplier the supplier which satisfies the constraint. May be null if - * the constraint is to be unresolved. + * @param supplier the supplier which satisfies the constraint. May be null if + * the constraint is to be unresolved. * @throws IllegalStateException if this is not done during a call to - * resolve + * resolve */ public void resolveConstraint(VersionConstraint constraint, BaseDescription supplier); /** * Sets whether or not the given bundle is selected in this state. *

    - * This method is intended to be used by resolvers in the process of - * determining which constraints are satisfied by which components. + * This method is intended to be used by resolvers in the process of determining + * which constraints are satisfied by which components. *

    * - * @param bundle the bundle to update - * @param status whether or not the given bundle is resolved, if false the other parameters are ignored - * @param hosts the host for the resolve fragment, can be null - * @param selectedExports the selected exported packages for this resolved bundle, can be null - * @param resolvedRequires the {@link BundleDescription}s that resolve the required bundles for this bundle, can be null - * @param resolvedImports the exported packages that resolve the imports for this bundle, can be null - * @throws IllegalStateException if this is not done during a call to resolve - * @deprecated use {@link #resolveBundle(BundleDescription, boolean, BundleDescription[], ExportPackageDescription[], ExportPackageDescription[], GenericDescription[], BundleDescription[], ExportPackageDescription[], GenericDescription[], Map)} + * @param bundle the bundle to update + * @param status whether or not the given bundle is resolved, if false + * the other parameters are ignored + * @param hosts the host for the resolve fragment, can be + * null + * @param selectedExports the selected exported packages for this resolved + * bundle, can be null + * @param resolvedRequires the {@link BundleDescription}s that resolve the + * required bundles for this bundle, can be + * null + * @param resolvedImports the exported packages that resolve the imports for + * this bundle, can be null + * @throws IllegalStateException if this is not done during a call to + * resolve + * @deprecated use + * {@link #resolveBundle(BundleDescription, boolean, BundleDescription[], ExportPackageDescription[], ExportPackageDescription[], GenericDescription[], BundleDescription[], ExportPackageDescription[], GenericDescription[], Map)} */ - public void resolveBundle(BundleDescription bundle, boolean status, BundleDescription[] hosts, ExportPackageDescription[] selectedExports, BundleDescription[] resolvedRequires, ExportPackageDescription[] resolvedImports); + public void resolveBundle(BundleDescription bundle, boolean status, BundleDescription[] hosts, + ExportPackageDescription[] selectedExports, BundleDescription[] resolvedRequires, + ExportPackageDescription[] resolvedImports); /** * Sets whether or not the given bundle is selected in this state. *

    - * This method is intended to be used by resolvers in the process of - * determining which constraints are satisfied by which components. + * This method is intended to be used by resolvers in the process of determining + * which constraints are satisfied by which components. *

    * - * @param bundle the bundle to update - * @param status whether or not the given bundle is resolved, if false the other parameters are ignored - * @param hosts the host for the resolve fragment, can be null - * @param selectedExports the selected exported packages for this resolved bundle, can be null - * @param substitutedExports the exported packages that resolve imports for this bundle and substitute exports, can be null - * @param resolvedRequires the {@link BundleDescription}s that resolve the required bundles for this bundle, can be null - * @param resolvedImports the exported packages that resolve the imports for this bundle, can be null - * @throws IllegalStateException if this is not done during a call to resolve + * @param bundle the bundle to update + * @param status whether or not the given bundle is resolved, if + * false the other parameters are ignored + * @param hosts the host for the resolve fragment, can be + * null + * @param selectedExports the selected exported packages for this resolved + * bundle, can be null + * @param substitutedExports the exported packages that resolve imports for this + * bundle and substitute exports, can be + * null + * @param resolvedRequires the {@link BundleDescription}s that resolve the + * required bundles for this bundle, can be + * null + * @param resolvedImports the exported packages that resolve the imports for + * this bundle, can be null + * @throws IllegalStateException if this is not done during a call to + * resolve * @since 3.4 - * @deprecated use {@link #resolveBundle(BundleDescription, boolean, BundleDescription[], ExportPackageDescription[], ExportPackageDescription[], GenericDescription[], BundleDescription[], ExportPackageDescription[], GenericDescription[], Map)} + * @deprecated use + * {@link #resolveBundle(BundleDescription, boolean, BundleDescription[], ExportPackageDescription[], ExportPackageDescription[], GenericDescription[], BundleDescription[], ExportPackageDescription[], GenericDescription[], Map)} */ - public void resolveBundle(BundleDescription bundle, boolean status, BundleDescription[] hosts, ExportPackageDescription[] selectedExports, ExportPackageDescription[] substitutedExports, BundleDescription[] resolvedRequires, ExportPackageDescription[] resolvedImports); + public void resolveBundle(BundleDescription bundle, boolean status, BundleDescription[] hosts, + ExportPackageDescription[] selectedExports, ExportPackageDescription[] substitutedExports, + BundleDescription[] resolvedRequires, ExportPackageDescription[] resolvedImports); /** * Sets whether or not the given bundle is selected in this state. *

    - * This method is intended to be used by resolvers in the process of - * determining which constraints are satisfied by which components. + * This method is intended to be used by resolvers in the process of determining + * which constraints are satisfied by which components. *

    * - * @param bundle the bundle to update - * @param status whether or not the given bundle is resolved, if false the other parameters are ignored - * @param hosts the host for the resolve fragment, can be null - * @param selectedExports the selected exported packages for this resolved bundle, can be null - * @param substitutedExports the exported packages that resolve imports for this bundle and substitute exports, can be null - * @param selectedCapabilities the selected capabilities for this resolved bundle, can be null - * @param resolvedRequires the {@link BundleDescription}s that resolve the required bundles for this bundle, can be null - * @param resolvedImports the exported packages that resolve the imports for this bundle, can be null - * @param resolvedCapabilities the capabilities that resolve the required capabilities for this bundle, can be null - * @param resolvedWires the map of state wires for the resolved requirements of the given bundle. The key is the name space of the requirement. - * @throws IllegalStateException if this is not done during a call to resolve + * @param bundle the bundle to update + * @param status whether or not the given bundle is resolved, if + * false the other parameters are ignored + * @param hosts the host for the resolve fragment, can be + * null + * @param selectedExports the selected exported packages for this resolved + * bundle, can be null + * @param substitutedExports the exported packages that resolve imports for + * this bundle and substitute exports, can be + * null + * @param selectedCapabilities the selected capabilities for this resolved + * bundle, can be null + * @param resolvedRequires the {@link BundleDescription}s that resolve the + * required bundles for this bundle, can be + * null + * @param resolvedImports the exported packages that resolve the imports + * for this bundle, can be null + * @param resolvedCapabilities the capabilities that resolve the required + * capabilities for this bundle, can be + * null + * @param resolvedWires the map of state wires for the resolved + * requirements of the given bundle. The key is the + * name space of the requirement. + * @throws IllegalStateException if this is not done during a call to + * resolve * @since 3.7 */ - public void resolveBundle(BundleDescription bundle, boolean status, BundleDescription[] hosts, ExportPackageDescription[] selectedExports, ExportPackageDescription[] substitutedExports, GenericDescription[] selectedCapabilities, BundleDescription[] resolvedRequires, ExportPackageDescription[] resolvedImports, GenericDescription[] resolvedCapabilities, Map> resolvedWires); + public void resolveBundle(BundleDescription bundle, boolean status, BundleDescription[] hosts, + ExportPackageDescription[] selectedExports, ExportPackageDescription[] substitutedExports, + GenericDescription[] selectedCapabilities, BundleDescription[] resolvedRequires, + ExportPackageDescription[] resolvedImports, GenericDescription[] resolvedCapabilities, + Map> resolvedWires); /** * Sets the given removal pending bundle to removal complete for this state. *

    - * This method is intended to be used by resolvers in the process of - * resolving bundles. + * This method is intended to be used by resolvers in the process of resolving + * bundles. *

    + * * @param bundle the bundle to set a removal complete. * @throws IllegalStateException if this is not done during a call to - * resolve + * resolve */ public void removeBundleComplete(BundleDescription bundle); /** * Adds a new ResolverError for the specified bundle. *

    - * This method is intended to be used by resolvers in the process of - * resolving. + * This method is intended to be used by resolvers in the process of resolving. *

    * - * @param bundle the bundle to add a new ResolverError for - * @param type the type of ResolverError to add - * @param data the data for the ResolverError - * @param unsatisfied the unsatisfied constraint or null if the resolver error was not caused - * by an unsatisfied constraint. - * @throws IllegalStateException if this is not done during a call to resolve + * @param bundle the bundle to add a new ResolverError for + * @param type the type of ResolverError to add + * @param data the data for the ResolverError + * @param unsatisfied the unsatisfied constraint or null if the resolver error + * was not caused by an unsatisfied constraint. + * @throws IllegalStateException if this is not done during a call to + * resolve * @since 3.2 */ public void addResolverError(BundleDescription bundle, int type, String data, VersionConstraint unsatisfied); @@ -273,18 +317,19 @@ public interface State { /** * Removes all ResolverErrors for the specified bundle. *

    - * This method is intended to be used by resolvers in the process of - * resolving. + * This method is intended to be used by resolvers in the process of resolving. *

    * * @param bundle the bundle to remove all ResolverErrors for - * @throws IllegalStateException if this is not done during a call to resolve + * @throws IllegalStateException if this is not done during a call to + * resolve * @since 3.2 */ public void removeResolverErrors(BundleDescription bundle); /** * Returns all ResolverErrors for the given bundle + * * @param bundle the bundle to get all ResolverErrors for * @return all ResolverErrors for the given bundle * @since 3.2 @@ -292,58 +337,58 @@ public interface State { public ResolverError[] getResolverErrors(BundleDescription bundle); /** - * Returns the resolver associated with this state. A state can work with - * at most one resolver at any given time. Similarly, a resolver can work - * with at most one state at a time. + * Returns the resolver associated with this state. A state can work with at + * most one resolver at any given time. Similarly, a resolver can work with at + * most one state at a time. * - * @return the resolver for this state. null is returned if the state does - * not have a resolver + * @return the resolver for this state. null is returned if the state does not + * have a resolver */ public Resolver getResolver(); /** - * Sets the resolver associated with this state. A state can work with at - * most one resolver at any given time. Similarly, a resolver can work with - * at most one state at a time. + * Sets the resolver associated with this state. A state can work with at most + * one resolver at any given time. Similarly, a resolver can work with at most + * one state at a time. *

    - * To ensure that this state and the given resovler are properly linked, - * the following expression must be included in this method if the given - * resolver (value) is not identical to the result of this.getResolver(). + * To ensure that this state and the given resovler are properly linked, the + * following expression must be included in this method if the given resolver + * (value) is not identical to the result of this.getResolver(). *

    * *
    -	 *  if (this.getResolver() != value) value.setState(this);
    +	 * if (this.getResolver() != value)
    +	 * 	value.setState(this);
     	 * 
    * */ // TODO what happens if you set the Resolver after some bundles have - // been added to the state but it is not resolved? Should setting + // been added to the state but it is not resolved? Should setting // the resolver force a state to be unresolved? public void setResolver(Resolver value); /** - * Resolves the constraints contained in this state using the resolver - * currently associated with the state and returns a delta describing the - * changes in resolved states and dependencies in the state. + * Resolves the constraints contained in this state using the resolver currently + * associated with the state and returns a delta describing the changes in + * resolved states and dependencies in the state. *

    * Note that this method is typically implemented using * *

    -	 *  this.getResolver().resolve();
    +	 * this.getResolver().resolve();
     	 * 
    * * and is the preferred path for invoking resolution. In particular, states - * should refuse to perform updates (@see #select() and - * #resolveConstraint()) if they are not currently involved in a resolution - * cycle. + * should refuse to perform updates (@see #select() and #resolveConstraint()) if + * they are not currently involved in a resolution cycle. *

    * Note the given state is destructively modified to reflect the results of * resolution. *

    * - * @param incremental a flag controlling whether resolution should be incremental - * @return a delta describing the changes in resolved state and - * interconnections + * @param incremental a flag controlling whether resolution should be + * incremental + * @return a delta describing the changes in resolved state and interconnections */ public StateDelta resolve(boolean incremental); @@ -353,61 +398,59 @@ public interface State { public StateDelta resolve(); /** - * Resolves the constraints contained in this state using the resolver - * currently associated with the state in an incremental, "least-perturbing" - * mode, and returns a delta describing the changes in resolved states and - * dependencies in the state. + * Resolves the constraints contained in this state using the resolver currently + * associated with the state in an incremental, "least-perturbing" mode, and + * returns a delta describing the changes in resolved states and dependencies in + * the state. * - * @param discard an array containing descriptions for bundles whose - * current resolution state should be forgotten. If null - * then all the current removal pending BundleDescriptions are refreshed. - * @return a delta describing the changes in resolved state and - * interconnections + * @param discard an array containing descriptions for bundles whose current + * resolution state should be forgotten. If null + * then all the current removal pending BundleDescriptions are + * refreshed. + * @return a delta describing the changes in resolved state and interconnections */ public StateDelta resolve(BundleDescription[] discard); /** - * Resolves the constraints contained in this state using the resolver - * currently associated with the state in an incremental, "least-perturbing" - * mode, and returns a delta describing the changes in resolved states and - * dependencies in the state. If discard is set to true the - * the descriptions contained in the resolve array will have their - * current resolution state discarded and will be re-resolved. - * This method will attempt to resolve the supplied descriptions - * and may attempt to resolve any other unresolved descriptions contained - * in this state. + * Resolves the constraints contained in this state using the resolver currently + * associated with the state in an incremental, "least-perturbing" mode, and + * returns a delta describing the changes in resolved states and dependencies in + * the state. If discard is set to true the the descriptions contained in the + * resolve array will have their current resolution state discarded and will be + * re-resolved. This method will attempt to resolve the supplied descriptions + * and may attempt to resolve any other unresolved descriptions contained in + * this state. * * @param resolve an array containing descriptions for bundles to resolve. - * @param discard a value of true indicates the resolve descriptions - * should have their current resolution state discarded and re-resolved. + * @param discard a value of true indicates the resolve descriptions should have + * their current resolution state discarded and re-resolved. * @return a delta describing the changes in the resolved state and - * interconnections. + * interconnections. * @since 3.7 */ public StateDelta resolve(BundleDescription[] resolve, boolean discard); /** - * Sets the version overrides which are to be applied during the resolution - * of this state. Version overrides allow external forces to - * refine/override the version constraints setup by the components in the - * state. + * Sets the version overrides which are to be applied during the resolution of + * this state. Version overrides allow external forces to refine/override the + * version constraints setup by the components in the state. * * @param value Format undefined. - * @deprecated The exact form of this has never been defined. There is - * no alternative method available. + * @deprecated The exact form of this has never been defined. There is no + * alternative method available. */ public void setOverrides(Object value); /** * Returns descriptions for all bundles currently resolved in this state. * - * @return the descriptions for all bundles currently resolved in this - * state. + * @return the descriptions for all bundles currently resolved in this state. */ public BundleDescription[] getResolvedBundles(); /** * Returns descriptions for all bundles in a removal pending state. + * * @return the descriptions for all bundles in a removal pending state. * @since 3.7 */ @@ -417,122 +460,146 @@ public interface State { * Returns the dependency closure for the specified bundles. * *

    - * A graph of bundles is computed starting with the specified bundles. The - * graph is expanded by adding any bundle that is either wired to a package - * that is currently exported by a bundle in the graph or requires a bundle - * in the graph. The graph is fully constructed when there is no bundle - * outside the graph that is wired to a bundle in the graph. The graph may - * contain removal pending bundles. + * A graph of bundles is computed starting with the specified bundles. The graph + * is expanded by adding any bundle that is either wired to a package that is + * currently exported by a bundle in the graph or requires a bundle in the + * graph. The graph is fully constructed when there is no bundle outside the + * graph that is wired to a bundle in the graph. The graph may contain removal + * pending bundles. * * @param bundles The initial bundles for which to generate the dependency - * closure. - * @return A collection containing a snapshot of the dependency closure of - * the specified bundles, or an empty collection if there were no - * specified bundles. + * closure. + * @return A collection containing a snapshot of the dependency closure of the + * specified bundles, or an empty collection if there were no specified + * bundles. * @since 3.7 */ public Collection getDependencyClosure(Collection bundles); /** * Returns whether this state is empty. + * * @return true if this state is empty, false - * otherwise + * otherwise */ public boolean isEmpty(); /** - * Returns all exported packages in this state, according to the OSGi rules for resolution. + * Returns all exported packages in this state, according to the OSGi rules for + * resolution. + * * @see org.osgi.service.packageadmin.PackageAdmin#getExportedPackages(org.osgi.framework.Bundle) */ public ExportPackageDescription[] getExportedPackages(); /** * Returns all bundle descriptions with the given bundle symbolic name. + * * @param symbolicName symbolic name of the bundles to query * @return the descriptors for all bundles known to this state with the - * specified symbolic name. + * specified symbolic name. */ public BundleDescription[] getBundles(String symbolicName); /** * Returns the factory that created this state. + * * @return the state object factory that created this state */ public StateObjectFactory getFactory(); /** - * Attempts to find an ExportPackageDescription that will satisfy a dynamic import - * for the specified requestedPackage for the specified importingBundle. If no - * ExportPackageDescription is available that satisfies a dynamic import for the - * importingBundle then null is returned. - * @param importingBundle the BundleDescription that is requesting a dynamic package + * Attempts to find an ExportPackageDescription that will satisfy a dynamic + * import for the specified requestedPackage for the specified importingBundle. + * If no ExportPackageDescription is available that satisfies a dynamic import + * for the importingBundle then null is returned. + * + * @param importingBundle the BundleDescription that is requesting a dynamic + * package * @param requestedPackage the name of the package that is being requested - * @return the ExportPackageDescription that satisfies the dynamic import request; - * a value of null is returned if none is available. + * @return the ExportPackageDescription that satisfies the dynamic import + * request; a value of null is returned if none is + * available. */ public ExportPackageDescription linkDynamicImport(BundleDescription importingBundle, String requestedPackage); /** - * Adds the specified dynamic imports to the specified importingBundle. The added - * dynamic imports are only valid for the instance of this state and will be - * forgotten if this state is read from a persistent cache. + * Adds the specified dynamic imports to the specified importingBundle. The + * added dynamic imports are only valid for the instance of this state and will + * be forgotten if this state is read from a persistent cache. + * * @param importingBundle the bundle to add the imports to. - * @param dynamicImports the dynamic imports to add. + * @param dynamicImports the dynamic imports to add. * @since 3.7 * @see BundleDescription#getAddedDynamicImportPackages() */ - public void addDynamicImportPackages(BundleDescription importingBundle, ImportPackageSpecification[] dynamicImports); + public void addDynamicImportPackages(BundleDescription importingBundle, + ImportPackageSpecification[] dynamicImports); /** - * Sets the platform properties of the state. The platform properties - * are used to resolve the following constraints: + * Sets the platform properties of the state. The platform properties are used + * to resolve the following constraints: *

      - *
    • The execution environment requirements (i.e. Bundle-RequiredExecutionEnvironment).
    • + *
    • The execution environment requirements (i.e. + * Bundle-RequiredExecutionEnvironment).
    • *
    • The platform filter requirements (i.e. Eclipse-PlatformFilter).
    • *
    • The native code requirements (i.e. Bundle-NativeCode).
    • *
    - * Arbitrary keys may be used in the platform properties but the following keys have a specified meaning: + * Arbitrary keys may be used in the platform properties but the following keys + * have a specified meaning: *
      *
    • osgi.nl - the platform language setting.
    • *
    • osgi.os - the platform operating system.
    • *
    • osgi.arch - the platform architecture.
    • *
    • osgi.ws - the platform windowing system.
    • - *
    • osgi.resolverMode - the resolver mode. A value of "strict" will set the resolver mode to strict.
    • - *
    • org.osgi.framework.system.packages - the packages exported by the system bundle.
    • - *
    • org.osgi.framework.executionenvironment - the comma separated list of supported execution environments. - * This property is then used to resolve the required execution environment the bundles in a state.
    • - *
    • org.osgi.framework.os.name - the name of the operating system. This property is used to resolve the osname attribute of - * bundle native code (i.e. Bundle-NativeCode).
    • - *
    • org.osgi.framework.os.version - the version of the operating system. This property is used to resolve the osversion attribute - * of bundle native code (i.e. Bundle-NativeCode).
    • - *
    • org.osgi.framework.processor - the processor name. This property is used to resolve the processor attribute - * of bundle native code (i.e. Bundle-NativeCode).
    • - *
    • org.osgi.framework.language - the language being used. This property is used to resolve the language attribute - * of bundle native code (i.e. Bundle-NativeCode).
    • + *
    • osgi.resolverMode - the resolver mode. A value of "strict" will set the + * resolver mode to strict.
    • + *
    • org.osgi.framework.system.packages - the packages exported by the system + * bundle.
    • + *
    • org.osgi.framework.executionenvironment - the comma separated list of + * supported execution environments. This property is then used to resolve the + * required execution environment the bundles in a state.
    • + *
    • org.osgi.framework.os.name - the name of the operating system. This + * property is used to resolve the osname attribute of bundle native code (i.e. + * Bundle-NativeCode).
    • + *
    • org.osgi.framework.os.version - the version of the operating system. This + * property is used to resolve the osversion attribute of bundle native code + * (i.e. Bundle-NativeCode).
    • + *
    • org.osgi.framework.processor - the processor name. This property is used + * to resolve the processor attribute of bundle native code (i.e. + * Bundle-NativeCode).
    • + *
    • org.osgi.framework.language - the language being used. This property is + * used to resolve the language attribute of bundle native code (i.e. + * Bundle-NativeCode).
    • *
    * The values used for the supported properties can be String type - * to specify a single value for the property or they can by String[] - * to specify a list of values for the property. + * to specify a single value for the property or they can by + * String[] to specify a list of values for the property. + * * @param platformProperties the platform properties of the state * @return false if the platformProperties specified do not change any of the - * supported properties already set. If any of the supported property values - * are changed as a result of calling this method then true is returned. + * supported properties already set. If any of the supported property + * values are changed as a result of calling this method then true is + * returned. */ public boolean setPlatformProperties(Dictionary platformProperties); /** * Sets the platform properties of the state to a list of platform properties. + * * @see #setPlatformProperties(Dictionary) * * @param platformProperties a set of platform properties for the state * @return false if the platformProperties specified do not change any of the - * supported properties already set. If any of the supported property values - * are changed as a result of calling this method then true is returned. + * supported properties already set. If any of the supported property + * values are changed as a result of calling this method then true is + * returned. */ public boolean setPlatformProperties(Dictionary[] platformProperties); /** * Returns the list of platform properties currently set for this state. + * * @return the list of platform properties currently set for this state. */ @SuppressWarnings("rawtypes") @@ -542,17 +609,18 @@ public interface State { * Returns the list of system packages which are exported by the system bundle. * The list of system packages is set by the org.osgi.framework.system.packages * value in the platform properties for this state. + * * @see #setPlatformProperties(Dictionary) * @return the list of system packages */ public ExportPackageDescription[] getSystemPackages(); /** - * Returns a state helper object. State helpers provide convenience methods - * for manipulating states. + * Returns a state helper object. State helpers provide convenience methods for + * manipulating states. *

    - * A possible implementation for this - * method would provide the same single StateHelper instance to all clients. + * A possible implementation for this method would provide the same single + * StateHelper instance to all clients. *

    * * @return a state helper @@ -562,60 +630,69 @@ public interface State { public StateHelper getStateHelper(); /** - * Returns the highest bundle ID. The value -1 is returned if no - * bundles exist in this state. + * Returns the highest bundle ID. The value -1 is returned if no bundles exist + * in this state. *

    * Note that this method returns the highest bundle ID the ever existed in this - * this state object. This bundle may have been removed from the state. + * this state object. This bundle may have been removed from the state. + * * @return the highest bundle ID. * @since 3.3 */ public long getHighestBundleId(); /** - * Sets the native code paths of a native code description as invalid. Native + * Sets the native code paths of a native code description as invalid. Native * code paths are invalid if they can not be found in the bundle content. *

    - * The framework, or some other entity which has access to bundle content, - * will call this method to validate or invalidate native code paths. + * The framework, or some other entity which has access to bundle content, will + * call this method to validate or invalidate native code paths. *

    + * * @param nativeCodeDescription the native code description. - * @param hasInvalidNativePaths true if the native code paths are invalid; false otherwise. + * @param hasInvalidNativePaths true if the native code paths are invalid; false + * otherwise. * @since 3.4 */ public void setNativePathsInvalid(NativeCodeDescription nativeCodeDescription, boolean hasInvalidNativePaths); /** - * Returns an array of BundleDescriptions for the bundles that are disabled - * in the system. Use {@link #getDisabledInfos(BundleDescription)} to interrogate the reason that - * each bundle is disabled. - * @return the array of disabled bundles. An empty array is returned if no bundles are disabled. + * Returns an array of BundleDescriptions for the bundles that are disabled in + * the system. Use {@link #getDisabledInfos(BundleDescription)} to interrogate + * the reason that each bundle is disabled. + * + * @return the array of disabled bundles. An empty array is returned if no + * bundles are disabled. * @see DisabledInfo * @since 3.4 */ public BundleDescription[] getDisabledBundles(); /** - * Adds the disabled info to this state. If a disable info already exists - * for the specified policy and the specified bundle then it is replaced with - * the given disabled info. + * Adds the disabled info to this state. If a disable info already exists for + * the specified policy and the specified bundle then it is replaced with the + * given disabled info. + * * @param disabledInfo the disabled info to add. * @throws IllegalArgumentException if the BundleDescription for - * the specified disabled info does not exist in this state. + * the specified disabled info does not exist + * in this state. * @since 3.4 */ public void addDisabledInfo(DisabledInfo disabledInfo); /** * Removes the disabled info from the state. + * * @param disabledInfo the disabled info to remove * @since 3.4 */ public void removeDisabledInfo(DisabledInfo disabledInfo); /** - * Returns an array of disabled info for the specified bundle. If no disabled info exist - * then an empty array is returned. + * Returns an array of disabled info for the specified bundle. If no disabled + * info exist then an empty array is returned. + * * @param bundle the bundle to get the disabled info for. * @return the array of disabled info. * @since 3.4 @@ -623,8 +700,9 @@ public interface State { public DisabledInfo[] getDisabledInfos(BundleDescription bundle); /** - * Returns the disabled info for the specified bundle with the specified policy name. - * If no disabled info exists then null is returned. + * Returns the disabled info for the specified bundle with the specified policy + * name. If no disabled info exists then null is returned. + * * @param bundle the bundle to get the disabled info for * @return the disabled info. * @since 3.4 @@ -632,9 +710,10 @@ public interface State { public DisabledInfo getDisabledInfo(BundleDescription bundle, String policyName); /** - * Sets the resolver hook factory for this state. The resolver hook factory is + * Sets the resolver hook factory for this state. The resolver hook factory is * used during resolve operations according to the OSGi specification for the * resolver hook factory. + * * @param hookFactory the resolver hook factory * @since 3.7 * @throws IllegalStateException if the resolver hook factory is already set diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/StateDelta.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/StateDelta.java index 7c82e295a61..6e7b6917fd8 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/StateDelta.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/StateDelta.java @@ -18,24 +18,25 @@ *

    * This interface is not intended to be implemented by clients. *

    + * * @since 3.1 * @noimplement This interface is not intended to be implemented by clients. */ public interface StateDelta { /** * Returns an array of all the bundle deltas in this delta regardless of type. + * * @return an array of bundle deltas */ public BundleDelta[] getChanges(); /** - * Returns an array of all the members - * of this delta which match the given flags. If an exact match is requested - * then only delta members whose type exactly matches the given mask are - * included. Otherwise, all bundle deltas whose type's bit-wise and with the - * mask is non-zero are included. + * Returns an array of all the members of this delta which match the given + * flags. If an exact match is requested then only delta members whose type + * exactly matches the given mask are included. Otherwise, all bundle deltas + * whose type's bit-wise and with the mask is non-zero are included. * - * @param mask match mask + * @param mask match mask * @param exact whether exact match or bit-wise matching should be performed * @return an array of bundle deltas matching the given match criteria. */ @@ -43,13 +44,15 @@ public interface StateDelta { /** * Returns the state whose changes are represented by this delta. + * * @return the state */ public State getState(); /** - * Returns the resolver hook exception if one occurred while - * resolving the state. + * Returns the resolver hook exception if one occurred while resolving the + * state. + * * @since 3.7 */ public ResolverHookException getResovlerHookException(); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/StateHelper.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/StateHelper.java index 9a91efa567e..c0ac9348d5b 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/StateHelper.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/StateHelper.java @@ -14,69 +14,76 @@ package org.eclipse.osgi.service.resolver; /** - * A helper class that provides convenience methods for manipulating - * state objects. PlatformAdmin provides an access point - * for a state helper. + * A helper class that provides convenience methods for manipulating state + * objects. PlatformAdmin provides an access point for a state + * helper. *

    * This interface is not intended to be implemented by clients. *

    + * * @since 3.1 * @see PlatformAdmin#getStateHelper * @noimplement This interface is not intended to be implemented by clients. */ public interface StateHelper { /** - * Indicates that access is encouraged to an ExportPackageDescription. + * Indicates that access is encouraged to an + * ExportPackageDescription. */ public static int ACCESS_ENCOURAGED = 0x01; /** - * Indicates that access is discouraged to an ExportPackageDescription. + * Indicates that access is discouraged to an + * ExportPackageDescription. */ public static int ACCESS_DISCOURAGED = 0x02; /** * An option to include packages available from the execution environment when - * getting the visible packages of a bundle. For example, when running on a - * J2SE 1.4 VM the system bundle will export the javax.xml.parsers package as part of the - * execution environment. When this option is used then any packages from the execution - * environment which the bundle is wired to will be included. + * getting the visible packages of a bundle. For example, when running on a J2SE + * 1.4 VM the system bundle will export the javax.xml.parsers package as part of + * the execution environment. When this option is used then any packages from + * the execution environment which the bundle is wired to will be included. + * * @see StateHelper#getVisiblePackages(BundleDescription, int) */ public static int VISIBLE_INCLUDE_EE_PACKAGES = 0x01; /** - * An option to get all visible packages that a host bundle is currently wired to. This - * includes packages wired to as a result of a dynamic import and packages wired to as a - * result of additional constraints specified by a fragment bundle. Using this option - * with a fragment will cause an empty array to be returned. + * An option to get all visible packages that a host bundle is currently wired + * to. This includes packages wired to as a result of a dynamic import and + * packages wired to as a result of additional constraints specified by a + * fragment bundle. Using this option with a fragment will cause an empty array + * to be returned. + * * @see StateHelper#getVisiblePackages(BundleDescription, int) * @since 3.6 */ public static int VISIBLE_INCLUDE_ALL_HOST_WIRES = 0x02; /** - * Returns all bundles in the state depending on the given bundles. The given bundles - * appear in the returned array. + * Returns all bundles in the state depending on the given bundles. The given + * bundles appear in the returned array. * * @param bundles the initial set of bundles * @return an array containing bundle descriptions for the given roots and all - * bundles in the state that depend on them + * bundles in the state that depend on them */ public BundleDescription[] getDependentBundles(BundleDescription[] bundles); /** - * Returns all the prerequisite bundles in the state for the given bundles. The given - * bundles appear in the returned array. + * Returns all the prerequisite bundles in the state for the given bundles. The + * given bundles appear in the returned array. + * * @param bundles the inital set of bundles - * @return an array containing bundle descriptions for the given leaves and their - * prerequisite bundles in the state. + * @return an array containing bundle descriptions for the given leaves and + * their prerequisite bundles in the state. * @since 3.2 */ public BundleDescription[] getPrerequisites(BundleDescription[] bundles); /** - * Returns all unsatisfied constraints in the given bundle. Returns an - * empty array if no unsatisfied constraints can be found. + * Returns all unsatisfied constraints in the given bundle. Returns an empty + * array if no unsatisfied constraints can be found. *

    * Note that a bundle may have no unsatisfied constraints and still not be * resolved. @@ -88,24 +95,29 @@ public interface StateHelper { public VersionConstraint[] getUnsatisfiedConstraints(BundleDescription bundle); /** - * Returns all unsatisfied constraints in the given bundles that have no possible supplier. - * Returns an empty array if no unsatisfied leaf constraints can be found. + * Returns all unsatisfied constraints in the given bundles that have no + * possible supplier. Returns an empty array if no unsatisfied leaf constraints + * can be found. *

    - * The returned constraints include only the unsatisfied constraints in the given - * state that have no possible supplier (leaf constraints). There may - * be additional unsatisfied constraints in the given bundles but these will have at - * least one possible supplier. In this case the possible supplier of the constraint - * is not resolved for some reason. For example, a given state only has Bundles X and Y - * installed and Bundles X and Y have the following constraints: + * The returned constraints include only the unsatisfied constraints in the + * given state that have no possible supplier (leaf constraints). There may be + * additional unsatisfied constraints in the given bundles but these will have + * at least one possible supplier. In this case the possible supplier of the + * constraint is not resolved for some reason. For example, a given state only + * has Bundles X and Y installed and Bundles X and Y have the following + * constraints: *

    + * *
     	 * Bundle X requires Bundle Y
    -	 * Bundle Y requires Bundle Z
    + * Bundle Y requires Bundle Z + * *

    - * In this case Bundle Y has an unsatisfied constraint leaf on Bundle Z. This will - * cause Bundle X's constraint on Bundle Y to be unsatisfied as well because the - * bundles are involved in a dependency chain. Bundle X's constraint on Bundle Y is - * not considered a leaf because there is a possible supplier Y in the given state. + * In this case Bundle Y has an unsatisfied constraint leaf on Bundle Z. This + * will cause Bundle X's constraint on Bundle Y to be unsatisfied as well + * because the bundles are involved in a dependency chain. Bundle X's constraint + * on Bundle Y is not considered a leaf because there is a possible supplier Y + * in the given state. *

    *

    * Note that a bundle may have no unsatisfied constraints and still not be @@ -113,55 +125,56 @@ public interface StateHelper { *

    * * @param bundles the bundles to examine - * @return an array containing all unsatisfied leaf constraints for the given bundles + * @return an array containing all unsatisfied leaf constraints for the given + * bundles * @since 3.2 */ public VersionConstraint[] getUnsatisfiedLeaves(BundleDescription[] bundles); /** - * Returns whether the given package specification constraint is resolvable. - * A package specification constraint may be - * resolvable but not resolved, which means that the bundle that provides - * it has not been resolved for some other reason (e.g. another constraint - * could not be resolved, another version has been picked, etc). + * Returns whether the given package specification constraint is resolvable. A + * package specification constraint may be resolvable but not resolved, which + * means that the bundle that provides it has not been resolved for some other + * reason (e.g. another constraint could not be resolved, another version has + * been picked, etc). * * @param specification the package specification constraint to be examined * @return true if the constraint can be resolved, - * false otherwise + * false otherwise */ public boolean isResolvable(ImportPackageSpecification specification); /** - * Returns whether the given bundle specification constraint is resolvable. - * A bundle specification constraint may be - * resolvable but not resolved, which means that the bundle that provides - * it has not been resolved for some other reason (e.g. another constraint - * could not be resolved, another version has been picked, etc). + * Returns whether the given bundle specification constraint is resolvable. A + * bundle specification constraint may be resolvable but not resolved, which + * means that the bundle that provides it has not been resolved for some other + * reason (e.g. another constraint could not be resolved, another version has + * been picked, etc). * * @param specification the bundle specification constraint to be examined * @return true if the constraint can be resolved, - * false otherwise + * false otherwise */ public boolean isResolvable(BundleSpecification specification); /** - * Returns whether the given host specification constraint is resolvable. - * A host specification constraint may be - * resolvable but not resolved, which means that the bundle that provides - * it has not been resolved for some other reason (e.g. another constraint - * could not be resolved, another version has been picked, etc). + * Returns whether the given host specification constraint is resolvable. A host + * specification constraint may be resolvable but not resolved, which means that + * the bundle that provides it has not been resolved for some other reason (e.g. + * another constraint could not be resolved, another version has been picked, + * etc). * * @param specification the host specification constraint to be examined * @return true if the constraint can be resolved, - * false otherwise + * false otherwise */ public boolean isResolvable(HostSpecification specification); /** - * Sorts the given array of resolved bundles in pre-requisite order. If A - * requires B, A appears after B. - * Fragments will appear after all of their hosts. Constraints contributed by fragments will - * be treated as if contributed by theirs hosts, affecting their position. This is true even if + * Sorts the given array of resolved bundles in pre-requisite + * order. If A requires B, A appears after B. Fragments will appear after all of + * their hosts. Constraints contributed by fragments will be treated as if + * contributed by theirs hosts, affecting their position. This is true even if * the fragment does not appear in the given bundle array. *

    * Unresolved bundles are ignored. @@ -173,29 +186,31 @@ public interface StateHelper { public Object[][] sortBundles(BundleDescription[] toSort); /** - * Returns a list of all packages that the specified bundle has access to which are - * exported by other bundles. + * Returns a list of all packages that the specified bundle has access to which + * are exported by other bundles. *

    * Same as calling getVisiblePackages(bundle, 0) *

    + * * @param bundle a bundle to get the list of packages for. - * @return a list of all packages that the specified bundle has access to which are - * exported by other bundles. + * @return a list of all packages that the specified bundle has access to which + * are exported by other bundles. */ public ExportPackageDescription[] getVisiblePackages(BundleDescription bundle); /** - * Returns a list of all packages that the specified bundle has access to which are - * exported by other bundles. This takes into account all constraint specifications - * (Import-Package, Require-Bundle etc). A deep dependency search is done for all - * packages which are available through the required bundles and any bundles which - * are reexported. This method also takes into account all directives - * which may be specified on the constraint specifications (e.g. uses, x-friends etc.) + * Returns a list of all packages that the specified bundle has access to which + * are exported by other bundles. This takes into account all constraint + * specifications (Import-Package, Require-Bundle etc). A deep dependency search + * is done for all packages which are available through the required bundles and + * any bundles which are reexported. This method also takes into account all + * directives which may be specified on the constraint specifications (e.g. + * uses, x-friends etc.) * - * @param bundle a bundle to get the list of packages for. + * @param bundle a bundle to get the list of packages for. * @param options the options for selecting the visible packages - * @return a list of all packages that the specified bundle has access to which are - * exported by other bundles. + * @return a list of all packages that the specified bundle has access to which + * are exported by other bundles. * @see StateHelper#VISIBLE_INCLUDE_EE_PACKAGES * @see StateHelper#VISIBLE_INCLUDE_ALL_HOST_WIRES * @since 3.3 @@ -203,8 +218,9 @@ public interface StateHelper { public ExportPackageDescription[] getVisiblePackages(BundleDescription bundle, int options); /** - * Returns the access code that the specified BundleDescription has to the - * specified ExportPackageDescription. + * Returns the access code that the specified BundleDescription has + * to the specified ExportPackageDescription. + * * @param bundle the bundle to find the access code for * @param export the export to find the access code for * @return the access code to the export. diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/StateObjectFactory.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/StateObjectFactory.java index 34974f5b4c9..f9cc4236f2c 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/StateObjectFactory.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/StateObjectFactory.java @@ -31,6 +31,7 @@ *

    * This interface is not intended to be implemented by clients. *

    + * * @since 3.1 * @noimplement This interface is not intended to be implemented by clients. */ @@ -38,14 +39,14 @@ public interface StateObjectFactory { /** * The default object factory that can be used to create, populate and resolve - * states. This is particularly useful when using the resolver outside the context - * of a running Equinox framework. + * states. This is particularly useful when using the resolver outside the + * context of a running Equinox framework. */ public static final StateObjectFactory defaultFactory = new StateObjectFactoryProxy(); /** - * Creates an empty state. The returned state does not have an - * attached resolver. + * Creates an empty state. The returned state does not have an attached + * resolver. * * @return the created state * @deprecated use {@link #createState(boolean) } @@ -55,7 +56,8 @@ public interface StateObjectFactory { /** * Creates an empty state with or without a resolver. * - * @param resolver true if the created state should be initialized with a resolver. + * @param resolver true if the created state should be initialized with a + * resolver. * @return the created state * @since 3.2 */ @@ -63,10 +65,10 @@ public interface StateObjectFactory { /** * Creates a new state that is a copy of the given state. The returned state - * will contain copies of all bundle descriptions in the given state. - * The user objects from the original bundle descriptions is not copied and - * no data pertaining to resolution is copied. The returned state will have a - * new resolver attached to it. + * will contain copies of all bundle descriptions in the given state. The user + * objects from the original bundle descriptions is not copied and no data + * pertaining to resolution is copied. The returned state will have a new + * resolver attached to it. * * @param state a state to be copied * @return the created state @@ -76,153 +78,226 @@ public interface StateObjectFactory { /** * Creates a bundle description from the given parameters. * - * @param id id for the bundle - * @param symbolicName symbolic name for the bundle (may be - * null) - * @param version version for the bundle (may be null) - * @param location location for the bundle (may be null) - * @param required version constraints for all required bundles (may be - * null) - * @param host version constraint specifying the host for the bundle to be - * created. Should be null if the bundle is not a fragment - * @param imports version constraints for all packages imported - * (may be null) - * @param exports package descriptions of all the exported packages - * (may be null) - * @param providedPackages the list of provided packages (may be null) - * @param singleton whether the bundle created should be a singleton + * @param id id for the bundle + * @param symbolicName symbolic name for the bundle (may be + * null) + * @param version version for the bundle (may be null) + * @param location location for the bundle (may be null) + * @param required version constraints for all required bundles (may be + * null) + * @param host version constraint specifying the host for the bundle + * to be created. Should be null if the + * bundle is not a fragment + * @param imports version constraints for all packages imported (may be + * null) + * @param exports package descriptions of all the exported packages + * (may be null) + * @param providedPackages the list of provided packages (may be + * null) + * @param singleton whether the bundle created should be a singleton * @return the created bundle description - * @deprecated use {@link #createBundleDescription(long, String, Version, String, BundleSpecification[], HostSpecification, ImportPackageSpecification[], ExportPackageDescription[], boolean, boolean, boolean, String, String[], GenericSpecification[], GenericDescription[])} + * @deprecated use + * {@link #createBundleDescription(long, String, Version, String, BundleSpecification[], HostSpecification, ImportPackageSpecification[], ExportPackageDescription[], boolean, boolean, boolean, String, String[], GenericSpecification[], GenericDescription[])} */ - public BundleDescription createBundleDescription(long id, String symbolicName, Version version, String location, BundleSpecification[] required, HostSpecification host, ImportPackageSpecification[] imports, ExportPackageDescription[] exports, String[] providedPackages, boolean singleton); + public BundleDescription createBundleDescription(long id, String symbolicName, Version version, String location, + BundleSpecification[] required, HostSpecification host, ImportPackageSpecification[] imports, + ExportPackageDescription[] exports, String[] providedPackages, boolean singleton); /** * Creates a bundle description from the given parameters. * - * @param id id for the bundle - * @param symbolicName symbolic name for the bundle (may be - * null) - * @param version version for the bundle (may be null) - * @param location location for the bundle (may be null) - * @param required version constraints for all required bundles (may be - * null) - * @param host version constraint specifying the host for the bundle to be - * created. Should be null if the bundle is not a fragment - * @param imports version constraints for all packages imported - * (may be null) - * @param exports package descriptions of all the exported packages - * (may be null) - * @param providedPackages the list of provided packages (may be null) - * @param singleton whether the bundle created should be a singleton - * @param attachFragments whether the bundle allows fragments to attach - * @param dynamicFragments whether the bundle allows fragments to dynamically attach - * @param platformFilter the platform filter (may be null) - * @param executionEnvironment the execution environment (may be null) - * @param genericRequires the version constraints for all required capabilities (may be null) - * @param genericCapabilities the specifications of all the capabilities of the bundle (may be null) + * @param id id for the bundle + * @param symbolicName symbolic name for the bundle (may be + * null) + * @param version version for the bundle (may be null) + * @param location location for the bundle (may be + * null) + * @param required version constraints for all required bundles (may + * be null) + * @param host version constraint specifying the host for the + * bundle to be created. Should be null + * if the bundle is not a fragment + * @param imports version constraints for all packages imported + * (may be null) + * @param exports package descriptions of all the exported packages + * (may be null) + * @param providedPackages the list of provided packages (may be + * null) + * @param singleton whether the bundle created should be a singleton + * @param attachFragments whether the bundle allows fragments to attach + * @param dynamicFragments whether the bundle allows fragments to + * dynamically attach + * @param platformFilter the platform filter (may be null) + * @param executionEnvironment the execution environment (may be + * null) + * @param genericRequires the version constraints for all required + * capabilities (may be null) + * @param genericCapabilities the specifications of all the capabilities of the + * bundle (may be null) * @return the created bundle description - * @deprecated use {@link #createBundleDescription(long, String, Version, String, BundleSpecification[], HostSpecification, ImportPackageSpecification[], ExportPackageDescription[], boolean, boolean, boolean, String, String[], GenericSpecification[], GenericDescription[])} + * @deprecated use + * {@link #createBundleDescription(long, String, Version, String, BundleSpecification[], HostSpecification, ImportPackageSpecification[], ExportPackageDescription[], boolean, boolean, boolean, String, String[], GenericSpecification[], GenericDescription[])} */ - public BundleDescription createBundleDescription(long id, String symbolicName, Version version, String location, BundleSpecification[] required, HostSpecification host, ImportPackageSpecification[] imports, ExportPackageDescription[] exports, String[] providedPackages, boolean singleton, boolean attachFragments, boolean dynamicFragments, String platformFilter, String executionEnvironment, GenericSpecification[] genericRequires, GenericDescription[] genericCapabilities); + public BundleDescription createBundleDescription(long id, String symbolicName, Version version, String location, + BundleSpecification[] required, HostSpecification host, ImportPackageSpecification[] imports, + ExportPackageDescription[] exports, String[] providedPackages, boolean singleton, boolean attachFragments, + boolean dynamicFragments, String platformFilter, String executionEnvironment, + GenericSpecification[] genericRequires, GenericDescription[] genericCapabilities); /** * Creates a bundle description from the given parameters. * - * @param id id for the bundle - * @param symbolicName symbolic name for the bundle (may be null) - * @param version version for the bundle (may be null) - * @param location location for the bundle (may be null) - * @param required version constraints for all required bundles (may be null) - * @param host version constraint specifying the host for the bundle to be created. Should be null if the bundle is not a fragment - * @param imports version constraints for all packages imported (may be null) - * @param exports package descriptions of all the exported packages (may be null) - * @param singleton whether the bundle created should be a singleton - * @param attachFragments whether the bundle allows fragments to attach - * @param dynamicFragments whether the bundle allows fragments to dynamically attach - * @param platformFilter the platform filter (may be null) - * @param executionEnvironments the execution environment (may be null) - * @param genericRequires the version constraints for all required capabilities (may be null) - * @param genericCapabilities the specifications of all the capabilities of the bundle (may be null) + * @param id id for the bundle + * @param symbolicName symbolic name for the bundle (may be + * null) + * @param version version for the bundle (may be + * null) + * @param location location for the bundle (may be + * null) + * @param required version constraints for all required bundles + * (may be null) + * @param host version constraint specifying the host for the + * bundle to be created. Should be + * null if the bundle is not a + * fragment + * @param imports version constraints for all packages imported + * (may be null) + * @param exports package descriptions of all the exported + * packages (may be null) + * @param singleton whether the bundle created should be a singleton + * @param attachFragments whether the bundle allows fragments to attach + * @param dynamicFragments whether the bundle allows fragments to + * dynamically attach + * @param platformFilter the platform filter (may be null) + * @param executionEnvironments the execution environment (may be + * null) + * @param genericRequires the version constraints for all required + * capabilities (may be null) + * @param genericCapabilities the specifications of all the capabilities of + * the bundle (may be null) * @return the created bundle description */ - public BundleDescription createBundleDescription(long id, String symbolicName, Version version, String location, BundleSpecification[] required, HostSpecification host, ImportPackageSpecification[] imports, ExportPackageDescription[] exports, boolean singleton, boolean attachFragments, boolean dynamicFragments, String platformFilter, String[] executionEnvironments, GenericSpecification[] genericRequires, GenericDescription[] genericCapabilities); + public BundleDescription createBundleDescription(long id, String symbolicName, Version version, String location, + BundleSpecification[] required, HostSpecification host, ImportPackageSpecification[] imports, + ExportPackageDescription[] exports, boolean singleton, boolean attachFragments, boolean dynamicFragments, + String platformFilter, String[] executionEnvironments, GenericSpecification[] genericRequires, + GenericDescription[] genericCapabilities); /** * Creates a bundle description from the given parameters. * - * @param id id for the bundle - * @param symbolicName symbolic name for the bundle (may be null) - * @param version version for the bundle (may be null) - * @param location location for the bundle (may be null) - * @param required version constraints for all required bundles (may be null) - * @param host version constraint specifying the host for the bundle to be created. Should be null if the bundle is not a fragment - * @param imports version constraints for all packages imported (may be null) - * @param exports package descriptions of all the exported packages (may be null) - * @param singleton whether the bundle created should be a singleton - * @param attachFragments whether the bundle allows fragments to attach - * @param dynamicFragments whether the bundle allows fragments to dynamically attach - * @param platformFilter the platform filter (may be null) - * @param executionEnvironments the execution environment (may be null) - * @param genericRequires the version constraints for all required capabilities (may be null) - * @param genericCapabilities the specifications of all the capabilities of the bundle (may be null) - * @param nativeCode the native code specification of the bundle (may be null) + * @param id id for the bundle + * @param symbolicName symbolic name for the bundle (may be + * null) + * @param version version for the bundle (may be + * null) + * @param location location for the bundle (may be + * null) + * @param required version constraints for all required bundles + * (may be null) + * @param host version constraint specifying the host for the + * bundle to be created. Should be + * null if the bundle is not a + * fragment + * @param imports version constraints for all packages imported + * (may be null) + * @param exports package descriptions of all the exported + * packages (may be null) + * @param singleton whether the bundle created should be a singleton + * @param attachFragments whether the bundle allows fragments to attach + * @param dynamicFragments whether the bundle allows fragments to + * dynamically attach + * @param platformFilter the platform filter (may be null) + * @param executionEnvironments the execution environment (may be + * null) + * @param genericRequires the version constraints for all required + * capabilities (may be null) + * @param genericCapabilities the specifications of all the capabilities of + * the bundle (may be null) + * @param nativeCode the native code specification of the bundle (may + * be null) * @return the created bundle description * @since 3.4 */ - public BundleDescription createBundleDescription(long id, String symbolicName, Version version, String location, BundleSpecification[] required, HostSpecification host, ImportPackageSpecification[] imports, ExportPackageDescription[] exports, boolean singleton, boolean attachFragments, boolean dynamicFragments, String platformFilter, String[] executionEnvironments, GenericSpecification[] genericRequires, GenericDescription[] genericCapabilities, NativeCodeSpecification nativeCode); + public BundleDescription createBundleDescription(long id, String symbolicName, Version version, String location, + BundleSpecification[] required, HostSpecification host, ImportPackageSpecification[] imports, + ExportPackageDescription[] exports, boolean singleton, boolean attachFragments, boolean dynamicFragments, + String platformFilter, String[] executionEnvironments, GenericSpecification[] genericRequires, + GenericDescription[] genericCapabilities, NativeCodeSpecification nativeCode); /** * Creates a bundle description from the given parameters. * - * @param id id for the bundle - * @param symbolicName the symbolic name of the bundle. This may include directives and/or attributes encoded using the Bundle-SymbolicName header. - * @param version version for the bundle (may be null) - * @param location location for the bundle (may be null) - * @param required version constraints for all required bundles (may be null) - * @param host version constraint specifying the host for the bundle to be created. Should be null if the bundle is not a fragment - * @param imports version constraints for all packages imported (may be null) - * @param exports package descriptions of all the exported packages (may be null) - * @param platformFilter the platform filter (may be null) - * @param executionEnvironments the execution environment (may be null) - * @param genericRequires the version constraints for all required capabilities (may be null) - * @param genericCapabilities the specifications of all the capabilities of the bundle (may be null) - * @param nativeCode the native code specification of the bundle (may be null) + * @param id id for the bundle + * @param symbolicName the symbolic name of the bundle. This may + * include directives and/or attributes encoded + * using the Bundle-SymbolicName header. + * @param version version for the bundle (may be + * null) + * @param location location for the bundle (may be + * null) + * @param required version constraints for all required bundles + * (may be null) + * @param host version constraint specifying the host for the + * bundle to be created. Should be + * null if the bundle is not a + * fragment + * @param imports version constraints for all packages imported + * (may be null) + * @param exports package descriptions of all the exported + * packages (may be null) + * @param platformFilter the platform filter (may be null) + * @param executionEnvironments the execution environment (may be + * null) + * @param genericRequires the version constraints for all required + * capabilities (may be null) + * @param genericCapabilities the specifications of all the capabilities of + * the bundle (may be null) + * @param nativeCode the native code specification of the bundle (may + * be null) * @return the created bundle description * @since 3.8 */ - public BundleDescription createBundleDescription(long id, String symbolicName, Version version, String location, BundleSpecification[] required, HostSpecification host, ImportPackageSpecification[] imports, ExportPackageDescription[] exports, String platformFilter, String[] executionEnvironments, GenericSpecification[] genericRequires, GenericDescription[] genericCapabilities, NativeCodeSpecification nativeCode); + public BundleDescription createBundleDescription(long id, String symbolicName, Version version, String location, + BundleSpecification[] required, HostSpecification host, ImportPackageSpecification[] imports, + ExportPackageDescription[] exports, String platformFilter, String[] executionEnvironments, + GenericSpecification[] genericRequires, GenericDescription[] genericCapabilities, + NativeCodeSpecification nativeCode); /** - * Returns a bundle description based on the information in the supplied manifest dictionary. - * The manifest should contain String keys and String values which correspond to - * proper OSGi manifest headers and values. + * Returns a bundle description based on the information in the supplied + * manifest dictionary. The manifest should contain String keys and String + * values which correspond to proper OSGi manifest headers and values. * - * @param state the state for which the description is being created + * @param state the state for which the description is being created * @param manifest a collection of OSGi manifest headers and values * @param location the URL location of the bundle (may be null) - * @param id the id of the bundle + * @param id the id of the bundle * @return a bundle description derived from the given information * @throws BundleException if an error occurs while reading the manifest */ - public BundleDescription createBundleDescription(State state, Dictionary manifest, String location, long id) throws BundleException; + public BundleDescription createBundleDescription(State state, Dictionary manifest, String location, + long id) throws BundleException; /** - * Returns a bundle description based on the information in the supplied manifest dictionary. - * The manifest should contain String keys and String values which correspond to - * proper OSGi manifest headers and values. + * Returns a bundle description based on the information in the supplied + * manifest dictionary. The manifest should contain String keys and String + * values which correspond to proper OSGi manifest headers and values. * * @param manifest a collection of OSGi manifest headers and values * @param location the URL location of the bundle (may be null) - * @param id the id of the bundle + * @param id the id of the bundle * @return a bundle description derived from the given information * @throws BundleException if an error occurs while reading the manifest - * @deprecated use {@link #createBundleDescription(State, Dictionary, String, long)} + * @deprecated use + * {@link #createBundleDescription(State, Dictionary, String, long)} */ - public BundleDescription createBundleDescription(Dictionary manifest, String location, long id) throws BundleException; + public BundleDescription createBundleDescription(Dictionary manifest, String location, long id) + throws BundleException; /** - * Creates a bundle description that is a copy of the given description. - * The user object of the original bundle description is not copied. + * Creates a bundle description that is a copy of the given description. The + * user object of the original bundle description is not copied. * * @param original the bundle description to be copied * @return the created bundle description @@ -233,13 +308,15 @@ public interface StateObjectFactory { * Creates a bundle specification from the given parameters. * * @param requiredSymbolicName the symbolic name for the required bundle - * @param requiredVersionRange the required version range (may be null) - * @param export whether the required bundle should be re-exported - * @param optional whether the constraint should be optional + * @param requiredVersionRange the required version range (may be + * null) + * @param export whether the required bundle should be re-exported + * @param optional whether the constraint should be optional * @return the created bundle specification * @see VersionConstraint for information on the available match rules */ - public BundleSpecification createBundleSpecification(String requiredSymbolicName, VersionRange requiredVersionRange, boolean export, boolean optional); + public BundleSpecification createBundleSpecification(String requiredSymbolicName, VersionRange requiredVersionRange, + boolean export, boolean optional); /** * Creates a bundle specification that is a copy of the given constraint. @@ -250,8 +327,9 @@ public interface StateObjectFactory { public BundleSpecification createBundleSpecification(BundleSpecification original); /** - * Creates bundle specifications from the given declaration. The declaration uses - * the bundle manifest syntax for the Require-Bundle header. + * Creates bundle specifications from the given declaration. The declaration + * uses the bundle manifest syntax for the Require-Bundle header. + * * @param declaration a string declaring bundle specifications * @return the bundle specifications * @since 3.8 @@ -262,15 +340,17 @@ public interface StateObjectFactory { * Creates a host specification from the given parameters. * * @param hostSymbolicName the symbolic name for the host bundle - * @param hostVersionRange the version range for the host bundle (may be null) + * @param hostVersionRange the version range for the host bundle (may be + * null) * @return the created host specification * @see VersionConstraint for information on the available match rules */ public HostSpecification createHostSpecification(String hostSymbolicName, VersionRange hostVersionRange); /** - * Creates host specifications from the given declaration. The declaration uses + * Creates host specifications from the given declaration. The declaration uses * the bundle manifest syntax for the Fragment-Host header. + * * @param declaration a string declaring host specifications * @return the host specifications * @since 3.8 @@ -288,27 +368,36 @@ public interface StateObjectFactory { /** * Creates an import package specification from the given parameters. * - * @param packageName the package name - * @param versionRange the package versionRange (may be null). - * @param bundleSymbolicName the Bundle-SymbolicName of the bundle that must export the package (may be null) + * @param packageName the package name + * @param versionRange the package versionRange (may be + * null). + * @param bundleSymbolicName the Bundle-SymbolicName of the bundle that must + * export the package (may be null) * @param bundleVersionRange the bundle versionRange (may be null). - * @param directives the directives for this package (may be null) - * @param attributes the arbitrary attributes for the package import (may be null) - * @param importer the importing bundle (may be null) + * @param directives the directives for this package (may be + * null) + * @param attributes the arbitrary attributes for the package import + * (may be null) + * @param importer the importing bundle (may be null) * @return the created package specification */ - public ImportPackageSpecification createImportPackageSpecification(String packageName, VersionRange versionRange, String bundleSymbolicName, VersionRange bundleVersionRange, Map directives, Map attributes, BundleDescription importer); + public ImportPackageSpecification createImportPackageSpecification(String packageName, VersionRange versionRange, + String bundleSymbolicName, VersionRange bundleVersionRange, Map directives, + Map attributes, BundleDescription importer); /** - * Creates an import package specification that is a copy of the given import package + * Creates an import package specification that is a copy of the given import + * package + * * @param original the import package to be copied * @return the created package specification */ public ImportPackageSpecification createImportPackageSpecification(ImportPackageSpecification original); /** - * Creates an import package specifications from the given declaration. The declaration uses - * the bundle manifest syntax for the Import-Package header. + * Creates an import package specifications from the given declaration. The + * declaration uses the bundle manifest syntax for the Import-Package header. + * * @param declaration a string declaring import package specifications * @return the import package specifications * @since 3.8 @@ -329,33 +418,47 @@ public interface StateObjectFactory { * @param exporter the exporter of the package (may be null) * @return the created package */ - public ExportPackageDescription createExportPackageDescription(String packageName, Version version, Map directives, Map attributes, boolean root, BundleDescription exporter); + public ExportPackageDescription createExportPackageDescription(String packageName, Version version, + Map directives, Map attributes, boolean root, BundleDescription exporter); /** * Creates a generic description from the given parameters - * @param name the name of the generic description - * @param type the type of the generic description (may be null) - * @param version the version of the generic description (may be null) - * @param attributes the attributes for the generic description (may be null) + * + * @param name the name of the generic description + * @param type the type of the generic description (may be + * null) + * @param version the version of the generic description (may be + * null) + * @param attributes the attributes for the generic description (may be + * null) * @return the created generic description - * @deprecated use {@link #createGenericDescription(String, String, Version, Map)} + * @deprecated use + * {@link #createGenericDescription(String, String, Version, Map)} */ - public GenericDescription createGenericDescription(String name, String type, Version version, Map attributes); + public GenericDescription createGenericDescription(String name, String type, Version version, + Map attributes); /** * Creates a generic description from the given parameters - * @param type the type of the generic description (may be null) - * @param attributes the attributes for the generic description (may be null) - * @param directives the directives for the generic description (may be null) - * @param supplier the supplier of the generic description (may be null) + * + * @param type the type of the generic description (may be + * null) + * @param attributes the attributes for the generic description (may be + * null) + * @param directives the directives for the generic description (may be + * null) + * @param supplier the supplier of the generic description (may be + * null) * @return the created generic description * @since 3.7 */ - public GenericDescription createGenericDescription(String type, Map attributes, Map directives, BundleDescription supplier); + public GenericDescription createGenericDescription(String type, Map attributes, + Map directives, BundleDescription supplier); /** - * Creates generic descriptions from the given declaration. The declaration uses + * Creates generic descriptions from the given declaration. The declaration uses * the bundle manifest syntax for the Provide-Capability header. + * * @param declaration a string declaring generic descriptions * @return the generic descriptions * @since 3.8 @@ -364,19 +467,23 @@ public interface StateObjectFactory { /** * Creates a generic specification from the given parameters - * @param name the name of the generic specification - * @param type the type of the generic specification (may be null) + * + * @param name the name of the generic specification + * @param type the type of the generic specification (may be + * null) * @param matchingFilter the matching filter (may be null) - * @param optional whether the specification is optional - * @param multiple whether the specification allows for multiple suppliers + * @param optional whether the specification is optional + * @param multiple whether the specification allows for multiple suppliers * @return the created generic specification * @throws InvalidSyntaxException if the matching filter is invalid */ - public GenericSpecification createGenericSpecification(String name, String type, String matchingFilter, boolean optional, boolean multiple) throws InvalidSyntaxException; + public GenericSpecification createGenericSpecification(String name, String type, String matchingFilter, + boolean optional, boolean multiple) throws InvalidSyntaxException; /** - * Creates generic specifications from the given declaration. The declaration uses - * the bundle manifest syntax for the Require-Capability header. + * Creates generic specifications from the given declaration. The declaration + * uses the bundle manifest syntax for the Require-Capability header. + * * @param declaration a string declaring generic specifications * @return the generic specifications * @since 3.8 @@ -385,37 +492,47 @@ public interface StateObjectFactory { /** * Creates a native code specification from the given parameters + * * @param nativeCodeDescriptions the native code descriptors - * @param optional whether the specification is optional + * @param optional whether the specification is optional * @return the created native code specification * @since 3.4 */ - public NativeCodeSpecification createNativeCodeSpecification(NativeCodeDescription[] nativeCodeDescriptions, boolean optional); + public NativeCodeSpecification createNativeCodeSpecification(NativeCodeDescription[] nativeCodeDescriptions, + boolean optional); /** * Creates a native code description from the given parameters + * * @param nativePaths the native code paths (may be null) - * @param processors the supported processors (may be null) - * @param osNames the supported operating system names (may be null) - * @param osVersions the supported operating system version ranges (may be null) - * @param languages the supported languages (may be null) - * @param filter the selection filter (may be null) + * @param processors the supported processors (may be null) + * @param osNames the supported operating system names (may be + * null) + * @param osVersions the supported operating system version ranges (may be + * null) + * @param languages the supported languages (may be null) + * @param filter the selection filter (may be null) * @return the created native code description * @throws InvalidSyntaxException if the selection filter is invalid * @since 3.4 */ - public NativeCodeDescription createNativeCodeDescription(String[] nativePaths, String[] processors, String[] osNames, VersionRange[] osVersions, String[] languages, String filter) throws InvalidSyntaxException; + public NativeCodeDescription createNativeCodeDescription(String[] nativePaths, String[] processors, + String[] osNames, VersionRange[] osVersions, String[] languages, String filter) + throws InvalidSyntaxException; /** - * Creates an export package specification that is a copy of the given constraint + * Creates an export package specification that is a copy of the given + * constraint + * * @param original the export package to be copied * @return the created package */ public ExportPackageDescription createExportPackageDescription(ExportPackageDescription original); /** - * Creates export package descriptions from the given declaration. The declaration uses - * the bundle manifest syntax for the Export-Package header. + * Creates export package descriptions from the given declaration. The + * declaration uses the bundle manifest syntax for the Export-Package header. + * * @param declaration a string declaring export package descriptions * @return the export package descriptions * @since 3.8 @@ -425,12 +542,12 @@ public interface StateObjectFactory { /** * Persists the given state in the given output stream. Closes the stream. * - * @param state the state to be written + * @param state the state to be written * @param stream the stream where to write the state to - * @throws IOException if an IOException happens while writing the state to - * the stream + * @throws IOException if an IOException happens while writing the + * state to the stream * @throws IllegalArgumentException if the state provided was not created by - * this factory + * this factory * @deprecated use {@link #writeState(State, File)} instead * @since 3.1 */ @@ -439,12 +556,12 @@ public interface StateObjectFactory { /** * Persists the given state in the given output stream. Closes the stream. * - * @param state the state to be written + * @param state the state to be written * @param stream the stream where to write the state to - * @throws IOException if an IOException happens while writing the state to - * the stream + * @throws IOException if an IOException happens while writing the + * state to the stream * @throws IllegalArgumentException if the state provided was not created by - * this factory + * this factory * @deprecated use {@link #writeState(State, File)} instead * @see #writeState(State, OutputStream) */ @@ -453,12 +570,12 @@ public interface StateObjectFactory { /** * Persists the given state in the given directory. * - * @param state the state to be written + * @param state the state to be written * @param stateDirectory the directory where to write the state to - * @throws IOException if an IOException happens while writing the state to - * the stream + * @throws IOException if an IOException happens while writing the + * state to the stream * @throws IllegalArgumentException if the state provided was not created by - * this factory + * this factory */ public void writeState(State state, File stateDirectory) throws IOException; @@ -468,7 +585,7 @@ public interface StateObjectFactory { * @param stream the stream where to read the state from * @return the state read * @throws IOException if an IOException happens while reading the state from - * the stream + * the stream * @deprecated use {@link #readState(File)} instead * @since 3.1 */ @@ -480,7 +597,7 @@ public interface StateObjectFactory { * @param stream the stream where to read the state from * @return the state read * @throws IOException if an IOException happens while reading the state from - * the stream + * the stream * @deprecated use {@link #readState(File)} instead * @see #readState(InputStream) */ @@ -492,7 +609,7 @@ public interface StateObjectFactory { * @param stateDirectory the directory where to read the state from * @return the state read * @throws IOException if an IOException happens while reading the state from - * the stream + * the stream */ public State readState(File stateDirectory) throws IOException; @@ -508,7 +625,8 @@ private StateObjectFactory getImplementation() { Class implClass = Class.forName(IMPL_NAME); implementation = (StateObjectFactory) implClass.getConstructor().newInstance(); } catch (Throwable t) { - throw new UnsupportedOperationException("Not able to create StateObjectFactory implementation: " + IMPL_NAME, t); //$NON-NLS-1$ + throw new UnsupportedOperationException( + "Not able to create StateObjectFactory implementation: " + IMPL_NAME, t); //$NON-NLS-1$ } } return implementation; @@ -533,39 +651,69 @@ public State createState(State state) { @Deprecated @Override - public BundleDescription createBundleDescription(long id, String symbolicName, Version version, String location, BundleSpecification[] required, HostSpecification host, ImportPackageSpecification[] imports, ExportPackageDescription[] exports, String[] providedPackages, boolean singleton) { - return getImplementation().createBundleDescription(id, symbolicName, version, location, required, host, imports, exports, providedPackages, singleton); + public BundleDescription createBundleDescription(long id, String symbolicName, Version version, String location, + BundleSpecification[] required, HostSpecification host, ImportPackageSpecification[] imports, + ExportPackageDescription[] exports, String[] providedPackages, boolean singleton) { + return getImplementation().createBundleDescription(id, symbolicName, version, location, required, host, + imports, exports, providedPackages, singleton); } @Deprecated @Override - public BundleDescription createBundleDescription(long id, String symbolicName, Version version, String location, BundleSpecification[] required, HostSpecification host, ImportPackageSpecification[] imports, ExportPackageDescription[] exports, String[] providedPackages, boolean singleton, boolean attachFragments, boolean dynamicFragments, String platformFilter, String executionEnvironment, GenericSpecification[] genericRequires, GenericDescription[] genericCapabilities) { - return getImplementation().createBundleDescription(id, symbolicName, version, location, required, host, imports, exports, providedPackages, singleton, attachFragments, dynamicFragments, platformFilter, executionEnvironment, genericRequires, genericCapabilities); + public BundleDescription createBundleDescription(long id, String symbolicName, Version version, String location, + BundleSpecification[] required, HostSpecification host, ImportPackageSpecification[] imports, + ExportPackageDescription[] exports, String[] providedPackages, boolean singleton, + boolean attachFragments, boolean dynamicFragments, String platformFilter, String executionEnvironment, + GenericSpecification[] genericRequires, GenericDescription[] genericCapabilities) { + return getImplementation().createBundleDescription(id, symbolicName, version, location, required, host, + imports, exports, providedPackages, singleton, attachFragments, dynamicFragments, platformFilter, + executionEnvironment, genericRequires, genericCapabilities); } @Override - public BundleDescription createBundleDescription(long id, String symbolicName, Version version, String location, BundleSpecification[] required, HostSpecification host, ImportPackageSpecification[] imports, ExportPackageDescription[] exports, boolean singleton, boolean attachFragments, boolean dynamicFragments, String platformFilter, String[] executionEnvironments, GenericSpecification[] genericRequires, GenericDescription[] genericCapabilities) { - return getImplementation().createBundleDescription(id, symbolicName, version, location, required, host, imports, exports, singleton, attachFragments, dynamicFragments, platformFilter, executionEnvironments, genericRequires, genericCapabilities); + public BundleDescription createBundleDescription(long id, String symbolicName, Version version, String location, + BundleSpecification[] required, HostSpecification host, ImportPackageSpecification[] imports, + ExportPackageDescription[] exports, boolean singleton, boolean attachFragments, + boolean dynamicFragments, String platformFilter, String[] executionEnvironments, + GenericSpecification[] genericRequires, GenericDescription[] genericCapabilities) { + return getImplementation().createBundleDescription(id, symbolicName, version, location, required, host, + imports, exports, singleton, attachFragments, dynamicFragments, platformFilter, + executionEnvironments, genericRequires, genericCapabilities); } @Override - public BundleDescription createBundleDescription(long id, String symbolicName, Version version, String location, BundleSpecification[] required, HostSpecification host, ImportPackageSpecification[] imports, ExportPackageDescription[] exports, boolean singleton, boolean attachFragments, boolean dynamicFragments, String platformFilter, String[] executionEnvironments, GenericSpecification[] genericRequires, GenericDescription[] genericCapabilities, NativeCodeSpecification nativeCode) { - return getImplementation().createBundleDescription(id, symbolicName, version, location, required, host, imports, exports, singleton, attachFragments, dynamicFragments, platformFilter, executionEnvironments, genericRequires, genericCapabilities, nativeCode); + public BundleDescription createBundleDescription(long id, String symbolicName, Version version, String location, + BundleSpecification[] required, HostSpecification host, ImportPackageSpecification[] imports, + ExportPackageDescription[] exports, boolean singleton, boolean attachFragments, + boolean dynamicFragments, String platformFilter, String[] executionEnvironments, + GenericSpecification[] genericRequires, GenericDescription[] genericCapabilities, + NativeCodeSpecification nativeCode) { + return getImplementation().createBundleDescription(id, symbolicName, version, location, required, host, + imports, exports, singleton, attachFragments, dynamicFragments, platformFilter, + executionEnvironments, genericRequires, genericCapabilities, nativeCode); } @Override - public BundleDescription createBundleDescription(long id, String symbolicName, Version version, String location, BundleSpecification[] required, HostSpecification host, ImportPackageSpecification[] imports, ExportPackageDescription[] exports, String platformFilter, String[] executionEnvironments, GenericSpecification[] genericRequires, GenericDescription[] genericCapabilities, NativeCodeSpecification nativeCode) { - return getImplementation().createBundleDescription(id, symbolicName, version, location, required, host, imports, exports, platformFilter, executionEnvironments, genericRequires, genericCapabilities, nativeCode); + public BundleDescription createBundleDescription(long id, String symbolicName, Version version, String location, + BundleSpecification[] required, HostSpecification host, ImportPackageSpecification[] imports, + ExportPackageDescription[] exports, String platformFilter, String[] executionEnvironments, + GenericSpecification[] genericRequires, GenericDescription[] genericCapabilities, + NativeCodeSpecification nativeCode) { + return getImplementation().createBundleDescription(id, symbolicName, version, location, required, host, + imports, exports, platformFilter, executionEnvironments, genericRequires, genericCapabilities, + nativeCode); } @Override - public BundleDescription createBundleDescription(State state, Dictionary manifest, String location, long id) throws BundleException { + public BundleDescription createBundleDescription(State state, Dictionary manifest, + String location, long id) throws BundleException { return getImplementation().createBundleDescription(state, manifest, location, id); } @Deprecated @Override - public BundleDescription createBundleDescription(Dictionary manifest, String location, long id) throws BundleException { + public BundleDescription createBundleDescription(Dictionary manifest, String location, long id) + throws BundleException { return getImplementation().createBundleDescription(manifest, location, id); } @@ -575,8 +723,10 @@ public BundleDescription createBundleDescription(BundleDescription original) { } @Override - public BundleSpecification createBundleSpecification(String requiredSymbolicName, VersionRange requiredVersionRange, boolean export, boolean optional) { - return getImplementation().createBundleSpecification(requiredSymbolicName, requiredVersionRange, export, optional); + public BundleSpecification createBundleSpecification(String requiredSymbolicName, + VersionRange requiredVersionRange, boolean export, boolean optional) { + return getImplementation().createBundleSpecification(requiredSymbolicName, requiredVersionRange, export, + optional); } @Override @@ -605,8 +755,11 @@ public HostSpecification createHostSpecification(HostSpecification original) { } @Override - public ImportPackageSpecification createImportPackageSpecification(String packageName, VersionRange versionRange, String bundleSymbolicName, VersionRange bundleVersionRange, Map directives, Map attributes, BundleDescription importer) { - return getImplementation().createImportPackageSpecification(packageName, versionRange, bundleSymbolicName, bundleVersionRange, directives, attributes, importer); + public ImportPackageSpecification createImportPackageSpecification(String packageName, + VersionRange versionRange, String bundleSymbolicName, VersionRange bundleVersionRange, + Map directives, Map attributes, BundleDescription importer) { + return getImplementation().createImportPackageSpecification(packageName, versionRange, bundleSymbolicName, + bundleVersionRange, directives, attributes, importer); } @Override @@ -620,18 +773,22 @@ public List createImportPackageSpecifications(String } @Override - public ExportPackageDescription createExportPackageDescription(String packageName, Version version, Map directives, Map attributes, boolean root, BundleDescription exporter) { - return getImplementation().createExportPackageDescription(packageName, version, directives, attributes, root, exporter); + public ExportPackageDescription createExportPackageDescription(String packageName, Version version, + Map directives, Map attributes, boolean root, BundleDescription exporter) { + return getImplementation().createExportPackageDescription(packageName, version, directives, attributes, + root, exporter); } @Deprecated @Override - public GenericDescription createGenericDescription(String name, String type, Version version, Map attributes) { + public GenericDescription createGenericDescription(String name, String type, Version version, + Map attributes) { return getImplementation().createGenericDescription(name, type, version, attributes); } @Override - public GenericDescription createGenericDescription(String type, Map attributes, Map directives, BundleDescription supplier) { + public GenericDescription createGenericDescription(String type, Map attributes, + Map directives, BundleDescription supplier) { return getImplementation().createGenericDescription(type, attributes, directives, supplier); } @@ -641,7 +798,8 @@ public List createGenericDescriptions(String declaration) { } @Override - public GenericSpecification createGenericSpecification(String name, String type, String matchingFilter, boolean optional, boolean multiple) throws InvalidSyntaxException { + public GenericSpecification createGenericSpecification(String name, String type, String matchingFilter, + boolean optional, boolean multiple) throws InvalidSyntaxException { return getImplementation().createGenericSpecification(name, type, matchingFilter, optional, multiple); } @@ -651,13 +809,17 @@ public List createGenericSpecifications(String declaration } @Override - public NativeCodeSpecification createNativeCodeSpecification(NativeCodeDescription[] nativeCodeDescriptions, boolean optional) { + public NativeCodeSpecification createNativeCodeSpecification(NativeCodeDescription[] nativeCodeDescriptions, + boolean optional) { return getImplementation().createNativeCodeSpecification(nativeCodeDescriptions, optional); } @Override - public NativeCodeDescription createNativeCodeDescription(String[] nativePaths, String[] processors, String[] osNames, VersionRange[] osVersions, String[] languages, String filter) throws InvalidSyntaxException { - return getImplementation().createNativeCodeDescription(nativePaths, processors, osNames, osVersions, languages, filter); + public NativeCodeDescription createNativeCodeDescription(String[] nativePaths, String[] processors, + String[] osNames, VersionRange[] osVersions, String[] languages, String filter) + throws InvalidSyntaxException { + return getImplementation().createNativeCodeDescription(nativePaths, processors, osNames, osVersions, + languages, filter); } @Override diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/StateWire.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/StateWire.java index 8a2057af061..db875d19d4e 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/StateWire.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/StateWire.java @@ -14,18 +14,23 @@ package org.eclipse.osgi.service.resolver; /** - * A state wire represents a decision made by a resolver to wire a requirement to a capability. - * There are 4 parts to a state wire. + * A state wire represents a decision made by a resolver to wire a requirement + * to a capability. There are 4 parts to a state wire. *
      - *
    • The requirement which may have been specified by a host bundle or one of its attached fragments.
    • - *
    • The host bundle which is associated with the requirement. There are cases where the host - * bundle may not be the same as the bundle which declared the requirement. For example, if a fragment - * specifies additional requirements.
    • - *
    • The capability which may have been specified by a host bundle or one of its attached fragments.
    • - *
    • The host bundle which is associated with the capability. There are cases where the host - * bundle may not be the same as the bundle which declared the capability. For example, if a fragment - * specifies additional capabilities.
    • + *
    • The requirement which may have been specified by a host bundle or one of + * its attached fragments.
    • + *
    • The host bundle which is associated with the requirement. There are cases + * where the host bundle may not be the same as the bundle which declared the + * requirement. For example, if a fragment specifies additional + * requirements.
    • + *
    • The capability which may have been specified by a host bundle or one of + * its attached fragments.
    • + *
    • The host bundle which is associated with the capability. There are cases + * where the host bundle may not be the same as the bundle which declared the + * capability. For example, if a fragment specifies additional + * capabilities.
    • *
    + * * @since 3.7 */ public class StateWire { @@ -36,12 +41,18 @@ public class StateWire { /** * Constructs a new state wire. - * @param requirementHost the bundle hosting the requirement. - * @param declaredRequirement the declared requirement. The bundle declaring the requirement may be different from the requirement host. - * @param capabilityHost the bundle hosting the capability. - * @param declaredCapability the declared capability. The bundle declaring the capability may be different from the capability host. + * + * @param requirementHost the bundle hosting the requirement. + * @param declaredRequirement the declared requirement. The bundle declaring the + * requirement may be different from the requirement + * host. + * @param capabilityHost the bundle hosting the capability. + * @param declaredCapability the declared capability. The bundle declaring the + * capability may be different from the capability + * host. */ - public StateWire(BundleDescription requirementHost, VersionConstraint declaredRequirement, BundleDescription capabilityHost, BaseDescription declaredCapability) { + public StateWire(BundleDescription requirementHost, VersionConstraint declaredRequirement, + BundleDescription capabilityHost, BaseDescription declaredCapability) { super(); this.requirementHost = requirementHost; this.declaredRequirement = declaredRequirement; @@ -52,6 +63,7 @@ public StateWire(BundleDescription requirementHost, VersionConstraint declaredRe /** * Gets the requirement host. + * * @return the requirement host. */ public BundleDescription getRequirementHost() { @@ -60,6 +72,7 @@ public BundleDescription getRequirementHost() { /** * Gets the declared requirement. + * * @return the declared requirement. */ public VersionConstraint getDeclaredRequirement() { @@ -68,6 +81,7 @@ public VersionConstraint getDeclaredRequirement() { /** * gets the capability host. + * * @return the capability host. */ public BundleDescription getCapabilityHost() { @@ -76,6 +90,7 @@ public BundleDescription getCapabilityHost() { /** * gets the declared capability. + * * @return the declared capability. */ public BaseDescription getDeclaredCapability() { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/VersionConstraint.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/VersionConstraint.java index 799a506ccf1..12059617467 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/VersionConstraint.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/VersionConstraint.java @@ -17,11 +17,13 @@ /** * VersionConstraints represent the relationship between two bundles (in the - * case of bundle requires) or a bundle and a package (in the case of import/export). + * case of bundle requires) or a bundle and a package (in the case of + * import/export). *

    - * This interface is not intended to be implemented by clients. The + * This interface is not intended to be implemented by clients. The * {@link StateObjectFactory} should be used to construct instances. *

    + * * @since 3.1 * @noimplement This interface is not intended to be implemented by clients. */ @@ -36,6 +38,7 @@ public interface VersionConstraint extends Cloneable { /** * Returns the version range for this constraint. + * * @return the version range for this constraint, or null */ public VersionRange getVersionRange(); @@ -48,11 +51,11 @@ public interface VersionConstraint extends Cloneable { public BundleDescription getBundle(); /** - * Returns whether this constraint is resolved. A resolved constraint - * is guaranteed to have its supplier defined. + * Returns whether this constraint is resolved. A resolved constraint is + * guaranteed to have its supplier defined. * * @return true if this bundle is resolved, false - * otherwise + * otherwise */ public boolean isResolved(); @@ -62,9 +65,9 @@ public interface VersionConstraint extends Cloneable { * versions and other arbitrary attributes * * @param supplier a supplier to be tested against this constraint (may be - * null) - * @return true if this constraint could be resolved using the supplier, - * false otherwise + * null) + * @return true if this constraint could be resolved using the + * supplier, false otherwise */ public boolean isSatisfiedBy(BaseDescription supplier); @@ -77,33 +80,31 @@ public interface VersionConstraint extends Cloneable { public BaseDescription getSupplier(); /** - * Returns the requirement represented by this constraint. - * Some constraint types may not be able to represent - * a requirement. In such cases null is - * returned. + * Returns the requirement represented by this constraint. Some constraint types + * may not be able to represent a requirement. In such cases null + * is returned. + * * @return the requirement represented by this constraint * @since 3.7 */ public BundleRequirement getRequirement(); /** - * Returns the user object associated to this constraint, or - * null if none exists. + * Returns the user object associated to this constraint, or null + * if none exists. * - * @return the user object associated to this constraint, - * or null + * @return the user object associated to this constraint, or null * @since 3.8 */ public Object getUserObject(); /** - * Associates a user-provided object to this constraint, or - * removes an existing association, if null is provided. The - * provided object is not interpreted in any ways by this - * constrain. + * Associates a user-provided object to this constraint, or removes an existing + * association, if null is provided. The provided object is not + * interpreted in any ways by this constrain. * * @param userObject an arbitrary object provided by the user, or - * null + * null * @since 3.8 */ public void setUserObject(Object userObject); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/VersionRange.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/VersionRange.java index d2dfe0b3c07..8b4bcd1ec21 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/VersionRange.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/resolver/VersionRange.java @@ -17,6 +17,7 @@ /** * This class represents a version range. + * * @since 3.1 * @noextend This class is not intended to be subclassed by clients. */ @@ -28,21 +29,23 @@ public class VersionRange extends org.osgi.framework.VersionRange { private static final char EXCLUDE_MAX = org.osgi.framework.VersionRange.RIGHT_OPEN; /** - * An empty version range: "0.0.0". The empty version range includes all valid versions - * (any version greater than or equal to the version 0.0.0). + * An empty version range: "0.0.0". The empty version range includes all valid + * versions (any version greater than or equal to the version 0.0.0). */ public static final VersionRange emptyRange = new VersionRange("0.0.0"); //$NON-NLS-1$ /** * Constructs a VersionRange with the specified minVersion and maxVersion. - * @param minVersion the minimum version of the range. If null - * then {@link Version#emptyVersion} is used. - * @param maxVersion the maximum version of the range. If null - * then new Version(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE) - * is used. + * + * @param minVersion the minimum version of the range. If null then + * {@link Version#emptyVersion} is used. + * @param maxVersion the maximum version of the range. If null then + * new Version(Integer.MAX_VALUE, Integer.MAX_VALUE, + * Integer.MAX_VALUE) is used. */ public VersionRange(Version minVersion, boolean includeMin, Version maxVersion, boolean includeMax) { - super(includeMin ? INCLUDE_MIN : EXCLUDE_MIN, minVersion == null ? Version.emptyVersion : minVersion, versionMax.equals(maxVersion) ? null : maxVersion, includeMax ? INCLUDE_MAX : EXCLUDE_MAX); + super(includeMin ? INCLUDE_MIN : EXCLUDE_MIN, minVersion == null ? Version.emptyVersion : minVersion, + versionMax.equals(maxVersion) ? null : maxVersion, includeMax ? INCLUDE_MAX : EXCLUDE_MAX); } /** @@ -51,6 +54,7 @@ public VersionRange(Version minVersion, boolean includeMin, Version maxVersion, *

    * Here is the grammar for version range strings. *

    + * *
     	 * version-range ::= interval | atleast
     	 * interval ::= ( include-min | exclude-min ) min-version ',' max-version ( include-max | exclude-max )
    @@ -63,8 +67,8 @@ public VersionRange(Version minVersion, boolean includeMin, Version maxVersion,
     	 * exclude-max ::= ')'
     	 * 
    * - * @param versionRange string representation of the version range or null - * for the empty range "0.0.0" + * @param versionRange string representation of the version range or + * null for the empty range "0.0.0" * @see Version#Version(String) definition of version */ public VersionRange(String versionRange) { @@ -73,6 +77,7 @@ public VersionRange(String versionRange) { /** * Returns the minimum Version of this VersionRange. + * * @return the minimum Version of this VersionRange */ public Version getMinimum() { @@ -81,8 +86,9 @@ public Version getMinimum() { /** * 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 + * otherwise false is returned */ public boolean getIncludeMinimum() { return getLeftType() == VersionRange.LEFT_CLOSED; @@ -91,10 +97,11 @@ public boolean getIncludeMinimum() { /** * Returns the maximum Version of this VersionRange. *

    - * This method is deprecated. For ranges that have no maximum this method + * This method is deprecated. For ranges that have no maximum this method * incorrectly returns a version equal to * Version(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE). * Use {@link org.osgi.framework.VersionRange#getRight()} instead. + * * @return the maximum Version of this VersionRange * @deprecated use {@link org.osgi.framework.VersionRange#getRight()} */ @@ -105,22 +112,23 @@ public Version getMaximum() { /** * 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 + * otherwise false is returned */ public boolean getIncludeMaximum() { return getRightType() == VersionRange.RIGHT_CLOSED; } /** - * 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. + * 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. - * If null then {@link Version#emptyVersion} is used. - * @return true if the version is included, - * false otherwise + * @param version a version to be tested for inclusion in this VersionRange. If + * null then {@link Version#emptyVersion} is used. + * @return true if the version is included, false + * otherwise */ public boolean isIncluded(Version version) { if (version == null) diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/security/TrustEngine.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/security/TrustEngine.java index b905b8f5183..2d49ae22883 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/security/TrustEngine.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/service/security/TrustEngine.java @@ -24,30 +24,38 @@ *

    * Clients may implement this interface. *

    + * * @since 3.4 */ public abstract class TrustEngine { /** * Returns the certificate trust anchor contained in the specified chain which - * was used to establish the authenticity of the chain. If no - * trust anchor is found in the chain then null is returned. - * @param chain - a complete or incomplete certificate chain, implementations *MAY* complete chains + * was used to establish the authenticity of the chain. If no trust anchor is + * found in the chain then null is returned. + * + * @param chain - a complete or incomplete certificate chain, implementations + * *MAY* complete chains * @return - the certificate trust anchor used to establish authenticity * @throws IOException if there is a problem connecting to the backing store */ public abstract Certificate findTrustAnchor(Certificate[] chain) throws IOException; /** - * Add a trust anchor point to this trust engine. A trust anchor implies that a certificate, - * and any of its children, is to be considered trusted. If null is used - * as the alias then an alias will be generated based on the trust anchor certificate. + * Add a trust anchor point to this trust engine. A trust anchor implies that a + * certificate, and any of its children, is to be considered trusted. If + * null is used as the alias then an alias will be generated based + * on the trust anchor certificate. + * * @param anchor - the certificate to add as an anchor point - * @param alias - a unique and human-readable 'friendly name' which can be used to reference the certificate. - * A null value may be used. + * @param alias - a unique and human-readable 'friendly name' which can be used + * to reference the certificate. A null value may be + * used. * @return the alias used to store the entry - * @throws IOException if there is a problem connecting to the backing store + * @throws IOException if there is a problem connecting to the + * backing store * @throws GeneralSecurityException if there is a certificate problem - * @throws IllegalArgumentException if the alias or anchor already exist in this trust engine + * @throws IllegalArgumentException if the alias or anchor already exist in this + * trust engine */ public String addTrustAnchor(Certificate anchor, String alias) throws IOException, GeneralSecurityException { String storedAlias = doAddTrustAnchor(anchor, alias); @@ -58,23 +66,31 @@ public String addTrustAnchor(Certificate anchor, String alias) throws IOExceptio } /** - * Add a trust anchor point to this trust engine. A trust anchor implies that a certificate, - * and any of its children, is to be considered trusted. If null is used - * as the alias then an alias will be generated based on the trust anchor certificate. + * Add a trust anchor point to this trust engine. A trust anchor implies that a + * certificate, and any of its children, is to be considered trusted. If + * null is used as the alias then an alias will be generated based + * on the trust anchor certificate. + * * @param anchor - the certificate to add as an anchor point - * @param alias - a unique and human-readable 'friendly name' which can be used to reference the certificate. - * A null value may be used. + * @param alias - a unique and human-readable 'friendly name' which can be used + * to reference the certificate. A null value may be + * used. * @return the alias used to store the entry - * @throws IOException if there is a problem connecting to the backing store + * @throws IOException if there is a problem connecting to the + * backing store * @throws GeneralSecurityException if there is a certificate problem - * @throws IllegalArgumentException if the alias or anchor already exist in this trust engine + * @throws IllegalArgumentException if the alias or anchor already exist in this + * trust engine */ - protected abstract String doAddTrustAnchor(Certificate anchor, String alias) throws IOException, GeneralSecurityException; + protected abstract String doAddTrustAnchor(Certificate anchor, String alias) + throws IOException, GeneralSecurityException; /** * Remove a trust anchor point from the engine, based on the certificate itself. + * * @param anchor - the certificate to be removed - * @throws IOException if there is a problem connecting to the backing store + * @throws IOException if there is a problem connecting to the + * backing store * @throws GeneralSecurityException if there is a certificate problem */ public final void removeTrustAnchor(Certificate anchor) throws IOException, GeneralSecurityException { @@ -86,16 +102,21 @@ public final void removeTrustAnchor(Certificate anchor) throws IOException, Gene /** * Remove a trust anchor point from the engine, based on the certificate itself. + * * @param anchor - the certificate to be removed - * @throws IOException if there is a problem connecting to the backing store + * @throws IOException if there is a problem connecting to the + * backing store * @throws GeneralSecurityException if there is a certificate problem */ protected abstract void doRemoveTrustAnchor(Certificate anchor) throws IOException, GeneralSecurityException; /** - * Remove a trust anchor point from the engine, based on the human readable "friendly name" + * Remove a trust anchor point from the engine, based on the human readable + * "friendly name" + * * @param alias - the name of the trust anchor - * @throws IOException if there is a problem connecting to the backing store + * @throws IOException if there is a problem connecting to the + * backing store * @throws GeneralSecurityException if there is a certificate problem */ public void removeTrustAnchor(String alias) throws IOException, GeneralSecurityException { @@ -109,26 +130,35 @@ public void removeTrustAnchor(String alias) throws IOException, GeneralSecurityE } /** - * Remove a trust anchor point from the engine, based on the human readable "friendly name" + * Remove a trust anchor point from the engine, based on the human readable + * "friendly name" + * * @param alias - the name of the trust anchor - * @throws IOException if there is a problem connecting to the backing store + * @throws IOException if there is a problem connecting to the + * backing store * @throws GeneralSecurityException if there is a certificate problem */ protected abstract void doRemoveTrustAnchor(String alias) throws IOException, GeneralSecurityException; /** - * Return the certificate associated with the unique "friendly name" in the engine. + * Return the certificate associated with the unique "friendly name" in the + * engine. + * * @param alias - the friendly name * @return the associated trust anchor - * @throws IOException if there is a problem connecting to the backing store + * @throws IOException if there is a problem connecting to the + * backing store * @throws GeneralSecurityException if there is a certificate problem */ public abstract Certificate getTrustAnchor(String alias) throws IOException, GeneralSecurityException; /** - * Return the list of friendly name aliases for the TrustAnchors installed in the engine. + * Return the list of friendly name aliases for the TrustAnchors installed in + * the engine. + * * @return string[] - the list of friendly name aliases - * @throws IOException if there is a problem connecting to the backing store + * @throws IOException if there is a problem connecting to the + * backing store * @throws GeneralSecurityException if there is a certificate problem */ public abstract String[] getAliases() throws IOException, GeneralSecurityException; @@ -136,14 +166,14 @@ public void removeTrustAnchor(String alias) throws IOException, GeneralSecurityE /** * Return a value indicate whether this trust engine is read-only. * - * @return true if this trust engine is read-only false otherwise. + * @return true if this trust engine is read-only false otherwise. */ public abstract boolean isReadOnly(); /** * Return a representation string of this trust engine * - * @return a string + * @return a string */ public abstract String getName(); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/signedcontent/InvalidContentException.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/signedcontent/InvalidContentException.java index 5f399462f2b..1440a582b42 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/signedcontent/InvalidContentException.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/signedcontent/InvalidContentException.java @@ -17,12 +17,14 @@ /** * Indicates that signed content is invalid according to one of the signers. + * * @since 3.4 * @noextend This class is not intended to be subclassed by clients. */ public class InvalidContentException extends IOException { private static final long serialVersionUID = -399150159330289387L; - // TODO may want to add error codes to indicate the reason for the invalid/corruption error. + // TODO may want to add error codes to indicate the reason for the + // invalid/corruption error. private final Throwable cause; /** @@ -30,7 +32,7 @@ public class InvalidContentException extends IOException { * message and cause. * * @param message the exception message - * @param cause the cause, may be null + * @param cause the cause, may be null */ public InvalidContentException(String message, Throwable cause) { super(message); @@ -38,10 +40,11 @@ public InvalidContentException(String message, Throwable cause) { } /** - * Returns the cause of this exception or null if no cause - * was specified when this exception was created. + * Returns the cause of this exception or null if no cause was + * specified when this exception was created. * - * @return The cause of this exception or null if no cause was created. + * @return The cause of this exception or null if no cause was + * created. */ @Override public Throwable getCause() { @@ -54,8 +57,9 @@ public Throwable getCause() { * @param t Cause of the exception. * @return This object. * @throws java.lang.IllegalStateException This method will always throw an - * IllegalStateException since the cause of this - * exception can only be set when constructed. + * IllegalStateException + * since the cause of this exception can + * only be set when constructed. */ @Override public Throwable initCause(Throwable t) { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/signedcontent/SignedContent.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/signedcontent/SignedContent.java index 6fdedc2c281..db626aa6216 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/signedcontent/SignedContent.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/signedcontent/SignedContent.java @@ -18,78 +18,96 @@ import java.util.Date; /** - * A SignedContent object represents content which may be signed. A + * A SignedContent object represents content which may be signed. A * {@link SignedContentFactory} is used to create signed content objects. *

    * A SignedContent object is intended to provide information about - * the signers of the content, and cannot be used to access the actual data of the content. + * the signers of the content, and cannot be used to access the actual data of + * the content. *

    *

    * This interface is not intended to be implemented by clients. *

    + * * @since 3.4 * @noimplement This interface is not intended to be implemented by clients. */ public interface SignedContent { /** - * Returns all entries of the content. The returned entries can be used - * to verify the entry content using {@link SignedContentEntry#verify()} and - * get signer info for each entry in this content using {@link SignedContentEntry#getSignerInfos()}. - * Note that this operation may be expensive because it requires an - * exhaustive search for entries over the entire content. + * Returns all entries of the content. The returned entries can be used to + * verify the entry content using {@link SignedContentEntry#verify()} and get + * signer info for each entry in this content using + * {@link SignedContentEntry#getSignerInfos()}. Note that this operation may be + * expensive because it requires an exhaustive search for entries over the + * entire content. *

    - * Unsigned entries are included in the result. Entries for which signer info exists - * but no content is found are also returned. For example, when an entry is removed from - * a signed jar but the jar is not resigned, the signer thinks the entry should exist - * but the content got removed. This would be considered an invalid entry which would fail verification. + * Unsigned entries are included in the result. Entries for which signer info + * exists but no content is found are also returned. For example, when an entry + * is removed from a signed jar but the jar is not resigned, the signer thinks + * the entry should exist but the content got removed. This would be considered + * an invalid entry which would fail verification. *

    + * * @return all entries of the content */ public SignedContentEntry[] getSignedEntries(); /** * Returns the signed entry for the specified name. + * * @param name the name of the entry * @return the entry or null if the entry could not be found */ public SignedContentEntry getSignedEntry(String name); /** - * Returns all the signer infos for this SignedContent. If the content - * is not signed then an empty array is returned. + * Returns all the signer infos for this SignedContent. If the + * content is not signed then an empty array is returned. + * * @return all the signer infos for this SignedContent */ public SignerInfo[] getSignerInfos(); /** - * Returns true if the content is signed; false otherwise. This is a convenience method - * equivalent to calling {@link #getSignerInfos()}.length > 0 + * Returns true if the content is signed; false otherwise. This is a convenience + * method equivalent to calling + * {@link #getSignerInfos()}.length > 0 + * * @return true if the content is signed */ public boolean isSigned(); /** - * Returns the signing time for the signer info. If no TSA signers exist then null is returned + * Returns the signing time for the signer info. If no TSA signers exist then + * null is returned + * * @param signerInfo the signer info to get the signing time for * @return the signing time */ public Date getSigningTime(SignerInfo signerInfo); /** - * Returns the TSA signer info used to authenticate the signer time of a signer info. + * Returns the TSA signer info used to authenticate the signer time of a signer + * info. + * * @param signerInfo the signer info to get the TSA signer for * @return the TSA signer info */ public SignerInfo getTSASignerInfo(SignerInfo signerInfo); /** - * Checks if the certificates are valid for the specified signer. If the signer has a singing time - * returned by {@link #getSigningTime(SignerInfo)} then that time is used to check the - * validity of the certificates; otherwise the current time is used. + * Checks if the certificates are valid for the specified signer. If the signer + * has a singing time returned by {@link #getSigningTime(SignerInfo)} then that + * time is used to check the validity of the certificates; otherwise the current + * time is used. + * * @param signerInfo the signer info to check validity for. - * @throws CertificateExpiredException if one of the certificates of this signer is expired - * @throws CertificateNotYetValidException if one of the certificates of this signer is not yet valid + * @throws CertificateExpiredException if one of the certificates of this + * signer is expired + * @throws CertificateNotYetValidException if one of the certificates of this + * signer is not yet valid */ - public void checkValidity(SignerInfo signerInfo) throws CertificateExpiredException, CertificateNotYetValidException; + public void checkValidity(SignerInfo signerInfo) + throws CertificateExpiredException, CertificateNotYetValidException; } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/signedcontent/SignedContentEntry.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/signedcontent/SignedContentEntry.java index 47603cf201f..b4f0d0a6ec7 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/signedcontent/SignedContentEntry.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/signedcontent/SignedContentEntry.java @@ -21,32 +21,38 @@ * A SignedContentEntry represents a content entry which may be * signed. *

    - * A SignedContentEntry object is intended to provide information about - * the signers of the content entry, and cannot be used to access the actual data of the entry. + * A SignedContentEntry object is intended to provide information + * about the signers of the content entry, and cannot be used to access the + * actual data of the entry. *

    *

    * This interface is not intended to be implemented by clients. *

    + * * @since 3.4 * @noimplement This interface is not intended to be implemented by clients. */ public interface SignedContentEntry { /** * Returns the name of the entry. + * * @return the name of the entry. */ public String getName(); /** - * Returns the signer infos for this SignedContentEntry. If the entry - * is not signed then an empty array is returned. + * Returns the signer infos for this SignedContentEntry. If the + * entry is not signed then an empty array is returned. + * * @return the signer infos for this SignedContentEntry */ public SignerInfo[] getSignerInfos(); /** - * Returns true if the entry is signed; false otherwise. This is a convenience method - * equivalent to calling {@link #getSignerInfos()}.length > 0 + * Returns true if the entry is signed; false otherwise. This is a convenience + * method equivalent to calling + * {@link #getSignerInfos()}.length > 0 + * * @return true if the content is signed */ public boolean isSigned(); @@ -55,7 +61,9 @@ public interface SignedContentEntry { // TODO: what does this mean in the face of multiple signers /** * Verifies the content of this this entry is valid. - * @throws IOException if an error occurred reading the entry content + * + * @throws IOException if an error occurred reading the entry + * content * @throws InvalidContentException if the entry content is not valid */ public void verify() throws IOException, InvalidContentException; diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/signedcontent/SignedContentFactory.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/signedcontent/SignedContentFactory.java index 64bc245c09a..5950f61a928 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/signedcontent/SignedContentFactory.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/signedcontent/SignedContentFactory.java @@ -22,42 +22,60 @@ /** * A factory used to create {@link SignedContent} objects. *

    - * The framework will register a factory implementation as an OSGi service. - * This service can be used to get SignedContent for a bundle. - * It can also be used to get SignedContent for a repository file. - * The supported formats for file repositories are jar files and directories containing the - * content of an extracted jar. + * The framework will register a factory implementation as an OSGi service. This + * service can be used to get SignedContent for a bundle. It can + * also be used to get SignedContent for a repository file. The + * supported formats for file repositories are jar files and directories + * containing the content of an extracted jar. *

    *

    * This interface is not intended to be implemented by clients. *

    + * * @since 3.4 * @noimplement This interface is not intended to be implemented by clients. */ public interface SignedContentFactory { /** - * Returns a SignedContent object for the specified content of a repository. + * Returns a SignedContent object for the specified content of a + * repository. + * * @param content the content of the repository * @return signed content for the specified repository - * @throws IOException if an IO exception occurs while reading the repository - * @throws NoSuchProviderException if there's no security provider for the signed content - * @throws NoSuchAlgorithmException if the cryptographic algorithm is not available for the signed content - * @throws CertificateException if there is a problem with one of the certificates of the signed content - * @throws SignatureException if there is a problem with one of the signatures of the signed content - * @throws InvalidKeyException if there is a problem with one of the certificate keys of the signed content + * @throws IOException if an IO exception occurs while reading the + * repository + * @throws NoSuchProviderException if there's no security provider for the + * signed content + * @throws NoSuchAlgorithmException if the cryptographic algorithm is not + * available for the signed content + * @throws CertificateException if there is a problem with one of the + * certificates of the signed content + * @throws SignatureException if there is a problem with one of the + * signatures of the signed content + * @throws InvalidKeyException if there is a problem with one of the + * certificate keys of the signed content */ - public SignedContent getSignedContent(File content) throws IOException, InvalidKeyException, SignatureException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException; + public SignedContent getSignedContent(File content) throws IOException, InvalidKeyException, SignatureException, + CertificateException, NoSuchAlgorithmException, NoSuchProviderException; /** * Returns a SignedContent object for the specified bundle. + * * @param bundle the bundle to get a signed content for. * @return signed content for the specified bundle. - * @throws IOException if an IO exception occurs while reading the bundle content - * @throws NoSuchProviderException if there's no security provider for the signed content - * @throws NoSuchAlgorithmException if the cryptographic algorithm is not available for the signed content - * @throws CertificateException if there is a problem with one of the certificates of the signed content - * @throws SignatureException if there is a problem with one of the signatures of the signed content - * @throws InvalidKeyException if there is a problem with one of the certificate keys of the signed content + * @throws IOException if an IO exception occurs while reading the + * bundle content + * @throws NoSuchProviderException if there's no security provider for the + * signed content + * @throws NoSuchAlgorithmException if the cryptographic algorithm is not + * available for the signed content + * @throws CertificateException if there is a problem with one of the + * certificates of the signed content + * @throws SignatureException if there is a problem with one of the + * signatures of the signed content + * @throws InvalidKeyException if there is a problem with one of the + * certificate keys of the signed content */ - public SignedContent getSignedContent(Bundle bundle) throws IOException, InvalidKeyException, SignatureException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException; + public SignedContent getSignedContent(Bundle bundle) throws IOException, InvalidKeyException, SignatureException, + CertificateException, NoSuchAlgorithmException, NoSuchProviderException; } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/signedcontent/SignerInfo.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/signedcontent/SignerInfo.java index 538415f75b8..7ea34967372 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/signedcontent/SignerInfo.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/signedcontent/SignerInfo.java @@ -20,6 +20,7 @@ *

    * This interface is not intended to be implemented by clients. *

    + * * @since 3.4 * @noimplement This interface is not intended to be implemented by clients. */ @@ -27,20 +28,24 @@ public interface SignerInfo { /** * Returns the certificate chain + * * @return the certificate chain */ public Certificate[] getCertificateChain(); /** - * Returns the certificate trust anchor used to establish authenticity. - * If authenticity cannot be established then null is returned. + * Returns the certificate trust anchor used to establish authenticity. If + * authenticity cannot be established then null is returned. + * * @return the trust anchor */ public Certificate getTrustAnchor(); /** - * Returns true if the trust anchor has been authenticated. This is a convenience - * method equivalent to calling {@link #getTrustAnchor()} != null + * Returns true if the trust anchor has been authenticated. This is a + * convenience method equivalent to calling + * {@link #getTrustAnchor()} != null + * * @return true if the the signer info is trusted */ public boolean isTrusted(); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/BundleInfo.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/BundleInfo.java index 5bdfdcfe020..63d1edb562a 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/BundleInfo.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/BundleInfo.java @@ -91,7 +91,8 @@ public final class Generation { this.cachedHeaders = new CachedManifest(this, Collections.emptyMap()); } - Generation(long generationId, File content, boolean isDirectory, Type contentType, boolean hasPackageInfo, Map cached, long lastModified, boolean isMRJar) { + Generation(long generationId, File content, boolean isDirectory, Type contentType, boolean hasPackageInfo, + Map cached, long lastModified, boolean isMRJar) { this.generationId = generationId; this.content = content; this.isDirectory = isDirectory; @@ -152,14 +153,17 @@ Map getRawHeaders() { rawHeaders = Collections.emptyMap(); } else { try { - Map merged = ManifestElement.parseBundleManifest(manifest.getInputStream(), new CaseInsensitiveDictionaryMap<>()); - // For MRJARs only replace Import-Package and Require-Capability if the versioned values are non-null + Map merged = ManifestElement.parseBundleManifest(manifest.getInputStream(), + new CaseInsensitiveDictionaryMap<>()); + // For MRJARs only replace Import-Package and Require-Capability if the + // versioned values are non-null if (Boolean.parseBoolean(merged.get(MULTI_RELEASE_HEADER))) { for (int i = getStorage().getRuntimeVersion().getMajor(); i > 8; i--) { String versionManifest = MULTI_RELEASE_VERSIONS + i + "/OSGI-INF/MANIFEST.MF"; //$NON-NLS-1$ BundleEntry versionEntry = getBundleFile().getEntry(versionManifest); if (versionEntry != null) { - Map versioned = ManifestElement.parseBundleManifest(versionEntry.getInputStream(), new CaseInsensitiveDictionaryMap<>()); + Map versioned = ManifestElement.parseBundleManifest( + versionEntry.getInputStream(), new CaseInsensitiveDictionaryMap<>()); String versionedImport = versioned.get(Constants.IMPORT_PACKAGE); String versionedRequireCap = versioned.get(Constants.REQUIRE_CAPABILITY); if (versionedImport != null) { @@ -202,7 +206,8 @@ public ResourceBundle getResourceBundle(String locale) { private ManifestLocalization getManifestLocalization() { synchronized (genMonitor) { if (headerLocalization == null) { - headerLocalization = new ManifestLocalization(this, getHeaders(), getStorage().getConfiguration().getConfiguration(EquinoxConfiguration.PROP_ROOT_LOCALE, "en")); //$NON-NLS-1$ + headerLocalization = new ManifestLocalization(this, getHeaders(), getStorage().getConfiguration() + .getConfiguration(EquinoxConfiguration.PROP_ROOT_LOCALE, "en")); //$NON-NLS-1$ } return headerLocalization; } @@ -273,7 +278,8 @@ void setContent(File content, Type contentType) { private void setLastModified(File content) { if (content == null) { - // Bug 477787: content will be null when the osgi.framework configuration property contains an invalid value. + // Bug 477787: content will be null when the osgi.framework configuration + // property contains an invalid value. lastModified = 0; return; } @@ -293,7 +299,8 @@ void setStorageHooks(List> storageHooks, boolean install) { } @SuppressWarnings("unchecked") - public > H getStorageHook(Class> factoryClass) { + public > H getStorageHook( + Class> factoryClass) { synchronized (this.genMonitor) { if (this.storageHooks == null) return null; @@ -338,28 +345,31 @@ public ProtectionDomain getDomain(boolean create) { } /** - * Gets called by BundleFile during {@link BundleFile#getFile(String, boolean)}. This method - * will allocate a File object where content of the specified path may be - * stored for this generation. The returned File object may - * not exist if the content has not previously been stored. + * Gets called by BundleFile during {@link BundleFile#getFile(String, boolean)}. + * This method will allocate a File object where content of the specified path + * may be stored for this generation. The returned File object may not exist if + * the content has not previously been stored. + * * @param path the path to the content to extract from the generation * @return a file object where content of the specified path may be stored. - * @throws StorageException if the path will escape the persistent storage of the generation + * @throws StorageException if the path will escape the persistent storage of + * the generation */ public File getExtractFile(String path) { return getExtractFile(null, path); } /** - * Gets called by BundleFile during {@link BundleFile#getFile(String, boolean)}. This method - * will allocate a File object where content of the specified path may be - * stored for this generation. The returned File object may - * not exist if the content has not previously been stored. + * Gets called by BundleFile during {@link BundleFile#getFile(String, boolean)}. + * This method will allocate a File object where content of the specified path + * may be stored for this generation. The returned File object may not exist if + * the content has not previously been stored. + * * @param path the path to the content to extract from the generation * @param base the base path that is prepended to the path, may be null * @return a file object where content of the specified path may be stored. * @throws StorageException if the path will escape the persistent storage of - * the generation starting at the specified base + * the generation starting at the specified base */ public File getExtractFile(String base, String path) { StringBuilder baseBuilder = new StringBuilder(); @@ -450,7 +460,8 @@ public String findLibrary(String libname) { } } - public ModuleRevisionBuilder adaptModuleRevisionBuilder(ModuleEvent operation, Module origin, ModuleRevisionBuilder builder) { + public ModuleRevisionBuilder adaptModuleRevisionBuilder(ModuleEvent operation, Module origin, + ModuleRevisionBuilder builder) { List> hooks = getStorageHooks(); if (hooks != null) { for (StorageHook hook : hooks) { @@ -496,10 +507,13 @@ Generation createGeneration() throws BundleException { lockedID = generationLocks.tryLock(nextGenerationId, 5, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); - throw new BundleException("Failed to obtain id locks for generation.", BundleException.STATECHANGE_ERROR, e); //$NON-NLS-1$ + throw new BundleException("Failed to obtain id locks for generation.", //$NON-NLS-1$ + BundleException.STATECHANGE_ERROR, e); } if (!lockedID) { - throw new BundleException("Failed to obtain id locks for generation.", BundleException.STATECHANGE_ERROR, new ThreadInfoReport(generationLocks.getLockInfo(nextGenerationId))); //$NON-NLS-1$ + throw new BundleException("Failed to obtain id locks for generation.", //$NON-NLS-1$ + BundleException.STATECHANGE_ERROR, + new ThreadInfoReport(generationLocks.getLockInfo(nextGenerationId))); } return new Generation(nextGenerationId++); } @@ -514,9 +528,11 @@ void unlockGeneration(Generation generation) { } } - Generation restoreGeneration(long generationId, File content, boolean isDirectory, Type contentType, boolean hasPackageInfo, Map cached, long lastModified, boolean isMRJar) { + Generation restoreGeneration(long generationId, File content, boolean isDirectory, Type contentType, + boolean hasPackageInfo, Map cached, long lastModified, boolean isMRJar) { synchronized (this.infoMonitor) { - return new Generation(generationId, content, isDirectory, contentType, hasPackageInfo, cached, lastModified, isMRJar); + return new Generation(generationId, content, isDirectory, contentType, hasPackageInfo, cached, lastModified, + isMRJar); } } @@ -528,7 +544,8 @@ public void delete() { try { getStorage().delete(getStorage().getFile(Long.toString(getBundleId()), false)); } catch (IOException e) { - storage.getLogServices().log(EquinoxContainer.NAME, FrameworkLogEntry.WARNING, "Error deleting bunlde info.", e); //$NON-NLS-1$ + storage.getLogServices().log(EquinoxContainer.NAME, FrameworkLogEntry.WARNING, + "Error deleting bunlde info.", e); //$NON-NLS-1$ } } @@ -536,7 +553,8 @@ void delete(Generation generation) { try { getStorage().delete(getStorage().getFile(getBundleId() + "/" + generation.getGenerationId(), false)); //$NON-NLS-1$ } catch (IOException e) { - storage.getLogServices().log(EquinoxContainer.NAME, FrameworkLogEntry.WARNING, "Error deleting generation.", e); //$NON-NLS-1$ + storage.getLogServices().log(EquinoxContainer.NAME, FrameworkLogEntry.WARNING, "Error deleting generation.", //$NON-NLS-1$ + e); } } @@ -548,7 +566,8 @@ public long getNextGenerationId() { public File getDataFile(String path) { File dataRoot = getStorage().getFile(getBundleId() + "/" + Storage.BUNDLE_DATA_DIR, false); //$NON-NLS-1$ - if (!Storage.secureAction.isDirectory(dataRoot) && (storage.isReadOnly() || !(Storage.secureAction.mkdirs(dataRoot) || Storage.secureAction.isDirectory(dataRoot)))) { + if (!Storage.secureAction.isDirectory(dataRoot) && (storage.isReadOnly() + || !(Storage.secureAction.mkdirs(dataRoot) || Storage.secureAction.isDirectory(dataRoot)))) { if (getStorage().getConfiguration().getDebug().DEBUG_STORAGE) Debug.println("Unable to create bundle data directory: " + dataRoot.getAbsolutePath()); //$NON-NLS-1$ return null; @@ -611,8 +630,10 @@ public String get(Object key) { if (cached.containsKey(key)) { return cached.get(key); } - if (!cached.isEmpty() && generation.getBundleInfo().getStorage().getConfiguration().getDebug().DEBUG_CACHED_MANIFEST) { - Debug.println("Header key is not cached: " + key + "; for bundle: " + generation.getBundleInfo().getBundleId()); //$NON-NLS-1$ //$NON-NLS-2$ + if (!cached.isEmpty() + && generation.getBundleInfo().getStorage().getConfiguration().getDebug().DEBUG_CACHED_MANIFEST) { + Debug.println("Header key is not cached: " + key + "; for bundle: " //$NON-NLS-1$ //$NON-NLS-2$ + + generation.getBundleInfo().getBundleId()); } return generation.getRawHeaders().get(key); } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/BundleLocalizationImpl.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/BundleLocalizationImpl.java index 099ba2d2dc8..21d9661c3cc 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/BundleLocalizationImpl.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/BundleLocalizationImpl.java @@ -22,19 +22,22 @@ import org.osgi.framework.Bundle; /** - * The implementation of the service that gets ResourceBundle objects from a given - * bundle with a given locale. + * The implementation of the service that gets ResourceBundle objects from a + * given bundle with a given locale. * - *

    Internal class.

    + *

    + * Internal class. + *

    */ public class BundleLocalizationImpl implements BundleLocalization { /** - * The getLocalization method gets a ResourceBundle object for the given - * locale and bundle. + * The getLocalization method gets a ResourceBundle object for the given locale + * and bundle. * * @return A ResourceBundle object for the given bundle and locale. - * If null is passed for the locale parameter, the default locale is used. + * If null is passed for the locale parameter, the default locale is + * used. */ @Override public ResourceBundle getLocalization(Bundle bundle, String locale) { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/ContentProvider.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/ContentProvider.java index 50f3f34b38c..fafc5ece04b 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/ContentProvider.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/ContentProvider.java @@ -17,12 +17,10 @@ import org.osgi.framework.BundleException; /** - * A content provider is a marker interface that is used - * but the framework internally to handle different kinds of - * bundles. For example, reference installed bundles or - * connect bundles. The type of the provider indicates - * how the framework will handle the install or update - * of the bundle content. + * A content provider is a marker interface that is used but the framework + * internally to handle different kinds of bundles. For example, reference + * installed bundles or connect bundles. The type of the provider indicates how + * the framework will handle the install or update of the bundle content. */ public interface ContentProvider { @@ -35,13 +33,15 @@ public enum Type { /** * A file of the content, may be {@code null} + * * @return the file, may be {@code null} - * @throws BundleException + * @throws BundleException */ File getContent() throws BundleException; /** * The type of content + * * @return the type of content */ Type getType(); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/FrameworkExtensionInstaller.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/FrameworkExtensionInstaller.java index 006a1179318..290904ef4f4 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/FrameworkExtensionInstaller.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/FrameworkExtensionInstaller.java @@ -53,7 +53,9 @@ public class FrameworkExtensionInstaller { private static final ClassLoader CL = FrameworkExtensionInstaller.class.getClassLoader(); private static final Method ADD_FWK_URL_METHOD = findAddURLMethod(CL, "addURL"); //$NON-NLS-1$ - private static final Method ADD_FWK_FILE_PATH_METHOD = ADD_FWK_URL_METHOD == null ? findAddFilePathMethod(CL, "appendToClassPathForInstrumentation") : null; //$NON-NLS-1$ + private static final Method ADD_FWK_FILE_PATH_METHOD = ADD_FWK_URL_METHOD == null + ? findAddFilePathMethod(CL, "appendToClassPathForInstrumentation") //$NON-NLS-1$ + : null; private final ArrayMap hookActivators = new ArrayMap<>(5); private static Method findAddURLMethod(ClassLoader cl, String name) { @@ -65,11 +67,13 @@ private static Method findAddURLMethod(ClassLoader cl, String name) { private static Method findAddFilePathMethod(ClassLoader cl, String name) { if (cl == null) return null; - return findMethod(cl.getClass(), name, new Class[] {String.class}, MultiplexingFactory.setAccessible); + return findMethod(cl.getClass(), name, new Class[] { String.class }, MultiplexingFactory.setAccessible); } - // recursively searches a class and it's superclasses for a (potentially inaccessable) method - private static Method findMethod(Class clazz, String name, Class[] args, Collection setAccessible) { + // recursively searches a class and it's superclasses for a (potentially + // inaccessable) method + private static Method findMethod(Class clazz, String name, Class[] args, + Collection setAccessible) { if (clazz == null) return null; // ends the recursion when getSuperClass returns null try { @@ -89,7 +93,7 @@ private static Method findMethod(Class clazz, String name, Class[] args, C private static void callAddURLMethod(URL arg) throws InvocationTargetException { try { - ADD_FWK_URL_METHOD.invoke(CL, new Object[] {arg}); + ADD_FWK_URL_METHOD.invoke(CL, new Object[] { arg }); } catch (Throwable t) { throw new InvocationTargetException(t); } @@ -97,7 +101,7 @@ private static void callAddURLMethod(URL arg) throws InvocationTargetException { private static void callAddFilePathMethod(File file) throws InvocationTargetException { try { - ADD_FWK_FILE_PATH_METHOD.invoke(CL, new Object[] {file.getCanonicalPath()}); + ADD_FWK_FILE_PATH_METHOD.invoke(CL, new Object[] { file.getCanonicalPath() }); } catch (Throwable t) { throw new InvocationTargetException(t); } @@ -109,7 +113,8 @@ public FrameworkExtensionInstaller(EquinoxConfiguration configuraiton) { this.configuration = configuraiton; } - public void addExtensionContent(final Collection revisions, final Module systemModule) throws BundleException { + public void addExtensionContent(final Collection revisions, final Module systemModule) + throws BundleException { if (System.getSecurityManager() == null) { addExtensionContent0(revisions, systemModule); } else { @@ -134,7 +139,9 @@ void addExtensionContent0(Collection revisions, Module systemMod for (ModuleRevision revision : revisions) { if (CL == null || (ADD_FWK_URL_METHOD == null && ADD_FWK_FILE_PATH_METHOD == null)) { // use the first revision as the blame - throw new BundleException("Cannot support framework extension bundles without a public addURL(URL) or appendToClassPathForInstrumentation(String) method on the framework class loader: " + revision.getBundle()); //$NON-NLS-1$ + throw new BundleException( + "Cannot support framework extension bundles without a public addURL(URL) or appendToClassPathForInstrumentation(String) method on the framework class loader: " //$NON-NLS-1$ + + revision.getBundle()); } File[] files = getExtensionFiles(revision); for (File file : files) { @@ -173,6 +180,7 @@ void addExtensionContent0(Collection revisions, Module systemMod /** * Returns a list of classpath files for an extension bundle + * * @param revision revision for the extension bundle * @return a list of classpath files for an extension bundle */ @@ -182,9 +190,11 @@ private File[] getExtensionFiles(ModuleRevision revision) { // Don't do anything for connect bundles return new File[0]; } - List metaDatas = revision.getModuleCapabilities(EquinoxModuleDataNamespace.MODULE_DATA_NAMESPACE); + List metaDatas = revision + .getModuleCapabilities(EquinoxModuleDataNamespace.MODULE_DATA_NAMESPACE); @SuppressWarnings("unchecked") - List paths = metaDatas.isEmpty() ? null : (List) metaDatas.get(0).getAttributes().get(EquinoxModuleDataNamespace.CAPABILITY_CLASSPATH); + List paths = metaDatas.isEmpty() ? null + : (List) metaDatas.get(0).getAttributes().get(EquinoxModuleDataNamespace.CAPABILITY_CLASSPATH); if (paths == null) { paths = new ArrayList<>(1); paths.add("."); //$NON-NLS-1$ @@ -218,10 +228,11 @@ public void startExtensionActivators(BundleContext context) { try { startActivator(activator, context, null); } catch (Exception e) { - configuration.getHookRegistry().getContainer().getEventPublisher().publishFrameworkEvent(FrameworkEvent.ERROR, null, e); + configuration.getHookRegistry().getContainer().getEventPublisher() + .publishFrameworkEvent(FrameworkEvent.ERROR, null, e); } } - // start the extension bundle activators. In Equinox we let + // start the extension bundle activators. In Equinox we let // framework extensions define Bundle-Activator headers. ModuleWiring systemWiring = (ModuleWiring) context.getBundle().adapt(BundleWiring.class); if (systemWiring != null) { @@ -246,8 +257,12 @@ public void stopExtensionActivators(BundleContext context) { activator.stop(context); } catch (Exception e) { Bundle b = current.get(activator); - BundleException eventException = new BundleException(NLS.bind(Msg.BUNDLE_ACTIVATOR_EXCEPTION, new Object[] {activator.getClass(), "stop", b == null ? "" : b.getSymbolicName()}), BundleException.ACTIVATOR_ERROR, e); //$NON-NLS-1$ //$NON-NLS-2$ - configuration.getHookRegistry().getContainer().getEventPublisher().publishFrameworkEvent(FrameworkEvent.ERROR, b, eventException); + BundleException eventException = new BundleException( + NLS.bind(Msg.BUNDLE_ACTIVATOR_EXCEPTION, + new Object[] { activator.getClass(), "stop", b == null ? "" : b.getSymbolicName() }), //$NON-NLS-1$ //$NON-NLS-2$ + BundleException.ACTIVATOR_ERROR, e); + configuration.getHookRegistry().getContainer().getEventPublisher() + .publishFrameworkEvent(FrameworkEvent.ERROR, b, eventException); } } } @@ -258,7 +273,8 @@ private void startExtensionActivator(ModuleRevision extensionRevision, BundleCon return; } - String activatorName = (String) metadata.get(0).getAttributes().get(EquinoxModuleDataNamespace.CAPABILITY_ACTIVATOR); + String activatorName = (String) metadata.get(0).getAttributes() + .get(EquinoxModuleDataNamespace.CAPABILITY_ACTIVATOR); if (activatorName == null) { return; } @@ -274,9 +290,13 @@ private void startExtensionActivator(ModuleRevision extensionRevision, BundleCon eventException = new BundleException(Msg.BundleContextImpl_LoadActivatorError + ' ' + extensionRevision, BundleException.ACTIVATOR_ERROR, e); } else { - eventException = new BundleException(NLS.bind(Msg.BUNDLE_ACTIVATOR_EXCEPTION, new Object[] {activator.getClass(), "start", extensionRevision.getSymbolicName()}), BundleException.ACTIVATOR_ERROR, e); //$NON-NLS-1$ + eventException = new BundleException( + NLS.bind(Msg.BUNDLE_ACTIVATOR_EXCEPTION, + new Object[] { activator.getClass(), "start", extensionRevision.getSymbolicName() }), //$NON-NLS-1$ + BundleException.ACTIVATOR_ERROR, e); } - configuration.getHookRegistry().getContainer().getEventPublisher().publishFrameworkEvent(FrameworkEvent.ERROR, extensionRevision.getBundle(), eventException); + configuration.getHookRegistry().getContainer().getEventPublisher() + .publishFrameworkEvent(FrameworkEvent.ERROR, extensionRevision.getBundle(), eventException); } } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/ManifestLocalization.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/ManifestLocalization.java index cc57377afe8..f1649ffe195 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/ManifestLocalization.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/ManifestLocalization.java @@ -76,13 +76,15 @@ Dictionary getHeaders(String localeString) { return rawHeaders; } ResourceBundle localeProperties = getResourceBundle(localeString, isDefaultLocale); - CaseInsensitiveDictionaryMap localeHeaders = new CaseInsensitiveDictionaryMap<>(this.rawHeaders); + CaseInsensitiveDictionaryMap localeHeaders = new CaseInsensitiveDictionaryMap<>( + this.rawHeaders); for (Entry entry : localeHeaders.entrySet()) { String value = entry.getValue(); if (value.startsWith("%") && (value.length() > 1)) { //$NON-NLS-1$ String propertiesKey = value.substring(1); try { - value = localeProperties == null ? propertiesKey : (String) localeProperties.getObject(propertiesKey); + value = localeProperties == null ? propertiesKey + : (String) localeProperties.getObject(propertiesKey); } catch (MissingResourceException ex) { value = propertiesKey; } @@ -144,8 +146,10 @@ ResourceBundle getResourceBundle(String localeString, boolean isDefaultLocale) { } private BundleResourceBundle lookupResourceBundle(String localeString) { - // get the localization header as late as possible to avoid accessing the raw headers - // getting the first value from the raw headers forces the manifest to be parsed (bug 332039) + // get the localization header as late as possible to avoid accessing the raw + // headers + // getting the first value from the raw headers forces the manifest to be parsed + // (bug 332039) String localizationHeader = rawHeaders.get(Constants.BUNDLE_LOCALIZATION); if (localizationHeader == null) localizationHeader = Constants.BUNDLE_LOCALIZATION_DEFAULT_BASENAME; @@ -155,14 +159,18 @@ private BundleResourceBundle lookupResourceBundle(String localeString) { return result.isEmpty() ? null : result; // Collect all the necessary inputstreams to create the resource bundle without - // holding any locks. Finding resources and inputstreams from the wirings requires a - // read lock on the module database. We must not hold the cache lock while doing this; - // otherwise out of order locks will be possible when the resolver needs to clear the cache + // holding any locks. Finding resources and inputstreams from the wirings + // requires a + // read lock on the module database. We must not hold the cache lock while doing + // this; + // otherwise out of order locks will be possible when the resolver needs to + // clear the cache String[] nlVarients = buildNLVariants(localeString); InputStream[] nlStreams = new InputStream[nlVarients.length]; for (int i = nlVarients.length - 1; i >= 0; i--) { - URL url = findResource(localizationHeader + (nlVarients[i].equals("") ? nlVarients[i] : '_' + nlVarients[i]) + ".properties"); //$NON-NLS-1$ //$NON-NLS-2$ + URL url = findResource(localizationHeader + (nlVarients[i].equals("") ? nlVarients[i] : '_' + nlVarients[i]) //$NON-NLS-1$ + + ".properties"); //$NON-NLS-1$ if (url != null) { try { nlStreams[i] = url.openStream(); @@ -189,7 +197,7 @@ private BundleResourceBundle lookupResourceBundle(String localeString) { try { varientStream.close(); } catch (IOException e3) { - //Ignore exception + // Ignore exception } } } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/NativeCodeFinder.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/NativeCodeFinder.java index 4607eb2c5ad..7d5e4a1956d 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/NativeCodeFinder.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/NativeCodeFinder.java @@ -40,7 +40,8 @@ public class NativeCodeFinder { public static final String EXTERNAL_LIB_PREFIX = "external:"; //$NON-NLS-1$ private final Generation generation; private final Debug debug; - // This is only used to keep track of when the same native library is loaded more than once + // This is only used to keep track of when the same native library is loaded + // more than once private final Collection loadedNativeCode = new ArrayList<>(1); public NativeCodeFinder(Generation generation) { @@ -50,8 +51,8 @@ public NativeCodeFinder(Generation generation) { /* * Maps an already mapped library name to additional library file extensions. - * This is needed on platforms like AIX where .a and .so can be used as library file - * extensions, but System.mapLibraryName only returns a single string. + * This is needed on platforms like AIX where .a and .so can be used as library + * file extensions, but System.mapLibraryName only returns a single string. */ public String[] mapLibraryNames(String mappedLibName) { int extIndex = mappedLibName.lastIndexOf('.'); @@ -69,8 +70,10 @@ String findLibrary(String libname) { String path = findLibrary0(libname); if (path != null) { synchronized (loadedNativeCode) { - if (loadedNativeCode.contains(path) || generation.getBundleInfo().getStorage().getConfiguration().COPY_NATIVES) { - // we must copy the library to a temp space to allow another class loader to load the library + if (loadedNativeCode.contains(path) + || generation.getBundleInfo().getStorage().getConfiguration().COPY_NATIVES) { + // we must copy the library to a temp space to allow another class loader to + // load the library String temp = generation.getBundleInfo().getStorage().copyToTempLibrary(generation, path); if (temp != null) path = temp; @@ -84,7 +87,8 @@ String findLibrary(String libname) { private String findLibrary0(String libname) { String path = null; - List hooks = generation.getBundleInfo().getStorage().getConfiguration().getHookRegistry().getClassLoaderHooks(); + List hooks = generation.getBundleInfo().getStorage().getConfiguration().getHookRegistry() + .getClassLoaderHooks(); for (ClassLoaderHook hook : hooks) { path = hook.findLocalLibrary(generation, libname); if (path != null) { @@ -114,7 +118,8 @@ private String findEclipseNativeCode(String libname, String mappedName, String[] } private String searchEclipseVariants(String path) { - List ECLIPSE_LIB_VARIANTS = generation.getBundleInfo().getStorage().getConfiguration().ECLIPSE_LIB_VARIANTS; + List ECLIPSE_LIB_VARIANTS = generation.getBundleInfo().getStorage() + .getConfiguration().ECLIPSE_LIB_VARIANTS; for (String variant : ECLIPSE_LIB_VARIANTS) { BundleFile baseBundleFile = generation.getBundleFile(); BundleEntry libEntry = baseBundleFile.getEntry(variant + path); @@ -123,10 +128,11 @@ private String searchEclipseVariants(String path) { if (libFile == null) return null; // see bug 88697 - HP requires libraries to have executable permissions - if (org.eclipse.osgi.service.environment.Constants.OS_HPUX.equals(generation.getBundleInfo().getStorage().getConfiguration().getOS())) { + if (org.eclipse.osgi.service.environment.Constants.OS_HPUX + .equals(generation.getBundleInfo().getStorage().getConfiguration().getOS())) { try { // use the string array method in case there is a space in the path - Runtime.getRuntime().exec(new String[] {"chmod", "755", libFile.getAbsolutePath()}).waitFor(); //$NON-NLS-1$ //$NON-NLS-2$ + Runtime.getRuntime().exec(new String[] { "chmod", "755", libFile.getAbsolutePath() }).waitFor(); //$NON-NLS-1$ //$NON-NLS-2$ } catch (Exception e) { e.printStackTrace(); } @@ -164,13 +170,13 @@ private List getNativePaths() { ModuleRevision revision = generation.getRevision(); ModuleWiring wiring = revision.getWiring(); if (wiring == null) { - // unresolved? should not be possible + // unresolved? should not be possible return Collections.emptyList(); } if ((revision.getTypes() & BundleRevision.TYPE_FRAGMENT) != 0) { List hosts = wiring.getRequiredModuleWires(HostNamespace.HOST_NAMESPACE); if (hosts == null) { - // unresolved or invalid? should not be possible + // unresolved or invalid? should not be possible return Collections.emptyList(); } if (!hosts.isEmpty()) { @@ -184,7 +190,8 @@ private List getNativePaths() { return Collections.emptyList(); } - // just taking the first paths for the revision, we sorted correctly when transforming to the requirement + // just taking the first paths for the revision, we sorted correctly when + // transforming to the requirement for (ModuleWire moduleWire : nativeCode) { if (moduleWire.getRequirement().getRevision().equals(revision)) { @SuppressWarnings("unchecked") @@ -192,9 +199,11 @@ private List getNativePaths() { .get(REQUIREMENT_NATIVE_PATHS_ATTRIBUTE); if (result != null) return result; - // this must be a multi-clause Bundle-NativeCode header, need to check for the correct one in the index + // this must be a multi-clause Bundle-NativeCode header, need to check for the + // correct one in the index try { - FilterImpl filter = FilterImpl.newInstance(moduleWire.getRequirement().getDirectives().get(NativeNamespace.REQUIREMENT_FILTER_DIRECTIVE)); + FilterImpl filter = FilterImpl.newInstance(moduleWire.getRequirement().getDirectives() + .get(NativeNamespace.REQUIREMENT_FILTER_DIRECTIVE)); int index = -1; Map capabilityAttrs = moduleWire.getCapability().getAttributes(); for (FilterImpl child : filter.getChildren()) { @@ -228,7 +237,8 @@ private String findNativePath(List nativePaths, String libname) { if (path.equals(libname)) { if (nativePath.startsWith(NativeCodeFinder.EXTERNAL_LIB_PREFIX)) { // references an external library; do variable substitution - String externalPath = generation.getBundleInfo().getStorage().getConfiguration().substituteVars(nativePath.substring(NativeCodeFinder.EXTERNAL_LIB_PREFIX.length())); + String externalPath = generation.getBundleInfo().getStorage().getConfiguration() + .substituteVars(nativePath.substring(NativeCodeFinder.EXTERNAL_LIB_PREFIX.length())); File nativeFile = new File(externalPath); return nativeFile.getAbsolutePath(); } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/PermissionData.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/PermissionData.java index 4b3087475fe..c15aae8a73b 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/PermissionData.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/PermissionData.java @@ -18,11 +18,12 @@ import java.util.*; /** - * Permission Storage interface for managing a persistent storage of - * bundle permissions. + * Permission Storage interface for managing a persistent storage of bundle + * permissions. * - *

    This class is used to provide methods to manage - * persistent storage of bundle permissions. + *

    + * This class is used to provide methods to manage persistent storage of bundle + * permissions. */ public class PermissionData { private static final int PERMDATA_VERSION = 1; @@ -32,13 +33,11 @@ public class PermissionData { private boolean dirty; /** - * Returns the locations that have permission data assigned to them, - * that is, locations for which permission data - * exists in persistent storage. + * Returns the locations that have permission data assigned to them, that is, + * locations for which permission data exists in persistent storage. * - * @return The locations that have permission data in - * persistent storage, or null if there is no permission data - * in persistent storage. + * @return The locations that have permission data in persistent storage, or + * null if there is no permission data in persistent storage. */ public String[] getLocations() { synchronized (locations) { @@ -51,16 +50,15 @@ public String[] getLocations() { } /** - * Gets the permission data assigned to the specified - * location. + * Gets the permission data assigned to the specified location. * - * @param location The location whose permission data is to - * be returned. - * The location can be null for the default permission data. + * @param location The location whose permission data is to be returned. The + * location can be null for the default permission + * data. * - * @return The permission data assigned to the specified - * location, or null if that location has not been assigned any - * permission data. + * @return The permission data assigned to the specified location, or + * null if that location has not been assigned any permission + * data. */ public String[] getPermissionData(String location) { if (location == null) @@ -73,14 +71,13 @@ public String[] getPermissionData(String location) { } /** - * Assigns the specified permission data to the specified - * location. + * Assigns the specified permission data to the specified location. * - * @param location The location that will be assigned the - * permissions. - * The location can be null for the default permission data. - * @param data The permission data to be assigned, or null - * if the specified location is to be removed from persistent storaqe. + * @param location The location that will be assigned the permissions. The + * location can be null for the default permission + * data. + * @param data The permission data to be assigned, or null if the + * specified location is to be removed from persistent storaqe. */ public void setPermissionData(String location, String[] data) { if (location == null) { @@ -98,6 +95,7 @@ public void setPermissionData(String location, String[] data) { /** * Persists the array of encoded ConditionalPermissionInfo strings + * * @param infos an array of encoded ConditionalPermissionInfo strings */ public void saveConditionalPermissionInfos(String[] infos) { @@ -107,8 +105,9 @@ public void saveConditionalPermissionInfos(String[] infos) { /** * Returns the persistent array of encoded ConditionalPermissionInfo strings - * @return an array of encoded ConditionalPermissionInfo strings or null - * if none exist in persistent storage. + * + * @return an array of encoded ConditionalPermissionInfo strings or null if none + * exist in persistent storage. */ public String[] getConditionalPermissionInfos() { return condPermInfos; diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/Storage.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/Storage.java index 5d980c34a43..24e97b8b306 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/Storage.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/Storage.java @@ -155,7 +155,7 @@ public StorageException(Throwable cause) { private static final String JAVASE = "JavaSE"; //$NON-NLS-1$ private static final String PROFILE_EXT = ".profile"; //$NON-NLS-1$ - private static final String NUL = new String(new byte[] {0}); + private static final String NUL = new String(new byte[] { 0 }); private static final String INITIAL_LOCATION = "initial@"; //$NON-NLS-1$ static final SecureAction secureAction = AccessController.doPrivileged(SecureAction.createSecureAction()); @@ -174,7 +174,8 @@ public StorageException(Throwable cause) { private long lastSavedTimestamp = -1; private final MRUBundleFileList mruList; private final FrameworkExtensionInstaller extensionInstaller; - private final List cachedHeaderKeys = Arrays.asList(Constants.BUNDLE_SYMBOLICNAME, Constants.BUNDLE_ACTIVATIONPOLICY, "Service-Component"); //$NON-NLS-1$ + private final List cachedHeaderKeys = Arrays.asList(Constants.BUNDLE_SYMBOLICNAME, + Constants.BUNDLE_ACTIVATIONPOLICY, "Service-Component"); //$NON-NLS-1$ private final boolean allowRestrictedProvides; private final AtomicBoolean refreshMRBundles = new AtomicBoolean(false); private final Version runtimeVersion; @@ -183,7 +184,8 @@ public StorageException(Throwable cause) { public static Storage createStorage(EquinoxContainer container) throws IOException, BundleException { String[] cachedInfo = new String[3]; Storage storage = new Storage(container, cachedInfo); - // Do some operations that need to happen on the fully constructed Storage before returning it + // Do some operations that need to happen on the fully constructed Storage + // before returning it storage.checkSystemBundle(cachedInfo); storage.refreshStaleBundles(); storage.installExtensions(); @@ -219,10 +221,12 @@ private Storage(EquinoxContainer container, String[] cachedInfo) throws IOExcept } runtimeVersion = javaVersion; javaSpecVersion = javaSpecVersionProp; - mruList = new MRUBundleFileList(getBundleFileLimit(container.getConfiguration()), container.getConfiguration().getDebug()); + mruList = new MRUBundleFileList(getBundleFileLimit(container.getConfiguration()), + container.getConfiguration().getDebug()); equinoxContainer = container; extensionInstaller = new FrameworkExtensionInstaller(container.getConfiguration()); - allowRestrictedProvides = Boolean.parseBoolean(container.getConfiguration().getConfiguration(EquinoxConfiguration.PROP_ALLOW_RESTRICTED_PROVIDES)); + allowRestrictedProvides = Boolean.parseBoolean( + container.getConfiguration().getConfiguration(EquinoxConfiguration.PROP_ALLOW_RESTRICTED_PROVIDES)); // we need to set the install path as soon as possible so we can determine // the absolute location of install relative URLs @@ -235,12 +239,15 @@ private Storage(EquinoxContainer container, String[] cachedInfo) throws IOExcept Location parentConfigLocation = configLocation.getParentLocation(); Location osgiParentLocation = null; if (parentConfigLocation != null) { - osgiParentLocation = parentConfigLocation.createLocation(null, parentConfigLocation.getDataArea(EquinoxContainer.NAME), true); + osgiParentLocation = parentConfigLocation.createLocation(null, + parentConfigLocation.getDataArea(EquinoxContainer.NAME), true); } - this.osgiLocation = configLocation.createLocation(osgiParentLocation, configLocation.getDataArea(EquinoxContainer.NAME), configLocation.isReadOnly()); + this.osgiLocation = configLocation.createLocation(osgiParentLocation, + configLocation.getDataArea(EquinoxContainer.NAME), configLocation.isReadOnly()); this.childRoot = new File(osgiLocation.getURL().getPath()); - if (Boolean.valueOf(container.getConfiguration().getConfiguration(EquinoxConfiguration.PROP_CLEAN)).booleanValue()) { + if (Boolean.valueOf(container.getConfiguration().getConfiguration(EquinoxConfiguration.PROP_CLEAN)) + .booleanValue()) { cleanOSGiStorage(osgiLocation, childRoot); } if (!this.osgiLocation.isReadOnly()) { @@ -251,8 +258,10 @@ private Storage(EquinoxContainer container, String[] cachedInfo) throws IOExcept if (container.getConfiguration().getConfiguration(Constants.FRAMEWORK_STORAGE) == null) { // Set the derived value if not already set as part of configuration. - // Note this is the parent directory of where the framework stores data (org.eclipse.osgi/) - container.getConfiguration().setConfiguration(Constants.FRAMEWORK_STORAGE, childRoot.getParentFile().getAbsolutePath()); + // Note this is the parent directory of where the framework stores data + // (org.eclipse.osgi/) + container.getConfiguration().setConfiguration(Constants.FRAMEWORK_STORAGE, + childRoot.getParentFile().getAbsolutePath()); } InputStream info = getInfoInputStream(); @@ -262,7 +271,10 @@ private Storage(EquinoxContainer container, String[] cachedInfo) throws IOExcept try { generations = loadGenerations(data, cachedInfo); } catch (IllegalArgumentException e) { - equinoxContainer.getLogServices().log(EquinoxContainer.NAME, FrameworkLogEntry.WARNING, "The persistent format for the framework data has changed. The framework will be reinitialized: " + e.getMessage(), null); //$NON-NLS-1$ + equinoxContainer.getLogServices().log(EquinoxContainer.NAME, FrameworkLogEntry.WARNING, + "The persistent format for the framework data has changed. The framework will be reinitialized: " //$NON-NLS-1$ + + e.getMessage(), + null); generations = new HashMap<>(0); data = null; cleanOSGiStorage(osgiLocation, childRoot); @@ -277,7 +289,8 @@ private Storage(EquinoxContainer container, String[] cachedInfo) throws IOExcept moduleDatabase.load(data); lastSavedTimestamp = moduleDatabase.getTimestamp(); } catch (IllegalArgumentException e) { - equinoxContainer.getLogServices().log(EquinoxContainer.NAME, FrameworkLogEntry.WARNING, "Incompatible version. Starting with empty framework.", e); //$NON-NLS-1$ + equinoxContainer.getLogServices().log(EquinoxContainer.NAME, FrameworkLogEntry.WARNING, + "Incompatible version. Starting with empty framework.", e); //$NON-NLS-1$ // Clean up the cache. // No need to clean up the database. Nothing got loaded. cleanOSGiStorage(osgiLocation, childRoot); @@ -374,7 +387,8 @@ private boolean needsDiscarding(Generation generation) { try { hook.validate(); } catch (IllegalStateException e) { - equinoxContainer.getLogServices().log(EquinoxContainer.NAME, FrameworkLogEntry.WARNING, "Error validating installed bundle.", e); //$NON-NLS-1$ + equinoxContainer.getLogServices().log(EquinoxContainer.NAME, FrameworkLogEntry.WARNING, + "Error validating installed bundle.", e); //$NON-NLS-1$ return true; } } @@ -417,7 +431,8 @@ private void checkSystemBundle(String[] cachedInfo) { moduleContainer.resolve(Collections.singletonList(systemModule), false); } else { ModuleRevision currentRevision = systemModule.getCurrentRevision(); - Generation currentGeneration = currentRevision == null ? null : (Generation) currentRevision.getRevisionInfo(); + Generation currentGeneration = currentRevision == null ? null + : (Generation) currentRevision.getRevisionInfo(); if (currentGeneration == null) { throw new IllegalStateException("No current revision for system bundle."); //$NON-NLS-1$ } @@ -428,7 +443,8 @@ private void checkSystemBundle(String[] cachedInfo) { String extraCapabilities = getSystemExtraCapabilities(); String extraExports = getSystemExtraPackages(); File contentFile = currentGeneration.getContent(); - if (systemNeedsUpdate(contentFile, currentRevision, currentGeneration, extraCapabilities, extraExports, cachedInfo)) { + if (systemNeedsUpdate(contentFile, currentRevision, currentGeneration, extraCapabilities, + extraExports, cachedInfo)) { newGeneration = currentGeneration.getBundleInfo().createGeneration(); newGeneration.setContent(contentFile, Type.DEFAULT); ModuleRevisionBuilder newBuilder = getBuilder(newGeneration, extraCapabilities, extraExports); @@ -445,7 +461,8 @@ private void checkSystemBundle(String[] cachedInfo) { } } ModuleRevision currentRevision = systemModule.getCurrentRevision(); - List nativeEnvironments = currentRevision.getModuleCapabilities(NativeNamespace.NATIVE_NAMESPACE); + List nativeEnvironments = currentRevision + .getModuleCapabilities(NativeNamespace.NATIVE_NAMESPACE); Map configMap = equinoxContainer.getConfiguration().getInitialConfig(); for (ModuleCapability nativeEnvironment : nativeEnvironments) { nativeEnvironment.setTransientAttrs(configMap); @@ -458,7 +475,8 @@ private void checkSystemBundle(String[] cachedInfo) { frameworkVersion = sVersion == null ? findFrameworkVersion() : Version.parseVersion(sVersion); } if (frameworkVersion != null) { - this.equinoxContainer.getConfiguration().setConfiguration(Constants.FRAMEWORK_VERSION, frameworkVersion.toString()); + this.equinoxContainer.getConfiguration().setConfiguration(Constants.FRAMEWORK_VERSION, + frameworkVersion.toString()); } } catch (Exception e) { if (e instanceof RuntimeException) { @@ -473,11 +491,16 @@ private void checkSystemBundle(String[] cachedInfo) { } private Version findFrameworkVersion() { - Requirement osgiPackageReq = ModuleContainer.createRequirement(PackageNamespace.PACKAGE_NAMESPACE, Collections.singletonMap(Namespace.REQUIREMENT_FILTER_DIRECTIVE, "(" + PackageNamespace.PACKAGE_NAMESPACE + "=org.osgi.framework)"), Collections.emptyMap()); //$NON-NLS-1$ //$NON-NLS-2$ + Requirement osgiPackageReq = ModuleContainer + .createRequirement(PackageNamespace.PACKAGE_NAMESPACE, + Collections.singletonMap(Namespace.REQUIREMENT_FILTER_DIRECTIVE, + "(" + PackageNamespace.PACKAGE_NAMESPACE + "=org.osgi.framework)"), //$NON-NLS-1$ //$NON-NLS-2$ + Collections.emptyMap()); Collection osgiPackages = moduleContainer.getFrameworkWiring().findProviders(osgiPackageReq); for (BundleCapability packageCapability : osgiPackages) { if (packageCapability.getRevision().getBundle().getBundleId() == 0) { - Version v = (Version) packageCapability.getAttributes().get(PackageNamespace.CAPABILITY_VERSION_ATTRIBUTE); + Version v = (Version) packageCapability.getAttributes() + .get(PackageNamespace.CAPABILITY_VERSION_ATTRIBUTE); if (v != null) { return v; } @@ -490,7 +513,8 @@ private Collection refreshMRJarBundles() throws BundleException { Collection mrJarBundles = new ArrayList<>(); for (Module m : moduleContainer.getModules()) { Generation generation = (Generation) m.getCurrentRevision().getRevisionInfo(); - // Note that we check the raw headers here incase we are working off an old version of the persistent storage + // Note that we check the raw headers here incase we are working off an old + // version of the persistent storage if (Boolean.parseBoolean(generation.getRawHeaders().get(BundleInfo.MULTI_RELEASE_HEADER))) { refresh(m); mrJarBundles.add(m); @@ -526,7 +550,8 @@ public void close() { adaptor.shutdownExecutors(); } - private boolean systemNeedsUpdate(File systemContent, ModuleRevision currentRevision, Generation existing, String extraCapabilities, String extraExports, String[] cachedInfo) throws BundleException { + private boolean systemNeedsUpdate(File systemContent, ModuleRevision currentRevision, Generation existing, + String extraCapabilities, String extraExports, String[] cachedInfo) throws BundleException { if (!extraCapabilities.equals(cachedInfo[1])) { return true; } @@ -547,7 +572,10 @@ private boolean systemNeedsUpdate(File systemContent, ModuleRevision currentRevi private void cleanOSGiStorage(Location location, File root) { if (location.isReadOnly() || !StorageUtil.rm(root, getConfiguration().getDebug().DEBUG_STORAGE)) { - equinoxContainer.getLogServices().log(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, "The -clean (osgi.clean) option was not successful. Unable to clean the storage area: " + root.getAbsolutePath(), null); //$NON-NLS-1$ + equinoxContainer.getLogServices().log(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, + "The -clean (osgi.clean) option was not successful. Unable to clean the storage area: " //$NON-NLS-1$ + + root.getAbsolutePath(), + null); } if (!location.isReadOnly()) { // make sure to recreate to root folder @@ -650,7 +678,8 @@ private URLConnection getContentConnection(final String spec) throws IOException return LocationHelper.getConnection(createURL(spec)); } try { - return AccessController.doPrivileged((PrivilegedExceptionAction) () -> LocationHelper.getConnection(createURL(spec))); + return AccessController.doPrivileged( + (PrivilegedExceptionAction) () -> LocationHelper.getConnection(createURL(spec))); } catch (PrivilegedActionException e) { if (e.getException() instanceof IOException) throw (IOException) e.getException(); @@ -660,7 +689,8 @@ private URLConnection getContentConnection(final String spec) throws IOException URL createURL(String spec) throws MalformedURLException { if (spec.startsWith(URLStreamHandlerFactoryImpl.PROTOCOL_REFERENCE)) { - return new URL(null, spec, new Handler(equinoxContainer.getConfiguration().getConfiguration(EquinoxLocations.PROP_INSTALL_AREA))); + return new URL(null, spec, new Handler( + equinoxContainer.getConfiguration().getConfiguration(EquinoxLocations.PROP_INSTALL_AREA))); } return new URL(spec); } @@ -686,7 +716,8 @@ public Generation install(Module origin, String bundleLocation, InputStream toIn if (existingLocation != null) { // NOTE this same logic is also in the ModuleContainer // This is necessary because the container does the location locking. - // Another thread could win the location lock and install before this thread does. + // Another thread could win the location lock and install before this thread + // does. try { in.close(); } catch (IOException e) { @@ -698,7 +729,10 @@ public Generation install(Module origin, String bundleLocation, InputStream toIn BundleContext context = bundle == null ? null : bundle.getBundleContext(); if (context != null && context.getBundle(existingLocation.getId()) == null) { Bundle b = existingLocation.getBundle(); - throw new BundleException(NLS.bind(Msg.ModuleContainer_NameCollisionWithLocation, new Object[] {b.getSymbolicName(), b.getVersion(), bundleLocation}), BundleException.REJECTED_BY_HOOK); + throw new BundleException( + NLS.bind(Msg.ModuleContainer_NameCollisionWithLocation, + new Object[] { b.getSymbolicName(), b.getVersion(), bundleLocation }), + BundleException.REJECTED_BY_HOOK); } } return (Generation) existingLocation.getCurrentRevision().getRevisionInfo(); @@ -783,7 +817,8 @@ private void setStorageHooks(Generation generation) throws BundleException { if (generation.getBundleInfo().getBundleId() == 0) { return; // ignore system bundle } - List> factories = new ArrayList<>(getConfiguration().getHookRegistry().getStorageHookFactories()); + List> factories = new ArrayList<>( + getConfiguration().getHookRegistry().getStorageHookFactories()); List> hooks = new ArrayList<>(factories.size()); for (StorageHookFactory storageHookFactory : factories) { @SuppressWarnings("unchecked") @@ -803,7 +838,8 @@ public ModuleRevisionBuilder getBuilder(Generation generation) throws BundleExce return getBuilder(generation, null, null); } - public ModuleRevisionBuilder getBuilder(Generation generation, String extraCapabilities, String extraExports) throws BundleException { + public ModuleRevisionBuilder getBuilder(Generation generation, String extraCapabilities, String extraExports) + throws BundleException { Dictionary headers = generation.getHeaders(); Map mapHeaders; if (headers instanceof Map) { @@ -822,8 +858,10 @@ public ModuleRevisionBuilder getBuilder(Generation generation, String extraCapab (generation.getContentType() == Type.CONNECT ? "" : null), //$NON-NLS-1$ (allowRestrictedProvides ? "" : null)); //$NON-NLS-1$ if ((builder.getTypes() & BundleRevision.TYPE_FRAGMENT) != 0) { - for (ModuleRevisionBuilder.GenericInfo reqInfo : builder.getRequirements(HostNamespace.HOST_NAMESPACE)) { - if (HostNamespace.EXTENSION_BOOTCLASSPATH.equals(reqInfo.getDirectives().get(HostNamespace.REQUIREMENT_EXTENSION_DIRECTIVE))) { + for (ModuleRevisionBuilder.GenericInfo reqInfo : builder + .getRequirements(HostNamespace.HOST_NAMESPACE)) { + if (HostNamespace.EXTENSION_BOOTCLASSPATH + .equals(reqInfo.getDirectives().get(HostNamespace.REQUIREMENT_EXTENSION_DIRECTIVE))) { throw new BundleException("Boot classpath extensions are not supported.", //$NON-NLS-1$ BundleException.UNSUPPORTED_OPERATION, new UnsupportedOperationException()); } @@ -832,7 +870,8 @@ public ModuleRevisionBuilder getBuilder(Generation generation, String extraCapab return builder; } - return OSGiManifestBuilderFactory.createBuilder(mapHeaders, Constants.SYSTEM_BUNDLE_SYMBOLICNAME, extraExports, extraCapabilities); + return OSGiManifestBuilderFactory.createBuilder(mapHeaders, Constants.SYSTEM_BUNDLE_SYMBOLICNAME, extraExports, + extraCapabilities); } private String getSystemExtraCapabilities() { @@ -868,13 +907,16 @@ private String getSystemExtraCapabilities() { result.append(NativeNamespace.NATIVE_NAMESPACE).append("; "); //$NON-NLS-1$ if (osName != null) { osName = getAliasList(equinoxConfig.getAliasMapper().getOSNameAliases(osName)); - result.append(NativeNamespace.CAPABILITY_OSNAME_ATTRIBUTE).append(":List=").append(osName).append("; "); //$NON-NLS-1$ //$NON-NLS-2$ + result.append(NativeNamespace.CAPABILITY_OSNAME_ATTRIBUTE).append(":List=").append(osName) //$NON-NLS-1$ + .append("; "); //$NON-NLS-1$ } if (processor != null) { processor = getAliasList(equinoxConfig.getAliasMapper().getProcessorAliases(processor)); - result.append(NativeNamespace.CAPABILITY_PROCESSOR_ATTRIBUTE).append(":List=").append(processor).append("; "); //$NON-NLS-1$ //$NON-NLS-2$ + result.append(NativeNamespace.CAPABILITY_PROCESSOR_ATTRIBUTE).append(":List=").append(processor) //$NON-NLS-1$ + .append("; "); //$NON-NLS-1$ } - result.append(NativeNamespace.CAPABILITY_OSVERSION_ATTRIBUTE).append(":Version").append("=\"").append(osVersion).append("\"; "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + result.append(NativeNamespace.CAPABILITY_OSVERSION_ATTRIBUTE).append(":Version").append("=\"").append(osVersion) //$NON-NLS-1$ //$NON-NLS-2$ + .append("\"; "); //$NON-NLS-1$ result.append(NativeNamespace.CAPABILITY_LANGUAGE_ATTRIBUTE).append("=\"").append(language).append('\"'); //$NON-NLS-1$ return result.toString(); } @@ -994,11 +1036,13 @@ private Generation update(Module module, URLConnection content) throws BundleExc return newGen; } - private File getContentFile(final File staged, Type contentType, final long bundleID, final long generationID) throws BundleException { + private File getContentFile(final File staged, Type contentType, final long bundleID, final long generationID) + throws BundleException { if (System.getSecurityManager() == null) return getContentFile0(staged, contentType, bundleID, generationID); try { - return AccessController.doPrivileged((PrivilegedExceptionAction) () -> getContentFile0(staged, contentType, bundleID, generationID)); + return AccessController.doPrivileged((PrivilegedExceptionAction) () -> getContentFile0(staged, + contentType, bundleID, generationID)); } catch (PrivilegedActionException e) { if (e.getException() instanceof BundleException) throw (BundleException) e.getException(); @@ -1031,14 +1075,15 @@ private static String getBundleFilePath(long bundleID, long generationID) { } /** - * Gets a file from storage and conditionally checks the parent storage area - * if the file does not exist in the child configuration. - * Note, this method does not check for escaping of paths from the root storage area. - * @param path the path relative to the root of the storage area - * @param checkParent if true then check the parent storage (if any) when the file - * does not exist in the child storage area - * @return the file being requested. A {@code null} value is never returned. The file - * returned may not exist. + * Gets a file from storage and conditionally checks the parent storage area if + * the file does not exist in the child configuration. Note, this method does + * not check for escaping of paths from the root storage area. + * + * @param path the path relative to the root of the storage area + * @param checkParent if true then check the parent storage (if any) when the + * file does not exist in the child storage area + * @return the file being requested. A {@code null} value is never returned. The + * file returned may not exist. * @throws StorageException if there was an issue getting the file */ public File getFile(String path, boolean checkParent) throws StorageException { @@ -1046,17 +1091,19 @@ public File getFile(String path, boolean checkParent) throws StorageException { } /** - * Same as {@link #getFile(String, boolean)} except takes a base parameter which is - * appended to the root storage area before looking for the path. If base is not - * null then additional checks are done to make sure the path does not escape out - * of the base path. - * @param base the additional base path to append to the root storage area. May be - * {@code null}, in which case no check is done for escaping out of the base path. - * @param path the path relative to the root + base storage area. - * @param checkParent if true then check the parent storage (if any) when the file - * does not exist in the child storage area - * @return the file being requested. A {@code null} value is never returned. The file - * returned may not exist. + * Same as {@link #getFile(String, boolean)} except takes a base parameter which + * is appended to the root storage area before looking for the path. If base is + * not null then additional checks are done to make sure the path does not + * escape out of the base path. + * + * @param base the additional base path to append to the root storage + * area. May be {@code null}, in which case no check is done + * for escaping out of the base path. + * @param path the path relative to the root + base storage area. + * @param checkParent if true then check the parent storage (if any) when the + * file does not exist in the child storage area + * @return the file being requested. A {@code null} value is never returned. The + * file returned may not exist. * @throws StorageException if there was an issue getting the file */ public File getFile(String base, String path, boolean checkParent) throws StorageException { @@ -1141,6 +1188,7 @@ File stageContent0(InputStream in, URL sourceURL) throws BundleException { /** * Attempts to set the permissions of the file in a system dependent way. + * * @param file the file to set the permissions on */ public void setPermissions(File file) { @@ -1173,7 +1221,8 @@ public BundleFile createBundleFile(File content, Generation generation, boolean BundleFile result = null; ConnectModule connectModule = null; if (generation.getContentType() == Type.CONNECT) { - connectModule = equinoxContainer.getConnectModules().getConnectModule(generation.getBundleInfo().getLocation()); + connectModule = equinoxContainer.getConnectModules() + .getConnectModule(generation.getBundleInfo().getLocation()); } try { if (connectModule != null && isBase) { @@ -1197,15 +1246,19 @@ public BundleFile createNestedBundleFile(String nestedDir, BundleFile bundleFile return createNestedBundleFile(nestedDir, bundleFile, generation, Collections.emptyList()); } - public BundleFile createNestedBundleFile(String nestedDir, BundleFile bundleFile, Generation generation, Collection filterPrefixes) { - // here we assume the content is a path offset into the base bundle file; create a NestedDirBundleFile + public BundleFile createNestedBundleFile(String nestedDir, BundleFile bundleFile, Generation generation, + Collection filterPrefixes) { + // here we assume the content is a path offset into the base bundle file; create + // a NestedDirBundleFile return wrapBundleFile(new NestedDirBundleFile(bundleFile, nestedDir, filterPrefixes), generation, false); } public BundleFile wrapBundleFile(BundleFile bundleFile, Generation generation, boolean isBase) { // try creating a wrapper bundlefile out of it. - List wrapperFactories = getConfiguration().getHookRegistry().getBundleFileWrapperFactoryHooks(); - BundleFileWrapperChain wrapped = wrapperFactories.isEmpty() ? null : new BundleFileWrapperChain(bundleFile, null); + List wrapperFactories = getConfiguration().getHookRegistry() + .getBundleFileWrapperFactoryHooks(); + BundleFileWrapperChain wrapped = wrapperFactories.isEmpty() ? null + : new BundleFileWrapperChain(bundleFile, null); for (BundleFileWrapperFactoryHook wrapperFactory : wrapperFactories) { BundleFileWrapper wrapperBundle = wrapperFactory.wrapBundleFile(bundleFile, generation, isBase); if (wrapperBundle != null && wrapperBundle != bundleFile) @@ -1377,12 +1430,14 @@ private void saveGenerations(DataOutputStream out) throws IOException { out.writeInt(contentType.ordinal()); out.writeBoolean(generation.hasPackageInfo()); if (bundleInfo.getBundleId() == 0 || contentType == Type.CONNECT) { - // just write empty string for system bundle content and connect content in this case + // just write empty string for system bundle content and connect content in this + // case out.writeUTF(""); //$NON-NLS-1$ } else { if (contentType == Type.REFERENCE) { // make reference installs relative to the install path - out.writeUTF(new FilePath(installPath).makeRelative(new FilePath(generation.getContent().getAbsolutePath()))); + out.writeUTF(new FilePath(installPath) + .makeRelative(new FilePath(generation.getContent().getAbsolutePath()))); } else { // make normal installs relative to the storage area out.writeUTF(Storage.getBundleFilePath(bundleInfo.getBundleId(), generation.getGenerationId())); @@ -1439,7 +1494,7 @@ private void saveStorageHookData(DataOutputStream out, List generati if (generation.getBundleInfo().getBundleId() == 0) { continue; // ignore system bundle } - @SuppressWarnings({"rawtypes", "unchecked"}) + @SuppressWarnings({ "rawtypes", "unchecked" }) StorageHook hook = generation.getStorageHook((Class) factory.getClass()); if (hook != null) { hook.save(saveContext, temp); @@ -1457,7 +1512,8 @@ private Map loadGenerations(DataInputStream in, String[] cache } int version = in.readInt(); if (version > VERSION || version < LOWEST_VERSION_SUPPORTED) { - throw new IllegalArgumentException("Found persistent version \"" + version + "\" expecting \"" + VERSION + "\""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + throw new IllegalArgumentException( + "Found persistent version \"" + version + "\" expecting \"" + VERSION + "\""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } Version savedRuntimeVersion = (version >= MR_JAR_VERSION) ? Version.parseVersion(in.readUTF()) : null; if (savedRuntimeVersion == null || !savedRuntimeVersion.equals(runtimeVersion)) { @@ -1538,7 +1594,8 @@ private Map loadGenerations(DataInputStream in, String[] cache } } BundleInfo info = new BundleInfo(this, infoId, infoLocation, nextGenId); - Generation generation = info.restoreGeneration(generationId, content, isDirectory, contentType, hasPackageInfo, cachedHeaders, lastModified, isMRJar); + Generation generation = info.restoreGeneration(generationId, content, isDirectory, contentType, + hasPackageInfo, cachedHeaders, lastModified, isMRJar); result.put(infoId, generation); generations.add(generation); } @@ -1563,7 +1620,8 @@ private void connectPersistentBundles(List generations) { } private void loadStorageHookData(List generations, DataInputStream in) throws IOException { - List> factories = new ArrayList<>(getConfiguration().getHookRegistry().getStorageHookFactories()); + List> factories = new ArrayList<>( + getConfiguration().getHookRegistry().getStorageHookFactories()); Map>> hookMap = new HashMap<>(); int numFactories = in.readInt(); for (int i = 0; i < numFactories; i++) { @@ -1572,7 +1630,8 @@ private void loadStorageHookData(List generations, DataInputStream i StorageHookFactory> factory = null; for (Iterator> iFactories = factories.iterator(); iFactories.hasNext();) { @SuppressWarnings("unchecked") - StorageHookFactory> next = (StorageHookFactory>) iFactories.next(); + StorageHookFactory> next = (StorageHookFactory>) iFactories + .next(); if (next.getKey().equals(factoryName)) { factory = next; iFactories.remove(); @@ -1590,7 +1649,8 @@ private void loadStorageHookData(List generations, DataInputStream i if (generation.getBundleInfo().getBundleId() == 0) { continue; // ignore system bundle } - StorageHook hook = factory.createStorageHookAndValidateFactoryClass(generation); + StorageHook hook = factory + .createStorageHookAndValidateFactoryClass(generation); if (hook != null) { hook.load(loadContext, temp); getHooks(hookMap, generation).add(hook); @@ -1602,7 +1662,8 @@ private void loadStorageHookData(List generations, DataInputStream i if (generation.getBundleInfo().getBundleId() == 0) { continue; // ignore system bundle } - StorageHook hook = factory.createStorageHookAndValidateFactoryClass(generation); + StorageHook hook = factory + .createStorageHookAndValidateFactoryClass(generation); if (hook != null) { hook.initialize(generation.getHeaders()); getHooks(hookMap, generation).add(hook); @@ -1640,7 +1701,8 @@ private void loadStorageHookData(List generations, DataInputStream i } } - private static List> getHooks(Map>> hookMap, Generation generation) { + private static List> getHooks(Map>> hookMap, + Generation generation) { List> result = hookMap.get(generation); if (result == null) { result = new ArrayList<>(); @@ -1650,14 +1712,16 @@ private void loadStorageHookData(List generations, DataInputStream i } private File getSystemContent() { - String frameworkValue = equinoxContainer.getConfiguration().getConfiguration(EquinoxConfiguration.PROP_FRAMEWORK); + String frameworkValue = equinoxContainer.getConfiguration() + .getConfiguration(EquinoxConfiguration.PROP_FRAMEWORK); if (frameworkValue == null || !frameworkValue.startsWith("file:")) { //$NON-NLS-1$ return null; } // TODO assumes the location is a file URL File result = new File(frameworkValue.substring(5)).getAbsoluteFile(); if (!result.exists()) { - throw new IllegalStateException("Configured framework location does not exist: " + result.getAbsolutePath()); //$NON-NLS-1$ + throw new IllegalStateException( + "Configured framework location does not exist: " + result.getAbsolutePath()); //$NON-NLS-1$ } return result; } @@ -1667,31 +1731,45 @@ private void loadVMProfile(Generation systemGeneration) { EquinoxConfiguration equinoxConfig = equinoxContainer.getConfiguration(); Properties profileProps = findVMProfile(systemGeneration); String systemExports = equinoxConfig.getConfiguration(Constants.FRAMEWORK_SYSTEMPACKAGES); - // set the system exports property using the vm profile; only if the property is not already set + // set the system exports property using the vm profile; only if the property is + // not already set if (systemExports == null) { systemExports = profileProps.getProperty(Constants.FRAMEWORK_SYSTEMPACKAGES); if (systemExports != null) equinoxConfig.setConfiguration(Constants.FRAMEWORK_SYSTEMPACKAGES, systemExports); } - // set the org.osgi.framework.bootdelegation property according to the java profile - String type = equinoxConfig.getConfiguration(EquinoxConfiguration.PROP_OSGI_JAVA_PROFILE_BOOTDELEGATION); // a null value means ignore + // set the org.osgi.framework.bootdelegation property according to the java + // profile + String type = equinoxConfig.getConfiguration(EquinoxConfiguration.PROP_OSGI_JAVA_PROFILE_BOOTDELEGATION); // a + // null + // value + // means + // ignore String profileBootDelegation = profileProps.getProperty(Constants.FRAMEWORK_BOOTDELEGATION); if (EquinoxConfiguration.PROP_OSGI_BOOTDELEGATION_OVERRIDE.equals(type)) { if (profileBootDelegation == null) equinoxConfig.clearConfiguration(Constants.FRAMEWORK_BOOTDELEGATION); // override with a null value else - equinoxConfig.setConfiguration(Constants.FRAMEWORK_BOOTDELEGATION, profileBootDelegation); // override with the profile value + equinoxConfig.setConfiguration(Constants.FRAMEWORK_BOOTDELEGATION, profileBootDelegation); // override + // with the + // profile + // value } else if (EquinoxConfiguration.PROP_OSGI_BOOTDELEGATION_NONE.equals(type)) - equinoxConfig.clearConfiguration(Constants.FRAMEWORK_BOOTDELEGATION); // remove the bootdelegation property in case it was set - // set the org.osgi.framework.executionenvironment property according to the java profile + equinoxConfig.clearConfiguration(Constants.FRAMEWORK_BOOTDELEGATION); // remove the bootdelegation property + // in case it was set + // set the org.osgi.framework.executionenvironment property according to the + // java profile if (equinoxConfig.getConfiguration(Constants.FRAMEWORK_EXECUTIONENVIRONMENT) == null) { - // get the ee from the java profile; if no ee is defined then try the java profile name - String ee = profileProps.getProperty(Constants.FRAMEWORK_EXECUTIONENVIRONMENT, profileProps.getProperty(EquinoxConfiguration.PROP_OSGI_JAVA_PROFILE_NAME)); + // get the ee from the java profile; if no ee is defined then try the java + // profile name + String ee = profileProps.getProperty(Constants.FRAMEWORK_EXECUTIONENVIRONMENT, + profileProps.getProperty(EquinoxConfiguration.PROP_OSGI_JAVA_PROFILE_NAME)); if (ee != null) equinoxConfig.setConfiguration(Constants.FRAMEWORK_EXECUTIONENVIRONMENT, ee); } - // set the org.osgi.framework.system.capabilities property according to the java profile + // set the org.osgi.framework.system.capabilities property according to the java + // profile if (equinoxConfig.getConfiguration(Constants.FRAMEWORK_SYSTEMCAPABILITIES) == null) { String systemCapabilities = profileProps.getProperty(Constants.FRAMEWORK_SYSTEMCAPABILITIES); if (systemCapabilities != null) @@ -1762,8 +1840,7 @@ private Properties findVMProfile(Generation systemGeneration) { return result; } - private InputStream createProfileStream(Generation systemGeneration, String vmProfile, - String embeddedProfileName) { + private InputStream createProfileStream(Generation systemGeneration, String vmProfile, String embeddedProfileName) { InputStream profileIn = null; if (vmProfile != null) { // look for a profile in the system bundle based on the vm profile @@ -1782,9 +1859,10 @@ private InputStream createProfileStream(Generation systemGeneration, String vmPr private Properties readConfiguredJavaProfile(Generation systemGeneration) { // check for the java profile property for a url - String propJavaProfile = equinoxContainer.getConfiguration().getConfiguration(EquinoxConfiguration.PROP_OSGI_JAVA_PROFILE); + String propJavaProfile = equinoxContainer.getConfiguration() + .getConfiguration(EquinoxConfiguration.PROP_OSGI_JAVA_PROFILE); if (propJavaProfile != null) { - try (InputStream profileIn = createPropStream(systemGeneration, propJavaProfile)){ + try (InputStream profileIn = createPropStream(systemGeneration, propJavaProfile)) { if (profileIn != null) { Properties result = new Properties(); result.load(profileIn); @@ -1824,7 +1902,8 @@ private Properties calculateVMProfile(Version javaVersion) { } private String calculateVMExecutionEnvs(Version javaVersion) { - StringBuilder result = new StringBuilder("OSGi/Minimum-1.0, OSGi/Minimum-1.1, OSGi/Minimum-1.2, JavaSE/compact1-1.8, JavaSE/compact2-1.8, JavaSE/compact3-1.8, JRE-1.1, J2SE-1.2, J2SE-1.3, J2SE-1.4, J2SE-1.5, JavaSE-1.6, JavaSE-1.7, JavaSE-1.8"); //$NON-NLS-1$ + StringBuilder result = new StringBuilder( + "OSGi/Minimum-1.0, OSGi/Minimum-1.1, OSGi/Minimum-1.2, JavaSE/compact1-1.8, JavaSE/compact2-1.8, JavaSE/compact3-1.8, JRE-1.1, J2SE-1.2, J2SE-1.3, J2SE-1.4, J2SE-1.5, JavaSE-1.6, JavaSE-1.7, JavaSE-1.8"); //$NON-NLS-1$ Version v = new Version(9, 0, 0); while (v.compareTo(javaVersion) <= 0) { result.append(',').append(' ').append(JAVASE).append('-').append(v.getMajor()); @@ -1853,7 +1932,8 @@ private String calculateEECapabilities(Version javaVersion) { } String versionsList = versionsBulder.toString(); - StringBuilder result = new StringBuilder("osgi.ee; osgi.ee=\"OSGi/Minimum\"; version:List=\"1.0, 1.1, 1.2\", osgi.ee; osgi.ee=\"JRE\"; version:List=\"1.0, 1.1\", osgi.ee; osgi.ee=\"JavaSE\"; version:List=\"1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8"); //$NON-NLS-1$ + StringBuilder result = new StringBuilder( + "osgi.ee; osgi.ee=\"OSGi/Minimum\"; version:List=\"1.0, 1.1, 1.2\", osgi.ee; osgi.ee=\"JRE\"; version:List=\"1.0, 1.1\", osgi.ee; osgi.ee=\"JavaSE\"; version:List=\"1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8"); //$NON-NLS-1$ result.append(versionsList).append("\""); //$NON-NLS-1$ result.append(",osgi.ee; osgi.ee=\"JavaSE/compact1\"; version:List=\"1.8"); //$NON-NLS-1$ result.append(versionsList).append("\""); //$NON-NLS-1$ @@ -1896,10 +1976,11 @@ private String calculateVMPackages() { Object descriptor = getDescriptor.invoke(m); if ((Boolean) isAutomatic.invoke(descriptor)) { /* - * Automatic modules are supposed to export all their packages. - * However, java.lang.module.ModuleDescriptor::exports returns an empty set for them. - * Add all their packages (as returned by java.lang.module.ModuleDescriptor::packages) - * to the list of VM supplied packages. + * Automatic modules are supposed to export all their packages. However, + * java.lang.module.ModuleDescriptor::exports returns an empty set for them. Add + * all their packages (as returned by + * java.lang.module.ModuleDescriptor::packages) to the list of VM supplied + * packages. */ packages.addAll((Set) packagesMethod.invoke(descriptor)); } else { @@ -1921,14 +2002,17 @@ private String calculateVMPackages() { } return result.toString(); } catch (Exception e) { - equinoxContainer.getLogServices().log(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, "Error determining system packages.", e); //$NON-NLS-1$ + equinoxContainer.getLogServices().log(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, + "Error determining system packages.", e); //$NON-NLS-1$ return null; } } - private InputStream getNextBestProfile(Generation systemGeneration, String javaEdition, Version javaVersion, String embeddedProfileName) { + private InputStream getNextBestProfile(Generation systemGeneration, String javaEdition, Version javaVersion, + String embeddedProfileName) { if (javaVersion == null || javaEdition != JAVASE) - return null; // we cannot automatically choose the next best profile unless this is a JavaSE vm + return null; // we cannot automatically choose the next best profile unless this is a JavaSE + // vm InputStream bestProfile = findNextBestProfile(systemGeneration, javaEdition, javaVersion, embeddedProfileName); if (bestProfile == null && !"-".equals(embeddedProfileName)) { //$NON-NLS-1$ // Just use the base javaEdition name without the profile name as backup @@ -1937,13 +2021,15 @@ private InputStream getNextBestProfile(Generation systemGeneration, String javaE return bestProfile; } - private InputStream findNextBestProfile(Generation systemGeneration, String javaEdition, Version javaVersion, String embeddedProfileName) { + private InputStream findNextBestProfile(Generation systemGeneration, String javaEdition, Version javaVersion, + String embeddedProfileName) { InputStream result = null; int major = javaVersion.getMajor(); int minor = javaVersion.getMinor(); do { // If minor is zero then it is not included in the name - String profileResourceName = javaEdition + embeddedProfileName + major + ((minor > 0) ? "." + minor : "") + PROFILE_EXT; //$NON-NLS-1$ //$NON-NLS-2$ + String profileResourceName = javaEdition + embeddedProfileName + major + ((minor > 0) ? "." + minor : "") //$NON-NLS-1$ //$NON-NLS-2$ + + PROFILE_EXT; result = findInSystemBundle(systemGeneration, profileResourceName); if (minor > 0) { minor -= 1; @@ -1979,7 +2065,8 @@ private InputStream findInSystemBundle(Generation systemGeneration, String entry return result; } - public static Enumeration findEntries(List generations, String path, String filePattern, int options) { + public static Enumeration findEntries(List generations, String path, String filePattern, + int options) { List bundleFiles = new ArrayList<>(generations.size()); for (Generation generation : generations) bundleFiles.add(generation.getBundleFile()); @@ -1995,27 +2082,32 @@ public static Enumeration findEntries(List generations, String } /** - * Returns the names of resources available from a list of bundle files. - * No duplicate resource names are returned, each name is unique. + * Returns the names of resources available from a list of bundle files. No + * duplicate resource names are returned, each name is unique. + * * @param bundleFiles the list of bundle files to search in - * @param path The path name in which to look. - * @param filePattern The file name pattern for selecting resource names in - * the specified path. - * @param options The options for listing resource names. - * @return a list of resource names. If no resources are found then - * the empty list is returned. + * @param path The path name in which to look. + * @param filePattern The file name pattern for selecting resource names in the + * specified path. + * @param options The options for listing resource names. + * @return a list of resource names. If no resources are found then the empty + * list is returned. * @see BundleWiring#listResources(String, String, int) */ - public static List listEntryPaths(List bundleFiles, String path, String filePattern, int options) { + public static List listEntryPaths(List bundleFiles, String path, String filePattern, + int options) { // Use LinkedHashSet for optimized performance of contains() plus // ordering guarantees. LinkedHashSet pathList = new LinkedHashSet<>(); Filter patternFilter = null; Hashtable patternProps = null; if (filePattern != null) { - // Optimization: If the file pattern does not include a wildcard or escape char then it must represent a single file. - // Avoid pattern matching and use BundleFile.getEntry() if recursion was not requested. - if ((options & BundleWiring.FINDENTRIES_RECURSE) == 0 && filePattern.indexOf('*') == -1 && filePattern.indexOf('\\') == -1) { + // Optimization: If the file pattern does not include a wildcard or escape char + // then it must represent a single file. + // Avoid pattern matching and use BundleFile.getEntry() if recursion was not + // requested. + if ((options & BundleWiring.FINDENTRIES_RECURSE) == 0 && filePattern.indexOf('*') == -1 + && filePattern.indexOf('\\') == -1) { if (path.length() == 0) path = filePattern; else @@ -2034,8 +2126,8 @@ public static List listEntryPaths(List bundleFiles, String p patternProps = new Hashtable<>(2); } catch (InvalidSyntaxException e) { // TODO something unexpected happened; log error and return nothing - // Bundle b = context == null ? null : context.getBundle(); - // eventPublisher.publishFrameworkEvent(FrameworkEvent.ERROR, b, e); + // Bundle b = context == null ? null : context.getBundle(); + // eventPublisher.publishFrameworkEvent(FrameworkEvent.ERROR, b, e); return new ArrayList<>(pathList); } } @@ -2052,33 +2144,33 @@ public static String sanitizeFilterInput(String filePattern) throws InvalidSynta for (int i = 0; i < filePattern.length(); i++) { char c = filePattern.charAt(i); switch (c) { - case '\\' : - // we either used the escape found or found a new escape. - foundEscape = foundEscape ? false : true; - if (buffer != null) - buffer.append(c); - break; - case '(' : - case ')' : - if (!foundEscape) { - if (buffer == null) { - buffer = new StringBuilder(filePattern.length() + 16); - buffer.append(filePattern.substring(0, i)); - } - // must escape with '\' - buffer.append('\\'); - } else { - foundEscape = false; // used the escape found + case '\\': + // we either used the escape found or found a new escape. + foundEscape = foundEscape ? false : true; + if (buffer != null) + buffer.append(c); + break; + case '(': + case ')': + if (!foundEscape) { + if (buffer == null) { + buffer = new StringBuilder(filePattern.length() + 16); + buffer.append(filePattern.substring(0, i)); } - if (buffer != null) - buffer.append(c); - break; - default : - // if we found an escape it has been used - foundEscape = false; - if (buffer != null) - buffer.append(c); - break; + // must escape with '\' + buffer.append('\\'); + } else { + foundEscape = false; // used the escape found + } + if (buffer != null) + buffer.append(c); + break; + default: + // if we found an escape it has been used + foundEscape = false; + if (buffer != null) + buffer.append(c); + break; } } if (foundEscape) @@ -2088,7 +2180,8 @@ public static String sanitizeFilterInput(String filePattern) throws InvalidSynta // Use LinkedHashSet for optimized performance of contains() plus ordering // guarantees. - private static LinkedHashSet listEntryPaths(BundleFile bundleFile, String path, Filter patternFilter, Hashtable patternProps, int options, LinkedHashSet pathList) { + private static LinkedHashSet listEntryPaths(BundleFile bundleFile, String path, Filter patternFilter, + Hashtable patternProps, int options, LinkedHashSet pathList) { if (pathList == null) pathList = new LinkedHashSet<>(); boolean recurse = (options & BundleWiring.FINDENTRIES_RECURSE) != 0; @@ -2133,12 +2226,17 @@ public String copyToTempLibrary(Generation generation, String absolutePath) { File bundleTempDir = null; File libTempFile = null; // We need a somewhat predictable temp dir for the libraries of a given bundle; - // This is not strictly necessary but it does help scenarios where one native library loads another native library without using java. - // On some OSes this causes issues because the second library is cannot be found. - // This has been worked around by the bundles loading the libraries in a particular order (and setting some LIB_PATH env). - // The one catch is that the libraries need to be in the same directory and they must use their original lib names. + // This is not strictly necessary but it does help scenarios where one native + // library loads another native library without using java. + // On some OSes this causes issues because the second library is cannot be + // found. + // This has been worked around by the bundles loading the libraries in a + // particular order (and setting some LIB_PATH env). + // The one catch is that the libraries need to be in the same directory and they + // must use their original lib names. // - // This bit of code attempts to do that by using the bundle ID as an ID for the temp dir along with an incrementing ID + // This bit of code attempts to do that by using the bundle ID as an ID for the + // temp dir along with an incrementing ID // in cases where the temp dir may already exist. long bundleID = generation.getBundleInfo().getBundleId(); for (int i = 0; i < Integer.MAX_VALUE; i++) { @@ -2154,7 +2252,8 @@ public String copyToTempLibrary(Generation generation, String absolutePath) { if (!bundleTempDir.isDirectory()) { bundleTempDir.mkdirs(); bundleTempDir.deleteOnExit(); - // This is just a safeguard incase the VM is terminated unexpectantly, it also looks like deleteOnExit cannot really work because + // This is just a safeguard incase the VM is terminated unexpectantly, it also + // looks like deleteOnExit cannot really work because // the VM likely will still have a lock on the lib file at the time of VM exit. try { // need to create a delete flag to force removal the temp libraries ensureDeleteFlagFileExists(libTempDir.toPath()); @@ -2167,7 +2266,8 @@ public String copyToTempLibrary(Generation generation, String absolutePath) { StorageUtil.copy(realLib, libTempFile); // set permissions if needed setPermissions(libTempFile); - libTempFile.deleteOnExit(); // this probably will not work because the VM will probably have the lib locked at exit + libTempFile.deleteOnExit(); // this probably will not work because the VM will probably have the lib locked + // at exit // return the temporary path return libTempFile.getAbsolutePath(); } catch (IOException e) { @@ -2178,7 +2278,7 @@ public String copyToTempLibrary(Generation generation, String absolutePath) { private static void ensureDeleteFlagFileExists(Path directory) throws IOException { Path deleteFlag = directory.resolve(DELETE_FLAG); - if (!Files.exists(deleteFlag) ) { + if (!Files.exists(deleteFlag)) { Files.createFile(deleteFlag); } } @@ -2188,8 +2288,10 @@ public SecurityAdmin getSecurityAdmin() { } protected StorageManager getChildStorageManager() throws IOException { - String locking = getConfiguration().getConfiguration(LocationHelper.PROP_OSGI_LOCKING, LocationHelper.LOCKING_NIO); - StorageManager sManager = new StorageManager(childRoot, isReadOnly() ? LocationHelper.LOCKING_NONE : locking, isReadOnly()); + String locking = getConfiguration().getConfiguration(LocationHelper.PROP_OSGI_LOCKING, + LocationHelper.LOCKING_NIO); + StorageManager sManager = new StorageManager(childRoot, isReadOnly() ? LocationHelper.LOCKING_NONE : locking, + isReadOnly()); try { sManager.open(!isReadOnly()); } catch (IOException ex) { @@ -2200,7 +2302,8 @@ protected StorageManager getChildStorageManager() throws IOException { String message = NLS.bind(Msg.ECLIPSE_STARTUP_FILEMANAGER_OPEN_ERROR, ex.getMessage()); equinoxContainer.getLogServices().log(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, message, ex); getConfiguration().setProperty(EclipseStarter.PROP_EXITCODE, "15"); //$NON-NLS-1$ - String errorDialog = "" + Msg.ADAPTOR_STORAGE_INIT_FAILED_TITLE + "" + NLS.bind(Msg.ADAPTOR_STORAGE_INIT_FAILED_MSG, childRoot) + "\n" + ex.getMessage(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + String errorDialog = "" + Msg.ADAPTOR_STORAGE_INIT_FAILED_TITLE + "" //$NON-NLS-1$ //$NON-NLS-2$ + + NLS.bind(Msg.ADAPTOR_STORAGE_INIT_FAILED_MSG, childRoot) + "\n" + ex.getMessage(); //$NON-NLS-1$ getConfiguration().setProperty(EclipseStarter.PROP_EXITDATA, errorDialog); throw ex; } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/StorageUtil.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/StorageUtil.java index 027ca79e307..d6d23834d37 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/StorageUtil.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/StorageUtil.java @@ -39,7 +39,8 @@ import org.osgi.framework.ServiceRegistration; /** - * A utility class with some generally useful static methods for adaptor hook implementations + * A utility class with some generally useful static methods for adaptor hook + * implementations */ public class StorageUtil { @@ -47,6 +48,7 @@ public class StorageUtil { * Copies the content of the given path (file or directory) to the specified * target. If the source is a directory all contained elements are copied * recursively. + * * @param inFile input directory to copy. * @param outFile output directory to copy to. * @throws IOException if any error occurs during the copy. @@ -68,7 +70,8 @@ public static void copy(File inFile, File outFile) throws IOException { /** * Read a file from an InputStream and write it to the file system. * - * @param in InputStream from which to read. This stream will be closed by this method. + * @param in InputStream from which to read. This stream will be closed by + * this method. * @param file output file to create. * @exception IOException */ @@ -81,7 +84,7 @@ public static void readFile(InputStream in, File file) throws IOException { /** * This function performs the equivalent of "rm -r" on a file or directory. * - * @param file file or directory to delete + * @param file file or directory to delete * @return false is the specified files still exists, true otherwise. */ public static boolean rm(File file, boolean DEBUG) { @@ -123,7 +126,8 @@ private FileVisitResult delete(Path pathToDelete, boolean debug) { /** * Register a service object. - * @param name the service class name + * + * @param name the service class name * @param service the service object * @param context the registering bundle context * @return the service registration object diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/SystemBundleFile.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/SystemBundleFile.java index ed49811192e..3db6abbb8e1 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/SystemBundleFile.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/SystemBundleFile.java @@ -99,12 +99,15 @@ URL getManifestURL() { ClassLoader cl = getClass().getClassLoader(); try { // get all manifests in your classloader delegation - Enumeration manifests = cl != null ? cl.getResources(BundleInfo.OSGI_BUNDLE_MANIFEST) : ClassLoader.getSystemResources(BundleInfo.OSGI_BUNDLE_MANIFEST); + Enumeration manifests = cl != null ? cl.getResources(BundleInfo.OSGI_BUNDLE_MANIFEST) + : ClassLoader.getSystemResources(BundleInfo.OSGI_BUNDLE_MANIFEST); while (manifests.hasMoreElements()) { URL url = manifests.nextElement(); try { - // check each manifest until we find one with the Eclipse-SystemBundle: true header - Map headers = ManifestElement.parseBundleManifest(url.openStream(), new CaseInsensitiveDictionaryMap<>()); + // check each manifest until we find one with the Eclipse-SystemBundle: true + // header + Map headers = ManifestElement.parseBundleManifest(url.openStream(), + new CaseInsensitiveDictionaryMap<>()); if ("true".equals(headers.get(Storage.ECLIPSE_SYSTEMBUNDLE))) //$NON-NLS-1$ return url; } catch (BundleException e) { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/BundleEntry.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/BundleEntry.java index ffbde9a61cb..95698a320de 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/BundleEntry.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/BundleEntry.java @@ -52,16 +52,18 @@ public abstract class BundleEntry { /** * Get the modification time for this BundleEntry. - *

    If the modification time has not been set, - * this method will return -1. + *

    + * If the modification time has not been set, this method will return + * -1. * * @return last modification time. */ public abstract long getTime(); /** - * Get a URL to the bundle entry that uses a common protocol (i.e. file: - * jar: or http: etc.). + * Get a URL to the bundle entry that uses a common protocol (i.e. file: jar: or + * http: etc.). + * * @return a URL to the bundle entry that uses a common protocol */ public abstract URL getLocalURL(); @@ -70,6 +72,7 @@ public abstract class BundleEntry { * Get a URL to the content of the bundle entry that uses the file: protocol. * The content of the bundle entry may be downloaded or extracted to the local * file system in order to create a file: URL. + * * @return a URL to the content of the bundle entry that uses the file: protocol */ public abstract URL getFileURL(); @@ -85,16 +88,18 @@ public String toString() { } /** - * Used for class loading. This default implementation gets the input stream from this entry - * and copies the content into a byte array. + * Used for class loading. This default implementation gets the input stream + * from this entry and copies the content into a byte array. + * * @return a byte array containing the content of this entry * @throws IOException */ public byte[] getBytes() throws IOException { InputStream in = getInputStream(); int length = (int) getSize(); - // if (Debug.DEBUG_LOADER) - // Debug.println(" about to read " + length + " bytes from " + getName()); //$NON-NLS-1$ //$NON-NLS-2$ + // if (Debug.DEBUG_LOADER) + // Debug.println(" about to read " + length + " bytes from " + getName()); + // //$NON-NLS-1$ //$NON-NLS-2$ return StorageUtil.getBytes(in, length, BUF_SIZE); } } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/BundleFile.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/BundleFile.java index 598782c3fda..2b508e1a0ee 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/BundleFile.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/BundleFile.java @@ -29,8 +29,8 @@ import org.eclipse.osgi.storage.url.bundleresource.Handler; /** - * The BundleFile API is used by Adaptors to read resources out of an - * installed Bundle in the Framework. + * The BundleFile API is used by Adaptors to read resources out of an installed + * Bundle in the Framework. *

    * Clients wishing to modify or extend the functionality of this class at * runtime should extend the associated {@link BundleFileWrapper decorator} @@ -46,18 +46,18 @@ abstract public class BundleFile { /** * BundleFile constructor - * @param basefile The File object where this BundleFile is - * persistently stored. + * + * @param basefile The File object where this BundleFile is persistently stored. */ protected BundleFile(File basefile) { this.basefile = basefile; } /** - * Returns a File for the bundle entry specified by the path. - * If required the content of the bundle entry is extracted into a file - * on the file system. - * @param path The path to the entry to locate a File for. + * Returns a File for the bundle entry specified by the path. If required the + * content of the bundle entry is extracted into a file on the file system. + * + * @param path The path to the entry to locate a File for. * @param nativeCode true if the path is native code. * @return A File object to access the contents of the bundle entry. */ @@ -67,75 +67,79 @@ protected BundleFile(File basefile) { * Locates a file name in this bundle and returns a BundleEntry object * * @param path path of the entry to locate in the bundle - * @return BundleEntry object or null if the file name - * does not exist in the bundle + * @return BundleEntry object or null if the file name does not exist in the + * bundle */ abstract public BundleEntry getEntry(String path); /** - * Performs the same function as calling - * {@link #getEntryPaths(String, boolean)} with recurse equal - * to false. + * Performs the same function as calling {@link #getEntryPaths(String, boolean)} + * with recurse equal to false. + * * @param path path of the entry to locate in the bundle - * @return an Enumeration of Strings that indicate the paths found or - * null if the path does not exist. + * @return an Enumeration of Strings that indicate the paths found or null if + * the path does not exist. */ public Enumeration getEntryPaths(String path) { return getEntryPaths(path, false); } /** - * Allows to access the entries of the bundle. - * Since the bundle content is usually a jar, this - * allows to access the jar contents. + * Allows to access the entries of the bundle. Since the bundle content is + * usually a jar, this allows to access the jar contents. * - * GetEntryPaths allows to enumerate the content of "path". - * If path is a directory, it is equivalent to listing the directory - * contents. The returned names are either files or directories - * themselves. If a returned name is a directory, it finishes with a - * slash. If a returned name is a file, it does not finish with a slash. - * @param path path of the entry to locate in the bundle + * GetEntryPaths allows to enumerate the content of "path". If path is a + * directory, it is equivalent to listing the directory contents. The returned + * names are either files or directories themselves. If a returned name is a + * directory, it finishes with a slash. If a returned name is a file, it does + * not finish with a slash. + * + * @param path path of the entry to locate in the bundle * @param recurse - If true, provide entries for the files and - * directories within the directory denoted by path plus - * all sub-directories and files; otherwise, provide only the entries - * within the immediate directory. - * @return an Enumeration of Strings that indicate the paths found or - * null if the path does not exist. + * directories within the directory denoted by path + * plus all sub-directories and files; otherwise, provide only + * the entries within the immediate directory. + * @return an Enumeration of Strings that indicate the paths found or null if + * the path does not exist. */ abstract public Enumeration getEntryPaths(String path, boolean recurse); /** * Closes the BundleFile. + * * @throws IOException if any error occurs. */ abstract public void close() throws IOException; /** * Opens the BundleFiles. + * * @throws IOException if any error occurs. */ abstract public void open() throws IOException; /** * Determines if any BundleEntries exist in the given directory path. + * * @param dir The directory path to check existence of. - * @return true if the BundleFile contains entries under the given directory path; - * false otherwise. + * @return true if the BundleFile contains entries under the given directory + * path; false otherwise. */ abstract public boolean containsDir(String dir); /** - * Returns a URL to access the contents of the entry specified by the path. - * This method first calls {@link #getEntry(String)} to locate the entry - * at the specified path. If no entry is found {@code null} is returned; - * otherwise {@link #createResourceURL(BundleEntry, Module, int, String)} - * is called in order to create the URL. Subclasses should not override - * this method. Instead the methods {@link #getEntry(String)} and/or - * {@link #createResourceURL(BundleEntry, Module, int, String)} may be - * overriden to augment the behavior. - * @param path the path to the resource + * Returns a URL to access the contents of the entry specified by the path. This + * method first calls {@link #getEntry(String)} to locate the entry at the + * specified path. If no entry is found {@code null} is returned; otherwise + * {@link #createResourceURL(BundleEntry, Module, int, String)} is called in + * order to create the URL. Subclasses should not override this method. Instead + * the methods {@link #getEntry(String)} and/or + * {@link #createResourceURL(BundleEntry, Module, int, String)} may be overriden + * to augment the behavior. + * + * @param path the path to the resource * @param hostModule the host module - * @param index the resource index + * @param index the resource index * @return a URL to access the contents of the entry specified by the path */ public URL getResourceURL(String path, Module hostModule, int index) { @@ -147,9 +151,10 @@ public URL getResourceURL(String path, Module hostModule, int index) { /** * Creates a URL to access the content of the specified entry + * * @param bundleEntry the bundle entry - * @param hostModule the host module - * @param index the resource index + * @param hostModule the host module + * @param index the resource index * @param path * @return a URL to access the contents of the specified entry */ @@ -164,6 +169,7 @@ protected URL createResourceURL(BundleEntry bundleEntry, Module hostModule, int /** * Returns the base file for this BundleFile + * * @return the base file for this BundleFile */ public File getBaseFile() { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/BundleFileWrapper.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/BundleFileWrapper.java index ee593ebdbb9..831f6a2e4f0 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/BundleFileWrapper.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/BundleFileWrapper.java @@ -25,17 +25,17 @@ * A {@link BundleFile bundle file} decorator. *

    * Clients wishing to modify or extend the behavior of a bundle file at runtime - * should extend this class instead. A hook is provided by the related {@link - * BundleFileWrapperFactoryHook abstract factory} class in response to a - * {@link BundleFileWrapperFactoryHook#wrapBundleFile(BundleFile, - * BundleInfo.Generation, boolean) call} from the framework. + * should extend this class instead. A hook is provided by the related + * {@link BundleFileWrapperFactoryHook abstract factory} class in response to a + * {@link BundleFileWrapperFactoryHook#wrapBundleFile(BundleFile, BundleInfo.Generation, boolean) + * call} from the framework. */ public class BundleFileWrapper extends BundleFile { private final BundleFile bundleFile; /** - * Creates a new BundleFileWrapper instance wrapping the - * given {@link BundleFile bundle file}. + * Creates a new BundleFileWrapper instance wrapping the given + * {@link BundleFile bundle file}. * * @param bundleFile - The bundle file to wrap. * @throws NullPointerException - If the bundle file is null. diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/BundleFileWrapperChain.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/BundleFileWrapperChain.java index 1fcabe05ee6..aaa58759dab 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/BundleFileWrapperChain.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/BundleFileWrapperChain.java @@ -17,8 +17,9 @@ import org.eclipse.osgi.internal.hookregistry.BundleFileWrapperFactoryHook; /** - * Used to chain the BundleFile objects returned from {@link BundleFileWrapperFactoryHook}. - * This class is useful for traversing the chain of wrapped bundle files. + * Used to chain the BundleFile objects returned from + * {@link BundleFileWrapperFactoryHook}. This class is useful for traversing the + * chain of wrapped bundle files. */ public class BundleFileWrapperChain extends BundleFileWrapper { private final BundleFile wrapped; @@ -37,6 +38,7 @@ public String toString() { /** * The BundleFile that is wrapped + * * @return the BunldeFile that is wrapped */ public BundleFile getWrapped() { @@ -44,8 +46,9 @@ public BundleFile getWrapped() { } /** - * The next WrapperBundleFile in the chain. A null value - * is returned if this is the end of the chain. + * The next WrapperBundleFile in the chain. A null value is + * returned if this is the end of the chain. + * * @return the next WrapperBundleFile */ public BundleFileWrapperChain getNext() { @@ -53,9 +56,10 @@ public BundleFileWrapperChain getNext() { } /** - * Returns the first bundle file wrapped in this chain which - * also is an instance of the specified type. - * @param The type being searched for + * Returns the first bundle file wrapped in this chain which also is an instance + * of the specified type. + * + * @param The type being searched for * @param type the class of the type being searched for * @return the found bundle file that is an instance of the specified type */ diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/CloseableBundleFile.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/CloseableBundleFile.java index 66860195ab7..25e792e6b06 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/CloseableBundleFile.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/CloseableBundleFile.java @@ -36,8 +36,11 @@ import org.eclipse.osgi.util.NLS; /** - * A BundleFile that manages the number of open bundle files by using the MRUBundleFileList - * @param a type specified by extending classes to call {@link #getInputStream(Object)} + * A BundleFile that manages the number of open bundle files by using the + * MRUBundleFileList + * + * @param a type specified by extending classes to call + * {@link #getInputStream(Object)} */ public abstract class CloseableBundleFile extends BundleFile { @@ -60,7 +63,8 @@ public abstract class CloseableBundleFile extends BundleFile { private int referenceCount = 0; - public CloseableBundleFile(File basefile, BundleInfo.Generation generation, MRUBundleFileList mruList, Debug debug) { + public CloseableBundleFile(File basefile, BundleInfo.Generation generation, MRUBundleFileList mruList, + Debug debug) { super(basefile); this.debug = debug; this.generation = generation; @@ -70,6 +74,7 @@ public CloseableBundleFile(File basefile, BundleInfo.Generation generation, MRUB /** * Checks if the bundle file is open + * * @return true if the bundle file is open and locked */ protected boolean lockOpen() { @@ -84,14 +89,16 @@ protected boolean lockOpen() { ModuleRevision r = generation.getRevision(); if (r != null) { ContainerEvent eventType = ContainerEvent.ERROR; - // If the revision has been removed from the list of revisions then it has been deleted + // If the revision has been removed from the list of revisions then it has been + // deleted // because the bundle has been uninstalled or updated if (e instanceof IOException && !r.getRevisions().getModuleRevisions().contains(r)) { // instead of filling the log with errors about missing files from // uninstalled/updated bundles just give it an info level eventType = ContainerEvent.INFO; } - generation.getBundleInfo().getStorage().getAdaptor().publishContainerEvent(eventType, r.getRevisions().getModule(), e); + generation.getBundleInfo().getStorage().getAdaptor().publishContainerEvent(eventType, + r.getRevisions().getModule(), e); } } if (!(e instanceof IOException)) { @@ -150,16 +157,18 @@ private void internalOpen() throws IOException { /** * Opens the bundle file + * * @throws IOException if an error occurs */ protected abstract void doOpen() throws IOException; /** * Extracts a directory and all sub content to disk + * * @param dirName the directory name to extract - * @return the File used to extract the content to. A value - * of null is returned if the directory to extract does - * not exist or if content extraction is not supported. + * @return the File used to extract the content to. A value of null + * is returned if the directory to extract does not exist or if content + * extraction is not supported. */ File extractDirectory(String dirName) { if (!lockOpen()) { @@ -213,7 +222,8 @@ public File getFile(String entry, boolean nativeCode) { if (!nested.isDirectory()) { if (debug.DEBUG_BUNDLE_FILE) Debug.println("Unable to create directory: " + nested.getPath()); //$NON-NLS-1$ - throw new IOException(NLS.bind(Msg.ADAPTOR_DIRECTORY_CREATE_EXCEPTION, nested.getAbsolutePath())); + throw new IOException( + NLS.bind(Msg.ADAPTOR_DIRECTORY_CREATE_EXCEPTION, nested.getAbsolutePath())); } extractDirectory(bEntry.getName()); } else { @@ -229,7 +239,9 @@ public File getFile(String entry, boolean nativeCode) { } catch (IOException | StorageException e) { if (debug.DEBUG_BUNDLE_FILE) Debug.printStackTrace(e); - generation.getBundleInfo().getStorage().getLogServices().log(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, "Unable to extract content: " + generation.getRevision() + ": " + entry, e); //$NON-NLS-1$ //$NON-NLS-2$ + generation.getBundleInfo().getStorage().getLogServices().log(EquinoxContainer.NAME, + FrameworkLogEntry.ERROR, + "Unable to extract content: " + generation.getRevision() + ": " + entry, e); //$NON-NLS-1$ //$NON-NLS-2$ } } finally { releaseOpen(); @@ -283,6 +295,7 @@ public BundleEntry getEntry(String path) { /** * Finds the bundle entry for the specified path + * * @param path the path of the entry to find * @return the entry or {@code null} if no entry exists */ @@ -345,16 +358,20 @@ public void close() throws IOException { if (!closed) { if (referenceCount > 0 && isMruListClosing()) { // there are some opened streams to this BundleFile still; - // wait for them all to close because this is being closed by the MRUBundleFileList + // wait for them all to close because this is being closed by the + // MRUBundleFileList try { refCondition.await(1000, TimeUnit.MICROSECONDS); // timeout after 1 second } catch (InterruptedException e) { // do nothing for now ... } if (referenceCount != 0 || closed) - // either another thread closed the bundle file or we timed waiting for all the reference inputstreams to close - // If the referenceCount did not reach zero then this bundle file will remain open until the - // bundle file is closed explicitly (i.e. bundle is updated/uninstalled or framework is shutdown) + // either another thread closed the bundle file or we timed waiting for all the + // reference inputstreams to close + // If the referenceCount did not reach zero then this bundle file will remain + // open until the + // bundle file is closed explicitly (i.e. bundle is updated/uninstalled or + // framework is shutdown) return; } @@ -373,6 +390,7 @@ public void close() throws IOException { /** * Closes the bundle file + * * @throws IOException if an error occurs closing */ protected abstract void doClose() throws IOException; @@ -447,14 +465,13 @@ void decrementReference() { } /** - * Gets the input stream for the specified entry. - * This method will ensure the bundle file is open, - * call {@link #doGetInputStream(Object)} to get the - * actual input stream, then if the bundle file limit - * is enabled it will wrapper the input stream in a - * special input stream that keeps track of active - * input streams to prevent the bundle file from being - * closed until the stream is closed (or a timeout happens). + * Gets the input stream for the specified entry. This method will ensure the + * bundle file is open, call {@link #doGetInputStream(Object)} to get the actual + * input stream, then if the bundle file limit is enabled it will wrapper the + * input stream in a special input stream that keeps track of active input + * streams to prevent the bundle file from being closed until the stream is + * closed (or a timeout happens). + * * @param entry the entry to get the input stream for * @return the input stream for the entry * @throws IOException @@ -476,8 +493,9 @@ public InputStream getInputStream(E entry) throws IOException { /** * Gets the input stream for the specified entry. - * @param entry the entry to get the input stream for. The type is specified by the - * extending class. + * + * @param entry the entry to get the input stream for. The type is specified by + * the extending class. * @return the input steam for the entry * @throws IOException if an error occurs */ diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/DirBundleFile.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/DirBundleFile.java index cef28b8fd84..69304444e4d 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/DirBundleFile.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/DirBundleFile.java @@ -38,6 +38,7 @@ public class DirBundleFile extends BundleFile { /** * Constructs a DirBundleFile + * * @param basefile the base file * @throws IOException */ @@ -78,7 +79,8 @@ public File getFile(String path, boolean nativeCode) { if (path != null) { isBundleRoot = path.equals("/");//$NON-NLS-1$ if (!isBundleRoot) { - normalize = checkInBundle || path.indexOf(POINTER_SAME_DIRECTORY_1) >= 0 || path.indexOf(POINTER_SAME_DIRECTORY_2) >= 0; + normalize = checkInBundle || path.indexOf(POINTER_SAME_DIRECTORY_1) >= 0 + || path.indexOf(POINTER_SAME_DIRECTORY_2) >= 0; } } File canonicalFile; diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/DirZipBundleEntry.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/DirZipBundleEntry.java index 288f43650f1..55d230868c5 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/DirZipBundleEntry.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/DirZipBundleEntry.java @@ -19,7 +19,7 @@ import java.net.URL; /** - * Represents a directory entry in a ZipBundleFile. This object is used to + * Represents a directory entry in a ZipBundleFile. This object is used to * reference a directory entry in a ZipBundleFile when the directory entries are * not included in the zip file. */ @@ -68,7 +68,7 @@ public URL getLocalURL() { try { return new URL("jar:" + bundleFile.basefile.toURL() + "!/" + name); //$NON-NLS-1$ //$NON-NLS-2$ } catch (MalformedURLException e) { - //This can not happen, unless the jar protocol is not supported. + // This can not happen, unless the jar protocol is not supported. return null; } } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/FileBundleEntry.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/FileBundleEntry.java index 77d605bce13..cc74697ff1d 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/FileBundleEntry.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/FileBundleEntry.java @@ -19,8 +19,8 @@ import java.net.URL; /** - * A BundleEntry represented by a File object. The FileBundleEntry class is - * used for bundles that are installed as extracted zips on a file system. + * A BundleEntry represented by a File object. The FileBundleEntry class is used + * for bundles that are installed as extracted zips on a file system. */ public class FileBundleEntry extends BundleEntry { /** @@ -34,6 +34,7 @@ public class FileBundleEntry extends BundleEntry { /** * Constructs the BundleEntry using a File. + * * @param file BundleFile object this entry is a member of * @param name the name of this BundleEntry */ @@ -81,8 +82,9 @@ public String getName() { /** * Get the modification time for this BundleEntry. - *

    If the modification time has not been set, - * this method will return -1. + *

    + * If the modification time has not been set, this method will return + * -1. * * @return last modification time. */ diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/MRUBundleFileList.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/MRUBundleFileList.java index 799d08f03e9..e2253fa0d16 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/MRUBundleFileList.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/MRUBundleFileList.java @@ -27,10 +27,10 @@ import org.eclipse.osgi.internal.debug.Debug; /** - * A simple/quick/small implementation of an MRU (Most Recently Used) list to keep - * track of open BundleFiles. The MRU will use the file limit specified by the property - * "osgi.bundlefile.limit" by default unless the MRU is constructed with a specific - * file limit. + * A simple/quick/small implementation of an MRU (Most Recently Used) list to + * keep track of open BundleFiles. The MRU will use the file limit specified by + * the property "osgi.bundlefile.limit" by default unless the MRU is + * constructed with a specific file limit. */ public class MRUBundleFileList implements EventDispatcher { private static final int MIN = 10; @@ -72,9 +72,10 @@ public MRUBundleFileList(int fileLimit, Debug debug) { } /** - * Adds a BundleFile which is about to be opened to the MRU list. If - * the number of open BundleFiles == the fileLimit then the least - * recently used BundleFile is closed. + * Adds a BundleFile which is about to be opened to the MRU list. If the number + * of open BundleFiles == the fileLimit then the least recently used BundleFile + * is closed. + * * @param bundleFile the bundle file about to be opened. * @return true if back pressure is needed */ @@ -106,7 +107,8 @@ public boolean add(BundleFile bundleFile) { index = i; toRemove = bundleFileList[index]; if (toRemove.getMruIndex() != index) - throw new IllegalStateException("The BundleFile has the incorrect mru index: " + index + " != " + toRemove.getMruIndex()); //$NON-NLS-1$//$NON-NLS-2$ + throw new IllegalStateException( + "The BundleFile has the incorrect mru index: " + index + " != " + toRemove.getMruIndex()); //$NON-NLS-1$//$NON-NLS-2$ removeInternal(toRemove); backpressureNeeded = isBackPressureNeeded(); } @@ -122,7 +124,8 @@ public boolean add(BundleFile bundleFile) { } } - // must not close the toRemove bundle file while holding the lock of another bundle file (bug 161976) + // must not close the toRemove bundle file while holding the lock of another + // bundle file (bug 161976) // This queues the bundle file for close asynchronously. closeBundleFile(toRemove, manager); @@ -131,6 +134,7 @@ public boolean add(BundleFile bundleFile) { /** * Removes a bundle file which is about to be closed + * * @param bundleFile the bundle file about to be closed * @return true if the bundleFile existed in the MRU; false otherwise */ @@ -158,6 +162,7 @@ private void removeInternal(BundleFile bundleFile) { /** * Increments the use stamp of a bundle file + * * @param bundleFile the bundle file to increment the use stamp for */ public void use(BundleFile bundleFile) { @@ -182,9 +187,11 @@ private void incUseStamp(int index) { } @Override - public final void dispatchEvent(Object eventListener, Object listenerObject, int eventAction, BundleFile eventObject) { + public final void dispatchEvent(Object eventListener, Object listenerObject, int eventAction, + BundleFile eventObject) { if (firstDispatch) { - // used to work around bug 275166; we don't want to leak the TCCL in this thread. + // used to work around bug 275166; we don't want to leak the TCCL in this + // thread. Thread.currentThread().setContextClassLoader(null); firstDispatch = false; } @@ -270,7 +277,9 @@ public void shutdown() { } /** - * Returns true if this MRUBundleFileList is currently closing the specified bundle file on the current thread. + * Returns true if this MRUBundleFileList is currently closing the specified + * bundle file on the current thread. + * * @param bundleFile the bundle file * @return true if the bundle file is being closed on the current thread */ diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/NestedDirBundleFile.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/NestedDirBundleFile.java index 100037a47aa..80ab03adf0d 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/NestedDirBundleFile.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/NestedDirBundleFile.java @@ -21,12 +21,13 @@ import java.util.Enumeration; /** - * A NestedDirBundleFile uses another BundleFile as its source but - * accesses all of its resources relative to a nested directory within - * the other BundleFile object. This is used to support zipped bundles - * that use a Bundle-ClassPath with an nested directory specified. + * A NestedDirBundleFile uses another BundleFile as its source but accesses all + * of its resources relative to a nested directory within the other BundleFile + * object. This is used to support zipped bundles that use a Bundle-ClassPath + * with an nested directory specified. *

    * For Example: + * *

      * Bundle-ClassPath: nested.jar,nesteddir/
      * 
    @@ -38,6 +39,7 @@ public class NestedDirBundleFile extends BundleFile { /** * Constructs a NestedDirBundleFile + * * @param baseBundlefile the base bundle file * @param nestedDirName */ @@ -47,6 +49,7 @@ public NestedDirBundleFile(BundleFile baseBundlefile, String nestedDirName) { /** * Constructs a NestedDirBundleFile + * * @param baseBundlefile the base bundle file * @param nestedDirName * @param filterPrefixes the prefixes to filter out for the bundle file @@ -122,12 +125,12 @@ public Enumeration getEntryPaths(String path, boolean recurse) { return null; return new Enumeration() { - @Override + @Override public boolean hasMoreElements() { return basePaths.hasMoreElements(); } - @Override + @Override public String nextElement() { String next = basePaths.nextElement(); return next.substring(cpLength); @@ -138,7 +141,8 @@ public String nextElement() { @Override public File getFile(String entry, boolean nativeCode) { // getFile is only valid if this is a root bundle file. - // TODO to catch bugs we probably should throw new UnsupportedOperationException() + // TODO to catch bugs we probably should throw new + // UnsupportedOperationException() return null; } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/ZipBundleEntry.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/ZipBundleEntry.java index b15a4cca454..8bcdddd5727 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/ZipBundleEntry.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/ZipBundleEntry.java @@ -22,7 +22,7 @@ import java.util.zip.ZipEntry; /** - * A BundleEntry represented by a ZipEntry in a ZipFile. The ZipBundleEntry + * A BundleEntry represented by a ZipEntry in a ZipFile. The ZipBundleEntry * class is used for bundles that are installed as a ZipFile on a file system. */ public class ZipBundleEntry extends BundleEntry { @@ -38,8 +38,9 @@ public class ZipBundleEntry extends BundleEntry { /** * Constructs the BundleEntry using a ZipEntry. + * * @param bundleFile BundleFile object this entry is a member of - * @param zipEntry ZipEntry object of this entry + * @param zipEntry ZipEntry object of this entry */ ZipBundleEntry(ZipEntry zipEntry, ZipBundleFile bundleFile) { this.zipEntry = zipEntry; @@ -79,8 +80,9 @@ public String getName() { /** * Get the modification time for this BundleEntry. - *

    If the modification time has not been set, - * this method will return -1. + *

    + * If the modification time has not been set, this method will return + * -1. * * @return last modification time. */ @@ -95,7 +97,7 @@ public URL getLocalURL() { try { return new URL("jar:" + bundleFile.basefile.toURL() + "!/" + zipEntry.getName()); //$NON-NLS-1$//$NON-NLS-2$ } catch (MalformedURLException e) { - //This can not happen. + // This can not happen. return null; } } @@ -108,7 +110,7 @@ public URL getFileURL() { if (file != null) return file.toURL(); } catch (MalformedURLException e) { - //This can not happen. + // This can not happen. } return null; } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/ZipBundleFile.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/ZipBundleFile.java index b5ff4ff27c7..39e0b060ddc 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/ZipBundleFile.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/bundlefile/ZipBundleFile.java @@ -52,12 +52,13 @@ protected void doOpen() throws IOException { } /** - * Returns a ZipEntry for the bundle file. Must be called while holding the open lock. - * This method does not ensure that the ZipFile is opened. Callers may need to call getZipfile() prior to calling this - * method. - * @param path the path to an entry - * @return a ZipEntry or null if the entry does not exist - */ + * Returns a ZipEntry for the bundle file. Must be called while holding the open + * lock. This method does not ensure that the ZipFile is opened. Callers may + * need to call getZipfile() prior to calling this method. + * + * @param path the path to an entry + * @return a ZipEntry or null if the entry does not exist + */ private ZipEntry getZipEntry(String path) { if (path.length() > 0 && path.charAt(0) == '/') path = path.substring(1); diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/url/BundleResourceHandler.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/url/BundleResourceHandler.java index 49cf6382e2b..3c360402269 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/url/BundleResourceHandler.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/url/BundleResourceHandler.java @@ -60,7 +60,8 @@ protected void parseURL(URL url, String str, int start, int end) { if (end < start) return; if (url.getPath() != null) - // A call to a URL constructor has been made that uses an authorized URL as its context. + // A call to a URL constructor has been made that uses an authorized URL as its + // context. // Null out bundleEntry because it will not be valid for the new path bundleEntry = null; String spec = ""; //$NON-NLS-1$ @@ -108,7 +109,8 @@ else if (end > pathIdx) { path = ""; //$NON-NLS-1$ // modify path if there's any relative references // see RFC2396 Section 5.2 - // Note: For ".." references above the root the approach taken is removing them from the resolved path + // Note: For ".." references above the root the approach taken is removing them + // from the resolved path if (path.endsWith("/.") || path.endsWith("/..")) //$NON-NLS-1$ //$NON-NLS-2$ path = path + '/'; int dotIndex; @@ -144,14 +146,15 @@ private Module getModule(long id) { } /** - * Establishes a connection to the resource specified by URL. - * Since different protocols may have unique ways of connecting, it must be - * overridden by the subclass. + * Establishes a connection to the resource specified by URL. Since + * different protocols may have unique ways of connecting, it must be overridden + * by the subclass. * * @return java.net.URLConnection * @param url java.net.URL * - * @exception IOException thrown if an IO error occurs during connection establishment + * @exception IOException thrown if an IO error occurs during connection + * establishment */ @Override protected URLConnection openConnection(URL url) throws IOException { @@ -166,7 +169,8 @@ protected URLConnection openConnection(URL url) throws IOException { try { bundleID = parseBundleIDFromURLHost(host); } catch (NumberFormatException nfe) { - throw (MalformedURLException) new MalformedURLException(NLS.bind(Msg.URL_INVALID_BUNDLE_ID, host)).initCause(nfe); + throw (MalformedURLException) new MalformedURLException(NLS.bind(Msg.URL_INVALID_BUNDLE_ID, host)) + .initCause(nfe); } Module module = getModule(bundleID); if (module == null) { @@ -183,11 +187,11 @@ protected URLConnection openConnection(URL url) throws IOException { } /** - * Finds the bundle entry for this protocal. This is handled - * differently for Bundle.gerResource() and Bundle.getEntry() - * because getResource uses the bundle classloader and getEntry - * only used the base bundle file. - * @param url The URL to find the entry for. + * Finds the bundle entry for this protocal. This is handled differently for + * Bundle.gerResource() and Bundle.getEntry() because getResource uses the + * bundle classloader and getEntry only used the base bundle file. + * + * @param url The URL to find the entry for. * @param module the module to find the entry for. * @return the bundle entry */ @@ -196,8 +200,8 @@ protected URLConnection openConnection(URL url) throws IOException { /** * Converts a bundle URL to a String. * - * @param url the URL. - * @return a string representation of the URL. + * @param url the URL. + * @return a string representation of the URL. */ @Override protected String toExternalForm(URL url) { @@ -267,11 +271,10 @@ protected boolean sameFile(URL url1, URL url2) { // do a hashcode test to allow each handler to check the adaptor first if (url1.hashCode() != url2.hashCode()) return false; - return equalsIgnoreCase(url1.getProtocol(), url2.getProtocol()) - && hostsEqual(url1, url2) - && url1.getPort() == url2.getPort() - && Objects.equals(url1.getPath(), url2.getPath()); - // note that the authority is not checked here because it can be different for two + return equalsIgnoreCase(url1.getProtocol(), url2.getProtocol()) && hostsEqual(url1, url2) + && url1.getPort() == url2.getPort() && Objects.equals(url1.getPath(), url2.getPath()); + // note that the authority is not checked here because it can be different for + // two // URLs depending on how they were constructed. } @@ -296,6 +299,7 @@ public static String createURLHostForBundleID(ModuleContainer container, long bu static long parseBundleIDFromURLHost(String host) { int dotIndex = host.indexOf(BID_FWKID_SEPARATOR); - return (dotIndex >= 0 && dotIndex < host.length() - 1) ? Long.parseLong(host.substring(0, dotIndex)) : Long.parseLong(host); + return (dotIndex >= 0 && dotIndex < host.length() - 1) ? Long.parseLong(host.substring(0, dotIndex)) + : Long.parseLong(host); } } diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/url/BundleURLConnection.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/url/BundleURLConnection.java index 5b2d0ba1b7c..6094e671f01 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/url/BundleURLConnection.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/url/BundleURLConnection.java @@ -45,8 +45,8 @@ public class BundleURLConnection extends URLConnection implements BundleReferenc /** * Constructor for a BundleClassLoader resource URLConnection. * - * @param url URL for this URLConnection. - * @param bundleEntry BundleEntry that the URLConnection is associated. + * @param url URL for this URLConnection. + * @param bundleEntry BundleEntry that the URLConnection is associated. */ public BundleURLConnection(URL url, ModuleContainer container, BundleEntry bundleEntry) { super(url); @@ -128,6 +128,7 @@ public long getLastModified() { /** * Converts the URL to a common local URL protocol (i.e file: or jar: protocol) + * * @return the local URL using a common local protocol */ public URL getLocalURL() { @@ -136,8 +137,10 @@ public URL getLocalURL() { } /** - * Converts the URL to a URL that uses the file: protocol. The content of this - * URL may be downloaded or extracted onto the local filesystem to create a file URL. + * Converts the URL to a URL that uses the file: protocol. The content of this + * URL may be downloaded or extracted onto the local filesystem to create a file + * URL. + * * @return the local URL that uses the file: protocol */ public URL getFileURL() { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/url/BundleURLConverter.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/url/BundleURLConverter.java index d3aa6d9bf26..a9b3c63295e 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/url/BundleURLConverter.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/url/BundleURLConverter.java @@ -21,24 +21,30 @@ import org.eclipse.osgi.util.NLS; /** - * The service implementation that allows bundleresource or bundleentry - * URLs to be converted to native file URLs on the local file system. + * The service implementation that allows bundleresource or bundleentry URLs to + * be converted to native file URLs on the local file system. * - *

    Internal class.

    + *

    + * Internal class. + *

    */ public class BundleURLConverter implements URLConverter { - /* (non-Javadoc) - * @see org.eclipse.osgi.service.urlconversion.URLConverter#toFileURL(java.net.URL) + /* + * (non-Javadoc) + * + * @see + * org.eclipse.osgi.service.urlconversion.URLConverter#toFileURL(java.net.URL) */ @Override public URL toFileURL(URL url) throws IOException { URLConnection connection = url.openConnection(); if (connection instanceof BundleURLConnection) { URL result = ((BundleURLConnection) connection).getFileURL(); - /* If we got a connection then we know the resource exists in - * the bundle but if connection.getFileURL returned null then there - * was a problem extracting the file to disk. See bug 259241. + /* + * If we got a connection then we know the resource exists in the bundle but if + * connection.getFileURL returned null then there was a problem extracting the + * file to disk. See bug 259241. **/ if (result == null) throw new IOException(NLS.bind(Msg.ECLIPSE_PLUGIN_EXTRACTION_PROBLEM, url)); @@ -47,8 +53,11 @@ public URL toFileURL(URL url) throws IOException { return url; } - /* (non-Javadoc) - * @see org.eclipse.osgi.service.urlconversion.URLConverter#resolve(java.net.URL) + /* + * (non-Javadoc) + * + * @see + * org.eclipse.osgi.service.urlconversion.URLConverter#resolve(java.net.URL) */ @Override public URL resolve(URL url) throws IOException { diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/url/reference/Handler.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/url/reference/Handler.java index 93c1e36089f..31c129df737 100644 --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/url/reference/Handler.java +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/url/reference/Handler.java @@ -18,12 +18,14 @@ import java.net.*; /** - * URLStreamHandler for reference protocol. A reference URL is used to hold a - * reference to a local file URL. A reference URL allows bundles to be installed - * by reference. This means the content of the bundle will not be copied. Instead - * the content of the bundle will be loaded from the reference location specified - * by the reference URL. The Framework only supports reference URLs that refer - * to a local file URL. For example:

    + * URLStreamHandler for reference protocol. A reference URL is used to hold a + * reference to a local file URL. A reference URL allows bundles to be installed + * by reference. This means the content of the bundle will not be copied. + * Instead the content of the bundle will be loaded from the reference location + * specified by the reference URL. The Framework only supports reference URLs + * that refer to a local file URL. For example: + *

    + * *

      *     reference:file:/eclipse/plugins/org.eclipse.myplugin_1.0.0/
      *     reference:file:/eclispe/plugins/org.eclipse.mybundle_1.0.0.jar
    diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/url/reference/ReferenceInputStream.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/url/reference/ReferenceInputStream.java
    index 1ce4ba33c0e..c5673e5da78 100644
    --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/url/reference/ReferenceInputStream.java
    +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/storage/url/reference/ReferenceInputStream.java
    @@ -20,8 +20,8 @@
     import org.eclipse.osgi.storage.ContentProvider;
     
     /**
    - * InputStream subclass which provides a reference (via File) to the data
    - * rather than allowing the input stream to be directly read.
    + * InputStream subclass which provides a reference (via File) to the data rather
    + * than allowing the input stream to be directly read.
      */
     public class ReferenceInputStream extends InputStream implements ContentProvider {
     	private final File reference;
    @@ -30,7 +30,8 @@ public ReferenceInputStream(File reference) {
     		this.reference = reference;
     	}
     
    -	/* This method should not be called.
    +	/*
    +	 * This method should not be called.
     	 */
     	@Override
     	public int read() throws IOException {
    diff --git a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/util/TextProcessor.java b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/util/TextProcessor.java
    index f871c4c3c5e..0146169e764 100644
    --- a/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/util/TextProcessor.java
    +++ b/bundles/org.eclipse.osgi/container/src/org/eclipse/osgi/util/TextProcessor.java
    @@ -80,20 +80,19 @@ public class TextProcessor {
     
     		if ("iw".equals(lang) || "he".equals(lang) || "ar".equals(lang) || "fa".equals(lang) || "ur".equals(lang)) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
     			String osName = System.getProperty("os.name").toLowerCase(); //$NON-NLS-1$
    -			if (osName.startsWith("windows") || osName.startsWith("linux") || osName.startsWith("mac") || osName.startsWith("freebsd")) { //$NON-NLS-1$	//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
    +			if (osName.startsWith("windows") || osName.startsWith("linux") || osName.startsWith("mac") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    +					|| osName.startsWith("freebsd")) { //$NON-NLS-1$
     				IS_PROCESSING_NEEDED = true;
     			}
     		}
     	}
     
     	/**
    -	 * Process the given text and return a string with the appropriate
    -	 * substitution based on the locale. This is equivalent to calling
    -	 * process(String, String) with the default set of
    -	 * delimiters.
    +	 * Process the given text and return a string with the appropriate substitution
    +	 * based on the locale. This is equivalent to calling
    +	 * process(String, String) with the default set of delimiters.
     	 *
    -	 * @param text
    -	 *            the text to be processed
    +	 * @param text the text to be processed
     	 * @return the manipulated string
     	 * @see #process(String, String)
     	 * @see #getDefaultDelimiters()
    @@ -106,51 +105,48 @@ public static String process(String text) {
     
     	/**
     	 * Process a string that has a particular semantic meaning to render on BiDi
    -	 * locales in way that maintains the semantic meaning of the text, but
    -	 * differs from the Unicode BiDi algorithm. The text is segmented according
    -	 * to the provided delimiters. Each segment has the Unicode BiDi algorithm
    -	 * applied to it, but as a whole, the string is oriented left to right.
    +	 * locales in way that maintains the semantic meaning of the text, but differs
    +	 * from the Unicode BiDi algorithm. The text is segmented according to the
    +	 * provided delimiters. Each segment has the Unicode BiDi algorithm applied to
    +	 * it, but as a whole, the string is oriented left to right.
     	 * 

    * For example a file path such as d:\myFolder\FOLDER\MYFILE.java * (where capital letters indicate RTL text) should render as * d:\myFolder\REDLOF\ELIFYM.java when using the Unicode BiDi - * algorithm and segmenting the string according to the specified delimiter - * set. + * algorithm and segmenting the string according to the specified delimiter set. *

    *

    * The following algorithm is used: *

    *
      *
    1. Scan the string to locate the delimiters.
    2. - *
    3. While scanning, note the direction of the last strong character - * scanned. Strong characters are characters which have a BiDi - * classification of L, R or AL as defined in the Unicode standard.
    4. - *
    5. If the last strong character before a separator is of class R or AL, - * add a LRM before the separator. Since LRM itself is a strong L character, - * following separators do not need an LRM until a strong R or AL character - * is found.
    6. + *
    7. While scanning, note the direction of the last strong character scanned. + * Strong characters are characters which have a BiDi classification of L, R or + * AL as defined in the Unicode standard.
    8. + *
    9. If the last strong character before a separator is of class R or AL, add + * a LRM before the separator. Since LRM itself is a strong L character, + * following separators do not need an LRM until a strong R or AL character is + * found.
    10. *
    11. If the component where the pattern is displayed has a RTL basic - * direction, add a LRE at the beginning of the pattern and a PDF at its - * end. The string is considered to have RTL direction if it contains RTL - * characters and the runtime locale is BiDi. There is no need to add - * LRE/PDF if the string begins with an LTR letter, contains no RTL letter, - * and ends with either a LTR letter or a digit.
    12. + * direction, add a LRE at the beginning of the pattern and a PDF at its end. + * The string is considered to have RTL direction if it contains RTL characters + * and the runtime locale is BiDi. There is no need to add LRE/PDF if the string + * begins with an LTR letter, contains no RTL letter, and ends with either a LTR + * letter or a digit. *
    *

    - * NOTE: this method will change the shape of the original string passed in - * by inserting punctuation characters into the text in order to make it - * render to correctly reflect the semantic meaning of the text. Methods - * like String.equals(String) and - * String.length() called on the resulting string will not - * return the same values as would be returned for the original string. + * NOTE: this method will change the shape of the original string passed in by + * inserting punctuation characters into the text in order to make it render to + * correctly reflect the semantic meaning of the text. Methods like + * String.equals(String) and String.length() called on + * the resulting string will not return the same values as would be returned for + * the original string. *

    * - * @param str - * the text to process, if null return the string - * as it was passed in - * @param delimiter - * delimiters by which the string will be segmented, if - * null the default delimiters are used + * @param str the text to process, if null return the string + * as it was passed in + * @param delimiter delimiters by which the string will be segmented, if + * null the default delimiters are used * @return the processed string */ public static String process(String str, String delimiter) { @@ -209,13 +205,11 @@ public static String process(String str, String delimiter) { target.append(ch); } /* - * TextProcessor is not aware of the orientation of the component owning - * the processed string. Enclose the string in LRE/PDF in either of 2 - * cases: - * (1) The string contains BiDi characters - implying that the - * string appearance depends on the basic orientation - * (2) The runtime locale is BiDi AND either the string does not start with - * an LTR character or it ends with LTR char or digit. + * TextProcessor is not aware of the orientation of the component owning the + * processed string. Enclose the string in LRE/PDF in either of 2 cases: (1) The + * string contains BiDi characters - implying that the string appearance depends + * on the basic orientation (2) The runtime locale is BiDi AND either the string + * does not start with an LTR character or it ends with LTR char or digit. */ if (isStringBidi || !Character.isLetter(str.charAt(0)) || isNeutral(str.charAt(str.length() - 1))) { target.append(PDF); @@ -226,9 +220,9 @@ public static String process(String str, String delimiter) { } /** - * Removes directional marker characters in the given string that were inserted by - * utilizing the process(String) or process(String, String) - * methods. + * Removes directional marker characters in the given string that were inserted + * by utilizing the process(String) or + * process(String, String) methods. * * @param str string with directional markers to remove * @return string with no directional markers @@ -244,14 +238,14 @@ public static String deprocess(String str) { for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); switch (c) { - case LRE : - continue; - case PDF : - continue; - case LRM : - continue; - default : - buf.append(c); + case LRE: + continue; + case PDF: + continue; + case LRM: + continue; + default: + buf.append(c); } } @@ -259,8 +253,8 @@ public static String deprocess(String str) { } /** - * Return the string containing all the default delimiter characters to be - * used to segment a given string. + * Return the string containing all the default delimiter characters to be used + * to segment a given string. * * @return delimiter string */ @@ -273,12 +267,11 @@ public static String getDefaultDelimiters() { */ private static boolean isRTL(char c) { /* - * Cannot use Character.getDirectionality() since the OSGi library can - * be compiled with execution environments that pre-date that API. + * Cannot use Character.getDirectionality() since the OSGi library can be + * compiled with execution environments that pre-date that API. * - * The first range of characters is Unicode Hebrew and Arabic - * characters. The second range of characters is Unicode Hebrew and - * Arabic presentation forms. + * The first range of characters is Unicode Hebrew and Arabic characters. The + * second range of characters is Unicode Hebrew and Arabic presentation forms. * * NOTE: Farsi and Urdu fall within the Arabic scripts. */