Skip to main content
summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorThomas Watson2012-06-13 14:04:56 +0000
committerThomas Watson2012-07-16 21:03:11 +0000
commit7e980cfb94c1eb742bf1c9986055e70373f76392 (patch)
treef652dd6795661a52dc837fe11cc2db363cc35903 /bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi
parentf843e83246bb55c8e035fb0fa3e5515516070cd2 (diff)
downloadrt.equinox.framework-7e980cfb94c1eb742bf1c9986055e70373f76392.tar.gz
rt.equinox.framework-7e980cfb94c1eb742bf1c9986055e70373f76392.tar.xz
rt.equinox.framework-7e980cfb94c1eb742bf1c9986055e70373f76392.zip
Consolidate the source folders
Diffstat (limited to 'bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi')
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/event/BatchBundleListener.java63
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/console/CommandInterpreter.java91
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/console/CommandProvider.java46
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/console/ConsoleSession.java95
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/console/package.html17
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/AbstractBundle.java1545
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/AliasMapper.java155
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/BundleContextImpl.java974
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/BundleFragment.java334
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/BundleHost.java686
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/BundleRepository.java196
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/BundleSource.java45
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/Constants.java254
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/CoreResolverHookFactory.java216
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/EquinoxLauncher.java347
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/ExportedPackageImpl.java99
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/FilterImpl.java1751
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/Framework.java2007
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/InternalSystemBundle.java433
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/ManifestLocalization.java241
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/PackageAdminImpl.java766
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/StartLevelEvent.java82
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/StartLevelManager.java678
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/SystemBundleActivator.java110
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/UniversalUniqueIdentifier.java270
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/Util.java208
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/osname.aliases46
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/processor.aliases28
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/ContentHandlerFactory.java163
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/ContentHandlerProxy.java152
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/MultiplexingContentHandler.java33
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/MultiplexingFactory.java173
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/MultiplexingURLStreamHandler.java247
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/NullURLStreamHandlerService.java74
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/ProtocolActivator.java22
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/StreamHandlerFactory.java223
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/URLStreamHandlerFactoryProxyFor15.java41
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/URLStreamHandlerProxy.java218
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/URLStreamHandlerSetter.java39
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/BundleLoader.java1270
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/BundleLoaderProxy.java247
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/FilteredSourcePackage.java112
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/MultiSourcePackage.java67
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/NullPackageSource.java70
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/PackageSource.java81
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/SingleSourcePackage.java69
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/SystemBundleLoader.java277
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/buddy/DependentPolicy.java119
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/buddy/GlobalPolicy.java70
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/buddy/IBuddyPolicy.java22
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/buddy/PolicyHandler.java219
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/buddy/RegisteredPolicy.java121
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/buddy/SystemPolicy.java93
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/BundlePermissions.java77
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/EquinoxSecurityManager.java192
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/PermissionAdminTable.java50
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/PermissionInfoCollection.java132
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/PermissionsHash.java103
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/SecurePermissionStorage.java109
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/SecurityAdmin.java874
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/SecurityRow.java457
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/SecurityRowSnapShot.java85
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/SecurityTable.java133
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/SecurityTableUpdate.java44
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/default.permissions25
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/implied.permissions50
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/profile/DefaultProfileLogger.java391
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/profile/Profile.java268
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/profile/ProfileLogger.java42
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/FilteredServiceListener.java205
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/HookContext.java49
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ModifiedServiceEvent.java71
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ServiceProperties.java186
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ServiceReferenceImpl.java275
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ServiceRegistrationImpl.java650
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ServiceRegistry.java1362
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ServiceUse.java294
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ShrinkableCollection.java196
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ShrinkableEntrySetValueCollection.java65
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ShrinkableValueCollectionMap.java191
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/launch/Equinox.java301
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/launch/EquinoxFWClassLoader.java71
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/launch/EquinoxFactory.java27
-rw-r--r--bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/launch/package.html17
84 files changed, 0 insertions, 22997 deletions
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/event/BatchBundleListener.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/event/BatchBundleListener.java
deleted file mode 100644
index a8dd74a8a..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/event/BatchBundleListener.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.event;
-
-import org.osgi.framework.*;
-
-/**
- * A batch <code>BundleEvent</code> listener.
- *
- * <p>
- * <code>BatchBundleListener</code> is a listener interface that may be
- * implemented by a bundle developer.
- * <p>
- * A <code>BatchBundleListener</code> object is registered with the
- * Framework using the {@link BundleContext#addBundleListener} method.
- * <code>BatchBundleListener</code> objects are called with a
- * <code>BundleEvent</code> object when a bundle has been installed, resolved,
- * started, stopped, updated, unresolved, or uninstalled.
- * <p>
- * A <code>BatchBundleListener</code> acts like a <code>BundleListener</code>
- * except the framework will call the {@link #batchBegin()} method at the beginning
- * of a batch process and call the {@link #batchEnd()} at the end of a batch
- * process. For example, the framework may notify a <code>BatchBundleListener</code>
- * of a batching process during a refresh packages operation or a resolve bundles
- * operation.
- * <p>
- * During a batching operation the framework will continue to deliver any events using
- * the {@link BundleListener#bundleChanged(BundleEvent)} method to the
- * <code>BatchBundleListener</code>. It is the responsiblity of the
- * <code>BatchBundleListener</code> to decide how to handle events when a
- * batching operation is in progress.
- * <p>
- * Note that the framework does not guarantee that batching operations will not
- * overlap. This can result in the method {@link #batchBegin()} being called
- * multiple times before the first {@link #batchEnd()} is called.
- *
- * <p>
- * Clients may implement this interface.
- * </p>
- * @since 3.1
- * @see BundleEvent
- * @see BundleListener
- */
-public interface BatchBundleListener extends BundleListener {
- /**
- * Indicates that a batching process has begun.
- */
- public abstract void batchBegin();
-
- /**
- * Indicates that a batching process has ended.
- */
- public abstract void batchEnd();
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/console/CommandInterpreter.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/console/CommandInterpreter.java
deleted file mode 100644
index 627d98180..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/console/CommandInterpreter.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.framework.console;
-
-import java.util.Dictionary;
-import org.osgi.framework.Bundle;
-
-/**
- * A command interpreter is a shell that can interpret command
- * lines. This object is passed as parameter when a CommandProvider
- * is invoked.
- * <p>
- * This interface is not intended to be implemented by clients.
- * </p>
- * @since 3.1
- * @noimplement This interface is not intended to be implemented by clients.
- */
-public interface CommandInterpreter {
- /**
- * Get the next argument in the input. If no arguments are left then null is returned.
- *
- * E.g. if the commandline is hello world, the _hello method
- * will get "world" as the first argument.
- * @return the next argument or null if no arguments are left.
- */
- public String nextArgument();
-
- /**
- * Execute a command line as if it came from the end user
- * and return the result.
- * @param cmd The command line to execute.
- * @return the result of the command.
- */
- public Object execute(String cmd);
-
- /**
- * Prints an object to the outputstream
- *
- * @param o the object to be printed
- */
- public void print(Object o);
-
- /**
- * Prints an empty line to the outputstream
- */
- public void println();
-
- /**
- * Prints an object to the output medium (appended with newline character).
- * <p>
- * If running on the target environment the user is prompted with '--more'
- * if more than the configured number of lines have been printed without user prompt.
- * That way the user of the program has control over the scrolling.
- * <p>
- * For this to work properly you should not embedded "\n" etc. into the string.
- *
- * @param o the object to be printed
- */
- public void println(Object o);
-
- /**
- * Print a stack trace including nested exceptions.
- * @param t The offending exception
- */
- public void printStackTrace(Throwable t);
-
- /**
- * Prints the given dictionary sorted by keys.
- *
- * @param dic the dictionary to print
- * @param title the header to print above the key/value pairs
- */
- public void printDictionary(Dictionary<?, ?> dic, String title);
-
- /**
- * Prints the given bundle resource if it exists
- *
- * @param bundle the bundle containing the resource
- * @param resource the resource to print
- */
- public void printBundleResource(Bundle bundle, String resource);
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/console/CommandProvider.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/console/CommandProvider.java
deleted file mode 100644
index a176cb392..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/console/CommandProvider.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2006 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.framework.console;
-
-/**
- When an object wants to provide a number of commands
- to the console, it should register an object with this
- interface. Some console can then pick this up and execute
- command lines.
- The SERVICE_RANKING registration property can be used to influence the
- order that a CommandProvider gets called. Specify a value less than
- Integer.MAXVALUE, where higher is more significant. The default value
- if SERVICE_RANKING is not set is 0.
- <p>
- The interface contains only methods for the help.
- The console should use inspection
- to find the commands. All public commands, starting with
- a '_' and taking a CommandInterpreter as parameter
- will be found. E.g.
- <pre>
- public Object _hello( CommandInterpreter intp ) {
- return "hello " + intp.nextArgument();
- }
- </pre>
- * <p>
- * Clients may implement this interface.
- * </p>
- * @since 3.1
- */
-public interface CommandProvider {
- /**
- Answer a string (may be as many lines as you like) with help
- texts that explain the command.
- */
- public String getHelp();
-
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/console/ConsoleSession.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/console/ConsoleSession.java
deleted file mode 100644
index 4ad021ca0..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/console/ConsoleSession.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2009, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.osgi.framework.console;
-
-import java.io.InputStream;
-import java.io.OutputStream;
-import org.osgi.framework.*;
-
-/**
- * A console session service provides the input and output to a single console session.
- * The input will be used by the console to read in console commands. The output will
- * be used to print the results of console commands.
- * <p>
- * The console session must be registered as an OSGi service in order to be associated
- * with a console instance. The console implementation will discover any console session
- * services and will create a new console instance using the console session for input and
- * output. When a session is closed then the console session service will be unregistered
- * and the console instance will terminate and be disposed of. The console instance will
- * also terminate if the console session service is unregistered for any reason.
- * </p>
- * @since 3.6
- */
-public abstract class ConsoleSession implements ServiceFactory<Object> {
- private volatile ServiceRegistration<Object> sessionRegistration;
-
- /**
- * Called by the console implementation to free resources associated
- * with this console session. This method will result in the console
- * session service being unregistered from the service registry.
- * @noreference This method is not intended to be referenced by clients.
- */
- public final void close() {
- doClose();
- ServiceRegistration<Object> current = sessionRegistration;
- if (current != null) {
- sessionRegistration = null;
- try {
- current.unregister();
- } catch (IllegalStateException e) {
- // This can happen if the service is in the process of being
- // unregistered or if another thread unregistered the service.
- // Ignoring the exception.
- }
- }
- }
-
- /**
- * Called by the {@link #close()} method to free resources associated
- * with this console session. For example, closing the streams
- * associated with the input and output for this session.
- * @noreference This method is not intended to be referenced by clients.
- */
- protected abstract void doClose();
-
- /**
- * Returns the input for this console session. This input will be used
- * to read console commands from the user of the session.
- * @return the input for this console session
- * @noreference This method is not intended to be referenced by clients.
- */
- public abstract InputStream getInput();
-
- /**
- * Returns the output for this console session. This output will be
- * used to write the results of console commands.
- * @return the output for this console session.
- * @noreference This method is not intended to be referenced by clients.
- */
- public abstract OutputStream getOutput();
-
- /**
- * @noreference This method is not intended to be referenced by clients.
- */
- public final Object getService(Bundle bundle, ServiceRegistration<Object> registration) {
- if (sessionRegistration == null)
- sessionRegistration = registration;
- return this;
- }
-
- /**
- * @noreference This method is not intended to be referenced by clients.
- */
- public final void ungetService(Bundle bundle, ServiceRegistration<Object> registration, Object service) {
- // do nothing
- }
-
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/console/package.html b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/console/package.html
deleted file mode 100644
index d140bf5b7..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/console/package.html
+++ /dev/null
@@ -1,17 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
-<html>
-<head>
- <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
- <title>Package-level Javadoc</title>
-</head>
-<body>
-Provides services related to the Equinox console.
-<h2>
-Package Specification</h2>
-This package specifies the API for services related to the Equinox console.
-<p>
-Clients which provide commands or provide sessions to the Equinox console
-will likely be interested in the types provided by this package.
-</p>
-</body>
-</html>
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/AbstractBundle.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/AbstractBundle.java
deleted file mode 100644
index d2b51fd00..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/AbstractBundle.java
+++ /dev/null
@@ -1,1545 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2012 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.osgi.framework.internal.core;
-
-import java.io.*;
-import java.net.URL;
-import java.net.URLConnection;
-import java.security.*;
-import java.security.cert.Certificate;
-import java.security.cert.X509Certificate;
-import java.util.*;
-import org.eclipse.osgi.framework.adaptor.*;
-import org.eclipse.osgi.framework.debug.Debug;
-import org.eclipse.osgi.framework.util.KeyedElement;
-import org.eclipse.osgi.internal.loader.BundleLoader;
-import org.eclipse.osgi.internal.permadmin.EquinoxSecurityManager;
-import org.eclipse.osgi.service.resolver.BundleDescription;
-import org.eclipse.osgi.service.resolver.ResolverError;
-import org.eclipse.osgi.signedcontent.*;
-import org.eclipse.osgi.util.NLS;
-import org.osgi.framework.*;
-import org.osgi.framework.hooks.bundle.CollisionHook;
-import org.osgi.framework.startlevel.BundleStartLevel;
-import org.osgi.framework.wiring.*;
-
-/**
- * This object is given out to bundles and wraps the internal Bundle object. It
- * is destroyed when a bundle is uninstalled and reused if a bundle is updated.
- * This class is abstract and is extended by BundleHost and BundleFragment.
- */
-public abstract class AbstractBundle implements Bundle, Comparable<Bundle>, KeyedElement, BundleStartLevel, BundleReference, BundleRevisions {
- private final static long STATE_CHANGE_TIMEOUT;
- static {
- long stateChangeWait = 5000;
- try {
- String prop = FrameworkProperties.getProperty("equinox.statechange.timeout"); //$NON-NLS-1$
- if (prop != null)
- stateChangeWait = Long.parseLong(prop);
- } catch (Throwable t) {
- // use default 5000
- stateChangeWait = 5000;
- }
- STATE_CHANGE_TIMEOUT = stateChangeWait;
- }
- /** The Framework this bundle is part of */
- protected final Framework framework;
- /** The state of the bundle. */
- protected volatile int state;
- /** A flag to denote whether a bundle state change is in progress */
- protected volatile Thread stateChanging;
- /** Bundle's BundleData object */
- protected BundleData bundledata;
- /** Internal object used for state change synchronization */
- protected final Object statechangeLock = new Object();
- /** ProtectionDomain for the bundle */
- protected BundleProtectionDomain domain;
-
- volatile protected ManifestLocalization manifestLocalization = null;
-
- /**
- * Bundle object constructor. This constructor should not perform any real
- * work.
- *
- * @param bundledata
- * BundleData for this bundle
- * @param framework
- * Framework this bundle is running in
- */
- protected static AbstractBundle createBundle(BundleData bundledata, Framework framework, boolean setBundle) throws BundleException {
- AbstractBundle result;
- if ((bundledata.getType() & BundleData.TYPE_FRAGMENT) > 0)
- result = new BundleFragment(bundledata, framework);
- else
- result = new BundleHost(bundledata, framework);
- if (setBundle)
- bundledata.setBundle(result);
- return result;
- }
-
- /**
- * Bundle object constructor. This constructor should not perform any real
- * work.
- *
- * @param bundledata
- * BundleData for this bundle
- * @param framework
- * Framework this bundle is running in
- */
- protected AbstractBundle(BundleData bundledata, Framework framework) {
- state = INSTALLED;
- stateChanging = null;
- this.bundledata = bundledata;
- this.framework = framework;
- }
-
- /**
- * Load the bundle.
- */
- protected abstract void load();
-
- /**
- * Reload from a new bundle. This method must be called while holding the
- * bundles lock.
- *
- * @param newBundle
- * Dummy Bundle which contains new data.
- * @return true if an exported package is "in use". i.e. it has been
- * imported by a bundle
- */
- protected abstract boolean reload(AbstractBundle newBundle);
-
- /**
- * Refresh the bundle. This is called by Framework.refreshPackages. This
- * method must be called while holding the bundles lock.
- * this.loader.unimportPackages must have already been called before
- * calling this method!
- */
- protected abstract void refresh();
-
- /**
- * Unload the bundle. This method must be called while holding the bundles
- * lock.
- *
- * @return true if an exported package is "in use". i.e. it has been
- * imported by a bundle
- */
- protected abstract boolean unload();
-
- /**
- * Close the the Bundle's file.
- *
- */
- protected void close() {
- if (Debug.DEBUG_GENERAL) {
- if ((state & (INSTALLED)) == 0) {
- Debug.println("Bundle.close called when state != INSTALLED: " + this); //$NON-NLS-1$
- Debug.printStackTrace(new Exception("Stack trace")); //$NON-NLS-1$
- }
- }
- state = UNINSTALLED;
- }
-
- /**
- * Load and instantiate bundle's BundleActivator class
- */
- protected BundleActivator loadBundleActivator() throws BundleException {
- /* load Bundle's BundleActivator if it has one */
- String activatorClassName = bundledata.getActivator();
- if (activatorClassName != null) {
- try {
- Class<?> activatorClass = loadClass(activatorClassName, false);
- /* Create the activator for the bundle */
- return (BundleActivator) (activatorClass.newInstance());
- } catch (Throwable t) {
- if (Debug.DEBUG_GENERAL) {
- Debug.printStackTrace(t);
- }
- throw new BundleException(NLS.bind(Msg.BUNDLE_INVALID_ACTIVATOR_EXCEPTION, activatorClassName, bundledata.getSymbolicName()), BundleException.ACTIVATOR_ERROR, t);
- }
- }
- return (null);
- }
-
- /**
- * This method loads a class from the bundle.
- *
- * @param name
- * the name of the desired Class.
- * @param checkPermission
- * indicates whether a permission check should be done.
- * @return the resulting Class
- * @exception java.lang.ClassNotFoundException
- * if the class definition was not found.
- */
- protected abstract Class<?> loadClass(String name, boolean checkPermission) throws ClassNotFoundException;
-
- /**
- * Returns the current state of the bundle.
- *
- * A bundle can only be in one state at any time.
- *
- * @return bundle's state.
- */
- public int getState() {
- return (state);
- }
-
- public Framework getFramework() {
- return framework;
- }
-
- /**
- * Return true if the bundle is starting or active.
- *
- */
- protected boolean isActive() {
- return ((state & (ACTIVE | STARTING)) != 0);
- }
-
- boolean isLazyStart() {
- int status = bundledata.getStatus();
- return (status & Constants.BUNDLE_ACTIVATION_POLICY) != 0 && (status & Constants.BUNDLE_LAZY_START) != 0;
- }
-
- /**
- * Return true if the bundle is resolved.
- *
- */
- public boolean isResolved() {
- return (state & (INSTALLED | UNINSTALLED)) == 0;
- }
-
- /**
- * Start this bundle.
- *
- * If the current start level is less than this bundle's start level, then
- * the Framework must persistently mark this bundle as started and delay
- * the starting of this bundle until the Framework's current start level
- * becomes equal or more than the bundle's start level.
- * <p>
- * Otherwise, the following steps are required to start a bundle:
- * <ol>
- * <li>If the bundle is {@link #UNINSTALLED}then an <code>IllegalStateException</code>
- * is thrown.
- * <li>If the bundle is {@link #ACTIVE}or {@link #STARTING}then this
- * method returns immediately.
- * <li>If the bundle is {@link #STOPPING}then this method may wait for
- * the bundle to return to the {@link #RESOLVED}state before continuing.
- * If this does not occur in a reasonable time, a {@link BundleException}
- * is thrown to indicate the bundle was unable to be started.
- * <li>If the bundle is not {@link #RESOLVED}, an attempt is made to
- * resolve the bundle. If the bundle cannot be resolved, a
- * {@link BundleException}is thrown.
- * <li>The state of the bundle is set to {@link #STARTING}.
- * <li>The {@link BundleActivator#start(BundleContext) start}method of the bundle's
- * {@link BundleActivator}, if one is specified, is called. If the
- * {@link BundleActivator}is invalid or throws an exception, the state of
- * the bundle is set back to {@link #RESOLVED}, the bundle's listeners, if
- * any, are removed, service's registered by the bundle, if any, are
- * unregistered, and service's used by the bundle, if any, are released. A
- * {@link BundleException}is then thrown.
- * <li>It is recorded that this bundle has been started, so that when the
- * framework is restarted, this bundle will be automatically started.
- * <li>The state of the bundle is set to {@link #ACTIVE}.
- * <li>A {@link BundleEvent}of type {@link BundleEvent#STARTED}is
- * broadcast.
- * </ol>
- *
- * <h5>Preconditons</h5>
- * <ul>
- * <li>getState() in {{@link #INSTALLED},{@link #RESOLVED}}.
- * </ul>
- * <h5>Postconditons, no exceptions thrown</h5>
- * <ul>
- * <li>getState() in {{@link #ACTIVE}}.
- * <li>{@link BundleActivator#start(BundleContext) BundleActivator.start}has been called
- * and did not throw an exception.
- * </ul>
- * <h5>Postconditions, when an exception is thrown</h5>
- * <ul>
- * <li>getState() not in {{@link #STARTING},{@link #ACTIVE}}.
- * </ul>
- *
- * @exception BundleException
- * If the bundle couldn't be started. This could be because
- * a code dependency could not be resolved or the specified
- * BundleActivator could not be loaded or threw an
- * exception.
- * @exception java.lang.IllegalStateException
- * If the bundle has been uninstalled or the bundle tries to
- * change its own state.
- * @exception java.lang.SecurityException
- * If the caller does not have {@link AdminPermission}
- * permission and the Java runtime environment supports
- * permissions.
- */
- public void start() throws BundleException {
- start(0);
- }
-
- public void start(int options) throws BundleException {
- framework.checkAdminPermission(this, AdminPermission.EXECUTE);
- checkValid();
- beginStateChange();
- try {
- startWorker(options);
- } finally {
- completeStateChange();
- }
- }
-
- /**
- * Internal worker to start a bundle.
- *
- * @param options
- */
- protected abstract void startWorker(int options) throws BundleException;
-
- /**
- * This method does the following
- * <ol>
- * <li> Return false if the bundle is a fragment
- * <li> Return false if the bundle is not at the correct start-level
- * <li> Return false if the bundle is not persistently marked for start
- * <li> Return true if the bundle's activation policy is persistently ignored
- * <li> Return true if the bundle does not define an activation policy
- * <li> Transition to STARTING state and Fire LAZY_ACTIVATION event
- * <li> Return false
- * </ol>
- * @return true if the bundle should be resumed
- */
- protected boolean readyToResume() {
- return false;
- }
-
- /**
- * Start this bundle w/o marking is persistently started.
- *
- * <p>
- * The following steps are followed to start a bundle:
- * <ol>
- * <li>If the bundle is {@link #UNINSTALLED}then an <code>IllegalStateException</code>
- * is thrown.
- * <li>If the bundle is {@link #ACTIVE}or {@link #STARTING}then this
- * method returns immediately.
- * <li>If the bundle is {@link #STOPPING}then this method may wait for
- * the bundle to return to the {@link #RESOLVED}state before continuing.
- * If this does not occur in a reasonable time, a {@link BundleException}
- * is thrown to indicate the bundle was unable to be started.
- * <li>If the bundle is not {@link #RESOLVED}, an attempt is made to
- * resolve the bundle. If the bundle cannot be resolved, a
- * {@link BundleException}is thrown.
- * <li>The state of the bundle is set to {@link #STARTING}.
- * <li>The {@link BundleActivator#start(BundleContext) start}method of the bundle's
- * {@link BundleActivator}, if one is specified, is called. If the
- * {@link BundleActivator}is invalid or throws an exception, the state of
- * the bundle is set back to {@link #RESOLVED}, the bundle's listeners, if
- * any, are removed, service's registered by the bundle, if any, are
- * unregistered, and service's used by the bundle, if any, are released. A
- * {@link BundleException}is then thrown.
- * <li>The state of the bundle is set to {@link #ACTIVE}.
- * <li>A {@link BundleEvent}of type {@link BundleEvent#STARTED}is
- * broadcast.
- * </ol>
- *
- * <h5>Preconditons</h5>
- * <ul>
- * <li>getState() in {{@link #INSTALLED},{@link #RESOLVED}}.
- * </ul>
- * <h5>Postconditons, no exceptions thrown</h5>
- * <ul>
- * <li>getState() in {{@link #ACTIVE}}.
- * <li>{@link BundleActivator#start(BundleContext) BundleActivator.start}has been called
- * and did not throw an exception.
- * </ul>
- * <h5>Postconditions, when an exception is thrown</h5>
- * <ul>
- * <li>getState() not in {{@link #STARTING},{@link #ACTIVE}}.
- * </ul>
- *
- * @exception BundleException
- * If the bundle couldn't be started. This could be because
- * a code dependency could not be resolved or the specified
- * BundleActivator could not be loaded or threw an
- * exception.
- * @exception java.lang.IllegalStateException
- * If the bundle tries to change its own state.
- */
- protected void resume() throws BundleException {
- if (state == UNINSTALLED) {
- return;
- }
- beginStateChange();
- try {
- if (readyToResume())
- startWorker(START_TRANSIENT);
- } finally {
- completeStateChange();
- }
- }
-
- /**
- * Stop this bundle.
- *
- * Any services registered by this bundle will be unregistered. Any
- * services used by this bundle will be released. Any listeners registered
- * by this bundle will be removed.
- *
- * <p>
- * The following steps are followed to stop a bundle:
- * <ol>
- * <li>If the bundle is {@link #UNINSTALLED}then an <code>IllegalStateException</code>
- * is thrown.
- * <li>If the bundle is {@link #STOPPING},{@link #RESOLVED}, or
- * {@link #INSTALLED}then this method returns immediately.
- * <li>If the bundle is {@link #STARTING}then this method may wait for
- * the bundle to reach the {@link #ACTIVE}state before continuing. If this
- * does not occur in a reasonable time, a {@link BundleException}is thrown
- * to indicate the bundle was unable to be stopped.
- * <li>The state of the bundle is set to {@link #STOPPING}.
- * <li>It is recorded that this bundle has been stopped, so that when the
- * framework is restarted, this bundle will not be automatically started.
- * <li>The {@link BundleActivator#stop(BundleContext) stop}method of the bundle's
- * {@link BundleActivator}, if one is specified, is called. If the
- * {@link BundleActivator}throws an exception, this method will continue
- * to stop the bundle. A {@link BundleException}will be thrown after
- * completion of the remaining steps.
- * <li>The bundle's listeners, if any, are removed, service's registered
- * by the bundle, if any, are unregistered, and service's used by the
- * bundle, if any, are released.
- * <li>The state of the bundle is set to {@link #RESOLVED}.
- * <li>A {@link BundleEvent}of type {@link BundleEvent#STOPPED}is
- * broadcast.
- * </ol>
- *
- * <h5>Preconditons</h5>
- * <ul>
- * <li>getState() in {{@link #ACTIVE}}.
- * </ul>
- * <h5>Postconditons, no exceptions thrown</h5>
- * <ul>
- * <li>getState() not in {{@link #ACTIVE},{@link #STOPPING}}.
- * <li>{@link BundleActivator#stop(BundleContext) BundleActivator.stop}has been called
- * and did not throw an exception.
- * </ul>
- * <h5>Postconditions, when an exception is thrown</h5>
- * <ul>
- * <li>None.
- * </ul>
- *
- * @exception BundleException
- * If the bundle's BundleActivator could not be loaded or
- * threw an exception.
- * @exception java.lang.IllegalStateException
- * If the bundle has been uninstalled or the bundle tries to
- * change its own state.
- * @exception java.lang.SecurityException
- * If the caller does not have {@link AdminPermission}
- * permission and the Java runtime environment supports
- * permissions.
- */
- public void stop() throws BundleException {
- stop(0);
- }
-
- public void stop(int options) throws BundleException {
- framework.checkAdminPermission(this, AdminPermission.EXECUTE);
- checkValid();
- beginStateChange();
- try {
- stopWorker(options);
- } finally {
- completeStateChange();
- }
- }
-
- /**
- * Internal worker to stop a bundle.
- *
- * @param options
- */
- protected abstract void stopWorker(int options) throws BundleException;
-
- /**
- * Set the persistent status bit for the bundle.
- *
- * @param mask
- * Mask for bit to set/clear
- * @param state
- * true to set bit, false to clear bit
- */
- protected void setStatus(final int mask, final boolean state) {
- try {
- AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
- public Object run() throws IOException {
- int status = bundledata.getStatus();
- boolean test = ((status & mask) != 0);
- if (test != state) {
- bundledata.setStatus(state ? (status | mask) : (status & ~mask));
- bundledata.save();
- }
- return null;
- }
- });
- } catch (PrivilegedActionException pae) {
- framework.publishFrameworkEvent(FrameworkEvent.ERROR, this, pae.getException());
- }
- }
-
- /**
- * Stop this bundle w/o marking is persistently stopped.
- *
- * Any services registered by this bundle will be unregistered. Any
- * services used by this bundle will be released. Any listeners registered
- * by this bundle will be removed.
- *
- * <p>
- * The following steps are followed to stop a bundle:
- * <ol>
- * <li>If the bundle is {@link #UNINSTALLED}then an <code>IllegalStateException</code>
- * is thrown.
- * <li>If the bundle is {@link #STOPPING},{@link #RESOLVED}, or
- * {@link #INSTALLED}then this method returns immediately.
- * <li>If the bundle is {@link #STARTING}then this method may wait for
- * the bundle to reach the {@link #ACTIVE}state before continuing. If this
- * does not occur in a reasonable time, a {@link BundleException}is thrown
- * to indicate the bundle was unable to be stopped.
- * <li>The state of the bundle is set to {@link #STOPPING}.
- * <li>The {@link BundleActivator#stop(BundleContext) stop}method of the bundle's
- * {@link BundleActivator}, if one is specified, is called. If the
- * {@link BundleActivator}throws an exception, this method will continue
- * to stop the bundle. A {@link BundleException}will be thrown after
- * completion of the remaining steps.
- * <li>The bundle's listeners, if any, are removed, service's registered
- * by the bundle, if any, are unregistered, and service's used by the
- * bundle, if any, are released.
- * <li>The state of the bundle is set to {@link #RESOLVED}.
- * <li>A {@link BundleEvent}of type {@link BundleEvent#STOPPED}is
- * broadcast.
- * </ol>
- *
- * <h5>Preconditons</h5>
- * <ul>
- * <li>getState() in {{@link #ACTIVE}}.
- * </ul>
- * <h5>Postconditons, no exceptions thrown</h5>
- * <ul>
- * <li>getState() not in {{@link #ACTIVE},{@link #STOPPING}}.
- * <li>{@link BundleActivator#stop(BundleContext) BundleActivator.stop}has been called
- * and did not throw an exception.
- * </ul>
- * <h5>Postconditions, when an exception is thrown</h5>
- * <ul>
- * <li>None.
- * </ul>
- *
- * @param lock
- * true if state change lock should be held when returning from
- * this method.
- * @exception BundleException
- * If the bundle's BundleActivator could not be loaded or
- * threw an exception.
- * @exception java.lang.IllegalStateException
- * If the bundle tries to change its own state.
- */
- protected void suspend(boolean lock) throws BundleException {
- if (state == UNINSTALLED) {
- return;
- }
- beginStateChange();
- try {
- stopWorker(STOP_TRANSIENT);
- } finally {
- if (!lock) {
- completeStateChange();
- }
- }
- }
-
- public void update() throws BundleException {
- update(null);
- }
-
- public void update(final InputStream in) throws BundleException {
- if (Debug.DEBUG_GENERAL) {
- Debug.println("update location " + bundledata.getLocation()); //$NON-NLS-1$
- Debug.println(" from: " + in); //$NON-NLS-1$
- }
- framework.checkAdminPermission(this, AdminPermission.LIFECYCLE);
- if ((bundledata.getType() & (BundleData.TYPE_BOOTCLASSPATH_EXTENSION | BundleData.TYPE_FRAMEWORK_EXTENSION | BundleData.TYPE_EXTCLASSPATH_EXTENSION)) != 0)
- // need special permission to update extensions
- framework.checkAdminPermission(this, AdminPermission.EXTENSIONLIFECYCLE);
- checkValid();
- beginStateChange();
- try {
- final AccessControlContext callerContext = AccessController.getContext();
- //note AdminPermission is checked again after updated bundle is loaded
- updateWorker(new PrivilegedExceptionAction<Object>() {
- public Object run() throws BundleException {
- /* compute the update location */
- URLConnection source = null;
- if (in == null) {
- String updateLocation = bundledata.getManifest().get(Constants.BUNDLE_UPDATELOCATION);
- if (updateLocation == null)
- updateLocation = bundledata.getLocation();
- if (Debug.DEBUG_GENERAL)
- Debug.println(" from location: " + updateLocation); //$NON-NLS-1$
- /* Map the update location to a URLConnection */
- source = framework.adaptor.mapLocationToURLConnection(updateLocation);
- } else {
- /* Map the InputStream to a URLConnection */
- source = new BundleSource(in);
- }
- /* call the worker */
- updateWorkerPrivileged(source, callerContext);
- return null;
- }
- });
- } finally {
- completeStateChange();
- }
- }
-
- /**
- * Update worker. Assumes the caller has the state change lock.
- */
- protected void updateWorker(PrivilegedExceptionAction<Object> action) throws BundleException {
- int previousState = 0;
- if (!isFragment())
- previousState = state;
- if ((previousState & (ACTIVE | STARTING)) != 0) {
- try {
- stopWorker(STOP_TRANSIENT);
- } catch (BundleException e) {
- framework.publishFrameworkEvent(FrameworkEvent.ERROR, this, e);
- if ((state & (ACTIVE | STARTING)) != 0) /* if the bundle is still active */{
- throw e;
- }
- }
- }
- try {
- AccessController.doPrivileged(action);
- framework.publishBundleEvent(BundleEvent.UPDATED, this);
- } catch (PrivilegedActionException pae) {
- if (pae.getException() instanceof RuntimeException)
- throw (RuntimeException) pae.getException();
- throw (BundleException) pae.getException();
- } finally {
- if ((previousState & (ACTIVE | STARTING)) != 0) {
- try {
- startWorker(START_TRANSIENT | ((previousState & STARTING) != 0 ? START_ACTIVATION_POLICY : 0));
- } catch (BundleException e) {
- framework.publishFrameworkEvent(FrameworkEvent.ERROR, this, e);
- }
- }
- }
- }
-
- /**
- * Update worker. Assumes the caller has the state change lock.
- */
- protected void updateWorkerPrivileged(URLConnection source, AccessControlContext callerContext) throws BundleException {
- AbstractBundle oldBundle = AbstractBundle.createBundle(bundledata, framework, false);
- boolean reloaded = false;
- BundleOperation storage = framework.adaptor.updateBundle(this.bundledata, source);
- BundleRepository bundles = framework.getBundles();
- try {
- BundleData newBundleData = storage.begin();
- // Must call framework createBundle to check execution environment.
- final AbstractBundle newBundle = framework.createAndVerifyBundle(CollisionHook.UPDATING, this, newBundleData, false);
- boolean exporting;
- int st = getState();
- synchronized (bundles) {
- String oldBSN = this.getSymbolicName();
- exporting = reload(newBundle);
- // update this to flush the old BSN/version etc.
- bundles.update(oldBSN, this);
- manifestLocalization = null;
- }
- // indicate we have loaded from the new version of the bundle
- reloaded = true;
- if (System.getSecurityManager() != null) {
- final boolean extension = (bundledata.getType() & (BundleData.TYPE_BOOTCLASSPATH_EXTENSION | BundleData.TYPE_FRAMEWORK_EXTENSION | BundleData.TYPE_EXTCLASSPATH_EXTENSION)) != 0;
- // must check for AllPermission before allow a bundle extension to be updated
- if (extension && !hasPermission(new AllPermission()))
- throw new BundleException(Msg.BUNDLE_EXTENSION_PERMISSION, BundleException.SECURITY_ERROR, new SecurityException(Msg.BUNDLE_EXTENSION_PERMISSION));
- try {
- AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
- public Object run() throws Exception {
- framework.checkAdminPermission(newBundle, AdminPermission.LIFECYCLE);
- if (extension) // need special permission to update extension bundles
- framework.checkAdminPermission(newBundle, AdminPermission.EXTENSIONLIFECYCLE);
- return null;
- }
- }, callerContext);
- } catch (PrivilegedActionException e) {
- throw e.getException();
- }
- }
- // send out unresolved events outside synch block (defect #80610)
- if (st == RESOLVED)
- framework.publishBundleEvent(BundleEvent.UNRESOLVED, this);
- storage.commit(exporting);
- } catch (Throwable t) {
- try {
- storage.undo();
- if (reloaded)
- /*
- * if we loaded from the new version of the
- * bundle
- */{
- synchronized (bundles) {
- String oldBSN = this.getSymbolicName();
- reload(oldBundle);
- // update this to flush the new BSN/version back to the old one etc.
- bundles.update(oldBSN, this);
- }
- }
- } catch (BundleException ee) {
- /* if we fail to revert then we are in big trouble */
- framework.publishFrameworkEvent(FrameworkEvent.ERROR, this, ee);
- }
- if (t instanceof SecurityException)
- throw (SecurityException) t;
- if (t instanceof BundleException)
- throw (BundleException) t;
- throw new BundleException(t.getMessage(), t);
- }
- }
-
- /**
- * Uninstall this bundle.
- * <p>
- * This method removes all traces of the bundle, including any data in the
- * persistent storage area provided for the bundle by the framework.
- *
- * <p>
- * The following steps are followed to uninstall a bundle:
- * <ol>
- * <li>If the bundle is {@link #UNINSTALLED}then an <code>IllegalStateException</code>
- * is thrown.
- * <li>If the bundle is {@link #ACTIVE}or {@link #STARTING}, the bundle
- * is stopped as described in the {@link #stop()}method. If {@link #stop()}
- * throws an exception, a {@link FrameworkEvent}of type
- * {@link FrameworkEvent#ERROR}is broadcast containing the exception.
- * <li>A {@link BundleEvent}of type {@link BundleEvent#UNINSTALLED}is
- * broadcast.
- * <li>The state of the bundle is set to {@link #UNINSTALLED}.
- * <li>The bundle and the persistent storage area provided for the bundle
- * by the framework, if any, is removed.
- * </ol>
- *
- * <h5>Preconditions</h5>
- * <ul>
- * <li>getState() not in {{@link #UNINSTALLED}}.
- * </ul>
- * <h5>Postconditons, no exceptions thrown</h5>
- * <ul>
- * <li>getState() in {{@link #UNINSTALLED}}.
- * <li>The bundle has been uninstalled.
- * </ul>
- * <h5>Postconditions, when an exception is thrown</h5>
- * <ul>
- * <li>getState() not in {{@link #UNINSTALLED}}.
- * <li>The Bundle has not been uninstalled.
- * </ul>
- *
- * @exception BundleException
- * If the uninstall failed.
- * @exception java.lang.IllegalStateException
- * If the bundle has been uninstalled or the bundle tries to
- * change its own state.
- * @exception java.lang.SecurityException
- * If the caller does not have {@link AdminPermission}
- * permission and the Java runtime environment supports
- * permissions.
- * @see #stop()
- */
- public void uninstall() throws BundleException {
- if (Debug.DEBUG_GENERAL) {
- Debug.println("uninstall location: " + bundledata.getLocation()); //$NON-NLS-1$
- }
- framework.checkAdminPermission(this, AdminPermission.LIFECYCLE);
- if ((bundledata.getType() & (BundleData.TYPE_BOOTCLASSPATH_EXTENSION | BundleData.TYPE_FRAMEWORK_EXTENSION | BundleData.TYPE_EXTCLASSPATH_EXTENSION)) != 0)
- // need special permission to uninstall extensions
- framework.checkAdminPermission(this, AdminPermission.EXTENSIONLIFECYCLE);
- checkValid();
- beginStateChange();
- try {
- uninstallWorker(new PrivilegedExceptionAction<Object>() {
- public Object run() throws BundleException {
- uninstallWorkerPrivileged();
- return null;
- }
- });
- } finally {
- completeStateChange();
- }
- }
-
- /**
- * Uninstall worker. Assumes the caller has the state change lock.
- */
- protected void uninstallWorker(PrivilegedExceptionAction<Object> action) throws BundleException {
- boolean bundleActive = false;
- if (!isFragment())
- bundleActive = (state & (ACTIVE | STARTING)) != 0;
- if (bundleActive) {
- try {
- stopWorker(STOP_TRANSIENT);
- } catch (BundleException e) {
- framework.publishFrameworkEvent(FrameworkEvent.ERROR, this, e);
- }
- }
- try {
- AccessController.doPrivileged(action);
- } catch (PrivilegedActionException pae) {
- if (bundleActive) /* if we stopped the bundle */{
- try {
- startWorker(START_TRANSIENT);
- } catch (BundleException e) {
- /*
- * if we fail to start the original bundle then we are in
- * big trouble
- */
- framework.publishFrameworkEvent(FrameworkEvent.ERROR, this, e);
- }
- }
- throw (BundleException) pae.getException();
- }
- framework.publishBundleEvent(BundleEvent.UNINSTALLED, this);
- }
-
- /**
- * Uninstall worker. Assumes the caller has the state change lock.
- */
- protected void uninstallWorkerPrivileged() throws BundleException {
- BundleWatcher bundleStats = framework.adaptor.getBundleWatcher();
- if (bundleStats != null)
- bundleStats.watchBundle(this, BundleWatcher.START_UNINSTALLING);
- boolean unloaded = false;
- //cache the bundle's headers
- getHeaders();
- BundleOperation storage = framework.adaptor.uninstallBundle(this.bundledata);
- BundleRepository bundles = framework.getBundles();
- try {
- storage.begin();
- boolean exporting;
- int st = getState();
- synchronized (bundles) {
- bundles.remove(this); /* remove before calling unload */
- exporting = unload();
- }
- // send out unresolved events outside synch block (defect #80610)
- if (st == RESOLVED)
- framework.publishBundleEvent(BundleEvent.UNRESOLVED, this);
- unloaded = true;
- storage.commit(exporting);
- close();
- } catch (BundleException e) {
- try {
- storage.undo();
- if (unloaded) /* if we unloaded the bundle */{
- synchronized (bundles) {
- load(); /* reload the bundle */
- bundles.add(this);
- }
- }
- } catch (BundleException ee) {
- /*
- * if we fail to load the original bundle then we are in big
- * trouble
- */
- framework.publishFrameworkEvent(FrameworkEvent.ERROR, this, ee);
- }
- throw e;
- } finally {
- if (bundleStats != null)
- bundleStats.watchBundle(this, BundleWatcher.END_UNINSTALLING);
- }
- }
-
- /**
- * Return the bundle's manifest headers and values from the manifest's
- * preliminary section. That is all the manifest's headers and values prior
- * to the first blank line.
- *
- * <p>
- * Manifest header names are case-insensitive. The methods of the returned
- * <code>Dictionary</code> object will operate on header names in a
- * case-insensitive manner.
- *
- * <p>
- * For example, the following manifest headers and values are included if
- * they are present in the manifest:
- *
- * <pre>
- * Bundle-Name
- * Bundle-Vendor
- * Bundle-Version
- * Bundle-Description
- * Bundle-DocURL
- * Bundle-ContactAddress
- * </pre>
- *
- * <p>
- * This method will continue to return this information when the bundle is
- * in the {@link #UNINSTALLED}state.
- *
- * @return A <code>Dictionary</code> object containing the bundle's
- * manifest headers and values.
- * @exception java.lang.SecurityException
- * If the caller does not have {@link AdminPermission}
- * permission and the Java runtime environment supports
- * permissions.
- */
- public Dictionary<String, String> getHeaders() {
- return getHeaders(null);
- }
-
- /**
- * Returns this bundle's Manifest headers and values. This method returns
- * all the Manifest headers and values from the main section of the
- * bundle's Manifest file; that is, all lines prior to the first blank
- * line.
- *
- * <p>
- * Manifest header names are case-insensitive. The methods of the returned
- * <tt>Dictionary</tt> object will operate on header names in a
- * case-insensitive manner.
- *
- * If a Manifest header begins with a '%', it will be evaluated with the
- * specified properties file for the specied Locale.
- *
- * <p>
- * For example, the following Manifest headers and values are included if
- * they are present in the Manifest file:
- *
- * <pre>
- * Bundle-Name
- * Bundle-Vendor
- * Bundle-Version
- * Bundle-Description
- * Bundle-DocURL
- * Bundle-ContactAddress
- * </pre>
- *
- * <p>
- * This method will continue to return Manifest header information while
- * this bundle is in the <tt>UNINSTALLED</tt> state.
- *
- * @return A <tt>Dictionary</tt> object containing this bundle's Manifest
- * headers and values.
- *
- * @exception java.lang.SecurityException
- * If the caller does not have the <tt>AdminPermission</tt>,
- * and the Java Runtime Environment supports permissions.
- */
- public Dictionary<String, String> getHeaders(String localeString) {
- framework.checkAdminPermission(this, AdminPermission.METADATA);
- ManifestLocalization localization;
- try {
- localization = getManifestLocalization();
- } catch (BundleException e) {
- framework.publishFrameworkEvent(FrameworkEvent.ERROR, this, e);
- // return an empty dictinary.
- return new Hashtable<String, String>();
- }
- if (localeString == null)
- localeString = Locale.getDefault().toString();
- return localization.getHeaders(localeString);
- }
-
- /**
- * Retrieve the bundle's unique identifier, which the framework assigned to
- * this bundle when it was installed.
- *
- * <p>
- * The unique identifier has the following attributes:
- * <ul>
- * <li>It is unique and persistent.
- * <li>The identifier is a long.
- * <li>Once its value is assigned to a bundle, that value is not reused
- * for another bundle, even after the bundle is uninstalled.
- * <li>Its value does not change as long as the bundle remains installed.
- * <li>Its value does not change when the bundle is updated
- * </ul>
- *
- * <p>
- * This method will continue to return the bundle's unique identifier when
- * the bundle is in the {@link #UNINSTALLED}state.
- *
- * @return This bundle's unique identifier.
- */
- public long getBundleId() {
- return (bundledata.getBundleID());
- }
-
- /**
- * Retrieve the location identifier of the bundle. This is typically the
- * location passed to
- * {@link BundleContextImpl#installBundle(String) BundleContext.installBundle}when the
- * bundle was installed. The location identifier of the bundle may change
- * during bundle update. Calling this method while framework is updating
- * the bundle results in undefined behavior.
- *
- * <p>
- * This method will continue to return the bundle's location identifier
- * when the bundle is in the {@link #UNINSTALLED}state.
- *
- * @return A string that is the location identifier of the bundle.
- * @exception java.lang.SecurityException
- * If the caller does not have {@link AdminPermission}
- * permission and the Java runtime environment supports
- * permissions.
- */
- public String getLocation() {
- framework.checkAdminPermission(this, AdminPermission.METADATA);
- return (bundledata.getLocation());
- }
-
- /**
- * Determine whether the bundle has the requested permission.
- *
- * <p>
- * If the Java runtime environment does not supports permissions this
- * method always returns <code>true</code>. The permission parameter is
- * of type <code>Object</code> to avoid referencing the <code>java.security.Permission</code>
- * class directly. This is to allow the framework to be implemented in Java
- * environments which do not support permissions.
- *
- * @param permission
- * The requested permission.
- * @return <code>true</code> if the bundle has the requested permission
- * or <code>false</code> if the bundle does not have the
- * permission or the permission parameter is not an <code>instanceof java.security.Permission</code>.
- * @exception java.lang.IllegalStateException
- * If the bundle has been uninstalled.
- */
- public boolean hasPermission(Object permission) {
- checkValid();
- if (domain != null) {
- if (permission instanceof 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.
- */
- AccessControlContext acc = getAccessControlContext();
- try {
- sm.checkPermission((Permission) permission, acc);
- return true;
- } catch (Exception e) {
- return false;
- }
- }
- return domain.implies((Permission) permission);
- }
- return false;
- }
- return true;
- }
-
- /**
- * This method marks the bundle's state as changing so that other calls to
- * start/stop/suspend/update/uninstall can wait until the state change is
- * complete. If stateChanging is non-null when this method is called, we
- * will wait for the state change to complete. If the timeout expires
- * without changing state (this may happen if the state change is back up
- * our call stack), a BundleException is thrown so that we don't wait
- * forever.
- *
- * A call to this method should be immediately followed by a try block
- * whose finally block calls completeStateChange().
- *
- * beginStateChange(); try { // change the bundle's state here... } finally {
- * completeStateChange(); }
- *
- * @exception org.osgi.framework.BundleException
- * if the bundles state is still changing after waiting for
- * the timeout.
- */
- protected void beginStateChange() throws BundleException {
- synchronized (statechangeLock) {
- boolean doubleFault = false;
- while (true) {
- if (stateChanging == null) {
- stateChanging = Thread.currentThread();
- return;
- }
- if (doubleFault || (stateChanging == Thread.currentThread())) {
- throw new BundleException(NLS.bind(Msg.BUNDLE_STATE_CHANGE_EXCEPTION, getBundleData().getLocation(), stateChanging.getName()), BundleException.STATECHANGE_ERROR, new BundleStatusException(null, StatusException.CODE_WARNING, stateChanging));
- }
- try {
- long start = 0;
- if (Debug.DEBUG_GENERAL) {
- Debug.println(" Waiting for state to change in bundle " + this); //$NON-NLS-1$
- start = System.currentTimeMillis();
- }
- statechangeLock.wait(STATE_CHANGE_TIMEOUT);
- /*
- * wait for other thread to
- * finish changing state
- */
- if (Debug.DEBUG_GENERAL) {
- long end = System.currentTimeMillis();
- if (end - start > 0)
- System.out.println("Waiting... : " + getSymbolicName() + ' ' + (end - start)); //$NON-NLS-1$
- }
- } catch (InterruptedException e) {
- //Nothing to do
- }
- doubleFault = true;
- }
- }
- }
-
- /**
- * This method completes the bundle state change by setting stateChanging
- * to null and notifying one waiter that the state change has completed.
- */
- protected void completeStateChange() {
- synchronized (statechangeLock) {
- if (stateChanging == Thread.currentThread()) {
- stateChanging = null;
- statechangeLock.notify();
- /*
- * notify one waiting thread that the
- * state change is complete
- */
- }
- }
- }
-
- /**
- * Return a string representation of this bundle.
- *
- * @return String
- */
- public String toString() {
- String name = bundledata.getSymbolicName();
- if (name == null)
- name = "unknown"; //$NON-NLS-1$
- return (name + '_' + bundledata.getVersion() + " [" + getBundleId() + "]"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /**
- * Answers an integer indicating the relative positions of the receiver and
- * the argument in the natural order of elements of the receiver's class.
- *
- * @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 Bundle an object to compare the receiver to
- * @exception ClassCastException
- * if the argument can not be converted into something
- * comparable with the receiver.
- */
- public int compareTo(Bundle obj) {
- int slcomp = getInternalStartLevel() - ((AbstractBundle) obj).getInternalStartLevel();
- if (slcomp != 0) {
- return slcomp;
- }
- long idcomp = getBundleId() - ((AbstractBundle) obj).getBundleId();
- return (idcomp < 0L) ? -1 : ((idcomp > 0L) ? 1 : 0);
- }
-
- /**
- * This method checks that the bundle is not uninstalled. If the bundle is
- * uninstalled, an IllegalStateException is thrown.
- *
- * @exception java.lang.IllegalStateException
- * If the bundle is uninstalled.
- */
- protected void checkValid() {
- if (state == UNINSTALLED) {
- throw new IllegalStateException(NLS.bind(Msg.BUNDLE_UNINSTALLED_EXCEPTION, getBundleData().getLocation()));
- }
- }
-
- /**
- * Get the bundle's ProtectionDomain.
- *
- * @return bundle's ProtectionDomain.
- */
- public BundleProtectionDomain getProtectionDomain() {
- return domain;
- }
-
- private AccessControlContext getAccessControlContext() {
- return new AccessControlContext(new ProtectionDomain[] {domain});
- }
-
- protected BundleFragment[] getFragments() {
- checkValid();
- return null;
- }
-
- protected boolean isFragment() {
- return false;
- }
-
- BundleHost[] getHosts() {
- checkValid();
- return null;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.osgi.framework.Bundle#findClass(java.lang.String)
- */
- public Class<?> loadClass(String classname) throws ClassNotFoundException {
- return loadClass(classname, true);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.osgi.framework.Bundle#getResourcePaths(java.lang.String)
- */
- public Enumeration<String> getEntryPaths(final String path) {
- try {
- framework.checkAdminPermission(this, AdminPermission.RESOURCE);
- } catch (SecurityException e) {
- return null;
- }
- checkValid();
- // TODO this doPrivileged is probably not needed. The adaptor isolates callers from disk access
- return AccessController.doPrivileged(new PrivilegedAction<Enumeration<String>>() {
- public Enumeration<String> run() {
- return bundledata.getEntryPaths(path);
- }
- });
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.osgi.framework.Bundle#getFile(java.lang.String)
- */
- public URL getEntry(String fileName) {
- try {
- framework.checkAdminPermission(this, AdminPermission.RESOURCE);
- } catch (SecurityException e) {
- return null;
- }
- return getEntry0(fileName);
- }
-
- URL getEntry0(String fileName) {
- checkValid();
- return bundledata.getEntry(fileName);
- }
-
- public String getSymbolicName() {
- return bundledata.getSymbolicName();
- }
-
- public long getLastModified() {
- return bundledata.getLastModified();
- }
-
- public BundleData getBundleData() {
- return bundledata;
- }
-
- public Version getVersion() {
- return bundledata.getVersion();
- }
-
- public BundleDescription getBundleDescription() {
- return framework.adaptor.getState().getBundle(getBundleId());
- }
-
- int getInternalStartLevel() {
- return bundledata.getStartLevel();
- }
-
- protected abstract BundleLoader getBundleLoader();
-
- /**
- * Mark this bundle as resolved.
- */
- protected void resolve() {
- if (Debug.DEBUG_GENERAL) {
- if ((state & (INSTALLED)) == 0) {
- Debug.println("Bundle.resolve called when state != INSTALLED: " + this); //$NON-NLS-1$
- Debug.printStackTrace(new Exception("Stack trace")); //$NON-NLS-1$
- }
- }
- if (state == INSTALLED) {
- state = RESOLVED;
- // Do not publish RESOLVED event here. This is done by caller
- // to resolve if appropriate.
- }
- }
-
- public BundleContext getBundleContext() {
- framework.checkAdminPermission(this, AdminPermission.CONTEXT);
- return getContext();
- }
-
- /**
- * Return the current context for this bundle.
- *
- * @return BundleContext for this bundle.
- */
- abstract protected BundleContextImpl getContext();
-
- public BundleException getResolutionFailureException() {
- BundleDescription bundleDescription = getBundleDescription();
- if (bundleDescription == null)
- return new BundleException(NLS.bind(Msg.BUNDLE_UNRESOLVED_EXCEPTION, this.toString()), BundleException.RESOLVE_ERROR);
- // just a sanity check - this would be an inconsistency between the framework and the state
- if (bundleDescription.isResolved())
- return new BundleException(Msg.BUNDLE_UNRESOLVED_STATE_CONFLICT, BundleException.RESOLVE_ERROR);
- return getResolverError(bundleDescription);
- }
-
- private BundleException getResolverError(BundleDescription bundleDesc) {
- ResolverError[] errors = framework.adaptor.getState().getResolverErrors(bundleDesc);
- if (errors == null || errors.length == 0)
- return new BundleException(NLS.bind(Msg.BUNDLE_UNRESOLVED_EXCEPTION, this.toString()), BundleException.RESOLVE_ERROR);
- StringBuffer message = new StringBuffer();
- int errorType = BundleException.RESOLVE_ERROR;
- for (int i = 0; i < errors.length; i++) {
- if ((errors[i].getType() & ResolverError.INVALID_NATIVECODE_PATHS) != 0)
- errorType = BundleException.NATIVECODE_ERROR;
- message.append(errors[i].toString());
- if (i < errors.length - 1)
- message.append(", "); //$NON-NLS-1$
- }
- return new BundleException(NLS.bind(Msg.BUNDLE_UNRESOLVED_UNSATISFIED_CONSTRAINT_EXCEPTION, this.toString(), message.toString()), errorType);
- }
-
- public int getKeyHashCode() {
- long id = getBundleId();
- return (int) (id ^ (id >>> 32));
- }
-
- public boolean compare(KeyedElement other) {
- return getBundleId() == ((AbstractBundle) other).getBundleId();
- }
-
- public Object getKey() {
- return new Long(getBundleId());
- }
-
- /* This method is used by the Bundle Localization Service to obtain
- * a ResourceBundle that resides in a bundle. This is not an OSGi
- * defined method for org.osgi.framework.Bundle
- *
- */
- public ResourceBundle getResourceBundle(String localeString) {
- ManifestLocalization localization;
- try {
- localization = getManifestLocalization();
- } catch (BundleException ex) {
- return (null);
- }
- String defaultLocale = Locale.getDefault().toString();
- if (localeString == null) {
- localeString = defaultLocale;
- }
- return localization.getResourceBundle(localeString, defaultLocale.equals(localeString));
- }
-
- private synchronized ManifestLocalization getManifestLocalization() throws BundleException {
- ManifestLocalization currentLocalization = manifestLocalization;
- if (currentLocalization == null) {
- Dictionary<String, String> rawHeaders = bundledata.getManifest();
- manifestLocalization = currentLocalization = new ManifestLocalization(this, rawHeaders);
- }
- return currentLocalization;
- }
-
- public boolean testStateChanging(Object thread) {
- return stateChanging == thread;
- }
-
- public Thread getStateChanging() {
- return stateChanging;
- }
-
- public Enumeration<URL> findEntries(String path, String filePattern, boolean recurse) {
- try {
- framework.checkAdminPermission(this, AdminPermission.RESOURCE);
- } catch (SecurityException e) {
- return null;
- }
- checkValid();
- // check to see if the bundle is resolved
- if (!isResolved())
- framework.packageAdmin.resolveBundles(new Bundle[] {this});
-
- // if this bundle is a host to fragments then search the fragments
- BundleFragment[] fragments = getFragments();
- List<BundleData> datas = new ArrayList<BundleData>((fragments == null ? 0 : fragments.length) + 1);
- datas.add(getBundleData());
- if (fragments != null)
- for (BundleFragment fragment : fragments)
- datas.add(fragment.getBundleData());
- int options = recurse ? BundleWiring.FINDENTRIES_RECURSE : 0;
- return framework.getAdaptor().findEntries(datas, path, filePattern, options);
- }
-
- class BundleStatusException extends Throwable implements StatusException {
- private static final long serialVersionUID = 7201911791818929100L;
- private int code;
- private transient Object status;
-
- BundleStatusException(String message, int code, Object status) {
- super(message);
- this.code = code;
- this.status = status;
- }
-
- public Object getStatus() {
- return status;
- }
-
- public int getStatusCode() {
- return code;
- }
-
- }
-
- public Map<X509Certificate, List<X509Certificate>> getSignerCertificates(int signersType) {
- @SuppressWarnings("unchecked")
- final Map<X509Certificate, List<X509Certificate>> empty = Collections.EMPTY_MAP;
- if (signersType != SIGNERS_ALL && signersType != SIGNERS_TRUSTED)
- throw new IllegalArgumentException("Invalid signers type: " + signersType); //$NON-NLS-1$
- if (framework == null)
- return empty;
- SignedContentFactory factory = framework.getSignedContentFactory();
- if (factory == null)
- return empty;
- try {
- SignedContent signedContent = factory.getSignedContent(this);
- SignerInfo[] infos = signedContent.getSignerInfos();
- if (infos.length == 0)
- return empty;
- Map<X509Certificate, List<X509Certificate>> results = new HashMap<X509Certificate, List<X509Certificate>>(infos.length);
- for (int i = 0; i < infos.length; i++) {
- if (signersType == SIGNERS_TRUSTED && !infos[i].isTrusted())
- continue;
- Certificate[] certs = infos[i].getCertificateChain();
- if (certs == null || certs.length == 0)
- continue;
- List<X509Certificate> certChain = new ArrayList<X509Certificate>();
- for (int j = 0; j < certs.length; j++)
- certChain.add((X509Certificate) certs[j]);
- results.put((X509Certificate) certs[0], certChain);
- }
- return results;
- } catch (Exception e) {
- return empty;
- }
- }
-
- public final <A> A adapt(Class<A> adapterType) {
- checkAdaptPermission(adapterType);
- return adapt0(adapterType);
- }
-
- public List<BundleRevision> getRevisions() {
- List<BundleRevision> revisions = new ArrayList<BundleRevision>();
- BundleDescription current = getBundleDescription();
- if (current != null)
- revisions.add(current);
- BundleDescription[] removals = framework.adaptor.getState().getRemovalPending();
- for (BundleDescription removed : removals) {
- if (removed.getBundleId() == getBundleId() && removed != current) {
- revisions.add(removed);
- }
- }
- return revisions;
- }
-
- @SuppressWarnings("unchecked")
- protected <A> A adapt0(Class<A> adapterType) {
- if (adapterType.isInstance(this))
- return (A) this;
- if (BundleContext.class.equals(adapterType)) {
- try {
- return (A) getBundleContext();
- } catch (SecurityException e) {
- return null;
- }
- }
-
- if (AccessControlContext.class.equals(adapterType)) {
- return (A) getAccessControlContext();
- }
-
- if (BundleWiring.class.equals(adapterType)) {
- if (state == UNINSTALLED)
- return null;
- BundleDescription description = getBundleDescription();
- return (A) description.getWiring();
- }
-
- if (BundleRevision.class.equals(adapterType)) {
- if (state == UNINSTALLED)
- return null;
- return (A) getBundleDescription();
- }
- return null;
- }
-
- /**
- * Check for permission to get a service.
- */
- private <A> void checkAdaptPermission(Class<A> adapterType) {
- SecurityManager sm = System.getSecurityManager();
- if (sm == null) {
- return;
- }
- sm.checkPermission(new AdaptPermission(adapterType.getName(), this, AdaptPermission.ADAPT));
- }
-
- public File getDataFile(String filename) {
- return framework.getDataFile(this, filename);
- }
-
- public Bundle getBundle() {
- return this;
- }
-
- public int getStartLevel() {
- if (getState() == Bundle.UNINSTALLED)
- throw new IllegalArgumentException(NLS.bind(Msg.BUNDLE_UNINSTALLED_EXCEPTION, getBundleData().getLocation()));
- return getInternalStartLevel();
- }
-
- public void setStartLevel(int startlevel) {
- framework.startLevelManager.setBundleStartLevel(this, startlevel);
- }
-
- public boolean isPersistentlyStarted() {
- if (getState() == Bundle.UNINSTALLED)
- throw new IllegalArgumentException(NLS.bind(Msg.BUNDLE_UNINSTALLED_EXCEPTION, getBundleData().getLocation()));
- return (getBundleData().getStatus() & Constants.BUNDLE_STARTED) != 0;
- }
-
- public boolean isActivationPolicyUsed() {
- if (getState() == Bundle.UNINSTALLED)
- throw new IllegalArgumentException(NLS.bind(Msg.BUNDLE_UNINSTALLED_EXCEPTION, getBundleData().getLocation()));
- return (getBundleData().getStatus() & Constants.BUNDLE_ACTIVATION_POLICY) != 0;
- }
-
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/AliasMapper.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/AliasMapper.java
deleted file mode 100644
index 728745362..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/AliasMapper.java
+++ /dev/null
@@ -1,155 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.osgi.framework.internal.core;
-
-import java.io.*;
-import java.util.*;
-import org.eclipse.osgi.framework.debug.Debug;
-
-/**
- * This class maps aliases.
- */
-public class AliasMapper {
- private static Map<String, Object> processorAliasTable;
- private static Map<String, Object> osnameAliasTable;
-
- // Safe lazy initialization
- private static synchronized Map<String, Object> getProcessorAliasTable() {
- if (processorAliasTable == null) {
- InputStream in = AliasMapper.class.getResourceAsStream(Constants.OSGI_PROCESSOR_ALIASES);
- if (in != null) {
- try {
- processorAliasTable = initAliases(in);
- } finally {
- try {
- in.close();
- } catch (IOException ee) {
- // nothing
- }
- }
- }
- }
- return processorAliasTable;
- }
-
- // Safe lazy initialization
- private static synchronized Map<String, Object> getOSNameAliasTable() {
- if (osnameAliasTable == null) {
- InputStream in = AliasMapper.class.getResourceAsStream(Constants.OSGI_OSNAME_ALIASES);
- if (in != null) {
- try {
- osnameAliasTable = initAliases(in);
- } finally {
- try {
- in.close();
- } catch (IOException ee) {
- // nothing
- }
- }
- }
- }
- return osnameAliasTable;
- }
-
- /**
- * Return the master alias for the processor.
- *
- * @param processor Input name
- * @return aliased name (if any)
- */
- public String aliasProcessor(String processor) {
- processor = processor.toLowerCase();
- Map<String, Object> aliases = getProcessorAliasTable();
- if (aliases != null) {
- String alias = (String) aliases.get(processor);
- if (alias != null) {
- processor = alias;
- }
- }
- return processor;
- }
-
- /**
- * Return the master alias for the osname.
- *
- * @param osname Input name
- * @return aliased name (if any)
- */
- public Object aliasOSName(String osname) {
- osname = osname.toLowerCase();
- Map<String, Object> aliases = getOSNameAliasTable();
- if (aliases != null) {
- Object aliasObject = aliases.get(osname);
- //String alias = (String) osnameAliasTable.get(osname);
- if (aliasObject != null)
- if (aliasObject instanceof String) {
- osname = (String) aliasObject;
- } else {
- return aliasObject;
- }
- }
- return osname;
- }
-
- /**
- * Read alias data and populate a Map.
- *
- * @param in InputStream from which to read alias data.
- * @return Map of aliases.
- */
- protected static Map<String, Object> initAliases(InputStream in) {
- Map<String, Object> aliases = new HashMap<String, Object>(37);
- try {
- BufferedReader br;
- try {
- br = new BufferedReader(new InputStreamReader(in, "UTF8")); //$NON-NLS-1$
- } catch (UnsupportedEncodingException e) {
- br = new BufferedReader(new InputStreamReader(in));
- }
- while (true) {
- String line = br.readLine();
- if (line == null) /* EOF */{
- break; /* done */
- }
- Tokenizer tokenizer = new Tokenizer(line);
- String master = tokenizer.getString("# \t"); //$NON-NLS-1$
- if (master != null) {
- aliases.put(master.toLowerCase(), master);
- parseloop: while (true) {
- String alias = tokenizer.getString("# \t"); //$NON-NLS-1$
- if (alias == null) {
- break parseloop;
- }
- String lowerCaseAlias = alias.toLowerCase();
- Object storedMaster = aliases.get(lowerCaseAlias);
- if (storedMaster == null) {
- aliases.put(lowerCaseAlias, master);
- } else if (storedMaster instanceof String) {
- List<String> newMaster = new ArrayList<String>();
- newMaster.add((String) storedMaster);
- newMaster.add(master);
- aliases.put(lowerCaseAlias, newMaster);
- } else {
- @SuppressWarnings("unchecked")
- List<String> newMaster = ((List<String>) storedMaster);
- newMaster.add(master);
- }
- }
- }
- }
- } catch (IOException e) {
- if (Debug.DEBUG_GENERAL) {
- Debug.printStackTrace(e);
- }
- }
- return aliases;
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/BundleContextImpl.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/BundleContextImpl.java
deleted file mode 100644
index a6581cd2d..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/BundleContextImpl.java
+++ /dev/null
@@ -1,974 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2011 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.framework.internal.core;
-
-import java.io.File;
-import java.io.InputStream;
-import java.security.*;
-import java.util.*;
-import org.eclipse.osgi.event.BatchBundleListener;
-import org.eclipse.osgi.framework.debug.Debug;
-import org.eclipse.osgi.framework.eventmgr.EventDispatcher;
-import org.eclipse.osgi.internal.profile.Profile;
-import org.eclipse.osgi.internal.serviceregistry.*;
-import org.eclipse.osgi.util.NLS;
-import org.osgi.framework.*;
-
-/**
- * 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.
- */
-
-public class BundleContextImpl implements BundleContext, EventDispatcher<Object, Object, Object> {
- private static boolean SET_TCCL = "true".equals(FrameworkProperties.getProperty("eclipse.bundle.setTCCL", "true")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- /** true if the bundle context is still valid */
- private volatile boolean valid;
-
- /** Bundle object this context is associated with. */
- // This slot is accessed directly by the Framework instead of using
- // the getBundle() method because the Framework needs access to the bundle
- // even when the context is invalid while the close method is being called.
- final BundleHost bundle;
-
- /** Internal framework object. */
- final Framework framework;
-
- /** Services that bundle is using. Key is ServiceRegistrationImpl,
- Value is ServiceUse */
- /* @GuardedBy("contextLock") */
- private HashMap<ServiceRegistrationImpl<?>, ServiceUse<?>> servicesInUse;
-
- /** The current instantiation of the activator. */
- protected BundleActivator activator;
-
- /** private object for locking */
- private final Object contextLock = new Object();
-
- /**
- * Construct a BundleContext which wrappers the framework for a
- * bundle
- *
- * @param bundle The bundle we are wrapping.
- */
- protected BundleContextImpl(BundleHost bundle) {
- this.bundle = bundle;
- valid = true;
- framework = bundle.framework;
- synchronized (contextLock) {
- servicesInUse = null;
- }
- activator = null;
- }
-
- /**
- * Destroy the wrapper. This is called when the bundle is stopped.
- *
- */
- protected void close() {
- valid = false; /* invalidate context */
-
- final ServiceRegistry registry = framework.getServiceRegistry();
-
- registry.removeAllServiceListeners(this);
- framework.removeAllListeners(this);
-
- /* service's registered by the bundle, if any, are unregistered. */
- registry.unregisterServices(this);
-
- /* service's used by the bundle, if any, are released. */
- registry.releaseServicesInUse(this);
-
- synchronized (contextLock) {
- servicesInUse = null;
- }
- }
-
- /**
- * Retrieve the value of the named environment property.
- *
- * @param key The name of the requested property.
- * @return The value of the requested property, or <code>null</code> if
- * the property is undefined.
- */
- public String getProperty(String key) {
- SecurityManager sm = System.getSecurityManager();
-
- if (sm != null) {
- sm.checkPropertyAccess(key);
- }
-
- return (framework.getProperty(key));
- }
-
- /**
- * Retrieve the Bundle object for the context bundle.
- *
- * @return The context bundle's Bundle object.
- */
- public Bundle getBundle() {
- checkValid();
-
- return getBundleImpl();
- }
-
- public AbstractBundle getBundleImpl() {
- return bundle;
- }
-
- public Bundle installBundle(String location) throws BundleException {
- return installBundle(location, null);
- }
-
- public Bundle installBundle(String location, InputStream in) throws BundleException {
- checkValid();
- //note AdminPermission is checked after bundle is loaded
- return framework.installBundle(location, in, this);
- }
-
- /**
- * Retrieve the bundle that has the given unique identifier.
- *
- * @param id The identifier of the bundle to retrieve.
- * @return A Bundle object, or <code>null</code>
- * if the identifier doesn't match any installed bundle.
- */
- public Bundle getBundle(long id) {
- return framework.getBundle(this, id);
- }
-
- public Bundle getBundle(String location) {
- return framework.getBundleByLocation(location);
- }
-
- /**
- * Retrieve the bundle that has the given location.
- *
- * @param location The location string of the bundle to retrieve.
- * @return A Bundle object, or <code>null</code>
- * if the location doesn't match any installed bundle.
- */
- public AbstractBundle getBundleByLocation(String location) {
- return (framework.getBundleByLocation(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.
- *
- * @return An array of {@link AbstractBundle} objects, one
- * object per installed bundle.
- */
- public Bundle[] getBundles() {
- return framework.getBundles(this);
- }
-
- /**
- * Add a service listener with a filter.
- * {@link ServiceListener}s are notified when a service has a lifecycle
- * state change.
- * See {@link #getServiceReferences(String, String) getServiceReferences}
- * for a description of the filter syntax.
- * The listener is added to the context bundle's list of listeners.
- * See {@link #getBundle() getBundle()}
- * for a definition of context bundle.
- *
- * <p>The listener is called if the filter criteria is met.
- * To filter based upon the class of the service, the filter
- * should reference the "objectClass" property.
- * If the filter paramater is <code>null</code>, all services
- * are considered to match the filter.
- * <p>If the Java runtime environment supports permissions, then additional
- * filtering is done.
- * {@link AbstractBundle#hasPermission(Object) Bundle.hasPermission} is called for the
- * bundle which defines the listener to validate that the listener has the
- * {@link ServicePermission} permission to <code>"get"</code> the service
- * using at least one of the named classes the service was registered under.
- *
- * @param listener The service listener to add.
- * @param filter The filter criteria.
- * @exception InvalidSyntaxException If the filter parameter contains
- * an invalid filter string which cannot be parsed.
- * @see ServiceEvent
- * @see ServiceListener
- * @exception java.lang.IllegalStateException
- * If the bundle context has stopped.
- */
- public void addServiceListener(ServiceListener listener, String filter) throws InvalidSyntaxException {
- checkValid();
-
- if (listener == null) {
- throw new IllegalArgumentException();
- }
- framework.getServiceRegistry().addServiceListener(this, listener, filter);
- }
-
- /**
- * Add a service listener.
- *
- * <p>This method is the same as calling
- * {@link #addServiceListener(ServiceListener, String)}
- * with filter set to <code>null</code>.
- *
- * @see #addServiceListener(ServiceListener, String)
- */
- public void addServiceListener(ServiceListener listener) {
- try {
- addServiceListener(listener, null);
- } catch (InvalidSyntaxException e) {
- if (Debug.DEBUG_GENERAL) {
- Debug.println("InvalidSyntaxException w/ null filter" + e.getMessage()); //$NON-NLS-1$
- Debug.printStackTrace(e);
- }
- }
- }
-
- /**
- * 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.
- *
- * <p>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.
- */
- public void removeServiceListener(ServiceListener listener) {
- checkValid();
-
- if (listener == null) {
- throw new IllegalArgumentException();
- }
- framework.getServiceRegistry().removeServiceListener(this, 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.
- *
- * @param listener The bundle listener to add.
- * @exception java.lang.IllegalStateException
- * If the bundle context has stopped.
- * @see BundleEvent
- * @see BundleListener
- */
- public void addBundleListener(BundleListener listener) {
- checkValid();
- if (listener == null) {
- throw new IllegalArgumentException();
- }
-
- if (Debug.DEBUG_EVENTS) {
- String listenerName = listener.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(listener)); //$NON-NLS-1$
- Debug.println("addBundleListener[" + bundle + "](" + listenerName + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- framework.addBundleListener(listener, this);
- }
-
- /**
- * 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.
- *
- * <p>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.
- */
- public void removeBundleListener(BundleListener listener) {
- checkValid();
- if (listener == null) {
- throw new IllegalArgumentException();
- }
-
- if (Debug.DEBUG_EVENTS) {
- String listenerName = listener.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(listener)); //$NON-NLS-1$
- Debug.println("removeBundleListener[" + bundle + "](" + listenerName + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- framework.removeBundleListener(listener, this);
- }
-
- /**
- * 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.
- * @see FrameworkEvent
- * @see FrameworkListener
- */
- public void addFrameworkListener(FrameworkListener listener) {
- checkValid();
- if (listener == null) {
- throw new IllegalArgumentException();
- }
-
- if (Debug.DEBUG_EVENTS) {
- String listenerName = listener.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(listener)); //$NON-NLS-1$
- Debug.println("addFrameworkListener[" + bundle + "](" + listenerName + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- framework.addFrameworkListener(listener, this);
- }
-
- /**
- * 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.
- *
- * <p>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.
- */
- public void removeFrameworkListener(FrameworkListener listener) {
- checkValid();
- if (listener == null) {
- throw new IllegalArgumentException();
- }
-
- if (Debug.DEBUG_EVENTS) {
- String listenerName = listener.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(listener)); //$NON-NLS-1$
- Debug.println("removeFrameworkListener[" + bundle + "](" + listenerName + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- framework.removeFrameworkListener(listener, this);
- }
-
- /**
- * 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.
- *
- * <p>A bundle can register a service object that implements the
- * {@link ServiceFactory} interface to
- * have more flexiblity in providing service objects to different
- * bundles.
- *
- * <p>The following steps are followed to register a service:
- * <ol>
- * <li>If the service parameter is not a {@link ServiceFactory},
- * an <code>IllegalArgumentException</code> is thrown if the
- * service parameter is not an <code>instanceof</code>
- * all the classes named.
- * <li>The service is added to the framework's service registry
- * and may now be used by other bundles.
- * <li>A {@link ServiceEvent} of type {@link ServiceEvent#REGISTERED}
- * is synchronously sent.
- * <li>A {@link ServiceRegistration} object for this registration
- * is returned.
- * </ol>
- *
- * @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 <code>null</code> 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:
- * <ul>
- * <li>The service parameter is null.
- * <li>The service parameter is not a {@link ServiceFactory} and is not an
- * <code>instanceof</code> all the named classes in the clazzes parameter.
- * </ul>
- * @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
- */
- public ServiceRegistration<?> registerService(String[] clazzes, Object service, Dictionary<String, ?> properties) {
- checkValid();
- return framework.getServiceRegistry().registerService(this, clazzes, service, properties);
- }
-
- /**
- * Register a service with a single name.
- * This method registers the given service object with the given properties
- * under the given class name.
- *
- * <p>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.
- *
- * @see #registerService(java.lang.String[], java.lang.Object, java.util.Dictionary)
- */
- public ServiceRegistration<?> registerService(String clazz, Object service, Dictionary<String, ?> properties) {
- String[] clazzes = new String[] {clazz};
-
- return registerService(clazzes, service, properties);
- }
-
- /**
- * Returns a list of <tt>ServiceReference</tt> objects. This method returns a list of
- * <tt>ServiceReference</tt> objects for services which implement and were registered under
- * the specified class and match the specified filter criteria.
- *
- * <p>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.
- *
- * <p><tt>filter</tt> 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.
- *
- * <p>If <tt>filter</tt> is <tt>null</tt>, all registered services
- * are considered to match the filter.
- * <p>If <tt>filter</tt> cannot be parsed, an {@link InvalidSyntaxException} will
- * be thrown with a human readable message where the filter became unparsable.
- *
- * <p>The following steps are required to select a service:
- * <ol>
- * <li>If the Java Runtime Environment supports permissions, the caller is checked for the
- * <tt>ServicePermission</tt> to get the service with the specified class.
- * If the caller does not have the correct permission, <tt>null</tt> is returned.
- * <li>If the filter string is not <tt>null</tt>, the filter string is
- * parsed and the set of registered services which satisfy the filter is
- * produced.
- * If the filter string is <tt>null</tt>, then all registered services
- * are considered to satisfy the filter.
- * <li>If <code>clazz</code> is not <tt>null</tt>, the set is further reduced to
- * those services which are an <tt>instanceof</tt> 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.
- * <li>An array of <tt>ServiceReference</tt> to the selected services is returned.
- * </ol>
- *
- * @param clazz The class name with which the service was registered, or
- * <tt>null</tt> for all services.
- * @param filter The filter criteria.
- * @return An array of <tt>ServiceReference</tt> objects, or
- * <tt>null</tt> if no services are registered which satisfy the search.
- * @exception InvalidSyntaxException If <tt>filter</tt> contains
- * an invalid filter string which cannot be parsed.
- */
- public ServiceReference<?>[] getServiceReferences(String clazz, String filter) throws InvalidSyntaxException {
- checkValid();
- return framework.getServiceRegistry().getServiceReferences(this, clazz, filter, false);
- }
-
- public ServiceReference<?>[] getAllServiceReferences(String clazz, String filter) throws InvalidSyntaxException {
- checkValid();
- return framework.getServiceRegistry().getServiceReferences(this, clazz, filter, true);
- }
-
- /**
- * Get a service reference.
- * Retrieves a {@link ServiceReference} for a service
- * which implements the named class.
- *
- * <p>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.
- *
- * <p>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 <code>null</code> 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 <code>null</code>
- * if no services are registered which implement the named class.
- * @see #getServiceReferences
- */
- public ServiceReference<?> getServiceReference(String clazz) {
- checkValid();
-
- return framework.getServiceRegistry().getServiceReference(this, 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.
- *
- * <p>This method will always return <code>null</code> when the
- * service associated with this reference has been unregistered.
- *
- * <p>The following steps are followed to get the service object:
- * <ol>
- * <li>If the service has been unregistered,
- * <code>null</code> is returned.
- * <li>The context bundle's use count for this service is incremented by one.
- * <li>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.
- * <br>If the service object returned by the {@link ServiceFactory}
- * is not an <code>instanceof</code>
- * all the classes named when the service was registered or
- * the {@link ServiceFactory} throws an exception,
- * <code>null</code> is returned and a
- * {@link FrameworkEvent} of type {@link FrameworkEvent#ERROR} is broadcast.
- * <li>The service object for the service is returned.
- * </ol>
- *
- * @param reference A reference to the service whose service object is desired.
- * @return A service object for the service associated with this
- * reference, or <code>null</code> 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
- */
- public <S> S getService(ServiceReference<S> reference) {
- checkValid();
- if (reference == null)
- throw new NullPointerException("A null service reference is not allowed."); //$NON-NLS-1$
- synchronized (contextLock) {
- if (servicesInUse == null)
- // Cannot predict how many services a bundle will use, start with a small table.
- servicesInUse = new HashMap<ServiceRegistrationImpl<?>, ServiceUse<?>>(10);
- }
-
- @SuppressWarnings("unchecked")
- S service = (S) framework.getServiceRegistry().getService(this, (ServiceReferenceImpl<S>) reference);
- return 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 <code>false</code>. Otherwise, the context bundle's use count for the
- * service is decremented by one.
- * See {@link #getBundle()} for a definition of context bundle.
- *
- * <p>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.
- *
- * <p>The following steps are followed to unget the service object:
- * <ol>
- * <li>If the context bundle's use count for the service is zero or
- * the service has been unregistered,
- * <code>false</code> is returned.
- * <li>The context bundle's use count for this service is decremented by one.
- * <li>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.
- * <li><code>true</code> is returned.
- * </ol>
- *
- * @param reference A reference to the service to be released.
- * @return <code>false</code> if the context bundle's use count for the service
- * is zero or if the service has been unregistered,
- * otherwise <code>true</code>.
- * @exception java.lang.IllegalStateException
- * If the bundle context has stopped.
- * @see #getService
- * @see ServiceFactory
- */
- public boolean ungetService(ServiceReference<?> reference) {
- checkValid();
-
- return framework.getServiceRegistry().ungetService(this, (ServiceReferenceImpl<?>) reference);
- }
-
- /**
- * Creates a <code>File</code> 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 <code>null</code>.
- *
- * <p>A <code>File</code> 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.
- *
- * <p>If the Java runtime environment supports permissions,
- * the framework the will ensure that the bundle has
- * <code>java.io.FilePermission</code> 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 <code>File</code> object that represents the requested file or
- * <code>null</code> if the adaptor does not have file system support.
- * @exception java.lang.IllegalStateException
- * If the bundle context has stopped.
- */
- public File getDataFile(String filename) {
- checkValid();
-
- return (framework.getDataFile(bundle, filename));
- }
-
- /**
- * 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
- */
- protected void start() throws BundleException {
- activator = bundle.loadBundleActivator();
-
- if (activator != null) {
- try {
- startActivator(activator);
- } catch (BundleException be) {
- activator = null;
- throw be;
- }
- }
-
- /* activator completed successfully. We must use this
- same activator object when we stop this bundle. */
- }
-
- /**
- * Calls the start method of a BundleActivator.
- * @param bundleActivator that activator to start
- */
- protected void startActivator(final BundleActivator bundleActivator) throws BundleException {
- if (Profile.PROFILE && Profile.STARTUP)
- Profile.logEnter("BundleContextImpl.startActivator()", null); //$NON-NLS-1$
- try {
- AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
- public Object run() throws Exception {
- if (bundleActivator != null) {
- if (Profile.PROFILE && Profile.STARTUP)
- Profile.logTime("BundleContextImpl.startActivator()", "calling " + bundle.getLocation() + " bundle activator"); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
- // make sure the context class loader is set correctly
- Object previousTCCL = setContextFinder();
- /* Start the bundle synchronously */
- try {
- bundleActivator.start(BundleContextImpl.this);
- } finally {
- if (previousTCCL != Boolean.FALSE)
- Thread.currentThread().setContextClassLoader((ClassLoader) previousTCCL);
- }
- if (Profile.PROFILE && Profile.STARTUP)
- Profile.logTime("BundleContextImpl.startActivator()", "returned from " + bundle.getLocation() + " bundle activator"); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
- }
- return null;
- }
- });
- } catch (Throwable t) {
- if (t instanceof PrivilegedActionException) {
- t = ((PrivilegedActionException) t).getException();
- }
-
- if (Debug.DEBUG_GENERAL) {
- Debug.printStackTrace(t);
- }
-
- 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$
- } finally {
- if (Profile.PROFILE && Profile.STARTUP)
- Profile.logExit("BundleContextImpl.startActivator()"); //$NON-NLS-1$
- }
- }
-
- Object setContextFinder() {
- if (!SET_TCCL)
- return Boolean.FALSE;
- Thread currentThread = Thread.currentThread();
- ClassLoader previousTCCL = currentThread.getContextClassLoader();
- ClassLoader contextFinder = framework.getContextFinder();
- if (previousTCCL != contextFinder) {
- currentThread.setContextClassLoader(framework.getContextFinder());
- return previousTCCL;
- }
- return Boolean.FALSE;
- }
-
- /**
- * 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
- */
- protected void stop() throws BundleException {
- try {
- AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
- public Object run() throws Exception {
- if (activator != null) {
- // make sure the context class loader is set correctly
- Object previousTCCL = setContextFinder();
- try {
- /* Stop the bundle synchronously */
- activator.stop(BundleContextImpl.this);
- } finally {
- if (previousTCCL != Boolean.FALSE)
- Thread.currentThread().setContextClassLoader((ClassLoader) previousTCCL);
- }
- }
- return null;
- }
- });
- } catch (Throwable t) {
- if (t instanceof PrivilegedActionException) {
- t = ((PrivilegedActionException) t).getException();
- }
-
- if (Debug.DEBUG_GENERAL) {
- Debug.printStackTrace(t);
- }
-
- 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$
- } finally {
- activator = null;
- }
- }
-
- /**
- * 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.
- */
- public Map<ServiceRegistrationImpl<?>, ServiceUse<?>> getServicesInUseMap() {
- synchronized (contextLock) {
- return servicesInUse;
- }
- }
-
- /**
- * 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
- */
- public void dispatchEvent(Object originalListener, Object l, int action, Object object) {
- // save the bundle ref to a local variable
- // to avoid interference from another thread closing this context
- AbstractBundle tmpBundle = bundle;
- Object previousTCCL = setContextFinder();
- try {
- if (isValid()) /* if context still valid */{
- switch (action) {
- case Framework.BUNDLEEVENT :
- case Framework.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[" + tmpBundle + "](" + listenerName + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- BundleEvent event = (BundleEvent) object;
- switch (event.getType()) {
- case Framework.BATCHEVENT_BEGIN : {
- if (listener instanceof BatchBundleListener)
- ((BatchBundleListener) listener).batchBegin();
- break;
- }
- case Framework.BATCHEVENT_END : {
- if (listener instanceof BatchBundleListener)
- ((BatchBundleListener) listener).batchEnd();
- break;
- }
- default : {
- listener.bundleChanged((BundleEvent) object);
- }
- }
- break;
- }
-
- case ServiceRegistry.SERVICEEVENT : {
- ServiceEvent event = (ServiceEvent) object;
-
- ServiceListener listener = (ServiceListener) l;
- if (Debug.DEBUG_EVENTS) {
- String listenerName = listener.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(listener)); //$NON-NLS-1$
- Debug.println("dispatchServiceEvent[" + tmpBundle + "](" + listenerName + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- listener.serviceChanged(event);
-
- break;
- }
-
- case Framework.FRAMEWORKEVENT : {
- FrameworkListener listener = (FrameworkListener) l;
-
- if (Debug.DEBUG_EVENTS) {
- String listenerName = listener.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(listener)); //$NON-NLS-1$
- Debug.println("dispatchFrameworkEvent[" + tmpBundle + "](" + listenerName + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- listener.frameworkEvent((FrameworkEvent) object);
- break;
- }
- default : {
- throw new InternalError();
- }
- }
- }
- } catch (Throwable t) {
- if (Debug.DEBUG_GENERAL) {
- Debug.println("Exception in bottom level event dispatcher: " + t.getMessage()); //$NON-NLS-1$
- Debug.printStackTrace(t);
- }
- // allow the adaptor to handle this unexpected error
- framework.adaptor.handleRuntimeError(t);
- publisherror: {
- if (action == Framework.FRAMEWORKEVENT) {
- FrameworkEvent event = (FrameworkEvent) object;
- if (event.getType() == FrameworkEvent.ERROR) {
- break publisherror; // avoid infinite loop
- }
- }
-
- framework.publishFrameworkEvent(FrameworkEvent.ERROR, tmpBundle, t);
- }
- } finally {
- if (previousTCCL != Boolean.FALSE)
- Thread.currentThread().setContextClassLoader((ClassLoader) previousTCCL);
- }
- }
-
- /**
- * 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.
- */
- public Filter createFilter(String filter) throws InvalidSyntaxException {
- checkValid();
-
- return FilterImpl.newInstance(filter);
- }
-
- /**
- * 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.
- */
- public void checkValid() {
- if (!isValid()) {
- throw new IllegalStateException(Msg.BUNDLE_CONTEXT_INVALID_EXCEPTION);
- }
- }
-
- /**
- * This method checks that the context is still valid.
- *
- * @return true if the context is still valid; false otherwise
- */
- protected boolean isValid() {
- return valid;
- }
-
- public Framework getFramework() {
- return framework;
- }
-
- public <S> ServiceRegistration<S> registerService(Class<S> clazz, S service, Dictionary<String, ?> properties) {
- @SuppressWarnings("unchecked")
- ServiceRegistration<S> registration = (ServiceRegistration<S>) registerService(clazz.getName(), service, properties);
- return registration;
- }
-
- public <S> ServiceReference<S> getServiceReference(Class<S> clazz) {
- @SuppressWarnings("unchecked")
- ServiceReference<S> reference = (ServiceReference<S>) getServiceReference(clazz.getName());
- return reference;
- }
-
- public <S> Collection<ServiceReference<S>> getServiceReferences(Class<S> clazz, String filter) throws InvalidSyntaxException {
- @SuppressWarnings("unchecked")
- ServiceReference<S>[] refs = (ServiceReference<S>[]) getServiceReferences(clazz.getName(), filter);
- if (refs == null) {
- @SuppressWarnings("unchecked")
- Collection<ServiceReference<S>> empty = Collections.EMPTY_LIST;
- return empty;
- }
- List<ServiceReference<S>> result = new ArrayList<ServiceReference<S>>(refs.length);
- for (ServiceReference<S> b : refs) {
- result.add(b);
- }
- return result;
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/BundleFragment.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/BundleFragment.java
deleted file mode 100644
index 98ca8ee24..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/BundleFragment.java
+++ /dev/null
@@ -1,334 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2011 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.framework.internal.core;
-
-import java.io.IOException;
-import java.net.URL;
-import java.util.Enumeration;
-import org.eclipse.osgi.framework.adaptor.BundleData;
-import org.eclipse.osgi.framework.debug.Debug;
-import org.eclipse.osgi.internal.loader.BundleLoader;
-import org.eclipse.osgi.util.NLS;
-import org.osgi.framework.*;
-
-public class BundleFragment extends AbstractBundle {
-
- /** The resolved host that this fragment is attached to */
- protected BundleHost[] hosts;
-
- /**
- * @param bundledata
- * @param framework
- * @throws BundleException
- */
- public BundleFragment(BundleData bundledata, Framework framework) throws BundleException {
- super(bundledata, framework);
- hosts = null;
- }
-
- /**
- * Load the bundle.
- */
- protected void load() {
- if (Debug.DEBUG_GENERAL) {
- if ((state & (INSTALLED)) == 0) {
- Debug.println("Bundle.load called when state != INSTALLED: " + this); //$NON-NLS-1$
- Debug.printStackTrace(new Exception("Stack trace")); //$NON-NLS-1$
- }
- }
-
- if (framework.isActive()) {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null && framework.securityAdmin != null) {
- domain = framework.securityAdmin.createProtectionDomain(this);
- }
- }
- }
-
- /**
- * Reload from a new bundle.
- * This method must be called while holding the bundles lock.
- *
- * @param newBundle Dummy Bundle which contains new data.
- * @return true if an exported package is "in use". i.e. it has been imported by a bundle
- */
- protected boolean reload(AbstractBundle newBundle) {
- if (Debug.DEBUG_GENERAL) {
- if ((state & (INSTALLED | RESOLVED)) == 0) {
- Debug.println("Bundle.reload called when state != INSTALLED | RESOLVED: " + this); //$NON-NLS-1$
- Debug.printStackTrace(new Exception("Stack trace")); //$NON-NLS-1$
- }
- }
-
- boolean exporting = false;
- if (framework.isActive()) {
- if (hosts != null) {
- if (state == RESOLVED) {
- exporting = true; // if we have a host we cannot be removed until the host is refreshed
- hosts = null;
- state = INSTALLED;
- }
- }
- } else {
- /* close the outgoing jarfile */
- try {
- this.bundledata.close();
- } catch (IOException e) {
- // Do Nothing
- }
- }
- if (!exporting) {
- /* close the outgoing jarfile */
- try {
- this.bundledata.close();
- } catch (IOException e) {
- // Do Nothing
- }
- }
-
- this.bundledata = newBundle.bundledata;
- this.bundledata.setBundle(this);
- // create a new domain for the bundle because its signers/symbolic-name may have changed
- if (framework.isActive() && System.getSecurityManager() != null && framework.securityAdmin != null)
- domain = framework.securityAdmin.createProtectionDomain(this);
- return (exporting);
- }
-
- /**
- * Refresh the bundle. This is called by Framework.refreshPackages.
- * This method must be called while holding the bundles lock.
- * this.loader.unimportPackages must have already been called before calling
- * this method!
- */
- protected void refresh() {
- if (Debug.DEBUG_GENERAL) {
- if ((state & (UNINSTALLED | INSTALLED | RESOLVED)) == 0) {
- Debug.println("Bundle.refresh called when state != UNINSTALLED | INSTALLED | RESOLVED: " + this); //$NON-NLS-1$
- Debug.printStackTrace(new Exception("Stack trace")); //$NON-NLS-1$
- }
- }
-
- if (state == RESOLVED) {
- hosts = null;
- state = INSTALLED;
- // Do not publish UNRESOLVED event here. This is done by caller
- // to resolve if appropriate.
- }
- manifestLocalization = null;
- }
-
- /**
- * Unload the bundle.
- * This method must be called while holding the bundles lock.
- *
- * @return true if an exported package is "in use". i.e. it has been imported by a bundle
- */
- protected boolean unload() {
- if (Debug.DEBUG_GENERAL) {
- if ((state & (UNINSTALLED | INSTALLED | RESOLVED)) == 0) {
- Debug.println("Bundle.unload called when state != UNINSTALLED | INSTALLED | RESOLVED: " + this); //$NON-NLS-1$
- Debug.printStackTrace(new Exception("Stack trace")); //$NON-NLS-1$
- }
- }
-
- boolean exporting = false;
- if (framework.isActive()) {
- if (hosts != null) {
- if (state == RESOLVED) {
- exporting = true; // if we have a host we cannot be removed until the host is refreshed
- hosts = null;
- state = INSTALLED;
- }
- domain = null;
- }
- }
- if (!exporting) {
- try {
- this.bundledata.close();
- } catch (IOException e) { // Do Nothing.
- }
- }
-
- return (exporting);
- }
-
- /**
- * This method loads a class from the bundle.
- *
- * @param name the name of the desired Class.
- * @param checkPermission indicates whether a permission check should be done.
- * @return the resulting Class
- * @exception java.lang.ClassNotFoundException if the class definition was not found.
- */
- protected Class<?> loadClass(String name, boolean checkPermission) throws ClassNotFoundException {
- if (checkPermission) {
- try {
- framework.checkAdminPermission(this, AdminPermission.CLASS);
- } catch (SecurityException e) {
- throw new ClassNotFoundException(name, e);
- }
- checkValid();
- }
- // cannot load a class from a fragment because there is no classloader
- // associated with fragments.
- throw new ClassNotFoundException(NLS.bind(Msg.BUNDLE_FRAGMENT_CNFE, name));
- }
-
- /**
- * Find the specified resource in this bundle.
- *
- * This bundle's class loader is called to search for the named resource.
- * If this bundle's state is <tt>INSTALLED</tt>, then only this bundle will
- * be searched for the specified resource. Imported packages cannot be searched
- * when a bundle has not been resolved.
- *
- * @param name The name of the resource.
- * See <tt>java.lang.ClassLoader.getResource</tt> for a description of
- * the format of a resource name.
- * @return a URL to the named resource, or <tt>null</tt> if the resource could
- * not be found or if the caller does not have
- * the <tt>AdminPermission</tt>, and the Java Runtime Environment supports permissions.
- *
- * @exception java.lang.IllegalStateException If this bundle has been uninstalled.
- */
- public URL getResource(String name) {
- checkValid();
- // cannot get a resource for a fragment because there is no classloader
- // associated with fragments.
- return (null);
-
- }
-
- public Enumeration<URL> getResources(String name) {
- checkValid();
- // cannot get a resource for a fragment because there is no classloader
- // associated with fragments.
- return null;
- }
-
- /**
- * Internal worker to start a bundle.
- *
- * @param options
- */
- protected void startWorker(int options) throws BundleException {
- throw new BundleException(NLS.bind(Msg.BUNDLE_FRAGMENT_START, this), BundleException.INVALID_OPERATION);
- }
-
- /**
- * Internal worker to stop a bundle.
- *
- * @param options
- */
- protected void stopWorker(int options) throws BundleException {
- throw new BundleException(NLS.bind(Msg.BUNDLE_FRAGMENT_STOP, this), BundleException.INVALID_OPERATION);
- }
-
- /**
- * Provides a list of {@link ServiceReference}s for the services
- * registered by this bundle
- * or <code>null</code> if the bundle has no registered
- * services.
- *
- * <p>The list is valid at the time
- * of the call to this method, but the framework is a very dynamic
- * environment and services can be modified or unregistered at anytime.
- *
- * @return An array of {@link ServiceReference} or <code>null</code>.
- * @exception java.lang.IllegalStateException If the
- * bundle has been uninstalled.
- * @see ServiceRegistration
- * @see ServiceReference
- */
- public ServiceReference<?>[] getRegisteredServices() {
- checkValid();
- // Fragments cannot have a BundleContext and therefore
- // cannot have any services registered.
- return null;
- }
-
- /**
- * Provides a list of {@link ServiceReference}s for the
- * services this bundle is using,
- * or <code>null</code> if the bundle is not using any services.
- * A bundle is considered to be using a service if the bundle's
- * use count for the service is greater than zero.
- *
- * <p>The list is valid at the time
- * of the call to this method, but the framework is a very dynamic
- * environment and services can be modified or unregistered at anytime.
- *
- * @return An array of {@link ServiceReference} or <code>null</code>.
- * @exception java.lang.IllegalStateException If the
- * bundle has been uninstalled.
- * @see ServiceReference
- */
- public ServiceReference<?>[] getServicesInUse() {
- checkValid();
- // Fragments cannot have a BundleContext and therefore
- // cannot have any services in use.
- return null;
- }
-
- synchronized BundleHost[] getHosts() {
- return hosts;
- }
-
- protected boolean isFragment() {
- return true;
- }
-
- /**
- * Adds a host bundle for this fragment.
- * @param host the BundleHost to add to the set of host bundles
- */
- boolean addHost(BundleHost host) {
- if (host == null)
- return false;
- try {
- host.attachFragment(this);
- } catch (BundleException be) {
- framework.publishFrameworkEvent(FrameworkEvent.ERROR, host, be);
- return false;
- }
- synchronized (this) {
- if (hosts == null) {
- hosts = new BundleHost[] {host};
- return true;
- }
- for (int i = 0; i < hosts.length; i++) {
- if (host == hosts[i])
- return true; // already a host
- }
- BundleHost[] newHosts = new BundleHost[hosts.length + 1];
- System.arraycopy(hosts, 0, newHosts, 0, hosts.length);
- newHosts[newHosts.length - 1] = host;
- hosts = newHosts;
- }
- return true;
- }
-
- protected BundleLoader getBundleLoader() {
- // Fragments cannot have a BundleLoader.
- return null;
- }
-
- /**
- * Return the current context for this bundle.
- *
- * @return BundleContext for this bundle.
- */
- protected BundleContextImpl getContext() {
- // Fragments cannot have a BundleContext.
- return null;
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/BundleHost.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/BundleHost.java
deleted file mode 100644
index cfc55b0a3..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/BundleHost.java
+++ /dev/null
@@ -1,686 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2011 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.framework.internal.core;
-
-import java.io.IOException;
-import java.net.URL;
-import java.util.Enumeration;
-import org.eclipse.osgi.framework.adaptor.*;
-import org.eclipse.osgi.framework.debug.Debug;
-import org.eclipse.osgi.framework.log.FrameworkLogEntry;
-import org.eclipse.osgi.internal.loader.BundleLoader;
-import org.eclipse.osgi.internal.loader.BundleLoaderProxy;
-import org.eclipse.osgi.service.resolver.BundleDescription;
-import org.eclipse.osgi.service.resolver.ResolverHookException;
-import org.eclipse.osgi.util.NLS;
-import org.osgi.framework.*;
-
-public class BundleHost extends AbstractBundle {
- public static final int LAZY_TRIGGER = 0x40000000;
- /**
- * The BundleLoader proxy; a lightweight object that acts as a proxy
- * to the BundleLoader and allows lazy creation of the BundleLoader object
- */
- private BundleLoaderProxy proxy;
-
- /** The BundleContext that represents this Bundle and all of its fragments */
- protected BundleContextImpl context;
-
- /** The List of BundleFragments */
- protected BundleFragment[] fragments;
-
- public BundleHost(BundleData bundledata, Framework framework) {
- super(bundledata, framework);
- context = null;
- fragments = null;
- }
-
- /**
- * Load the bundle.
- */
- protected void load() {
- if (Debug.DEBUG_GENERAL) {
- if ((state & (INSTALLED)) == 0) {
- Debug.println("Bundle.load called when state != INSTALLED: " + this); //$NON-NLS-1$
- Debug.printStackTrace(new Exception("Stack trace")); //$NON-NLS-1$
- }
- if (proxy != null) {
- Debug.println("Bundle.load called when proxy != null: " + this); //$NON-NLS-1$
- Debug.printStackTrace(new Exception("Stack trace")); //$NON-NLS-1$
- }
- }
-
- if (framework.isActive()) {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null && framework.securityAdmin != null) {
- domain = framework.securityAdmin.createProtectionDomain(this);
- }
- }
- proxy = null;
- }
-
- /**
- * Reload from a new bundle.
- * This method must be called while holding the bundles lock.
- *
- * @param newBundle Dummy Bundle which contains new data.
- * @return true if an exported package is "in use". i.e. it has been imported by a bundle
- */
- protected boolean reload(AbstractBundle newBundle) {
- if (Debug.DEBUG_GENERAL) {
- if ((state & (INSTALLED | RESOLVED)) == 0) {
- Debug.println("Bundle.reload called when state != INSTALLED | RESOLVED: " + this); //$NON-NLS-1$
- Debug.printStackTrace(new Exception("Stack trace")); //$NON-NLS-1$
- }
- }
-
- boolean exporting = false;
-
- if (framework.isActive()) {
- if (state == RESOLVED) {
- BundleLoaderProxy curProxy = getLoaderProxy();
- exporting = curProxy.inUse();
- if (exporting) {
- // make sure the BundleLoader is created.
- curProxy.getBundleLoader().createClassLoader();
- } else
- BundleLoader.closeBundleLoader(proxy);
- state = INSTALLED;
- proxy = null;
- fragments = null;
- }
-
- } else {
- /* close the outgoing jarfile */
- try {
- this.bundledata.close();
- } catch (IOException e) {
- // Do Nothing
- }
- }
- this.bundledata = newBundle.bundledata;
- this.bundledata.setBundle(this);
- // create a new domain for the bundle because its signers/symbolic-name may have changed
- if (framework.isActive() && System.getSecurityManager() != null && framework.securityAdmin != null)
- domain = framework.securityAdmin.createProtectionDomain(this);
- return (exporting);
- }
-
- /**
- * Refresh the bundle. This is called by Framework.refreshPackages.
- * This method must be called while holding the bundles lock.
- */
- protected void refresh() {
- if (Debug.DEBUG_GENERAL) {
- if ((state & (UNINSTALLED | INSTALLED | RESOLVED)) == 0) {
- Debug.println("Bundle.reload called when state != UNINSTALLED | INSTALLED | RESOLVED: " + this); //$NON-NLS-1$
- Debug.printStackTrace(new Exception("Stack trace")); //$NON-NLS-1$
- }
- }
- if (state == RESOLVED) {
- BundleLoader.closeBundleLoader(proxy);
- proxy = null;
- fragments = null;
- state = INSTALLED;
- // Do not publish UNRESOLVED event here. This is done by caller
- // to resolve if appropriate.
- }
- manifestLocalization = null;
- }
-
- /**
- * Unload the bundle.
- * This method must be called while holding the bundles lock.
- *
- * @return true if an exported package is "in use". i.e. it has been imported by a bundle
- */
- protected boolean unload() {
- if (Debug.DEBUG_GENERAL) {
- if ((state & (UNINSTALLED | INSTALLED | RESOLVED)) == 0) {
- Debug.println("Bundle.unload called when state != UNINSTALLED | INSTALLED | RESOLVED: " + this); //$NON-NLS-1$
- Debug.printStackTrace(new Exception("Stack trace")); //$NON-NLS-1$
- }
- }
-
- boolean exporting = false;
-
- if (framework.isActive()) {
- if (state == RESOLVED) {
- BundleLoaderProxy curProxy = getLoaderProxy();
- exporting = curProxy.inUse();
- if (exporting) {
- // make sure the BundleLoader is created.
- curProxy.getBundleLoader().createClassLoader();
- } else
- BundleLoader.closeBundleLoader(proxy);
-
- state = INSTALLED;
- proxy = null;
- fragments = null;
- domain = null;
- }
- }
- if (!exporting) {
- try {
- this.bundledata.close();
- } catch (IOException e) { // Do Nothing.
- }
- }
-
- return (exporting);
- }
-
- private BundleLoader checkLoader() {
- checkValid();
-
- // check to see if the bundle is resolved
- if (!isResolved()) {
- if (!framework.packageAdmin.resolveBundles(new Bundle[] {this})) {
- return null;
- }
- }
- if (Debug.DEBUG_GENERAL) {
- if ((state & (STARTING | ACTIVE | STOPPING | RESOLVED)) == 0) {
- Debug.println("Bundle.checkLoader() called when state != STARTING | ACTIVE | STOPPING | RESOLVED: " + this); //$NON-NLS-1$
- Debug.printStackTrace(new Exception("Stack trace")); //$NON-NLS-1$
- }
- }
-
- BundleLoader loader = getBundleLoader();
- if (loader == null) {
- if (Debug.DEBUG_GENERAL) {
- Debug.println("Bundle.checkLoader() called when loader == null: " + this); //$NON-NLS-1$
- Debug.printStackTrace(new Exception("Stack trace")); //$NON-NLS-1$
- }
- return null;
- }
- return loader;
- }
-
- /**
- * This method loads a class from the bundle.
- *
- * @param name the name of the desired Class.
- * @param checkPermission indicates whether a permission check should be done.
- * @return the resulting Class
- * @exception java.lang.ClassNotFoundException if the class definition was not found.
- */
- protected Class<?> loadClass(String name, boolean checkPermission) throws ClassNotFoundException {
- if (checkPermission) {
- try {
- framework.checkAdminPermission(this, AdminPermission.CLASS);
- } catch (SecurityException e) {
- throw new ClassNotFoundException(name, e);
- }
- }
- BundleLoader loader = checkLoader();
- if (loader == null)
- throw new ClassNotFoundException(NLS.bind(Msg.BUNDLE_CNFE_NOT_RESOLVED, name, getBundleData().getLocation()));
- try {
- return (loader.loadClass(name));
- } catch (ClassNotFoundException e) {
- // this is to support backward compatibility in eclipse
- // we always attempted to start a bundle even if the class was not found
- if (!(e instanceof StatusException) && (bundledata.getStatus() & Constants.BUNDLE_LAZY_START) != 0 && !testStateChanging(Thread.currentThread()))
- try {
- // only start the bundle if this is a simple CNFE
- loader.setLazyTrigger();
- } catch (BundleException be) {
- framework.adaptor.getFrameworkLog().log(new FrameworkLogEntry(FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME, FrameworkLogEntry.WARNING, 0, be.getMessage(), 0, be, null));
- }
- throw e;
- }
- }
-
- /**
- * Find the specified resource in this bundle.
- *
- * This bundle's class loader is called to search for the named resource.
- * If this bundle's state is <tt>INSTALLED</tt>, then only this bundle will
- * be searched for the specified resource. Imported packages cannot be searched
- * when a bundle has not been resolved.
- *
- * @param name The name of the resource.
- * See <tt>java.lang.ClassLoader.getResource</tt> for a description of
- * the format of a resource name.
- * @return a URL to the named resource, or <tt>null</tt> if the resource could
- * not be found or if the caller does not have
- * the <tt>AdminPermission</tt>, and the Java Runtime Environment supports permissions.
- *
- * @exception java.lang.IllegalStateException If this bundle has been uninstalled.
- */
- public URL getResource(String name) {
- BundleLoader loader = null;
- try {
- framework.checkAdminPermission(this, AdminPermission.RESOURCE);
- } catch (SecurityException ee) {
- return null;
- }
- loader = checkLoader();
- if (loader == null) {
- Enumeration<URL> result = bundledata.findLocalResources(name);
- if (result != null && result.hasMoreElements())
- return result.nextElement();
- return null;
- }
- return loader.findResource(name);
- }
-
- public Enumeration<URL> getResources(String name) throws IOException {
- BundleLoader loader = null;
- try {
- framework.checkAdminPermission(this, AdminPermission.RESOURCE);
- } catch (SecurityException ee) {
- return null;
- }
- Enumeration<URL> result;
- loader = checkLoader();
- if (loader == null)
- result = bundledata.findLocalResources(name);
- else
- result = loader.getResources(name);
- if (result != null && result.hasMoreElements())
- return result;
- return null;
- }
-
- /**
- * Internal worker to start a bundle.
- *
- * @param options the start options
- */
- protected void startWorker(int options) throws BundleException {
- if ((options & START_TRANSIENT) == 0) {
- setStatus(Constants.BUNDLE_STARTED, true);
- setStatus(Constants.BUNDLE_ACTIVATION_POLICY, (options & START_ACTIVATION_POLICY) != 0);
- if (Debug.MONITOR_ACTIVATION)
- new Exception("A persistent start has been called on bundle: " + getBundleData()).printStackTrace(); //$NON-NLS-1$
- }
- if (!framework.active || (state & ACTIVE) != 0)
- return;
- if (getInternalStartLevel() > framework.startLevelManager.getStartLevel()) {
- if ((options & LAZY_TRIGGER) == 0 && (options & START_TRANSIENT) != 0) {
- // throw exception if this is a transient start
- String msg = NLS.bind(Msg.BUNDLE_TRANSIENT_START_ERROR, this);
- // Use a StatusException to indicate to the lazy starter that this should result in a warning
- throw new BundleException(msg, BundleException.INVALID_OPERATION, new BundleStatusException(msg, StatusException.CODE_WARNING, this));
- }
- return;
- }
-
- if (state == INSTALLED) {
- try {
- if (!framework.packageAdmin.resolveBundles(new Bundle[] {this}, true))
- throw getResolutionFailureException();
- } catch (IllegalStateException e) {
- // Can happen if the resolver detects a nested resolve process
- throw new BundleException("Unexpected resolution exception.", BundleException.RESOLVE_ERROR, e); //$NON-NLS-1$
- } catch (ResolverHookException e) {
- throw new BundleException("Unexpected resolution exception.", BundleException.REJECTED_BY_HOOK, e.getCause()); //$NON-NLS-1$
- }
-
- }
-
- if ((options & START_ACTIVATION_POLICY) != 0 && (bundledata.getStatus() & Constants.BUNDLE_LAZY_START) != 0) {
- // the bundle must use the activation policy here.
- if ((state & RESOLVED) != 0) {
- // now we must publish the LAZY_ACTIVATION event and return
- state = STARTING;
- // release the state change lock before sending lazy activation event (bug 258659)
- completeStateChange();
- framework.publishBundleEvent(BundleEvent.LAZY_ACTIVATION, this);
- }
- return;
- }
-
- if (Debug.DEBUG_GENERAL) {
- Debug.println("Bundle: Active sl = " + framework.startLevelManager.getStartLevel() + "; Bundle " + getBundleId() + " sl = " + getInternalStartLevel()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- if ((options & LAZY_TRIGGER) != 0) {
- if ((state & RESOLVED) != 0) {
- // Should publish the lazy activation event here before the starting event
- // This can happen if another bundle in the same start-level causes a class load from the lazy start bundle.
- state = STARTING;
- // release the state change lock before sending lazy activation event (bug 258659)
- completeStateChange();
- framework.publishBundleEvent(BundleEvent.LAZY_ACTIVATION, this);
- beginStateChange();
- if (state != STARTING) {
- // while firing the LAZY_ACTIVATION event some one else caused the bundle to transition
- // out of STARTING. This could have happened because some listener called start on the bundle
- // or another class load could have caused the start trigger to get fired again.
- return;
- }
- }
- }
- state = STARTING;
- framework.publishBundleEvent(BundleEvent.STARTING, this);
- context = getContext();
- //STARTUP TIMING Start here
- long start = 0;
-
- BundleWatcher bundleStats = framework.adaptor.getBundleWatcher();
- if (bundleStats != null)
- bundleStats.watchBundle(this, BundleWatcher.START_ACTIVATION);
- if (Debug.DEBUG_BUNDLE_TIME) {
- start = System.currentTimeMillis();
- System.out.println("Starting " + getSymbolicName()); //$NON-NLS-1$
- }
-
- try {
- context.start();
- startHook();
- if (framework.active) {
- state = ACTIVE;
-
- if (Debug.DEBUG_GENERAL) {
- Debug.println("->started " + this); //$NON-NLS-1$
- }
- // release the state change lock before sending lazy activation event (bug 258659)
- completeStateChange();
- framework.publishBundleEvent(BundleEvent.STARTED, this);
- }
-
- } catch (BundleException e) {
- // we must fire the stopping event
- state = STOPPING;
- framework.publishBundleEvent(BundleEvent.STOPPING, this);
-
- stopHook();
- context.close();
- context = null;
-
- state = RESOLVED;
- // if this is a lazy start bundle that fails to start then
- // we must fire the stopped event
- framework.publishBundleEvent(BundleEvent.STOPPED, this);
- throw e;
- } finally {
- if (bundleStats != null)
- bundleStats.watchBundle(this, BundleWatcher.END_ACTIVATION);
- if (Debug.DEBUG_BUNDLE_TIME)
- System.out.println("End starting " + getSymbolicName() + " " + (System.currentTimeMillis() - start)); //$NON-NLS-1$ //$NON-NLS-2$
-
- }
-
- if (state == UNINSTALLED) {
- context.close();
- context = null;
- throw new BundleException(NLS.bind(Msg.BUNDLE_UNINSTALLED_EXCEPTION, getBundleData().getLocation()), BundleException.STATECHANGE_ERROR);
- }
- }
-
- /**
- * @throws BundleException
- */
- protected void startHook() throws BundleException {
- // do nothing by default
- }
-
- protected boolean readyToResume() {
- // Return false if the bundle is not at the correct start-level
- if (getInternalStartLevel() > framework.startLevelManager.getStartLevel())
- return false;
- int status = bundledata.getStatus();
- // Return false if the bundle is not persistently marked for start
- if ((status & Constants.BUNDLE_STARTED) == 0)
- return false;
- if ((status & Constants.BUNDLE_ACTIVATION_POLICY) == 0 || (status & Constants.BUNDLE_LAZY_START) == 0 || isLazyTriggerSet())
- return true;
- if (!isResolved()) {
- if (framework.getAdaptor().getState().isResolved() || !framework.packageAdmin.resolveBundles(new Bundle[] {this}))
- // should never transition from UNRESOLVED -> STARTING
- return false;
- }
- // now we can publish the LAZY_ACTIVATION event
- state = STARTING;
- // release the state change lock before sending lazy activation event (bug 258659)
- completeStateChange();
- framework.publishBundleEvent(BundleEvent.LAZY_ACTIVATION, this);
- return false;
- }
-
- private synchronized boolean isLazyTriggerSet() {
- if (proxy == null)
- return false;
- BundleLoader loader = proxy.getBasicBundleLoader();
- return loader != null ? loader.isLazyTriggerSet() : false;
- }
-
- /**
- * Create a BundleContext for this bundle.
- *
- * @return BundleContext for this bundle.
- */
- protected BundleContextImpl createContext() {
- return (new BundleContextImpl(this));
- }
-
- /**
- * Return the current context for this bundle.
- *
- * @return BundleContext for this bundle.
- */
- protected synchronized BundleContextImpl getContext() {
- if (context == null) {
- // only create the context if we are starting, active or stopping
- // this is so that SCR can get the context for lazy-start bundles
- if ((state & (STARTING | ACTIVE | STOPPING)) != 0)
- context = createContext();
- }
- return (context);
- }
-
- /**
- * Internal worker to stop a bundle.
- *
- * @param options the stop options
- */
- protected void stopWorker(int options) throws BundleException {
- if ((options & STOP_TRANSIENT) == 0) {
- setStatus(Constants.BUNDLE_STARTED, false);
- setStatus(Constants.BUNDLE_ACTIVATION_POLICY, false);
- if (Debug.MONITOR_ACTIVATION)
- new Exception("A persistent start has been called on bundle: " + getBundleData()).printStackTrace(); //$NON-NLS-1$
- }
- if (framework.active) {
- if ((state & (STOPPING | RESOLVED | INSTALLED)) != 0) {
- return;
- }
-
- BundleWatcher bundleStats = framework.adaptor.getBundleWatcher();
- if (bundleStats != null)
- bundleStats.watchBundle(this, BundleWatcher.START_DEACTIVATION);
-
- state = STOPPING;
- framework.publishBundleEvent(BundleEvent.STOPPING, this);
- try {
- // context may be null if a lazy-start bundle is STARTING
- if (context != null)
- context.stop();
- } finally {
- stopHook();
- if (context != null) {
- context.close();
- context = null;
- }
-
- checkValid();
-
- state = RESOLVED;
-
- if (Debug.DEBUG_GENERAL) {
- Debug.println("->stopped " + this); //$NON-NLS-1$
- }
-
- framework.publishBundleEvent(BundleEvent.STOPPED, this);
- if (bundleStats != null)
- bundleStats.watchBundle(this, BundleWatcher.END_DEACTIVATION);
-
- }
- }
- }
-
- /**
- * @throws BundleException
- */
- protected void stopHook() throws BundleException {
- // do nothing
- }
-
- /**
- * Provides a list of {@link ServiceReference}s for the services
- * registered by this bundle
- * or <code>null</code> if the bundle has no registered
- * services.
- *
- * <p>The list is valid at the time
- * of the call to this method, but the framework is a very dynamic
- * environment and services can be modified or unregistered at anytime.
- *
- * @return An array of {@link ServiceReference} or <code>null</code>.
- * @exception java.lang.IllegalStateException If the
- * bundle has been uninstalled.
- * @see ServiceRegistration
- * @see ServiceReference
- */
- public ServiceReference<?>[] getRegisteredServices() {
- checkValid();
-
- if (context == null) {
- return null;
- }
-
- return context.getFramework().getServiceRegistry().getRegisteredServices(context);
- }
-
- /**
- * Provides a list of {@link ServiceReference}s for the
- * services this bundle is using,
- * or <code>null</code> if the bundle is not using any services.
- * A bundle is considered to be using a service if the bundle's
- * use count for the service is greater than zero.
- *
- * <p>The list is valid at the time
- * of the call to this method, but the framework is a very dynamic
- * environment and services can be modified or unregistered at anytime.
- *
- * @return An array of {@link ServiceReference} or <code>null</code>.
- * @exception java.lang.IllegalStateException If the
- * bundle has been uninstalled.
- * @see ServiceReference
- */
- public ServiceReference<?>[] getServicesInUse() {
- checkValid();
-
- if (context == null) {
- return null;
- }
-
- return context.getFramework().getServiceRegistry().getServicesInUse(context);
- }
-
- public BundleFragment[] getFragments() {
- synchronized (framework.bundles) {
- if (fragments == null)
- return null;
- BundleFragment[] result = new BundleFragment[fragments.length];
- System.arraycopy(fragments, 0, result, 0, result.length);
- return result;
- }
- }
-
- /**
- * Attaches a fragment to this BundleHost. Fragments must be attached to
- * the host by ID order. If the ClassLoader of the host is already created
- * then the fragment must be attached to the host ClassLoader
- * @param fragment The fragment bundle to attach
- * return true if the fragment successfully attached; false if the fragment
- * could not be logically inserted at the end of the fragment chain.
- */
- protected void attachFragment(BundleFragment fragment) throws BundleException {
- // do not force the creation of the bundle loader here
- BundleLoader loader = getLoaderProxy().getBasicBundleLoader();
- // If the Host ClassLoader exists then we must attach
- // the fragment to the ClassLoader.
- if (loader != null)
- loader.attachFragment(fragment);
-
- if (fragments == null) {
- fragments = new BundleFragment[] {fragment};
- } else {
- boolean inserted = false;
- // We must keep our fragments ordered by bundle ID; or
- // install order.
- BundleFragment[] newFragments = new BundleFragment[fragments.length + 1];
- for (int i = 0; i < fragments.length; i++) {
- if (fragment == fragments[i])
- return; // this fragment is already attached
- // need to flush the other attached fragment manifest caches in case the attaching fragment provides translations (bug 339211)
- fragments[i].manifestLocalization = null;
- if (!inserted && fragment.getBundleId() < fragments[i].getBundleId()) {
- // if the loader has already been created
- // then we cannot attach a fragment into the middle
- // of the fragment chain.
- if (loader != null) {
- throw new BundleException(NLS.bind(Msg.BUNDLE_LOADER_ATTACHMENT_ERROR, fragments[i].getSymbolicName(), getSymbolicName()), BundleException.INVALID_OPERATION);
- }
- newFragments[i] = fragment;
- inserted = true;
- }
- newFragments[inserted ? i + 1 : i] = fragments[i];
- }
- if (!inserted)
- newFragments[newFragments.length - 1] = fragment;
- fragments = newFragments;
- }
- // need to flush the manifest cache in case the attaching fragment provides translations
- manifestLocalization = null;
- }
-
- protected BundleLoader getBundleLoader() {
- BundleLoaderProxy curProxy = getLoaderProxy();
- return curProxy == null ? null : curProxy.getBundleLoader();
- }
-
- public synchronized BundleLoaderProxy getLoaderProxy() {
- if (proxy != null)
- return proxy;
- BundleDescription bundleDescription = getBundleDescription();
- if (bundleDescription == null)
- return null;
- proxy = new BundleLoaderProxy(this, bundleDescription);
- // Note that BundleLoaderProxy is a BundleReference
- // this is necessary to ensure the resolver can continue
- // to provide BundleRevision objects to resolver hooks.
- bundleDescription.setUserObject(proxy);
- return proxy;
- }
-
- /**
- * Gets the class loader for the host bundle. This may end up
- * creating the bundle class loader if it was not already created.
- * A null value may be returned if the bundle is not resolved.
- * @return the bundle class loader or null if the bundle is not resolved.
- */
- public ClassLoader getClassLoader() {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null)
- sm.checkPermission(new RuntimePermission("getClassLoader")); //$NON-NLS-1$
- BundleLoaderProxy curProxy = getLoaderProxy();
- BundleLoader loader = curProxy == null ? null : curProxy.getBundleLoader();
- BundleClassLoader bcl = loader == null ? null : loader.createClassLoader();
- return (bcl instanceof ClassLoader) ? (ClassLoader) bcl : null;
- }
-
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/BundleRepository.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/BundleRepository.java
deleted file mode 100644
index f10edf828..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/BundleRepository.java
+++ /dev/null
@@ -1,196 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2011 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- * Rob Harrop - SpringSource Inc. (bug 247521)
- *******************************************************************************/
-
-package org.eclipse.osgi.framework.internal.core;
-
-import java.util.*;
-import org.eclipse.osgi.framework.util.KeyedHashSet;
-import org.osgi.framework.Version;
-
-/**
- * The BundleRepository holds all installed Bundle object for the
- * Framework. The BundleRepository is also used to mark and unmark
- * bundle dependancies.
- *
- * <p>
- * This class is internally synchronized and supports client locking. Clients
- * wishing to perform threadsafe composite operations on instances of this
- * class can synchronize on the instance itself when doing these operations.
- */
-public final class BundleRepository {
- /** bundles by install order */
- private List<AbstractBundle> bundlesByInstallOrder;
-
- /** bundles keyed by bundle Id */
- private KeyedHashSet bundlesById;
-
- /** bundles keyed by SymbolicName */
- private Map<String, AbstractBundle[]> bundlesBySymbolicName;
-
- public BundleRepository(int initialCapacity) {
- synchronized (this) {
- bundlesByInstallOrder = new ArrayList<AbstractBundle>(initialCapacity);
- bundlesById = new KeyedHashSet(initialCapacity, true);
- bundlesBySymbolicName = new HashMap<String, AbstractBundle[]>(initialCapacity);
- }
- }
-
- /**
- * Gets a list of bundles ordered by install order.
- * @return List of bundles by install order.
- */
- public synchronized List<AbstractBundle> getBundles() {
- return bundlesByInstallOrder;
- }
-
- /**
- * Gets a bundle by its bundle Id.
- * @param bundleId
- * @return a bundle with the specified id or null if one does not exist
- */
- public synchronized AbstractBundle getBundle(long bundleId) {
- Long key = new Long(bundleId);
- return (AbstractBundle) bundlesById.getByKey(key);
- }
-
- public synchronized AbstractBundle[] getBundles(String symbolicName) {
- if (Constants.SYSTEM_BUNDLE_SYMBOLICNAME.equals(symbolicName))
- symbolicName = Constants.getInternalSymbolicName();
- return bundlesBySymbolicName.get(symbolicName);
- }
-
- @SuppressWarnings("unchecked")
- public synchronized List<AbstractBundle> getBundles(String symbolicName, Version version) {
- AbstractBundle[] bundles = getBundles(symbolicName);
- List<AbstractBundle> result = null;
- if (bundles != null) {
- if (bundles.length > 0) {
- for (int i = 0; i < bundles.length; i++) {
- if (bundles[i].getVersion().equals(version)) {
- if (result == null)
- result = new ArrayList<AbstractBundle>();
- result.add(bundles[i]);
- }
- }
- }
- }
- return result == null ? Collections.EMPTY_LIST : result;
- }
-
- public synchronized void add(AbstractBundle bundle) {
- bundlesByInstallOrder.add(bundle);
- bundlesById.add(bundle);
- addSymbolicName(bundle);
- }
-
- private void addSymbolicName(AbstractBundle bundle) {
- String symbolicName = bundle.getSymbolicName();
- if (symbolicName == null)
- return;
- AbstractBundle[] bundles = bundlesBySymbolicName.get(symbolicName);
- if (bundles == null) {
- // making the initial capacity on this 1 since it
- // should be rare that multiple version exist
- bundles = new AbstractBundle[1];
- bundles[0] = bundle;
- bundlesBySymbolicName.put(symbolicName, bundles);
- return;
- }
-
- List<AbstractBundle> list = new ArrayList<AbstractBundle>(bundles.length + 1);
- // find place to insert the bundle
- Version newVersion = bundle.getVersion();
- boolean added = false;
- for (int i = 0; i < bundles.length; i++) {
- AbstractBundle oldBundle = bundles[i];
- Version oldVersion = oldBundle.getVersion();
- if (!added && newVersion.compareTo(oldVersion) >= 0) {
- added = true;
- list.add(bundle);
- }
- list.add(oldBundle);
- }
- if (!added) {
- list.add(bundle);
- }
-
- bundles = new AbstractBundle[list.size()];
- list.toArray(bundles);
- bundlesBySymbolicName.put(symbolicName, bundles);
- }
-
- public synchronized boolean remove(AbstractBundle bundle) {
- // remove by bundle ID
- boolean found = bundlesById.remove(bundle);
- if (!found)
- return false;
-
- // remove by install order
- bundlesByInstallOrder.remove(bundle);
- // remove by symbolic name
- String symbolicName = bundle.getSymbolicName();
- if (symbolicName == null)
- return true;
- removeSymbolicName(symbolicName, bundle);
- return true;
- }
-
- private void removeSymbolicName(String symbolicName, AbstractBundle bundle) {
- AbstractBundle[] bundles = bundlesBySymbolicName.get(symbolicName);
- if (bundles == null)
- return;
-
- // found some bundles with the global name.
- // remove all references to the specified bundle.
- int numRemoved = 0;
- for (int i = 0; i < bundles.length; i++) {
- if (bundle == bundles[i]) {
- numRemoved++;
- bundles[i] = null;
- }
- }
- if (numRemoved > 0) {
- if (bundles.length - numRemoved <= 0) {
- // no bundles left in the array remove the array from the hash
- bundlesBySymbolicName.remove(symbolicName);
- } else {
- // create a new array with the null entries removed.
- AbstractBundle[] newBundles = new AbstractBundle[bundles.length - numRemoved];
- int indexCnt = 0;
- for (int i = 0; i < bundles.length; i++) {
- if (bundles[i] != null) {
- newBundles[indexCnt] = bundles[i];
- indexCnt++;
- }
- }
- bundlesBySymbolicName.put(symbolicName, newBundles);
- }
- }
- }
-
- public synchronized void update(String oldSymbolicName, AbstractBundle bundle) {
- if (oldSymbolicName != null) {
- if (!oldSymbolicName.equals(bundle.getSymbolicName())) {
- removeSymbolicName(oldSymbolicName, bundle);
- addSymbolicName(bundle);
- }
- } else {
- addSymbolicName(bundle);
- }
- }
-
- public synchronized void removeAllBundles() {
- bundlesByInstallOrder.clear();
- bundlesById = new KeyedHashSet();
- bundlesBySymbolicName.clear();
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/BundleSource.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/BundleSource.java
deleted file mode 100644
index a27e1ee9a..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/BundleSource.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.framework.internal.core;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URLConnection;
-
-/**
- * BundleSource class to wrap in InputStream.
- *
- * <p>This class implements a URLConnection which
- * wraps an InputStream.
- */
-public class BundleSource extends URLConnection {
- private InputStream in;
-
- protected BundleSource(InputStream in) {
- super(null);
- this.in = in;
- }
-
- /**
- * @throws IOException
- */
- public void connect() throws IOException {
- connected = true;
- }
-
- /**
- * @throws IOException
- */
- public InputStream getInputStream() throws IOException {
- return (in);
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/Constants.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/Constants.java
deleted file mode 100644
index 1bd279453..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/Constants.java
+++ /dev/null
@@ -1,254 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2004, 2011 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.framework.internal.core;
-
-/**
- * This interface contains the constants used by the eclipse
- * OSGi implementation.
- */
-
-public class Constants implements org.osgi.framework.Constants {
- /** Default framework version */
- public static final String OSGI_FRAMEWORK_VERSION = "1.3"; //$NON-NLS-1$
-
- /** Framework vendor */
- public static final String OSGI_FRAMEWORK_VENDOR = "Eclipse"; //$NON-NLS-1$
-
- /** Bundle manifest name */
- public static final String OSGI_BUNDLE_MANIFEST = "META-INF/MANIFEST.MF"; //$NON-NLS-1$
-
- /** OSGi framework package name. */
- public static final String OSGI_FRAMEWORK_PACKAGE = "org.osgi.framework"; //$NON-NLS-1$
-
- /** Bundle resource URL protocol */
- public static final String OSGI_RESOURCE_URL_PROTOCOL = "bundleresource"; //$NON-NLS-1$
-
- /** Bundle entry URL protocol */
- public static final String OSGI_ENTRY_URL_PROTOCOL = "bundleentry"; //$NON-NLS-1$
-
- /** Processor aliases resource */
- public static final String OSGI_PROCESSOR_ALIASES = "processor.aliases"; //$NON-NLS-1$
-
- /** OS name aliases resource */
- public static final String OSGI_OSNAME_ALIASES = "osname.aliases"; //$NON-NLS-1$
-
- /** Default permissions for bundles with no permission set
- * and there are no default permissions set.
- */
- public static final String OSGI_DEFAULT_DEFAULT_PERMISSIONS = "default.permissions"; //$NON-NLS-1$
-
- /** Base implied permissions for all bundles */
- public static final String OSGI_BASE_IMPLIED_PERMISSIONS = "implied.permissions"; //$NON-NLS-1$
-
- /** Name of OSGi LogService */
- public static final String OSGI_LOGSERVICE_NAME = "org.osgi.service.log.LogService"; //$NON-NLS-1$
-
- /** Name of OSGi PackageAdmin */
- public static final String OSGI_PACKAGEADMIN_NAME = "org.osgi.service.packageadmin.PackageAdmin"; //$NON-NLS-1$
-
- /** Name of OSGi PermissionAdmin */
- public static final String OSGI_PERMISSIONADMIN_NAME = "org.osgi.service.permissionadmin.PermissionAdmin"; //$NON-NLS-1$
-
- /** Name of OSGi StartLevel */
- public static final String OSGI_STARTLEVEL_NAME = "org.osgi.service.startlevel.StartLevel"; //$NON-NLS-1$
-
- /** JVM java.vm.name property name */
- public static final String JVM_VM_NAME = "java.vm.name"; //$NON-NLS-1$
-
- /** JVM os.arch property name */
- public static final String JVM_OS_ARCH = "os.arch"; //$NON-NLS-1$
-
- /** JVM os.name property name */
- public static final String JVM_OS_NAME = "os.name"; //$NON-NLS-1$
-
- /** JVM os.version property name */
- public static final String JVM_OS_VERSION = "os.version"; //$NON-NLS-1$
-
- /** JVM user.language property name */
- public static final String JVM_USER_LANGUAGE = "user.language"; //$NON-NLS-1$
-
- /** JVM user.region property name */
- public static final String JVM_USER_REGION = "user.region"; //$NON-NLS-1$
-
- /** J2ME configuration property name */
- public static final String J2ME_MICROEDITION_CONFIGURATION = "microedition.configuration"; //$NON-NLS-1$
-
- /** J2ME profile property name */
- public static final String J2ME_MICROEDITION_PROFILES = "microedition.profiles"; //$NON-NLS-1$
-
- /** Persistent start bundle status */
- public static final int BUNDLE_STARTED = 0x00000001;
- /** Lazy start flag bundle status */
- public static final int BUNDLE_LAZY_START = 0x00000002;
- public static final int BUNDLE_ACTIVATION_POLICY = 0x00000004;
-
- /** Property file locations and default names. */
- public static final String OSGI_PROPERTIES = "osgi.framework.properties"; //$NON-NLS-1$
- public static final String DEFAULT_OSGI_PROPERTIES = "osgi.properties"; //$NON-NLS-1$
-
- private static String INTERNAL_SYSTEM_BUNDLE = "org.eclipse.osgi"; //$NON-NLS-1$
-
- public static String getInternalSymbolicName() {
- return INTERNAL_SYSTEM_BUNDLE;
- }
-
- static void setInternalSymbolicName(String name) {
- INTERNAL_SYSTEM_BUNDLE = name;
- }
-
- /** OSGI implementation version properties key */
- public static final String OSGI_IMPL_VERSION_KEY = "osgi.framework.version"; //$NON-NLS-1$
- /** OSGi java profile; used to give a URL to a java profile */
- public static final String OSGI_JAVA_PROFILE = "osgi.java.profile"; //$NON-NLS-1$
- public static final String 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
- */
- public static final String 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 */
- public static final String OSGI_BOOTDELEGATION_IGNORE = "ignore"; //$NON-NLS-1$
- /** indicates that the org.osgi.framework.bootdelegation in the java profile should override the system property */
- public static final String 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 */
- public static final String OSGI_BOOTDELEGATION_NONE = "none"; //$NON-NLS-1$
- /** OSGi strict delegation **/
- public static final String OSGI_RESOLVER_MODE = "osgi.resolverMode"; //$NON-NLS-1$
- public static final String STRICT_MODE = "strict"; //$NON-NLS-1$
- public static final String DEVELOPMENT_MODE = "development"; //$NON-NLS-1$
-
- public static final String STATE_SYSTEM_BUNDLE = "osgi.system.bundle"; //$NON-NLS-1$
-
- public static final String PROP_OSGI_RELAUNCH = "osgi.framework.relaunch"; //$NON-NLS-1$
-
- public static String OSGI_COMPATIBILITY_BOOTDELEGATION = "osgi.compatibility.bootdelegation"; //$NON-NLS-1$
-
- /** Eclipse-SystemBundle header */
- public static final String ECLIPSE_SYSTEMBUNDLE = "Eclipse-SystemBundle"; //$NON-NLS-1$
- public static final String ECLIPSE_PLATFORMFILTER = "Eclipse-PlatformFilter"; //$NON-NLS-1$
- public static final String Eclipse_JREBUNDLE = "Eclipse-JREBundle"; //$NON-NLS-1$
- /**
- * Manifest Export-Package directive indicating that the exported package should only
- * be made available when the resolver is not in strict mode.
- */
- public static final String INTERNAL_DIRECTIVE = "x-internal"; //$NON-NLS-1$
-
- /**
- * Manifest Export-Package directive indicating that the exported package should only
- * be made available to friends of the exporting bundle.
- */
- public static final String FRIENDS_DIRECTIVE = "x-friends"; //$NON-NLS-1$
-
- /**
- * Manifest header (named &quot;Provide-Package&quot;)
- * identifying the packages name
- * provided to other bundles which require the bundle.
- *
- * <p>
- * NOTE: this is only used for backwards compatibility, bundles manifest using
- * syntax version 2 will not recognize this header.
- *
- * <p>The attribute value may be retrieved from the
- * <tt>Dictionary</tt> object returned by the <tt>Bundle.getHeaders</tt> method.
- * @deprecated
- */
- public final static String PROVIDE_PACKAGE = "Provide-Package"; //$NON-NLS-1$
-
- /**
- * Manifest header attribute (named &quot;reprovide&quot;)
- * for Require-Bundle
- * identifying that any packages that are provided
- * by the required bundle must be reprovided by the requiring bundle.
- * The default value is <tt>false</tt>.
- * <p>
- * The attribute value is encoded in the Require-Bundle manifest
- * header like:
- * <pre>
- * Require-Bundle: com.acme.module.test; reprovide="true"
- * </pre>
- * <p>
- * NOTE: this is only used for backwards compatibility, bundles manifest using
- * syntax version 2 will not recognize this attribute.
- * @deprecated
- */
- public final static String REPROVIDE_ATTRIBUTE = "reprovide"; //$NON-NLS-1$
-
- /**
- * Manifest header attribute (named &quot;optional&quot;)
- * for Require-Bundle
- * identifying that a required bundle is optional and that
- * the requiring bundle can be resolved if there is no
- * suitable required bundle.
- * The default value is <tt>false</tt>.
- *
- * <p>The attribute value is encoded in the Require-Bundle manifest
- * header like:
- * <pre>
- * Require-Bundle: com.acme.module.test; optional="true"
- * </pre>
- * <p>
- * NOTE: this is only used for backwards compatibility, bundles manifest using
- * syntax version 2 will not recognize this attribute.
- * @since 1.3 <b>EXPERIMENTAL</b>
- * @deprecated
- */
- public final static String OPTIONAL_ATTRIBUTE = "optional"; //$NON-NLS-1$
-
- /**
- * The key used to designate the buddy loader associated with a given bundle.
- */
- public final static String BUDDY_LOADER = "Eclipse-BuddyPolicy"; //$NON-NLS-1$
-
- public final static String REGISTERED_POLICY = "Eclipse-RegisterBuddy"; //$NON-NLS-1$
-
- static public final String INTERNAL_HANDLER_PKGS = "equinox.interal.handler.pkgs"; //$NON-NLS-1$
-
- // TODO rename it to Eclipse-PluginClass
- public static final String PLUGIN_CLASS = "Plugin-Class"; //$NON-NLS-1$
-
- /** Manifest header used to specify the lazy start properties of a bundle */
- public static final String ECLIPSE_LAZYSTART = "Eclipse-LazyStart"; //$NON-NLS-1$
-
- /** An Eclipse-LazyStart attribute used to specify exception classes for auto start */
- public static final String ECLIPSE_LAZYSTART_EXCEPTIONS = "exceptions"; //$NON-NLS-1$
-
- /**
- * Manifest header used to specify the auto start properties of a bundle
- * @deprecated use {@link #ECLIPSE_LAZYSTART}
- */
- public static final String ECLIPSE_AUTOSTART = "Eclipse-AutoStart"; //$NON-NLS-1$
-
- /**
- * @deprecated use {@link #ECLIPSE_LAZYSTART_EXCEPTIONS}
- */
- public static final String ECLIPSE_AUTOSTART_EXCEPTIONS = ECLIPSE_LAZYSTART_EXCEPTIONS;
-
- /**
- * Framework launching property specifying whether Equinox's FrameworkWiring
- * implementation should refresh bundles with equal symbolic names.
- *
- * <p>
- * Default value is <b>TRUE</b> in this release of the Equinox.
- * This default may change to <b>FALSE</b> in a future Equinox release.
- * Therefore, code must not assume the default behavior is
- * <b>TRUE</b> and should interrogate the value of this property to
- * determine the behavior.
- *
- * <p>
- * The value of this property may be retrieved by calling the
- * {@code BundleContext.getProperty} method.
- * @see <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=351519">bug 351519</a>
- * @since 3.7.1
- */
- public static final String REFRESH_DUPLICATE_BSN = "equinox.refresh.duplicate.bsn"; //$NON-NLS-1$
-
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/CoreResolverHookFactory.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/CoreResolverHookFactory.java
deleted file mode 100644
index 986de041d..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/CoreResolverHookFactory.java
+++ /dev/null
@@ -1,216 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2010, 2012 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.osgi.framework.internal.core;
-
-import java.util.*;
-import org.eclipse.osgi.framework.debug.Debug;
-import org.eclipse.osgi.internal.serviceregistry.*;
-import org.eclipse.osgi.service.resolver.ResolverHookException;
-import org.eclipse.osgi.util.NLS;
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.framework.hooks.resolver.ResolverHook;
-import org.osgi.framework.hooks.resolver.ResolverHookFactory;
-import org.osgi.framework.wiring.*;
-
-/**
- * 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.
- *
- */
-public 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<ResolverHookFactory> reference, ResolverHook hook) {
- this.reference = reference;
- this.hook = hook;
- }
-
- final ServiceReferenceImpl<ResolverHookFactory> reference;
- final ResolverHook hook;
- }
-
- private final BundleContextImpl context;
- private final ServiceRegistry registry;
-
- public CoreResolverHookFactory(BundleContextImpl context, ServiceRegistry registry) {
- this.context = context;
- this.registry = registry;
- }
-
- void handleHookException(Throwable t, Object hook, String method) {
- if (Debug.DEBUG_HOOKS) {
- Debug.println(hook.getClass().getName() + "." + method + "() exception:"); //$NON-NLS-1$ //$NON-NLS-2$
- if (t != null)
- Debug.printStackTrace(t);
- }
- String message = NLS.bind(Msg.SERVICE_FACTORY_EXCEPTION, hook.getClass().getName(), method);
- throw new ResolverHookException(message, t);
- }
-
- private ServiceReferenceImpl<ResolverHookFactory>[] getHookReferences() {
- try {
- @SuppressWarnings("unchecked")
- ServiceReferenceImpl<ResolverHookFactory>[] result = (ServiceReferenceImpl<ResolverHookFactory>[]) registry.getServiceReferences(context, ResolverHookFactory.class.getName(), null, false, false);
- return result;
- } catch (InvalidSyntaxException e) {
- // cannot happen; no filter
- return null;
- }
- }
-
- public ResolverHook begin(Collection<BundleRevision> triggers) {
- if (Debug.DEBUG_HOOKS) {
- Debug.println("ResolverHook.begin"); //$NON-NLS-1$
- }
- ServiceReferenceImpl<ResolverHookFactory>[] refs = getHookReferences();
- @SuppressWarnings("unchecked")
- List<HookReference> hookRefs = refs == null ? Collections.EMPTY_LIST : new ArrayList<CoreResolverHookFactory.HookReference>(refs.length);
- if (refs != null)
- for (ServiceReferenceImpl<ResolverHookFactory> hookRef : refs) {
- ResolverHookFactory factory = context.getService(hookRef);
- if (factory != null) {
- try {
- ResolverHook hook = factory.begin(triggers);
- if (hook != null)
- hookRefs.add(new HookReference(hookRef, hook));
- } catch (Throwable t) {
- // need to force an end call on the ResolverHooks we got and release them
- try {
- new CoreResolverHook(hookRefs).end();
- } catch (Throwable endError) {
- // we are already in failure mode; just continue
- }
- handleHookException(t, factory, "begin"); //$NON-NLS-1$
- }
- }
- }
- return new CoreResolverHook(hookRefs);
- }
-
- void releaseHooks(List<HookReference> hookRefs) {
- for (HookReference hookRef : hookRefs)
- context.ungetService(hookRef.reference);
- hookRefs.clear();
- }
-
- class CoreResolverHook implements ResolverHook {
- private final List<HookReference> hooks;
-
- CoreResolverHook(List<HookReference> hooks) {
- this.hooks = hooks;
- }
-
- public void filterResolvable(Collection<BundleRevision> candidates) {
- if (Debug.DEBUG_HOOKS) {
- Debug.println("ResolverHook.filterResolvable(" + candidates + ")"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- if (hooks.isEmpty())
- return;
- candidates = new ShrinkableCollection<BundleRevision>(candidates);
- for (Iterator<HookReference> iHooks = hooks.iterator(); iHooks.hasNext();) {
- HookReference hookRef = iHooks.next();
- if (hookRef.reference.getBundle() == null) {
- handleHookException(null, hookRef.hook, "filterResolvable"); //$NON-NLS-1$
- } else {
- try {
- hookRef.hook.filterResolvable(candidates);
- } catch (Throwable t) {
- handleHookException(t, hookRef.hook, "filterResolvable"); //$NON-NLS-1$
- }
- }
- }
- }
-
- public void filterSingletonCollisions(BundleCapability singleton, Collection<BundleCapability> collisionCandidates) {
- if (Debug.DEBUG_HOOKS) {
- Debug.println("ResolverHook.filterSingletonCollisions(" + singleton + ", " + collisionCandidates + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- if (hooks.isEmpty())
- return;
- collisionCandidates = new ShrinkableCollection<BundleCapability>(collisionCandidates);
- for (Iterator<HookReference> iHooks = hooks.iterator(); iHooks.hasNext();) {
- HookReference hookRef = iHooks.next();
- if (hookRef.reference.getBundle() == null) {
- handleHookException(null, hookRef.hook, "filterSingletonCollisions"); //$NON-NLS-1$
- } else {
- try {
- hookRef.hook.filterSingletonCollisions(singleton, collisionCandidates);
- } catch (Throwable t) {
- handleHookException(t, hookRef.hook, "filterSingletonCollisions"); //$NON-NLS-1$
- }
- }
- }
- }
-
- public void filterMatches(BundleRequirement requirement, Collection<BundleCapability> candidates) {
- if (Debug.DEBUG_HOOKS) {
- Debug.println("ResolverHook.filterMatches(" + requirement + ", " + candidates + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- if (hooks.isEmpty())
- return;
- candidates = new ShrinkableCollection<BundleCapability>(candidates);
- for (Iterator<HookReference> iHooks = hooks.iterator(); iHooks.hasNext();) {
- HookReference hookRef = iHooks.next();
- if (hookRef.reference.getBundle() == null) {
- handleHookException(null, hookRef.hook, "filterMatches"); //$NON-NLS-1$
- } else {
- try {
- hookRef.hook.filterMatches(requirement, candidates);
- } catch (Throwable t) {
- handleHookException(t, hookRef.hook, "filterMatches"); //$NON-NLS-1$
- }
- }
- }
- }
-
- public void end() {
- if (Debug.DEBUG_HOOKS) {
- Debug.println("ResolverHook.end"); //$NON-NLS-1$
- }
- if (hooks.isEmpty())
- return;
- try {
- HookReference missingHook = null;
- Throwable endError = null;
- HookReference endBadHook = null;
- for (Iterator<HookReference> iHooks = hooks.iterator(); iHooks.hasNext();) {
- HookReference hookRef = iHooks.next();
- // 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;
- } else {
- try {
- hookRef.hook.end();
- } catch (Throwable t) {
- // Must continue on to the next hook.end method
- // save the error for throwing at the end
- if (endError == null) {
- endError = t;
- endBadHook = hookRef;
- }
- }
- }
- }
- if (missingHook != null)
- handleHookException(null, missingHook.hook, "end"); //$NON-NLS-1$
- if (endError != null)
- handleHookException(endError, endBadHook.hook, "end"); //$NON-NLS-1$
- } finally {
- releaseHooks(hooks);
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/EquinoxLauncher.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/EquinoxLauncher.java
deleted file mode 100644
index 2b71f2467..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/EquinoxLauncher.java
+++ /dev/null
@@ -1,347 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008, 2011 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.osgi.framework.internal.core;
-
-import java.io.*;
-import java.net.URL;
-import java.security.*;
-import java.security.cert.X509Certificate;
-import java.util.*;
-import org.eclipse.core.runtime.adaptor.EclipseStarter;
-import org.eclipse.osgi.baseadaptor.BaseAdaptor;
-import org.eclipse.osgi.framework.adaptor.FrameworkAdaptor;
-import org.osgi.framework.*;
-
-public class EquinoxLauncher implements org.osgi.framework.launch.Framework {
-
- private volatile Framework framework;
- private volatile Bundle systemBundle;
- private final Map<String, String> configuration;
- private volatile ConsoleManager consoleMgr = null;
-
- public EquinoxLauncher(Map<String, String> configuration) {
- this.configuration = configuration;
- }
-
- public void init() {
- checkAdminPermission(AdminPermission.EXECUTE);
- if (System.getSecurityManager() == null)
- internalInit();
- else {
- AccessController.doPrivileged(new PrivilegedAction<Object>() {
- public Object run() {
- internalInit();
- return null;
- }
- });
- }
- }
-
- synchronized Framework internalInit() {
- if ((getState() & (Bundle.ACTIVE | Bundle.STARTING | Bundle.STOPPING)) != 0)
- return framework; // no op
-
- if (System.getSecurityManager() != null && configuration.get(Constants.FRAMEWORK_SECURITY) != null)
- throw new SecurityException("Cannot specify the \"" + Constants.FRAMEWORK_SECURITY + "\" configuration property when a security manager is already installed."); //$NON-NLS-1$ //$NON-NLS-2$
-
- Framework current = framework;
- if (current != null) {
- current.close();
- framework = null;
- systemBundle = null;
- }
- ClassLoader tccl = Thread.currentThread().getContextClassLoader();
- try {
- FrameworkProperties.setProperties(configuration);
- FrameworkProperties.initializeProperties();
- // make sure the active framework thread is used
- setEquinoxProperties(configuration);
- current = new Framework(new BaseAdaptor(new String[0]));
- consoleMgr = ConsoleManager.startConsole(current);
- current.launch();
- framework = current;
- systemBundle = current.systemBundle;
- } finally {
- ClassLoader currentCCL = Thread.currentThread().getContextClassLoader();
- if (currentCCL != tccl)
- Thread.currentThread().setContextClassLoader(tccl);
- }
- return current;
- }
-
- private void setEquinoxProperties(Map<String, String> configuration) {
- Object threadBehavior = configuration == null ? null : configuration.get(Framework.PROP_FRAMEWORK_THREAD);
- if (threadBehavior == null) {
- if (FrameworkProperties.getProperty(Framework.PROP_FRAMEWORK_THREAD) == null)
- FrameworkProperties.setProperty(Framework.PROP_FRAMEWORK_THREAD, Framework.THREAD_NORMAL);
- } else {
- FrameworkProperties.setProperty(Framework.PROP_FRAMEWORK_THREAD, (String) threadBehavior);
- }
-
- // set the compatibility boot delegation flag to false to get "standard" OSGi behavior WRT boot delegation (bug 344850)
- if (FrameworkProperties.getProperty(Constants.OSGI_COMPATIBILITY_BOOTDELEGATION) == null)
- FrameworkProperties.setProperty(Constants.OSGI_COMPATIBILITY_BOOTDELEGATION, "false"); //$NON-NLS-1$
- // set the support for multiple host to true to get "standard" OSGi behavior (bug 344850)
- if (FrameworkProperties.getProperty("osgi.support.multipleHosts") == null) //$NON-NLS-1$
- FrameworkProperties.setProperty("osgi.support.multipleHosts", "true"); //$NON-NLS-1$ //$NON-NLS-2$
- // first check props we are required to provide reasonable defaults for
- Object windowSystem = configuration == null ? null : configuration.get(Constants.FRAMEWORK_WINDOWSYSTEM);
- if (windowSystem == null) {
- windowSystem = FrameworkProperties.getProperty(EclipseStarter.PROP_WS);
- if (windowSystem != null)
- FrameworkProperties.setProperty(Constants.FRAMEWORK_WINDOWSYSTEM, (String) windowSystem);
- }
- // rest of props can be ignored if the configuration is null
- if (configuration == null)
- return;
- // check each osgi clean property and set the appropriate equinox one
- Object clean = configuration.get(Constants.FRAMEWORK_STORAGE_CLEAN);
- if (Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT.equals(clean)) {
- // remove this so we only clean on first init
- configuration.remove(Constants.FRAMEWORK_STORAGE_CLEAN);
- FrameworkProperties.setProperty(EclipseStarter.PROP_CLEAN, Boolean.TRUE.toString());
- }
- }
-
- public FrameworkEvent waitForStop(long timeout) throws InterruptedException {
- Framework current = framework;
- if (current == null)
- return new FrameworkEvent(FrameworkEvent.STOPPED, this, null);
- return current.waitForStop(timeout);
- }
-
- public Enumeration<URL> findEntries(String path, String filePattern, boolean recurse) {
- Bundle current = systemBundle;
- if (current == null)
- return null;
- return current.findEntries(path, filePattern, recurse);
- }
-
- public BundleContext getBundleContext() {
- Bundle current = systemBundle;
- if (current == null)
- return null;
- return current.getBundleContext();
- }
-
- public long getBundleId() {
- return 0;
- }
-
- public URL getEntry(String path) {
- Bundle current = systemBundle;
- if (current == null)
- return null;
- return current.getEntry(path);
- }
-
- public Enumeration<String> getEntryPaths(String path) {
- Bundle current = systemBundle;
- if (current == null)
- return null;
- return current.getEntryPaths(path);
- }
-
- public Dictionary<String, String> getHeaders() {
- Bundle current = systemBundle;
- if (current == null)
- return null;
- return current.getHeaders();
- }
-
- public Dictionary<String, String> getHeaders(String locale) {
- Bundle current = systemBundle;
- if (current == null)
- return null;
- return current.getHeaders(locale);
- }
-
- public long getLastModified() {
- Bundle current = systemBundle;
- if (current == null)
- return System.currentTimeMillis();
- return current.getLastModified();
- }
-
- public String getLocation() {
- return Constants.SYSTEM_BUNDLE_LOCATION;
- }
-
- public ServiceReference<?>[] getRegisteredServices() {
- Bundle current = systemBundle;
- if (current == null)
- return null;
- return current.getRegisteredServices();
- }
-
- public URL getResource(String name) {
- Bundle current = systemBundle;
- if (current == null)
- return null;
- return current.getResource(name);
- }
-
- public Enumeration<URL> getResources(String name) throws IOException {
- Bundle current = systemBundle;
- if (current == null)
- return null;
- return current.getResources(name);
- }
-
- public ServiceReference<?>[] getServicesInUse() {
- Bundle current = systemBundle;
- if (current == null)
- return null;
- return current.getServicesInUse();
- }
-
- public int getState() {
- Bundle current = systemBundle;
- if (current == null)
- return Bundle.INSTALLED;
- return current.getState();
- }
-
- public String getSymbolicName() {
- return FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME;
- }
-
- public boolean hasPermission(Object permission) {
- Bundle current = systemBundle;
- if (current == null)
- return false;
- return current.hasPermission(permission);
- }
-
- public Class<?> loadClass(String name) throws ClassNotFoundException {
- Bundle current = systemBundle;
- if (current == null)
- return null;
- return current.loadClass(name);
- }
-
- public void start(int options) throws BundleException {
- start();
- }
-
- /**
- * @throws BundleException
- */
- public void start() throws BundleException {
- checkAdminPermission(AdminPermission.EXECUTE);
- if (System.getSecurityManager() == null)
- internalStart();
- else
- try {
- AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
- public Object run() {
- internalStart();
- return null;
- }
- });
- } catch (PrivilegedActionException e) {
- throw (BundleException) e.getException();
- }
- }
-
- private void checkAdminPermission(String actions) {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null)
- sm.checkPermission(new AdminPermission(this, actions));
- }
-
- void internalStart() {
- if (getState() == Bundle.ACTIVE)
- return;
- Framework current = internalInit();
- int level = 1;
- try {
- level = Integer.parseInt(configuration.get(Constants.FRAMEWORK_BEGINNING_STARTLEVEL));
- } catch (Throwable t) {
- // do nothing
- }
- current.startLevelManager.doSetStartLevel(level);
- }
-
- public void stop(int options) throws BundleException {
- stop();
- }
-
- public void stop() throws BundleException {
- Bundle current = systemBundle;
- if (current == null)
- return;
- ConsoleManager currentConsole = consoleMgr;
- if (currentConsole != null) {
- currentConsole.stopConsole();
- consoleMgr = null;
- }
- current.stop();
- }
-
- public void uninstall() throws BundleException {
- throw new BundleException(Msg.BUNDLE_SYSTEMBUNDLE_UNINSTALL_EXCEPTION, BundleException.INVALID_OPERATION);
- }
-
- public void update() throws BundleException {
- Bundle current = systemBundle;
- if (current == null)
- return;
- current.update();
- }
-
- public void update(InputStream in) throws BundleException {
- try {
- in.close();
- } catch (IOException e) {
- // nothing; just being nice
- }
- update();
- }
-
- public Map<X509Certificate, List<X509Certificate>> getSignerCertificates(int signersType) {
- Bundle current = systemBundle;
- if (current != null)
- return current.getSignerCertificates(signersType);
- @SuppressWarnings("unchecked")
- final Map<X509Certificate, List<X509Certificate>> empty = Collections.EMPTY_MAP;
- return empty;
- }
-
- public Version getVersion() {
- Bundle current = systemBundle;
- if (current != null)
- return current.getVersion();
- return Version.emptyVersion;
- }
-
- public <A> A adapt(Class<A> adapterType) {
- Bundle current = systemBundle;
- if (current != null) {
- return current.adapt(adapterType);
- }
- return null;
- }
-
- public int compareTo(Bundle o) {
- Bundle current = systemBundle;
- if (current != null)
- return current.compareTo(o);
- throw new IllegalStateException();
- }
-
- public File getDataFile(String filename) {
- Bundle current = systemBundle;
- if (current != null)
- return current.getDataFile(filename);
- return null;
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/ExportedPackageImpl.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/ExportedPackageImpl.java
deleted file mode 100644
index a26998541..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/ExportedPackageImpl.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2011 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.osgi.framework.internal.core;
-
-import java.util.ArrayList;
-import java.util.List;
-import org.eclipse.osgi.internal.loader.*;
-import org.eclipse.osgi.service.resolver.BundleDescription;
-import org.eclipse.osgi.service.resolver.ExportPackageDescription;
-import org.osgi.framework.*;
-import org.osgi.framework.Constants;
-import org.osgi.service.packageadmin.ExportedPackage;
-
-/**
- * @deprecated
- */
-public class ExportedPackageImpl implements ExportedPackage {
-
- private final ExportPackageDescription exportedPackage;
- private final BundleLoaderProxy supplier;
-
- public ExportedPackageImpl(ExportPackageDescription exportedPackage, BundleLoaderProxy supplier) {
- this.exportedPackage = exportedPackage;
- this.supplier = supplier;
- }
-
- public String getName() {
- return exportedPackage.getName();
- }
-
- public org.osgi.framework.Bundle getExportingBundle() {
- if (supplier.isStale())
- return null;
- return supplier.getBundleHost();
- }
-
- /*
- * get the bundle without checking if it is stale
- */
- AbstractBundle getBundle() {
- return supplier.getBundleHost();
- }
-
- public Bundle[] getImportingBundles() {
- if (supplier.isStale())
- return null;
- AbstractBundle bundle = (AbstractBundle) getExportingBundle();
- if (bundle == null)
- return null;
- AbstractBundle[] bundles = bundle.framework.getAllBundles();
- List<Bundle> importers = new ArrayList<Bundle>(10);
- PackageSource supplierSource = supplier.createPackageSource(exportedPackage, false);
- for (int i = 0; i < bundles.length; i++) {
- if (!(bundles[i] instanceof BundleHost))
- continue;
- BundleLoader loader = ((BundleHost) bundles[i]).getBundleLoader();
- if (loader == null || loader.getBundle() == supplier.getBundle())
- continue; // do not include include the exporter of the package
- PackageSource importerSource = loader.getPackageSource(getName());
- if (supplierSource != null && supplierSource.hasCommonSource(importerSource))
- importers.add(bundles[i]);
- }
- return importers.toArray(new Bundle[importers.size()]);
- }
-
- /**
- * @deprecated
- */
- public String getSpecificationVersion() {
- return exportedPackage.getVersion().toString();
- }
-
- public Version getVersion() {
- return exportedPackage.getVersion();
- }
-
- public boolean isRemovalPending() {
- BundleDescription exporter = exportedPackage.getExporter();
- if (exporter != null)
- return exporter.isRemovalPending();
- return true;
- }
-
- public String toString() {
- StringBuffer result = new StringBuffer(getName());
- result.append("; ").append(Constants.VERSION_ATTRIBUTE); //$NON-NLS-1$
- result.append("=\"").append(exportedPackage.getVersion().toString()).append("\""); //$NON-NLS-1$//$NON-NLS-2$
-
- return result.toString();
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/FilterImpl.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/FilterImpl.java
deleted file mode 100644
index 4611c63cb..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/FilterImpl.java
+++ /dev/null
@@ -1,1751 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.framework.internal.core;
-
-import java.lang.reflect.*;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.util.*;
-import org.eclipse.osgi.framework.debug.Debug;
-import org.eclipse.osgi.framework.util.Headers;
-import org.eclipse.osgi.internal.serviceregistry.ServiceReferenceImpl;
-import org.eclipse.osgi.util.NLS;
-import org.osgi.framework.*;
-
-/**
- * RFC 1960-based Filter. Filter objects can be created by calling
- * the constructor with the desired filter string.
- * A Filter object can be called numerous times to determine if the
- * match argument matches the filter string that was used to create the Filter
- * object.
- *
- * <p>The syntax of a filter string is the string representation
- * of LDAP search filters as defined in RFC 1960:
- * <i>A String Representation of LDAP Search Filters</i> (available at
- * http://www.ietf.org/rfc/rfc1960.txt).
- * It should be noted that RFC 2254:
- * <i>A String Representation of LDAP Search Filters</i>
- * (available at http://www.ietf.org/rfc/rfc2254.txt) supersedes
- * RFC 1960 but only adds extensible matching and is not applicable for this
- * API.
- *
- * <p>The string representation of an LDAP search filter is defined by the
- * following grammar. It uses a prefix format.
- * <pre>
- * &lt;filter&gt; ::= '(' &lt;filtercomp&gt; ')'
- * &lt;filtercomp&gt; ::= &lt;and&gt; | &lt;or&gt; | &lt;not&gt; | &lt;item&gt;
- * &lt;and&gt; ::= '&' &lt;filterlist&gt;
- * &lt;or&gt; ::= '|' &lt;filterlist&gt;
- * &lt;not&gt; ::= '!' &lt;filter&gt;
- * &lt;filterlist&gt; ::= &lt;filter&gt; | &lt;filter&gt; &lt;filterlist&gt;
- * &lt;item&gt; ::= &lt;simple&gt; | &lt;present&gt; | &lt;substring&gt;
- * &lt;simple&gt; ::= &lt;attr&gt; &lt;filtertype&gt; &lt;value&gt;
- * &lt;filtertype&gt; ::= &lt;equal&gt; | &lt;approx&gt; | &lt;greater&gt; | &lt;less&gt;
- * &lt;equal&gt; ::= '='
- * &lt;approx&gt; ::= '~='
- * &lt;greater&gt; ::= '&gt;='
- * &lt;less&gt; ::= '&lt;='
- * &lt;present&gt; ::= &lt;attr&gt; '=*'
- * &lt;substring&gt; ::= &lt;attr&gt; '=' &lt;initial&gt; &lt;any&gt; &lt;final&gt;
- * &lt;initial&gt; ::= NULL | &lt;value&gt;
- * &lt;any&gt; ::= '*' &lt;starval&gt;
- * &lt;starval&gt; ::= NULL | &lt;value&gt; '*' &lt;starval&gt;
- * &lt;final&gt; ::= NULL | &lt;value&gt;
- * </pre>
- *
- * <code>&lt;attr&gt;</code> is a string representing an attribute, or
- * key, in the properties objects of the registered services.
- * Attribute names are not case sensitive;
- * that is cn and CN both refer to the same attribute.
- * <code>&lt;value&gt;</code> is a string representing the value, or part of
- * one, of a key in the properties objects of the registered services.
- * If a <code>&lt;value&gt;</code> must
- * contain one of the characters '<code>*</code>' or '<code>(</code>'
- * or '<code>)</code>', these characters
- * should be escaped by preceding them with the backslash '<code>\</code>'
- * character.
- * Note that although both the <code>&lt;substring&gt;</code> and
- * <code>&lt;present&gt;</code> productions can
- * produce the <code>'attr=*'</code> construct, this construct is used only to
- * denote a presence filter.
- *
- * <p>Examples of LDAP filters are:
- *
- * <pre>
- * &quot;(cn=Babs Jensen)&quot;
- * &quot;(!(cn=Tim Howes))&quot;
- * &quot;(&(&quot; + Constants.OBJECTCLASS + &quot;=Person)(|(sn=Jensen)(cn=Babs J*)))&quot;
- * &quot;(o=univ*of*mich*)&quot;
- * </pre>
- *
- * <p>The approximate match (<code>~=</code>) is implementation specific but
- * should at least ignore case and white space differences. Optional are
- * codes like soundex or other smart "closeness" comparisons.
- *
- * <p>Comparison of values is not straightforward. Strings
- * are compared differently than numbers and it is
- * possible for a key to have multiple values. Note that
- * that keys in the match argument must always be strings.
- * The comparison is defined by the object type of the key's
- * value. The following rules apply for comparison:
- *
- * <blockquote>
- * <TABLE BORDER=0>
- * <TR><TD><b>Property Value Type </b></TD><TD><b>Comparison Type</b></TD></TR>
- * <TR><TD>String </TD><TD>String comparison</TD></TR>
- * <TR valign=top><TD>Integer, Long, Float, Double, Byte, Short, BigInteger, BigDecimal </TD><TD>numerical comparison</TD></TR>
- * <TR><TD>Character </TD><TD>character comparison</TD></TR>
- * <TR><TD>Boolean </TD><TD>equality comparisons only</TD></TR>
- * <TR><TD>[] (array)</TD><TD>recursively applied to values </TD></TR>
- * <TR><TD>Vector</TD><TD>recursively applied to elements </TD></TR>
- * </TABLE>
- * Note: arrays of primitives are also supported.
- * </blockquote>
- *
- * A filter matches a key that has multiple values if it
- * matches at least one of those values. For example,
- * <pre>
- * Dictionary d = new Hashtable();
- * d.put( "cn", new String[] { "a", "b", "c" } );
- * </pre>
- * d will match <code>(cn=a)</code> and also <code>(cn=b)</code>
- *
- * <p>A filter component that references a key having an unrecognizable
- * data type will evaluate to <code>false</code> .
- */
-
-public class FilterImpl implements Filter /* since Framework 1.1 */{
- /* public methods in org.osgi.framework.Filter */
-
- /**
- * Constructs a {@link FilterImpl} object. This filter object may be used
- * to match a {@link ServiceReferenceImpl} or a Dictionary.
- *
- * <p> 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.
- * @exception InvalidSyntaxException If the filter parameter contains
- * an invalid filter string that cannot be parsed.
- */
- public static FilterImpl newInstance(String filterString) throws InvalidSyntaxException {
- return new Parser(filterString).parse();
- }
-
- /**
- * Filter using a service's properties.
- * <p>
- * 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.
- */
- public boolean match(ServiceReference<?> reference) {
- if (reference instanceof ServiceReferenceImpl) {
- return matchCase(((ServiceReferenceImpl<?>) reference).getRegistration().getProperties());
- }
- return matchCase(new ServiceReferenceDictionary(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.
- *
- * @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.
- */
- public boolean match(Dictionary<String, ?> dictionary) {
- if (dictionary != null) {
- dictionary = new Headers<String, Object>(dictionary);
- }
-
- return matchCase(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.
- *
- * @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
- */
- public boolean matchCase(Dictionary<String, ?> dictionary) {
- switch (op) {
- case AND : {
- FilterImpl[] filters = (FilterImpl[]) value;
- for (FilterImpl f : filters) {
- if (!f.matchCase(dictionary)) {
- return false;
- }
- }
-
- return true;
- }
-
- case OR : {
- FilterImpl[] filters = (FilterImpl[]) value;
- for (FilterImpl f : filters) {
- if (f.matchCase(dictionary)) {
- return true;
- }
- }
-
- return false;
- }
-
- case NOT : {
- FilterImpl filter = (FilterImpl) value;
-
- return !filter.matchCase(dictionary);
- }
-
- case SUBSTRING :
- case EQUAL :
- case GREATER :
- case LESS :
- case APPROX : {
- Object prop = (dictionary == null) ? null : dictionary.get(attr);
-
- return compare(op, prop, value);
- }
-
- case PRESENT : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("PRESENT(" + attr + ")"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- Object prop = (dictionary == null) ? null : dictionary.get(attr);
-
- return prop != null;
- }
- }
-
- return false;
- }
-
- /**
- * 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.
- *
- * @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
- */
- public boolean matches(Map<String, ?> map) {
- switch (op) {
- case AND : {
- FilterImpl[] filters = (FilterImpl[]) value;
- for (FilterImpl f : filters) {
- if (!f.matches(map)) {
- return false;
- }
- }
-
- return true;
- }
-
- case OR : {
- FilterImpl[] filters = (FilterImpl[]) value;
- for (FilterImpl f : filters) {
- if (f.matches(map)) {
- return true;
- }
- }
-
- return false;
- }
-
- case NOT : {
- FilterImpl filter = (FilterImpl) value;
-
- return !filter.matches(map);
- }
-
- case SUBSTRING :
- case EQUAL :
- case GREATER :
- case LESS :
- case APPROX : {
- Object prop = (map == null) ? null : map.get(attr);
-
- return compare(op, prop, value);
- }
-
- case PRESENT : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("PRESENT(" + attr + ")"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- Object prop = (map == null) ? null : map.get(attr);
-
- return prop != null;
- }
- }
-
- return false;
- }
-
- /**
- * Returns this <code>Filter</code> object's filter string.
- * <p>
- * The filter string is normalized by removing whitespace which does not
- * affect the meaning of the filter.
- *
- * @return Filter string.
- */
-
- public String toString() {
- String result = filterString;
- if (result == null) {
- filterString = result = normalize().toString();
- }
- return result;
- }
-
- /**
- * Returns this <code>Filter</code>'s normalized filter string.
- * <p>
- * The filter string is normalized by removing whitespace which does not
- * affect the meaning of the filter.
- *
- * @return This <code>Filter</code>'s filter string.
- */
- private StringBuffer normalize() {
- StringBuffer sb = new StringBuffer();
- sb.append('(');
-
- switch (op) {
- case AND : {
- sb.append('&');
-
- FilterImpl[] filters = (FilterImpl[]) value;
- for (FilterImpl f : filters) {
- sb.append(f.normalize());
- }
-
- break;
- }
-
- case OR : {
- sb.append('|');
-
- FilterImpl[] filters = (FilterImpl[]) value;
- for (FilterImpl f : filters) {
- sb.append(f.normalize());
- }
-
- break;
- }
-
- case NOT : {
- sb.append('!');
- FilterImpl filter = (FilterImpl) value;
- sb.append(filter.normalize());
-
- break;
- }
-
- case SUBSTRING : {
- sb.append(attr);
- sb.append('=');
-
- String[] substrings = (String[]) value;
-
- for (String substr : substrings) {
- if (substr == null) /* * */{
- sb.append('*');
- } else /* xxx */{
- sb.append(encodeValue(substr));
- }
- }
-
- break;
- }
- case EQUAL : {
- sb.append(attr);
- sb.append('=');
- sb.append(encodeValue((String) value));
-
- break;
- }
- case GREATER : {
- sb.append(attr);
- sb.append(">="); //$NON-NLS-1$
- sb.append(encodeValue((String) value));
-
- break;
- }
- case LESS : {
- sb.append(attr);
- sb.append("<="); //$NON-NLS-1$
- sb.append(encodeValue((String) value));
-
- break;
- }
- case APPROX : {
- sb.append(attr);
- sb.append("~="); //$NON-NLS-1$
- sb.append(encodeValue(approxString((String) value)));
-
- break;
- }
-
- case PRESENT : {
- sb.append(attr);
- sb.append("=*"); //$NON-NLS-1$
-
- break;
- }
- }
-
- sb.append(')');
-
- return sb;
- }
-
- /**
- * Compares this <code>Filter</code> object to another object.
- *
- * @param obj The object to compare against this <code>Filter</code>
- * object.
- * @return If the other object is a <code>Filter</code> object, then
- * returns <code>this.toString().equals(obj.toString()</code>;
- * <code>false</code> otherwise.
- */
- public boolean equals(Object obj) {
- if (obj == this) {
- return true;
- }
-
- if (!(obj instanceof Filter)) {
- return false;
- }
-
- return this.toString().equals(obj.toString());
- }
-
- /**
- * Returns the hashCode for this <code>Filter</code> object.
- *
- * @return The hashCode of the filter string; that is,
- * <code>this.toString().hashCode()</code>.
- */
- public int hashCode() {
- return this.toString().hashCode();
- }
-
- /* non public fields and methods for the Filter implementation */
-
- /** filter operation */
- private final int op;
- private static final int EQUAL = 1;
- private static final int APPROX = 2;
- private static final int GREATER = 3;
- private static final int LESS = 4;
- private static final int PRESENT = 5;
- private static final int SUBSTRING = 6;
- private static final int AND = 7;
- private static final int OR = 8;
- private static final int NOT = 9;
-
- /** filter attribute or null if operation AND, OR or NOT */
- private final String attr;
- /** filter operands */
- private final Object value;
-
- /* normalized filter string for topLevel Filter object */
- private transient volatile String filterString;
-
- FilterImpl(int operation, String attr, Object value) {
- this.op = operation;
- this.attr = attr;
- this.value = value;
- }
-
- /**
- * Encode the value string such that '(', '*', ')'
- * and '\' are escaped.
- *
- * @param value unencoded value string.
- * @return encoded value string.
- */
- private static String encodeValue(String value) {
- boolean encoded = false;
- int inlen = value.length();
- int outlen = inlen << 1; /* inlen * 2 */
-
- char[] output = new char[outlen];
- value.getChars(0, inlen, output, inlen);
-
- int cursor = 0;
- for (int i = inlen; i < outlen; i++) {
- char c = output[i];
-
- switch (c) {
- case '(' :
- case '*' :
- case ')' :
- case '\\' : {
- output[cursor] = '\\';
- cursor++;
- encoded = true;
-
- break;
- }
- }
-
- output[cursor] = c;
- cursor++;
- }
-
- return encoded ? new String(output, 0, cursor) : value;
- }
-
- private boolean compare(int operation, Object value1, Object value2) {
- if (value1 == null) {
- if (Debug.DEBUG_FILTER) {
- Debug.println("compare(" + value1 + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- return false;
- }
-
- if (value1 instanceof String) {
- return compare_String(operation, (String) value1, value2);
- }
-
- Class<?> clazz = value1.getClass();
- if (clazz.isArray()) {
- Class<?> type = clazz.getComponentType();
- if (type.isPrimitive()) {
- return compare_PrimitiveArray(operation, type, value1, value2);
- }
- return compare_ObjectArray(operation, (Object[]) value1, value2);
- }
- if (value1 instanceof Collection<?>) {
- return compare_Collection(operation, (Collection<?>) value1, value2);
- }
-
- if (value1 instanceof Integer) {
- return compare_Integer(operation, ((Integer) value1).intValue(), value2);
- }
-
- if (value1 instanceof Long) {
- return compare_Long(operation, ((Long) value1).longValue(), value2);
- }
-
- if (value1 instanceof Byte) {
- return compare_Byte(operation, ((Byte) value1).byteValue(), value2);
- }
-
- if (value1 instanceof Short) {
- return compare_Short(operation, ((Short) value1).shortValue(), value2);
- }
-
- if (value1 instanceof Character) {
- return compare_Character(operation, ((Character) value1).charValue(), value2);
- }
-
- if (value1 instanceof Float) {
- return compare_Float(operation, ((Float) value1).floatValue(), value2);
- }
-
- if (value1 instanceof Double) {
- return compare_Double(operation, ((Double) value1).doubleValue(), value2);
- }
-
- if (value1 instanceof Boolean) {
- return compare_Boolean(operation, ((Boolean) value1).booleanValue(), value2);
- }
- if (value1 instanceof Comparable<?>) {
- @SuppressWarnings("unchecked")
- Comparable<Object> comparable = (Comparable<Object>) value1;
- return compare_Comparable(operation, comparable, value2);
- }
-
- return compare_Unknown(operation, value1, value2); // RFC 59
- }
-
- private boolean compare_Collection(int operation, Collection<?> collection, Object value2) {
- for (Object value1 : collection) {
- if (compare(operation, value1, value2)) {
- return true;
- }
- }
-
- return false;
- }
-
- private boolean compare_ObjectArray(int operation, Object[] array, Object value2) {
- for (Object value1 : array) {
- if (compare(operation, value1, value2)) {
- return true;
- }
- }
-
- return false;
- }
-
- private boolean compare_PrimitiveArray(int operation, Class<?> type, Object primarray, Object value2) {
- if (Integer.TYPE.isAssignableFrom(type)) {
- int[] array = (int[]) primarray;
- for (int value1 : array) {
- if (compare_Integer(operation, value1, value2)) {
- return true;
- }
- }
-
- return false;
- }
-
- if (Long.TYPE.isAssignableFrom(type)) {
- long[] array = (long[]) primarray;
- for (long value1 : array) {
- if (compare_Long(operation, value1, value2)) {
- return true;
- }
- }
-
- return false;
- }
-
- if (Byte.TYPE.isAssignableFrom(type)) {
- byte[] array = (byte[]) primarray;
- for (byte value1 : array) {
- if (compare_Byte(operation, value1, value2)) {
- return true;
- }
- }
-
- return false;
- }
-
- if (Short.TYPE.isAssignableFrom(type)) {
- short[] array = (short[]) primarray;
- for (short value1 : array) {
- if (compare_Short(operation, value1, value2)) {
- return true;
- }
- }
-
- return false;
- }
-
- if (Character.TYPE.isAssignableFrom(type)) {
- char[] array = (char[]) primarray;
- for (char value1 : array) {
- if (compare_Character(operation, value1, value2)) {
- return true;
- }
- }
-
- return false;
- }
-
- if (Float.TYPE.isAssignableFrom(type)) {
- float[] array = (float[]) primarray;
- for (float value1 : array) {
- if (compare_Float(operation, value1, value2)) {
- return true;
- }
- }
-
- return false;
- }
-
- if (Double.TYPE.isAssignableFrom(type)) {
- double[] array = (double[]) primarray;
- for (double value1 : array) {
- if (compare_Double(operation, value1, value2)) {
- return true;
- }
- }
-
- return false;
- }
-
- if (Boolean.TYPE.isAssignableFrom(type)) {
- boolean[] array = (boolean[]) primarray;
- for (boolean value1 : array) {
- if (compare_Boolean(operation, value1, value2)) {
- return true;
- }
- }
-
- return false;
- }
-
- return false;
- }
-
- private boolean compare_String(int operation, String string, Object value2) {
- switch (operation) {
- case SUBSTRING : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("SUBSTRING(" + string + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- String[] substrings = (String[]) value2;
- int pos = 0;
- for (int i = 0, size = substrings.length; i < size; i++) {
- String substr = substrings[i];
-
- if (i + 1 < size) /* if this is not that last substr */{
- if (substr == null) /* * */{
- String substr2 = substrings[i + 1];
-
- if (substr2 == null) /* ** */
- continue; /* ignore first star */
- /* *xxx */
- if (Debug.DEBUG_FILTER) {
- Debug.println("indexOf(\"" + substr2 + "\"," + pos + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- int index = string.indexOf(substr2, pos);
- if (index == -1) {
- return false;
- }
-
- pos = index + substr2.length();
- if (i + 2 < size) // if there are more substrings, increment over the string we just matched; otherwise need to do the last substr check
- i++;
- } else /* xxx */{
- int len = substr.length();
-
- if (Debug.DEBUG_FILTER) {
- Debug.println("regionMatches(" + pos + ",\"" + substr + "\")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- if (string.regionMatches(pos, substr, 0, len)) {
- pos += len;
- } else {
- return false;
- }
- }
- } else /* last substr */{
- if (substr == null) /* * */{
- return true;
- }
- /* xxx */
- if (Debug.DEBUG_FILTER) {
- Debug.println("regionMatches(" + pos + "," + substr + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return string.endsWith(substr);
- }
- }
-
- return true;
- }
- case EQUAL : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("EQUAL(" + string + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return string.equals(value2);
- }
- case APPROX : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("APPROX(" + string + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- string = approxString(string);
- String string2 = approxString((String) value2);
-
- return string.equalsIgnoreCase(string2);
- }
- case GREATER : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("GREATER(" + string + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return string.compareTo((String) value2) >= 0;
- }
- case LESS : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("LESS(" + string + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return string.compareTo((String) value2) <= 0;
- }
- }
-
- return false;
- }
-
- private boolean compare_Integer(int operation, int intval, Object value2) {
- if (operation == SUBSTRING) {
- if (Debug.DEBUG_FILTER) {
- Debug.println("SUBSTRING(" + intval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return false;
- }
-
- int intval2;
- try {
- intval2 = Integer.parseInt(((String) value2).trim());
- } catch (IllegalArgumentException e) {
- return false;
- }
- switch (operation) {
- case EQUAL : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("EQUAL(" + intval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return intval == intval2;
- }
- case APPROX : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("APPROX(" + intval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return intval == intval2;
- }
- case GREATER : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("GREATER(" + intval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return intval >= intval2;
- }
- case LESS : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("LESS(" + intval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return intval <= intval2;
- }
- }
-
- return false;
- }
-
- private boolean compare_Long(int operation, long longval, Object value2) {
- if (operation == SUBSTRING) {
- if (Debug.DEBUG_FILTER) {
- Debug.println("SUBSTRING(" + longval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return false;
- }
-
- long longval2;
- try {
- longval2 = Long.parseLong(((String) value2).trim());
- } catch (IllegalArgumentException e) {
- return false;
- }
- switch (operation) {
- case EQUAL : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("EQUAL(" + longval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return longval == longval2;
- }
- case APPROX : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("APPROX(" + longval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return longval == longval2;
- }
- case GREATER : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("GREATER(" + longval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return longval >= longval2;
- }
- case LESS : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("LESS(" + longval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return longval <= longval2;
- }
- }
-
- return false;
- }
-
- private boolean compare_Byte(int operation, byte byteval, Object value2) {
- if (operation == SUBSTRING) {
- if (Debug.DEBUG_FILTER) {
- Debug.println("SUBSTRING(" + byteval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return false;
- }
-
- byte byteval2;
- try {
- byteval2 = Byte.parseByte(((String) value2).trim());
- } catch (IllegalArgumentException e) {
- return false;
- }
- switch (operation) {
- case EQUAL : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("EQUAL(" + byteval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return byteval == byteval2;
- }
- case APPROX : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("APPROX(" + byteval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return byteval == byteval2;
- }
- case GREATER : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("GREATER(" + byteval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return byteval >= byteval2;
- }
- case LESS : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("LESS(" + byteval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return byteval <= byteval2;
- }
- }
-
- return false;
- }
-
- private boolean compare_Short(int operation, short shortval, Object value2) {
- if (operation == SUBSTRING) {
- if (Debug.DEBUG_FILTER) {
- Debug.println("SUBSTRING(" + shortval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return false;
- }
-
- short shortval2;
- try {
- shortval2 = Short.parseShort(((String) value2).trim());
- } catch (IllegalArgumentException e) {
- return false;
- }
- switch (operation) {
- case EQUAL : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("EQUAL(" + shortval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return shortval == shortval2;
- }
- case APPROX : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("APPROX(" + shortval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return shortval == shortval2;
- }
- case GREATER : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("GREATER(" + shortval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return shortval >= shortval2;
- }
- case LESS : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("LESS(" + shortval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return shortval <= shortval2;
- }
- }
-
- return false;
- }
-
- private boolean compare_Character(int operation, char charval, Object value2) {
- if (operation == SUBSTRING) {
- if (Debug.DEBUG_FILTER) {
- Debug.println("SUBSTRING(" + charval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return false;
- }
-
- char charval2;
- try {
- charval2 = ((String) value2).charAt(0);
- } catch (IndexOutOfBoundsException e) {
- return false;
- }
- switch (operation) {
- case EQUAL : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("EQUAL(" + charval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return charval == charval2;
- }
- case APPROX : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("APPROX(" + charval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return (charval == charval2) || (Character.toUpperCase(charval) == Character.toUpperCase(charval2)) || (Character.toLowerCase(charval) == Character.toLowerCase(charval2));
- }
- case GREATER : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("GREATER(" + charval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return charval >= charval2;
- }
- case LESS : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("LESS(" + charval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return charval <= charval2;
- }
- }
-
- return false;
- }
-
- private boolean compare_Boolean(int operation, boolean boolval, Object value2) {
- if (operation == SUBSTRING) {
- if (Debug.DEBUG_FILTER) {
- Debug.println("SUBSTRING(" + boolval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return false;
- }
-
- boolean boolval2 = Boolean.valueOf(((String) value2).trim()).booleanValue();
- switch (operation) {
- case EQUAL : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("EQUAL(" + boolval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return boolval == boolval2;
- }
- case APPROX : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("APPROX(" + boolval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return boolval == boolval2;
- }
- case GREATER : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("GREATER(" + boolval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return boolval == boolval2;
- }
- case LESS : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("LESS(" + boolval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return boolval == boolval2;
- }
- }
-
- return false;
- }
-
- private boolean compare_Float(int operation, float floatval, Object value2) {
- if (operation == SUBSTRING) {
- if (Debug.DEBUG_FILTER) {
- Debug.println("SUBSTRING(" + floatval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return false;
- }
-
- float floatval2;
- try {
- floatval2 = Float.parseFloat(((String) value2).trim());
- } catch (IllegalArgumentException e) {
- return false;
- }
- switch (operation) {
- case EQUAL : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("EQUAL(" + floatval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return Float.compare(floatval, floatval2) == 0;
- }
- case APPROX : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("APPROX(" + floatval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return Float.compare(floatval, floatval2) == 0;
- }
- case GREATER : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("GREATER(" + floatval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return Float.compare(floatval, floatval2) >= 0;
- }
- case LESS : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("LESS(" + floatval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return Float.compare(floatval, floatval2) <= 0;
- }
- }
-
- return false;
- }
-
- private boolean compare_Double(int operation, double doubleval, Object value2) {
- if (operation == SUBSTRING) {
- if (Debug.DEBUG_FILTER) {
- Debug.println("SUBSTRING(" + doubleval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return false;
- }
-
- double doubleval2;
- try {
- doubleval2 = Double.parseDouble(((String) value2).trim());
- } catch (IllegalArgumentException e) {
- return false;
- }
- switch (operation) {
- case EQUAL : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("EQUAL(" + doubleval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return Double.compare(doubleval, doubleval2) == 0;
- }
- case APPROX : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("APPROX(" + doubleval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return Double.compare(doubleval, doubleval2) == 0;
- }
- case GREATER : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("GREATER(" + doubleval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return Double.compare(doubleval, doubleval2) >= 0;
- }
- case LESS : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("LESS(" + doubleval + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return Double.compare(doubleval, doubleval2) <= 0;
- }
- }
-
- return false;
- }
-
- private static Object valueOf(Class<?> target, String value2) {
- do {
- Method method;
- try {
- method = target.getMethod("valueOf", String.class); //$NON-NLS-1$
- } catch (NoSuchMethodException e) {
- break;
- }
- if (Modifier.isStatic(method.getModifiers()) && target.isAssignableFrom(method.getReturnType())) {
- setAccessible(method);
- try {
- return method.invoke(null, value2.trim());
- } catch (IllegalAccessException e) {
- return null;
- } catch (InvocationTargetException e) {
- return null;
- }
- }
- } while (false);
-
- do {
- Constructor<?> constructor;
- try {
- constructor = target.getConstructor(String.class);
- } catch (NoSuchMethodException e) {
- break;
- }
- setAccessible(constructor);
- try {
- return constructor.newInstance(value2.trim());
- } catch (IllegalAccessException e) {
- return null;
- } catch (InvocationTargetException e) {
- return null;
- } catch (InstantiationException e) {
- return null;
- }
- } while (false);
-
- return null;
- }
-
- private static void setAccessible(AccessibleObject accessible) {
- if (!accessible.isAccessible()) {
- AccessController.doPrivileged(new SetAccessibleAction(accessible));
- }
- }
-
- private boolean compare_Comparable(int operation, Comparable<Object> value1, Object value2) {
- if (operation == SUBSTRING) {
- if (Debug.DEBUG_FILTER) {
- Debug.println("SUBSTRING(" + value1 + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return false;
- }
- value2 = valueOf(value1.getClass(), (String) value2);
- if (value2 == null) {
- return false;
- }
-
- try {
- switch (operation) {
- case EQUAL : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("EQUAL(" + value1 + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return value1.compareTo(value2) == 0;
- }
- case APPROX : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("APPROX(" + value1 + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return value1.compareTo(value2) == 0;
- }
- case GREATER : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("GREATER(" + value1 + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return value1.compareTo(value2) >= 0;
- }
- case LESS : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("LESS(" + value1 + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return value1.compareTo(value2) <= 0;
- }
- }
- } catch (Exception e) {
- // if the compareTo method throws an exception; return false
- return false;
- }
- return false;
- }
-
- private boolean compare_Unknown(int operation, Object value1, Object value2) { //RFC 59
- if (operation == SUBSTRING) {
- if (Debug.DEBUG_FILTER) {
- Debug.println("SUBSTRING(" + value1 + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return false;
- }
- value2 = valueOf(value1.getClass(), (String) value2);
- if (value2 == null) {
- return false;
- }
-
- try {
- switch (operation) {
- case EQUAL : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("EQUAL(" + value1 + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return value1.equals(value2);
- }
- case APPROX : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("APPROX(" + value1 + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return value1.equals(value2);
- }
- case GREATER : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("GREATER(" + value1 + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return value1.equals(value2);
- }
- case LESS : {
- if (Debug.DEBUG_FILTER) {
- Debug.println("LESS(" + value1 + "," + value2 + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return value1.equals(value2);
- }
- }
- } catch (Exception e) {
- // if the equals method throws an exception; return false
- return false;
- }
-
- return false;
- }
-
- /**
- * 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.
- */
- private static String approxString(String input) {
- boolean changed = false;
- char[] output = input.toCharArray();
- int cursor = 0;
- for (char c : output) {
- if (Character.isWhitespace(c)) {
- changed = true;
- continue;
- }
-
- output[cursor] = c;
- cursor++;
- }
-
- return changed ? new String(output, 0, cursor) : input;
- }
-
- /**
- * 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.
- */
- 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.
- * @param primaryKey the primary key
- * @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
- // (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
- switch (op) {
- case EQUAL :
- if (attr.equalsIgnoreCase(primaryKey) && (value instanceof String))
- return (String) value;
- break;
- case AND :
- FilterImpl[] clauses = (FilterImpl[]) value;
- for (FilterImpl clause : clauses)
- if (clause.op == EQUAL) {
- String result = clause.getPrimaryKeyValue(primaryKey);
- if (result != null)
- return result;
- }
- break;
- }
- return null;
- }
-
- /**
- * Returns all the attributes contained within this filter
- * @return all the attributes contained within this filter
- */
- public String[] getAttributes() {
- List<String> results = new ArrayList<String>();
- getAttributesInternal(results);
- return results.toArray(new String[results.size()]);
- }
-
- private void getAttributesInternal(List<String> results) {
- if (value instanceof FilterImpl[]) {
- FilterImpl[] children = (FilterImpl[]) value;
- for (FilterImpl child : children)
- child.getAttributesInternal(results);
- return;
- } else if (value instanceof FilterImpl) {
- // The NOT operation only has one child filter (bug 188075)
- FilterImpl child = ((FilterImpl) value);
- child.getAttributesInternal(results);
- return;
- }
- if (attr != null)
- results.add(attr);
- }
-
- /**
- * Parser class for OSGi filter strings. This class parses
- * the complete filter string and builds a tree of Filter
- * objects rooted at the parent.
- */
- private static class Parser {
- private final String filterstring;
- private final char[] filterChars;
- private int pos;
-
- Parser(String filterstring) {
- this.filterstring = filterstring;
- filterChars = filterstring.toCharArray();
- pos = 0;
- }
-
- FilterImpl parse() throws InvalidSyntaxException {
- FilterImpl filter;
- try {
- filter = parse_filter();
- } catch (ArrayIndexOutOfBoundsException e) {
- throw new InvalidSyntaxException(Msg.FILTER_TERMINATED_ABRUBTLY, filterstring);
- }
-
- if (pos != filterChars.length) {
- throw new InvalidSyntaxException(NLS.bind(Msg.FILTER_TRAILING_CHARACTERS, filterstring.substring(pos)), filterstring);
- }
- return filter;
- }
-
- private FilterImpl parse_filter() throws InvalidSyntaxException {
- FilterImpl filter;
- skipWhiteSpace();
-
- if (filterChars[pos] != '(') {
- throw new InvalidSyntaxException(NLS.bind(Msg.FILTER_MISSING_LEFTPAREN, filterstring.substring(pos)), filterstring);
- }
-
- pos++;
-
- filter = parse_filtercomp();
-
- skipWhiteSpace();
-
- if (filterChars[pos] != ')') {
- throw new InvalidSyntaxException(NLS.bind(Msg.FILTER_MISSING_RIGHTPAREN, filterstring.substring(pos)), filterstring);
- }
-
- pos++;
-
- skipWhiteSpace();
-
- return filter;
- }
-
- private FilterImpl parse_filtercomp() throws InvalidSyntaxException {
- skipWhiteSpace();
-
- char c = filterChars[pos];
-
- switch (c) {
- case '&' : {
- pos++;
- return parse_and();
- }
- case '|' : {
- pos++;
- return parse_or();
- }
- case '!' : {
- pos++;
- return parse_not();
- }
- }
- return parse_item();
- }
-
- private FilterImpl parse_and() throws InvalidSyntaxException {
- int lookahead = pos;
- skipWhiteSpace();
-
- if (filterChars[pos] != '(') {
- pos = lookahead - 1;
- return parse_item();
- }
-
- List<FilterImpl> operands = new ArrayList<FilterImpl>(10);
-
- while (filterChars[pos] == '(') {
- FilterImpl child = parse_filter();
- operands.add(child);
- }
-
- return new FilterImpl(FilterImpl.AND, null, operands.toArray(new FilterImpl[operands.size()]));
- }
-
- private FilterImpl parse_or() throws InvalidSyntaxException {
- int lookahead = pos;
- skipWhiteSpace();
-
- if (filterChars[pos] != '(') {
- pos = lookahead - 1;
- return parse_item();
- }
-
- List<FilterImpl> operands = new ArrayList<FilterImpl>(10);
-
- while (filterChars[pos] == '(') {
- FilterImpl child = parse_filter();
- operands.add(child);
- }
-
- return new FilterImpl(FilterImpl.OR, null, operands.toArray(new FilterImpl[operands.size()]));
- }
-
- private FilterImpl parse_not() throws InvalidSyntaxException {
- int lookahead = pos;
- skipWhiteSpace();
-
- if (filterChars[pos] != '(') {
- pos = lookahead - 1;
- return parse_item();
- }
-
- FilterImpl child = parse_filter();
-
- return new FilterImpl(FilterImpl.NOT, null, child);
- }
-
- private FilterImpl parse_item() throws InvalidSyntaxException {
- String attr = parse_attr();
-
- skipWhiteSpace();
-
- switch (filterChars[pos]) {
- case '~' : {
- if (filterChars[pos + 1] == '=') {
- pos += 2;
- return new FilterImpl(FilterImpl.APPROX, attr, parse_value());
- }
- break;
- }
- case '>' : {
- if (filterChars[pos + 1] == '=') {
- pos += 2;
- return new FilterImpl(FilterImpl.GREATER, attr, parse_value());
- }
- break;
- }
- case '<' : {
- if (filterChars[pos + 1] == '=') {
- pos += 2;
- return new FilterImpl(FilterImpl.LESS, attr, parse_value());
- }
- break;
- }
- case '=' : {
- if (filterChars[pos + 1] == '*') {
- int oldpos = pos;
- pos += 2;
- skipWhiteSpace();
- if (filterChars[pos] == ')') {
- return new FilterImpl(FilterImpl.PRESENT, attr, null);
- }
- pos = oldpos;
- }
-
- pos++;
- Object string = parse_substring();
-
- if (string instanceof String) {
- return new FilterImpl(FilterImpl.EQUAL, attr, string);
- }
- return new FilterImpl(FilterImpl.SUBSTRING, attr, string);
- }
- }
-
- throw new InvalidSyntaxException(NLS.bind(Msg.FILTER_INVALID_OPERATOR, filterstring.substring(pos)), filterstring);
- }
-
- private String parse_attr() throws InvalidSyntaxException {
- skipWhiteSpace();
-
- int begin = pos;
- int end = pos;
-
- char c = filterChars[pos];
-
- while (c != '~' && c != '<' && c != '>' && c != '=' && c != '(' && c != ')') {
- pos++;
-
- if (!Character.isWhitespace(c)) {
- end = pos;
- }
-
- c = filterChars[pos];
- }
-
- int length = end - begin;
-
- if (length == 0) {
- throw new InvalidSyntaxException(NLS.bind(Msg.FILTER_MISSING_ATTR, filterstring.substring(pos)), filterstring);
- }
-
- return new String(filterChars, begin, length);
- }
-
- private String parse_value() throws InvalidSyntaxException {
- StringBuffer sb = new StringBuffer(filterChars.length - pos);
-
- parseloop: while (true) {
- char c = filterChars[pos];
-
- switch (c) {
- case ')' : {
- break parseloop;
- }
-
- case '(' : {
- throw new InvalidSyntaxException(NLS.bind(Msg.FILTER_INVALID_VALUE, filterstring.substring(pos)), filterstring);
- }
-
- case '\\' : {
- pos++;
- c = filterChars[pos];
- /* fall through into default */
- }
-
- default : {
- sb.append(c);
- pos++;
- break;
- }
- }
- }
-
- if (sb.length() == 0) {
- throw new InvalidSyntaxException(NLS.bind(Msg.FILTER_MISSING_VALUE, filterstring.substring(pos)), filterstring);
- }
-
- return sb.toString();
- }
-
- private Object parse_substring() throws InvalidSyntaxException {
- StringBuffer sb = new StringBuffer(filterChars.length - pos);
-
- List<String> operands = new ArrayList<String>(10);
-
- parseloop: while (true) {
- char c = filterChars[pos];
-
- switch (c) {
- case ')' : {
- if (sb.length() > 0) {
- operands.add(sb.toString());
- }
-
- break parseloop;
- }
-
- case '(' : {
- throw new InvalidSyntaxException(NLS.bind(Msg.FILTER_INVALID_VALUE, filterstring.substring(pos)), filterstring);
- }
-
- case '*' : {
- if (sb.length() > 0) {
- operands.add(sb.toString());
- }
-
- sb.setLength(0);
-
- operands.add(null);
- pos++;
-
- break;
- }
-
- case '\\' : {
- pos++;
- c = filterChars[pos];
- /* fall through into default */
- }
-
- default : {
- sb.append(c);
- pos++;
- break;
- }
- }
- }
-
- int size = operands.size();
-
- if (size == 0) {
- return ""; //$NON-NLS-1$
- }
-
- if (size == 1) {
- Object single = operands.get(0);
-
- if (single != null) {
- return single;
- }
- }
-
- return operands.toArray(new String[size]);
- }
-
- private void skipWhiteSpace() {
- for (int length = filterChars.length; (pos < length) && Character.isWhitespace(filterChars[pos]);) {
- pos++;
- }
- }
- }
-
- /**
- * This Dictionary is used for key lookup from a ServiceReference during
- * filter evaluation. This Dictionary implementation only supports the get
- * operation using a String key as no other operations are used by the
- * Filter implementation.
- *
- */
- private static class ServiceReferenceDictionary extends Dictionary<String, Object> {
- private final ServiceReference<?> reference;
-
- ServiceReferenceDictionary(ServiceReference<?> reference) {
- this.reference = reference;
- }
-
- public Object get(Object key) {
- if (reference == null) {
- return null;
- }
- return reference.getProperty((String) key);
- }
-
- public boolean isEmpty() {
- throw new UnsupportedOperationException();
- }
-
- public Enumeration<String> keys() {
- throw new UnsupportedOperationException();
- }
-
- public Enumeration<Object> elements() {
- throw new UnsupportedOperationException();
- }
-
- public Object put(String key, Object value) {
- throw new UnsupportedOperationException();
- }
-
- public Object remove(Object key) {
- throw new UnsupportedOperationException();
- }
-
- public int size() {
- throw new UnsupportedOperationException();
- }
- }
-
- private static class SetAccessibleAction implements PrivilegedAction<Object> {
- private final AccessibleObject accessible;
-
- SetAccessibleAction(AccessibleObject accessible) {
- this.accessible = accessible;
- }
-
- public Object run() {
- accessible.setAccessible(true);
- return null;
- }
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/Framework.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/Framework.java
deleted file mode 100644
index d3aeaf645..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/Framework.java
+++ /dev/null
@@ -1,2007 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2012 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.osgi.framework.internal.core;
-
-import java.io.*;
-import java.lang.reflect.*;
-import java.net.*;
-import java.security.*;
-import java.util.*;
-import org.eclipse.core.runtime.internal.adaptor.ContextFinder;
-import org.eclipse.osgi.baseadaptor.BaseAdaptor;
-import org.eclipse.osgi.framework.adaptor.*;
-import org.eclipse.osgi.framework.debug.Debug;
-import org.eclipse.osgi.framework.eventmgr.*;
-import org.eclipse.osgi.framework.internal.protocol.ContentHandlerFactory;
-import org.eclipse.osgi.framework.internal.protocol.StreamHandlerFactory;
-import org.eclipse.osgi.framework.log.FrameworkLogEntry;
-import org.eclipse.osgi.framework.util.SecureAction;
-import org.eclipse.osgi.internal.loader.*;
-import org.eclipse.osgi.internal.permadmin.EquinoxSecurityManager;
-import org.eclipse.osgi.internal.permadmin.SecurityAdmin;
-import org.eclipse.osgi.internal.profile.Profile;
-import org.eclipse.osgi.internal.serviceregistry.*;
-import org.eclipse.osgi.signedcontent.SignedContentFactory;
-import org.eclipse.osgi.util.ManifestElement;
-import org.eclipse.osgi.util.NLS;
-import org.osgi.framework.*;
-import org.osgi.framework.hooks.bundle.*;
-import org.osgi.util.tracker.ServiceTracker;
-
-/**
- * Core OSGi Framework class.
- */
-public class Framework implements EventPublisher, Runnable {
- // System property used to set the context classloader parent classloader type (ccl is the default)
- private static final String PROP_CONTEXTCLASSLOADER_PARENT = "osgi.contextClassLoaderParent"; //$NON-NLS-1$
- private static final String CONTEXTCLASSLOADER_PARENT_APP = "app"; //$NON-NLS-1$
- private static final String CONTEXTCLASSLOADER_PARENT_EXT = "ext"; //$NON-NLS-1$
- private static final String CONTEXTCLASSLOADER_PARENT_BOOT = "boot"; //$NON-NLS-1$
- private static final String CONTEXTCLASSLOADER_PARENT_FWK = "fwk"; //$NON-NLS-1$
-
- public static final String PROP_FRAMEWORK_THREAD = "osgi.framework.activeThreadType"; //$NON-NLS-1$
- public static final String THREAD_NORMAL = "normal"; //$NON-NLS-1$
- public static final String PROP_EQUINOX_SECURITY = "eclipse.security"; //$NON-NLS-1$
- public static final String SECURITY_OSGI = "osgi"; //$NON-NLS-1$
-
- private static String J2SE = "J2SE-"; //$NON-NLS-1$
- private static String JAVASE = "JavaSE-"; //$NON-NLS-1$
- private static String PROFILE_EXT = ".profile"; //$NON-NLS-1$
- /** FrameworkAdaptor specific functions. */
- protected FrameworkAdaptor adaptor;
- /** Framework properties object. A reference to the
- * System.getProperies() object. The properties from
- * the adaptor will be merged into these properties.
- */
- protected Properties properties;
- /** Has the framework been started */
- protected boolean active;
- /** Event indicating the reason for shutdown*/
- private FrameworkEvent[] shutdownEvent;
- /** The bundles installed in the framework */
- protected BundleRepository bundles;
- /** Package Admin object. This object manages the exported packages. */
- protected PackageAdminImpl packageAdmin;
- /** PermissionAdmin and ConditionalPermissionAdmin impl. This object manages the bundle permissions. */
- protected SecurityAdmin securityAdmin;
- /** Startlevel object. This object manages the framework and bundle startlevels */
- protected StartLevelManager startLevelManager;
- /** The ServiceRegistry */
- private ServiceRegistry serviceRegistry;
- private final int BSN_VERSION;
- private static final int BSN_VERSION_SINGLE = 1;
- private static final int BSN_VERSION_MULTIPLE = 2;
- private static final int BSN_VERSION_MANAGED = 3;
-
- /*
- * 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<BundleContextImpl, CopyOnWriteIdentityMap<BundleListener, BundleListener>> allBundleListeners = new HashMap<BundleContextImpl, CopyOnWriteIdentityMap<BundleListener, BundleListener>>();
- protected static final int BUNDLEEVENT = 1;
- // Map of BundleContexts for bundle's SynchronousBundleListeners.
- private final Map<BundleContextImpl, CopyOnWriteIdentityMap<SynchronousBundleListener, SynchronousBundleListener>> allSyncBundleListeners = new HashMap<BundleContextImpl, CopyOnWriteIdentityMap<SynchronousBundleListener, SynchronousBundleListener>>();
- protected static final int BUNDLEEVENTSYNC = 2;
- /* SERVICEEVENT(3) is now handled by ServiceRegistry */
- // Map of BundleContexts for bundle's FrameworkListeners.
- private final Map<BundleContextImpl, CopyOnWriteIdentityMap<FrameworkListener, FrameworkListener>> allFrameworkListeners = new HashMap<BundleContextImpl, CopyOnWriteIdentityMap<FrameworkListener, FrameworkListener>>();
- protected static final int FRAMEWORKEVENT = 4;
- protected static final int BATCHEVENT_BEGIN = Integer.MIN_VALUE + 1;
- protected static final int BATCHEVENT_END = Integer.MIN_VALUE;
- static final String eventHookName = EventHook.class.getName();
- static final String findHookName = FindHook.class.getName();
- static final String collisionHookName = CollisionHook.class.getName();
- /** EventManager for event delivery. */
- protected EventManager eventManager;
- /* Reservation object for install synchronization */
- private Map<String, Thread> installLock;
- /** System Bundle object */
- protected InternalSystemBundle systemBundle;
- private String[] bootDelegation;
- private String[] bootDelegationStems;
- private boolean bootDelegateAll = false;
- public final boolean contextBootDelegation = "true".equals(FrameworkProperties.getProperty("osgi.context.bootdelegation", "true")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- public final boolean compatibiltyBootDelegation = "true".equals(FrameworkProperties.getProperty(Constants.OSGI_COMPATIBILITY_BOOTDELEGATION, "true")); //$NON-NLS-1$ //$NON-NLS-2$
- private final boolean allowRefreshDuplicateBSN = Boolean.TRUE.toString().equals(FrameworkProperties.getProperty(Constants.REFRESH_DUPLICATE_BSN, "true")); //$NON-NLS-1$
- ClassLoaderDelegateHook[] delegateHooks;
- private volatile boolean forcedRestart = false;
- /**
- * The AliasMapper used to alias OS Names.
- */
- protected static AliasMapper aliasMapper = new AliasMapper();
- SecureAction secureAction = AccessController.doPrivileged(SecureAction.createSecureAction());
- // cache of AdminPermissions keyed by Bundle ID
- private final Map<Long, Map<String, AdminPermission>> adminPermissions = new HashMap<Long, Map<String, AdminPermission>>();
-
- // we need to hold these so that we can unregister them at shutdown
- private StreamHandlerFactory streamHandlerFactory;
- private ContentHandlerFactory contentHandlerFactory;
-
- private volatile ServiceTracker<SignedContentFactory, SignedContentFactory> signedContentFactory;
- private volatile ContextFinder contextFinder;
-
- /*
- * We need to make sure that the GetDataFileAction class loads early to prevent a ClassCircularityError when checking permissions.
- * see bug 161561
- */
- static {
- Class<?> c;
- c = GetDataFileAction.class;
- c.getName(); // to prevent compiler warnings
- }
-
- static class GetDataFileAction implements PrivilegedAction<File> {
- private AbstractBundle bundle;
- private String filename;
-
- public GetDataFileAction(AbstractBundle bundle, String filename) {
- this.bundle = bundle;
- this.filename = filename;
- }
-
- public File run() {
- return bundle.getBundleData().getDataFile(filename);
- }
- }
-
- /**
- * Constructor for the Framework instance. This method initializes the
- * framework to an unlaunched state.
- *
- */
- public Framework(FrameworkAdaptor adaptor) {
- if (Profile.PROFILE && Profile.STARTUP)
- Profile.logEnter("Framework.initialze()", null); //$NON-NLS-1$
- String bsnVersion = FrameworkProperties.getProperty(Constants.FRAMEWORK_BSNVERSION);
- if (Constants.FRAMEWORK_BSNVERSION_SINGLE.equals(bsnVersion)) {
- BSN_VERSION = BSN_VERSION_SINGLE;
- } else if (Constants.FRAMEWORK_BSNVERSION_MULTIPLE.equals(bsnVersion)) {
- BSN_VERSION = BSN_VERSION_MULTIPLE;
- } else {
- BSN_VERSION = BSN_VERSION_MANAGED;
- }
- long start = System.currentTimeMillis();
- this.adaptor = adaptor;
- delegateHooks = adaptor instanceof BaseAdaptor ? ((BaseAdaptor) adaptor).getHookRegistry().getClassLoaderDelegateHooks() : null;
- active = false;
- installSecurityManager();
- if (Debug.DEBUG_SECURITY) {
- Debug.println("SecurityManager: " + System.getSecurityManager()); //$NON-NLS-1$
- Debug.println("ProtectionDomain of Framework.class: \n" + this.getClass().getProtectionDomain()); //$NON-NLS-1$
- }
- setNLSFrameworkLog();
- // initialize ContextFinder
- initializeContextFinder();
- /* initialize the adaptor */
- adaptor.initialize(this);
- if (Profile.PROFILE && Profile.STARTUP)
- Profile.logTime("Framework.initialze()", "adapter initialized"); //$NON-NLS-1$//$NON-NLS-2$
- try {
- adaptor.initializeStorage();
- } catch (IOException e) /* fatal error */{
- throw new RuntimeException(e.getMessage(), e);
- }
- if (Profile.PROFILE && Profile.STARTUP)
- Profile.logTime("Framework.initialze()", "adapter storage initialized"); //$NON-NLS-1$//$NON-NLS-2$
- /*
- * This must be done before calling any of the framework getProperty
- * methods.
- */
- initializeProperties(adaptor.getProperties());
- /* initialize admin objects */
- packageAdmin = new PackageAdminImpl(this);
- try {
- // always create security admin even with security off
- securityAdmin = new SecurityAdmin(null, this, adaptor.getPermissionStorage());
- } catch (IOException e) /* fatal error */{
- e.printStackTrace();
- throw new RuntimeException(e.getMessage(), e);
- }
- if (Profile.PROFILE && Profile.STARTUP)
- Profile.logTime("Framework.initialze()", "done init props & new PermissionAdminImpl"); //$NON-NLS-1$//$NON-NLS-2$
- startLevelManager = new StartLevelManager(this);
- /* create the event manager and top level event dispatchers */
- eventManager = new EventManager("Framework Event Dispatcher"); //$NON-NLS-1$
- if (Profile.PROFILE && Profile.STARTUP)
- Profile.logTime("Framework.initialze()", "done new EventManager"); //$NON-NLS-1$ //$NON-NLS-2$
- /* create the service registry */
- serviceRegistry = new ServiceRegistry(this);
- // Initialize the installLock; there is no way of knowing
- // what the initial size should be, at most it will be the number
- // of threads trying to install a bundle (probably a very low number).
- installLock = new HashMap<String, Thread>(10);
- /* create the system bundle */
- createSystemBundle();
- loadVMProfile(); // load VM profile after the system bundle has been created
- setBootDelegation(); //set boot delegation property after system exports have been set
- if (Profile.PROFILE && Profile.STARTUP)
- Profile.logTime("Framework.initialze()", "done createSystemBundle"); //$NON-NLS-1$ //$NON-NLS-2$
- /* install URLStreamHandlerFactory */
- installURLStreamHandlerFactory(systemBundle.context, adaptor);
- /* install ContentHandlerFactory for OSGi URLStreamHandler support */
- installContentHandlerFactory(systemBundle.context, adaptor);
- if (Profile.PROFILE && Profile.STARTUP)
- Profile.logTime("Framework.initialze()", "done new URLStream/Content HandlerFactory"); //$NON-NLS-1$//$NON-NLS-2$
- /* create bundle objects for all installed bundles. */
- BundleData[] bundleDatas = adaptor.getInstalledBundles();
- bundles = new BundleRepository(bundleDatas == null ? 10 : bundleDatas.length + 1);
- /* add the system bundle to the Bundle Repository */
- bundles.add(systemBundle);
- if (bundleDatas != null) {
- for (int i = 0; i < bundleDatas.length; i++) {
- try {
- AbstractBundle bundle = AbstractBundle.createBundle(bundleDatas[i], this, true);
- bundles.add(bundle);
- } catch (BundleException be) {
- // This is not a fatal error. Publish the framework event.
- publishFrameworkEvent(FrameworkEvent.ERROR, systemBundle, be);
- }
- }
- }
- if (Debug.DEBUG_GENERAL)
- System.out.println("Initialize the framework: " + (System.currentTimeMillis() - start)); //$NON-NLS-1$
- if (Profile.PROFILE && Profile.STARTUP)
- Profile.logExit("Framework.initialize()"); //$NON-NLS-1$
- }
-
- public FrameworkAdaptor getAdaptor() {
- return adaptor;
- }
-
- public ClassLoaderDelegateHook[] getDelegateHooks() {
- return delegateHooks;
- }
-
- public ServiceRegistry getServiceRegistry() {
- return serviceRegistry;
- }
-
- private void setNLSFrameworkLog() {
- try {
- Field frameworkLogField = NLS.class.getDeclaredField("frameworkLog"); //$NON-NLS-1$
- frameworkLogField.setAccessible(true);
- frameworkLogField.set(null, adaptor.getFrameworkLog());
- } catch (Exception e) {
- adaptor.getFrameworkLog().log(new FrameworkLogEntry(FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME, FrameworkLogEntry.ERROR, 0, e.getMessage(), 0, e, null));
- }
- }
-
- private void createSystemBundle() {
- try {
- systemBundle = new InternalSystemBundle(this);
- systemBundle.getBundleData().setBundle(systemBundle);
- } catch (BundleException e) { // fatal error
- e.printStackTrace();
- throw new RuntimeException(NLS.bind(Msg.OSGI_SYSTEMBUNDLE_CREATE_EXCEPTION, e.getMessage()), e);
- }
- }
-
- /**
- * Initialize the System properties by copying properties from the adaptor
- * properties object. This method is called by the initialize method.
- *
- */
- protected void initializeProperties(Properties adaptorProperties) {
- properties = FrameworkProperties.getProperties();
- Enumeration<?> enumKeys = adaptorProperties.propertyNames();
- while (enumKeys.hasMoreElements()) {
- String key = (String) enumKeys.nextElement();
- if (properties.getProperty(key) == null) {
- properties.put(key, adaptorProperties.getProperty(key));
- }
- }
- properties.put(Constants.FRAMEWORK_VENDOR, Constants.OSGI_FRAMEWORK_VENDOR);
- properties.put(Constants.FRAMEWORK_VERSION, Constants.OSGI_FRAMEWORK_VERSION);
- String value = properties.getProperty(Constants.FRAMEWORK_PROCESSOR);
- if (value == null) {
- value = properties.getProperty(Constants.JVM_OS_ARCH);
- if (value != null) {
- properties.put(Constants.FRAMEWORK_PROCESSOR, aliasMapper.aliasProcessor(value));
- }
- }
- value = properties.getProperty(Constants.FRAMEWORK_OS_NAME);
- if (value == null) {
- value = properties.getProperty(Constants.JVM_OS_NAME);
- try {
- String canonicalValue = (String) aliasMapper.aliasOSName(value);
- if (canonicalValue != null) {
- value = canonicalValue;
- }
- } catch (ClassCastException ex) {
- //A vector was returned from the alias mapper.
- //The alias mapped to more than one canonical value
- //such as "win32" for example
- }
- if (value != null) {
- properties.put(Constants.FRAMEWORK_OS_NAME, value);
- }
- }
- value = properties.getProperty(Constants.FRAMEWORK_OS_VERSION);
- if (value == null) {
- value = properties.getProperty(Constants.JVM_OS_VERSION);
- if (value != null) {
- // only use the value upto the first space
- int space = value.indexOf(' ');
- if (space > 0) {
- value = value.substring(0, space);
- }
- // fix up cases where the os version does not make a valid Version string.
- int major = 0, minor = 0, micro = 0;
- String qualifier = ""; //$NON-NLS-1$
- try {
- StringTokenizer st = new StringTokenizer(value, ".", true); //$NON-NLS-1$
- major = parseVersionInt(st.nextToken());
-
- if (st.hasMoreTokens()) {
- st.nextToken(); // consume delimiter
- minor = parseVersionInt(st.nextToken());
-
- if (st.hasMoreTokens()) {
- st.nextToken(); // consume delimiter
- micro = parseVersionInt(st.nextToken());
-
- if (st.hasMoreTokens()) {
- st.nextToken(); // consume delimiter
- qualifier = st.nextToken();
- }
- }
- }
- } catch (NoSuchElementException e) {
- // ignore, use the values parsed so far
- }
- try {
- value = new Version(major, minor, micro, qualifier).toString();
- } catch (IllegalArgumentException e) {
- // must be an invalid qualifier; just ignore it
- value = new Version(major, minor, micro).toString();
- }
- properties.put(Constants.FRAMEWORK_OS_VERSION, value);
- }
- }
- value = properties.getProperty(Constants.FRAMEWORK_LANGUAGE);
- if (value == null)
- // set the value of the framework language property
- properties.put(Constants.FRAMEWORK_LANGUAGE, Locale.getDefault().getLanguage());
- // set the support properties for fragments and require-bundle (bug 173090)
- properties.put(Constants.SUPPORTS_FRAMEWORK_FRAGMENT, "true"); //$NON-NLS-1$
- properties.put(Constants.SUPPORTS_FRAMEWORK_REQUIREBUNDLE, "true"); //$NON-NLS-1$
- properties.put(Constants.FRAMEWORK_UUID, new UniversalUniqueIdentifier().toString());
- }
-
- private int parseVersionInt(String value) {
- try {
- return Integer.parseInt(value);
- } catch (NumberFormatException e) {
- // try up to the first non-number char
- StringBuffer sb = new StringBuffer(value.length());
- char[] chars = value.toCharArray();
- for (int i = 0; i < chars.length; i++) {
- if (!Character.isDigit(chars[i]))
- break;
- sb.append(chars[i]);
- }
- if (sb.length() > 0)
- return Integer.parseInt(sb.toString());
- return 0;
- }
- }
-
- private void setBootDelegation() {
- // set the boot delegation according to the osgi boot delegation property
- String bootDelegationProp = properties.getProperty(Constants.FRAMEWORK_BOOTDELEGATION);
- if (bootDelegationProp == null)
- return;
- if (bootDelegationProp.trim().length() == 0)
- return;
- String[] bootPackages = ManifestElement.getArrayFromList(bootDelegationProp);
- List<String> exactMatch = new ArrayList<String>(bootPackages.length);
- List<String> stemMatch = new ArrayList<String>(bootPackages.length);
- for (int i = 0; i < bootPackages.length; i++) {
- if (bootPackages[i].equals("*")) { //$NON-NLS-1$
- bootDelegateAll = true;
- return;
- } else if (bootPackages[i].endsWith("*")) { //$NON-NLS-1$
- if (bootPackages[i].length() > 2 && bootPackages[i].endsWith(".*")) //$NON-NLS-1$
- stemMatch.add(bootPackages[i].substring(0, bootPackages[i].length() - 1));
- } else {
- exactMatch.add(bootPackages[i]);
- }
- }
- if (!exactMatch.isEmpty())
- bootDelegation = exactMatch.toArray(new String[exactMatch.size()]);
- if (!stemMatch.isEmpty())
- bootDelegationStems = stemMatch.toArray(new String[stemMatch.size()]);
- }
-
- @SuppressWarnings("deprecation")
- private void loadVMProfile() {
- Properties profileProps = findVMProfile();
- String systemExports = properties.getProperty(Constants.FRAMEWORK_SYSTEMPACKAGES);
- // 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)
- properties.put(Constants.FRAMEWORK_SYSTEMPACKAGES, systemExports);
- }
- // set the org.osgi.framework.bootdelegation property according to the java profile
- String type = properties.getProperty(Constants.OSGI_JAVA_PROFILE_BOOTDELEGATION); // a null value means ignore
- String profileBootDelegation = profileProps.getProperty(Constants.FRAMEWORK_BOOTDELEGATION);
- if (Constants.OSGI_BOOTDELEGATION_OVERRIDE.equals(type)) {
- if (profileBootDelegation == null)
- properties.remove(Constants.FRAMEWORK_BOOTDELEGATION); // override with a null value
- else
- properties.put(Constants.FRAMEWORK_BOOTDELEGATION, profileBootDelegation); // override with the profile value
- } else if (Constants.OSGI_BOOTDELEGATION_NONE.equals(type))
- properties.remove(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 (properties.getProperty(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(Constants.OSGI_JAVA_PROFILE_NAME));
- if (ee != null)
- properties.put(Constants.FRAMEWORK_EXECUTIONENVIRONMENT, ee);
- }
- // set the org.osgi.framework.system.capabilities property according to the java profile
- if (properties.getProperty(Constants.FRAMEWORK_SYSTEMCAPABILITIES) == null) {
- String systemCapabilities = profileProps.getProperty(Constants.FRAMEWORK_SYSTEMCAPABILITIES);
- if (systemCapabilities != null)
- properties.put(Constants.FRAMEWORK_SYSTEMCAPABILITIES, systemCapabilities);
- }
- }
-
- private Properties findVMProfile() {
- Properties result = new Properties();
- // Find the VM profile name using J2ME properties
- String j2meConfig = properties.getProperty(Constants.J2ME_MICROEDITION_CONFIGURATION);
- String j2meProfiles = properties.getProperty(Constants.J2ME_MICROEDITION_PROFILES);
- String vmProfile = null;
- String javaEdition = null;
- Version javaVersion = null;
- if (j2meConfig != null && j2meConfig.length() > 0 && j2meProfiles != null && j2meProfiles.length() > 0) {
- // save the vmProfile based off of the config and profile
- // use the last profile; assuming that is the highest one
- String[] j2meProfileList = ManifestElement.getArrayFromList(j2meProfiles, " "); //$NON-NLS-1$
- if (j2meProfileList != null && j2meProfileList.length > 0)
- vmProfile = j2meConfig + '_' + j2meProfileList[j2meProfileList.length - 1];
- } else {
- // No J2ME properties; use J2SE properties
- // Note that the CDC spec appears not to require VM implementations to set the
- // javax.microedition properties!! So we will try to fall back to the
- // java.specification.name property, but this is pretty ridiculous!!
- String javaSpecVersion = properties.getProperty("java.specification.version"); //$NON-NLS-1$
- // set the profile and EE based off of the java.specification.version
- // TODO We assume J2ME Foundation and J2SE here. need to support other profiles J2EE ...
- if (javaSpecVersion != null) {
- StringTokenizer st = new StringTokenizer(javaSpecVersion, " _-"); //$NON-NLS-1$
- javaSpecVersion = st.nextToken();
- String javaSpecName = properties.getProperty("java.specification.name"); //$NON-NLS-1$
- // See bug 291269 we check for Foundation Specification and Foundation Profile Specification
- if (javaSpecName != null && (javaSpecName.indexOf("Foundation Specification") >= 0 || javaSpecName.indexOf("Foundation Profile Specification") >= 0)) //$NON-NLS-1$ //$NON-NLS-2$
- vmProfile = "CDC-" + javaSpecVersion + "_Foundation-" + javaSpecVersion; //$NON-NLS-1$ //$NON-NLS-2$
- else {
- // look for JavaSE if 1.6 or greater; otherwise look for J2SE
- Version v16 = new Version("1.6"); //$NON-NLS-1$
- javaEdition = J2SE;
- try {
- javaVersion = new Version(javaSpecVersion);
- if (v16.compareTo(javaVersion) <= 0)
- javaEdition = JAVASE;
- } catch (IllegalArgumentException e) {
- // do nothing
- }
- vmProfile = javaEdition + javaSpecVersion;
- }
- }
- }
- URL url = null;
- // check for the java profile property for a url
- String propJavaProfile = FrameworkProperties.getProperty(Constants.OSGI_JAVA_PROFILE);
- if (propJavaProfile != null)
- try {
- // we assume a URL
- url = new URL(propJavaProfile);
- } catch (MalformedURLException e1) {
- // try using a relative path in the system bundle
- url = findInSystemBundle(propJavaProfile);
- }
- if (url == null && vmProfile != null) {
- // look for a profile in the system bundle based on the vm profile
- String javaProfile = vmProfile + PROFILE_EXT;
- url = findInSystemBundle(javaProfile);
- if (url == null)
- url = getNextBestProfile(javaEdition, javaVersion);
- }
- if (url == null)
- // the profile url is still null then use the osgi min profile in OSGi by default
- url = findInSystemBundle("OSGi_Minimum-1.2.profile"); //$NON-NLS-1$
- if (url != null) {
- InputStream in = null;
- try {
- in = url.openStream();
- result.load(new BufferedInputStream(in));
- } catch (IOException e) {
- // TODO consider logging ...
- } finally {
- if (in != null)
- try {
- in.close();
- } catch (IOException ee) {
- // do nothing
- }
- }
- }
- // set the profile name if it does not provide one
- if (result.getProperty(Constants.OSGI_JAVA_PROFILE_NAME) == null)
- if (vmProfile != null)
- result.put(Constants.OSGI_JAVA_PROFILE_NAME, vmProfile.replace('_', '/'));
- else
- // last resort; default to the absolute minimum profile name for the framework
- result.put(Constants.OSGI_JAVA_PROFILE_NAME, "OSGi/Minimum-1.2"); //$NON-NLS-1$
- return result;
- }
-
- private URL getNextBestProfile(String javaEdition, Version javaVersion) {
- if (javaVersion == null || (javaEdition != J2SE && javaEdition != JAVASE))
- return null; // we cannot automatically choose the next best profile unless this is a J2SE or JavaSE vm
- URL bestProfile = findNextBestProfile(javaEdition, javaVersion);
- if (bestProfile == null && javaEdition == JAVASE)
- // if this is a JavaSE VM then search for a lower J2SE profile
- bestProfile = findNextBestProfile(J2SE, javaVersion);
- return bestProfile;
- }
-
- private URL findNextBestProfile(String javaEdition, Version javaVersion) {
- URL result = null;
- int minor = javaVersion.getMinor();
- do {
- result = findInSystemBundle(javaEdition + javaVersion.getMajor() + "." + minor + PROFILE_EXT); //$NON-NLS-1$
- minor = minor - 1;
- } while (result == null && minor > 0);
- return result;
- }
-
- private URL findInSystemBundle(String entry) {
- URL result = systemBundle.getEntry0(entry);
- if (result == null) {
- // Check the ClassLoader in case we're launched off the Java boot classpath
- ClassLoader loader = getClass().getClassLoader();
- result = loader == null ? ClassLoader.getSystemResource(entry) : loader.getResource(entry);
- }
- return result;
- }
-
- /**
- * This method return the state of the framework.
- *
- */
- protected boolean isActive() {
- return (active);
- }
-
- /**
- * This method is called to destory the framework instance.
- *
- */
- public synchronized void close() {
- if (adaptor == null)
- return;
- if (active)
- shutdown(FrameworkEvent.STOPPED);
-
- synchronized (bundles) {
- List<AbstractBundle> allBundles = bundles.getBundles();
- int size = allBundles.size();
- for (int i = 0; i < size; i++) {
- AbstractBundle bundle = allBundles.get(i);
- bundle.close();
- }
- bundles.removeAllBundles();
- }
- serviceRegistry = null;
- allBundleListeners.clear();
- allSyncBundleListeners.clear();
- allFrameworkListeners.clear();
- if (eventManager != null) {
- eventManager.close();
- eventManager = null;
- }
- secureAction = null;
- packageAdmin = null;
- adaptor = null;
- uninstallURLStreamHandlerFactory();
- uninstallContentHandlerFactory();
- if (System.getSecurityManager() instanceof EquinoxSecurityManager)
- System.setSecurityManager(null);
- }
-
- /**
- * Start the framework.
- *
- * When the framework is started. The following actions occur: 1. Event
- * handling is enabled. Events can now be delivered to listeners. 2. All
- * bundles which are recorded as started are started as described in the
- * Bundle.start() method. These bundles are the bundles that were started
- * when the framework was last stopped. Reports any exceptions that occur
- * during startup using FrameworkEvents. 3. A FrameworkEvent of type
- * FrameworkEvent.STARTED is broadcast.
- *
- */
- public synchronized void launch() {
- /* Return if framework already started */
- if (active) {
- return;
- }
- /* mark framework as started */
- active = true;
- shutdownEvent = new FrameworkEvent[1];
- if (THREAD_NORMAL.equals(FrameworkProperties.getProperty(PROP_FRAMEWORK_THREAD, THREAD_NORMAL))) {
- Thread fwkThread = new Thread(this, "Framework Active Thread"); //$NON-NLS-1$
- fwkThread.setDaemon(false);
- fwkThread.start();
- }
- /* Resume systembundle */
- if (Debug.DEBUG_GENERAL) {
- Debug.println("Trying to launch framework"); //$NON-NLS-1$
- }
- systemBundle.resume();
- signedContentFactory = new ServiceTracker<SignedContentFactory, SignedContentFactory>(systemBundle.getBundleContext(), SignedContentFactory.class.getName(), null);
- signedContentFactory.open();
- }
-
- /**
- * Stop the framework.
- *
- * When the framework is stopped. The following actions occur: 1. Suspend
- * all started bundles as described in the Bundle.stop method except that
- * the bundle is recorded as started. These bundles will be restarted when
- * the framework is next started. Reports any exceptions that occur during
- * stopping using FrameworkEvents. 2. Event handling is disabled.
- *
- */
- public synchronized void shutdown(int eventType) {
- /* Return if framework already stopped */
- if (!active)
- return;
- this.shutdownEvent[0] = new FrameworkEvent(eventType, systemBundle, null);
- /*
- * set the state of the System Bundle to STOPPING.
- * this must be done first according to section 4.19.2 from the OSGi R3 spec.
- */
- systemBundle.state = Bundle.STOPPING;
- publishBundleEvent(BundleEvent.STOPPING, systemBundle); // need to send system bundle stopping event
- /* call the FrameworkAdaptor.frameworkStopping method first */
- try {
- adaptor.frameworkStopping(systemBundle.getContext());
- } catch (Throwable t) {
- publishFrameworkEvent(FrameworkEvent.ERROR, systemBundle, t);
- }
- /* Suspend systembundle */
- if (Debug.DEBUG_GENERAL) {
- Debug.println("Trying to shutdown Framework"); //$NON-NLS-1$
- }
- systemBundle.suspend();
- try {
- adaptor.compactStorage();
- } catch (IOException e) {
- publishFrameworkEvent(FrameworkEvent.ERROR, systemBundle, e);
- }
- if (signedContentFactory != null)
- signedContentFactory.close();
- /* mark framework as stopped */
- active = false;
- notifyAll();
- }
-
- /**
- * Create a new Bundle object.
- * @param bundledata the BundleData of the Bundle to create
- */
- AbstractBundle createAndVerifyBundle(int operationType, Bundle target, BundleData bundledata, boolean setBundle) throws BundleException {
- // Check for a bundle already installed with the same symbolic name and version.
- if (BSN_VERSION != BSN_VERSION_MULTIPLE && bundledata.getSymbolicName() != null) {
- List<AbstractBundle> installedBundles = getBundleBySymbolicName(bundledata.getSymbolicName(), bundledata.getVersion());
- if (operationType == CollisionHook.UPDATING) {
- installedBundles.remove(target);
- }
- if (BSN_VERSION == BSN_VERSION_MANAGED && !installedBundles.isEmpty()) {
- notifyCollisionHooks(operationType, target, installedBundles);
- }
- if (!installedBundles.isEmpty()) {
- Bundle installedBundle = installedBundles.iterator().next();
- String msg = NLS.bind(Msg.BUNDLE_INSTALL_SAME_UNIQUEID, new Object[] {installedBundle.getSymbolicName(), installedBundle.getVersion().toString(), installedBundle.getLocation()});
- throw new DuplicateBundleException(msg, installedBundle);
- }
- }
- return AbstractBundle.createBundle(bundledata, this, setBundle);
- }
-
- private class DuplicateBundleException extends BundleException implements StatusException {
- private static final long serialVersionUID = 135669822846323624L;
- private transient Bundle duplicate;
-
- public DuplicateBundleException(String msg, Bundle duplicate) {
- super(msg, BundleException.DUPLICATE_BUNDLE_ERROR);
- this.duplicate = duplicate;
- }
-
- public Object getStatus() {
- return duplicate;
- }
-
- public int getStatusCode() {
- return StatusException.CODE_OK;
- }
-
- }
-
- /**
- * Retrieve the value of the named environment property. Values are
- * provided for the following properties:
- * <dl>
- * <dt><code>org.osgi.framework.version</code>
- * <dd>The version of the framework.
- * <dt><code>org.osgi.framework.vendor</code>
- * <dd>The vendor of this framework implementation.
- * <dt><code>org.osgi.framework.language</code>
- * <dd>The language being used. See ISO 639 for possible values.
- * <dt><code>org.osgi.framework.os.name</code>
- * <dd>The name of the operating system of the hosting computer.
- * <dt><code>org.osgi.framework.os.version</code>
- * <dd>The version number of the operating system of the hosting computer.
- * <dt><code>org.osgi.framework.processor</code>
- * <dd>The name of the processor of the hosting computer.
- * </dl>
- *
- * <p>
- * Note: These last four properties are used by the <code>Bundle-NativeCode</code>
- * manifest header's matching algorithm for selecting native code.
- *
- * @param key
- * The name of the requested property.
- * @return The value of the requested property, or <code>null</code> if
- * the property is undefined.
- */
- public String getProperty(String key) {
- return properties.getProperty(key);
- }
-
- /**
- * Retrieve the value of the named environment property. Values are
- * provided for the following properties:
- * <dl>
- * <dt><code>org.osgi.framework.version</code>
- * <dd>The version of the framework.
- * <dt><code>org.osgi.framework.vendor</code>
- * <dd>The vendor of this framework implementation.
- * <dt><code>org.osgi.framework.language</code>
- * <dd>The language being used. See ISO 639 for possible values.
- * <dt><code>org.osgi.framework.os.name</code>
- * <dd>The name of the operating system of the hosting computer.
- * <dt><code>org.osgi.framework.os.version</code>
- * <dd>The version number of the operating system of the hosting computer.
- * <dt><code>org.osgi.framework.processor</code>
- * <dd>The name of the processor of the hosting computer.
- * </dl>
- *
- * <p>
- * Note: These last four properties are used by the <code>Bundle-NativeCode</code>
- * manifest header's matching algorithm for selecting native code.
- *
- * @param key
- * The name of the requested property.
- * @param def
- * A default value is the requested property is not present.
- * @return The value of the requested property, or the default value if the
- * property is undefined.
- */
- protected String getProperty(String key, String def) {
- return properties.getProperty(key, def);
- }
-
- /**
- * Set a system property.
- *
- * @param key
- * The name of the property to set.
- * @param value
- * The value to set.
- * @return The previous value of the property or null if the property was
- * not previously set.
- */
- protected Object setProperty(String key, String value) {
- return properties.put(key, value);
- }
-
- /**
- * Install a bundle from an InputStream.
- *
- * @param location
- * The location identifier of the bundle to install.
- * @param in
- * The InputStream from which the bundle will be read. If null
- * then the location is used to get the bundle content.
- * @return The Bundle of the installed bundle.
- */
- AbstractBundle installBundle(final String location, final InputStream in, final BundleContextImpl origin) throws BundleException {
- if (Debug.DEBUG_GENERAL) {
- Debug.println("install from inputstream: " + location + ", " + in); //$NON-NLS-1$ //$NON-NLS-2$
- }
- final AccessControlContext callerContext = AccessController.getContext();
- return installWorker(location, new PrivilegedExceptionAction<AbstractBundle>() {
- public AbstractBundle run() throws BundleException {
- /* Map the InputStream or location to a URLConnection */
- URLConnection source = in != null ? new BundleSource(in) : adaptor.mapLocationToURLConnection(location);
- /* call the worker to install the bundle */
- return installWorkerPrivileged(location, source, callerContext, origin);
- }
- }, origin);
- }
-
- /**
- * Worker method to install a bundle. It obtains the reservation for the
- * location and calls the specified action.
- *
- * @param location
- * The location identifier of the bundle to install.
- * @param action
- * A PrivilegedExceptionAction which calls the real worker.
- * @return The {@link AbstractBundle}of the installed bundle.
- * @exception BundleException
- * If the action throws an error.
- */
- protected AbstractBundle installWorker(String location, PrivilegedExceptionAction<AbstractBundle> action, BundleContext origin) throws BundleException {
- synchronized (installLock) {
- while (true) {
- /* Check that the bundle is not already installed. */
- AbstractBundle bundle = getBundleByLocation(location);
- /* If already installed, return bundle object */
- if (bundle != null) {
- Bundle visible = origin.getBundle(bundle.getBundleId());
- if (visible == null) {
- BundleData data = bundle.getBundleData();
- String msg = NLS.bind(Msg.BUNDLE_INSTALL_SAME_UNIQUEID, new Object[] {data.getSymbolicName(), data.getVersion().toString(), data.getLocation()});
- throw new BundleException(msg, BundleException.REJECTED_BY_HOOK);
- }
- return bundle;
- }
- Thread current = Thread.currentThread();
- /* Check for and make reservation */
- Thread reservation = installLock.put(location, current);
- /* if the location is not already reserved */
- if (reservation == null) {
- /* we have made the reservation and can continue */
- break;
- }
- /* the location was already reserved */
- /*
- * If the reservation is held by the current thread, we have
- * recursed to install the same bundle!
- */
- if (current.equals(reservation)) {
- throw new BundleException(Msg.BUNDLE_INSTALL_RECURSION_EXCEPTION, BundleException.STATECHANGE_ERROR);
- }
- try {
- /* wait for the reservation to be released */
- installLock.wait();
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- throw new BundleException("Thread has been interrupted while waiting for the location lock.", e); //$NON-NLS-1$
- }
- }
- }
- /* Don't call adaptor while holding the install lock */
- try {
- AbstractBundle bundle = AccessController.doPrivileged(action);
- publishBundleEvent(new BundleEvent(BundleEvent.INSTALLED, bundle, origin.getBundle()));
- return bundle;
- } catch (PrivilegedActionException e) {
- if (e.getException() instanceof RuntimeException)
- throw (RuntimeException) e.getException();
- throw (BundleException) e.getException();
- } finally {
- synchronized (installLock) {
- /* release reservation */
- installLock.remove(location);
- /* wake up all waiters */
- installLock.notifyAll();
- }
- }
- }
-
- /**
- * Worker method to install a bundle. It calls the FrameworkAdaptor object
- * to install the bundle in persistent storage.
- *
- * @param location
- * The location identifier of the bundle to install.
- * @param source
- * The URLConnection from which the bundle will be read.
- * @param callerContext
- * The caller access control context
- * @param origin
- * The origin bundle context that is installing the the bundle
- * @return The {@link AbstractBundle}of the installed bundle.
- * @exception BundleException
- * If the provided stream cannot be read.
- */
- protected AbstractBundle installWorkerPrivileged(String location, URLConnection source, AccessControlContext callerContext, BundleContextImpl origin) throws BundleException {
- BundleOperation storage = adaptor.installBundle(location, source);
- final AbstractBundle bundle;
- try {
- BundleData bundledata = storage.begin();
- bundle = createAndVerifyBundle(CollisionHook.INSTALLING, origin.getBundle(), bundledata, true);
-
- BundleWatcher bundleStats = adaptor.getBundleWatcher();
- if (bundleStats != null)
- bundleStats.watchBundle(bundle, BundleWatcher.START_INSTALLING);
-
- try {
- bundle.load();
- if (System.getSecurityManager() != null) {
- final boolean extension = (bundledata.getType() & (BundleData.TYPE_BOOTCLASSPATH_EXTENSION | BundleData.TYPE_FRAMEWORK_EXTENSION | BundleData.TYPE_EXTCLASSPATH_EXTENSION)) != 0;
- // must check for AllPermission before allow a bundle extension to be installed
- if (extension && !bundle.hasPermission(new AllPermission()))
- throw new BundleException(Msg.BUNDLE_EXTENSION_PERMISSION, BundleException.SECURITY_ERROR, new SecurityException(Msg.BUNDLE_EXTENSION_PERMISSION));
- try {
- AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
- public Object run() throws Exception {
- checkAdminPermission(bundle, AdminPermission.LIFECYCLE);
- if (extension) // need special permission to install extension bundles
- checkAdminPermission(bundle, AdminPermission.EXTENSIONLIFECYCLE);
- return null;
- }
- }, callerContext);
- } catch (PrivilegedActionException e) {
- throw e.getException();
- }
- }
- // must add the bundle before committing (bug 330905)
- bundles.add(bundle);
- storage.commit(false);
- } catch (Throwable error) {
- bundles.remove(bundle);
- synchronized (bundles) {
- bundle.unload();
- }
- bundle.close();
- throw error;
- } finally {
- if (bundleStats != null)
- bundleStats.watchBundle(bundle, BundleWatcher.END_INSTALLING);
- }
-
- } catch (Throwable t) {
- try {
- storage.undo();
- } catch (BundleException ee) {
- publishFrameworkEvent(FrameworkEvent.ERROR, systemBundle, ee);
- }
- if (t instanceof SecurityException)
- throw (SecurityException) t;
- if (t instanceof BundleException)
- throw (BundleException) t;
- throw new BundleException(t.getMessage(), t);
- }
- return bundle;
- }
-
- /**
- * Retrieve the bundle that has the given unique identifier.
- *
- * @param id
- * The identifier of the bundle to retrieve.
- * @return A {@link AbstractBundle}object, or <code>null</code> if the
- * identifier doesn't match any installed bundle.
- */
- // changed visibility to gain access through the adaptor
- public AbstractBundle getBundle(long id) {
- synchronized (bundles) {
- return bundles.getBundle(id);
- }
- }
-
- AbstractBundle getBundle(final BundleContextImpl context, long id) {
- AbstractBundle bundle = getBundle(id);
- // TODO we make the system bundle special because there are lots of places
- // where we assume the system bundle can get all bundles
- if (bundle == null || context.getBundle().getBundleId() == 0)
- return bundle;
- List<AbstractBundle> single = new ArrayList<AbstractBundle>(1);
- single.add(bundle);
- notifyFindHooks(context, single);
- return single.size() == 0 ? null : bundle;
- }
-
- public BundleContextImpl getSystemBundleContext() {
- if (systemBundle == null)
- return null;
- return systemBundle.context;
- }
-
- public PackageAdminImpl getPackageAdmin() {
- return packageAdmin;
- }
-
- /**
- * Retrieve the bundles that has the given symbolic name and version.
- *
- * @param symbolicName
- * The symbolic name of the bundle to retrieve
- * @param version The version of the bundle to retrieve
- * @return A collection of {@link AbstractBundle} that match the symbolic name and version
- */
- public List<AbstractBundle> getBundleBySymbolicName(String symbolicName, Version version) {
- synchronized (bundles) {
- return bundles.getBundles(symbolicName, version);
- }
- }
-
- /**
- * Retrieve the BundleRepository 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 The BundleRepository.
- */
- protected BundleRepository getBundles() {
- return (bundles);
- }
-
- /**
- * Retrieve a list of all installed bundles. The list is valid at the time
- * of the call to getBundleAlls, but the framework is a very dynamic
- * environment and bundles can be installed or uninstalled at anytime.
- *
- * @return An Array of {@link AbstractBundle}objects, one object per installed
- * bundle.
- */
- protected AbstractBundle[] getAllBundles() {
- synchronized (bundles) {
- List<AbstractBundle> allBundles = bundles.getBundles();
- int size = allBundles.size();
- if (size == 0) {
- return (null);
- }
- AbstractBundle[] bundlelist = new AbstractBundle[size];
- allBundles.toArray(bundlelist);
- return (bundlelist);
- }
- }
-
- AbstractBundle[] getBundles(final BundleContextImpl context) {
- List<AbstractBundle> allBundles;
- synchronized (bundles) {
- allBundles = new ArrayList<AbstractBundle>(bundles.getBundles());
- }
- notifyFindHooks(context, allBundles);
- return allBundles.toArray(new AbstractBundle[allBundles.size()]);
- }
-
- private void notifyFindHooks(final BundleContextImpl context, List<AbstractBundle> allBundles) {
- final Collection<Bundle> shrinkable = new ShrinkableCollection<Bundle>(allBundles);
- if (System.getSecurityManager() == null) {
- notifyFindHooksPriviledged(context, shrinkable);
- } else {
- AccessController.doPrivileged(new PrivilegedAction<Object>() {
- public Object run() {
- notifyFindHooksPriviledged(context, shrinkable);
- return null;
- }
- });
- }
- }
-
- void notifyFindHooksPriviledged(final BundleContextImpl context, final Collection<Bundle> allBundles) {
- if (Debug.DEBUG_HOOKS) {
- Debug.println("notifyBundleFindHooks(" + allBundles + ")"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- getServiceRegistry().notifyHooksPrivileged(new HookContext() {
- public void call(Object hook, ServiceRegistration<?> hookRegistration) throws Exception {
- if (hook instanceof FindHook) {
- ((FindHook) hook).find(context, allBundles);
- }
- }
-
- public String getHookClassName() {
- return findHookName;
- }
-
- public String getHookMethodName() {
- return "find"; //$NON-NLS-1$
- }
- });
- }
-
- private void notifyCollisionHooks(final int operationType, final Bundle target, List<AbstractBundle> collisionCandidates) {
- final Collection<Bundle> shrinkable = new ShrinkableCollection<Bundle>(collisionCandidates);
- if (System.getSecurityManager() == null) {
- notifyCollisionHooksPriviledged(operationType, target, shrinkable);
- } else {
- AccessController.doPrivileged(new PrivilegedAction<Object>() {
- public Object run() {
- notifyCollisionHooksPriviledged(operationType, target, shrinkable);
- return null;
- }
- });
- }
- }
-
- void notifyCollisionHooksPriviledged(final int operationType, final Bundle target, final Collection<Bundle> collisionCandidates) {
- if (Debug.DEBUG_HOOKS) {
- Debug.println("notifyCollisionHooks(" + operationType + ", " + target + ", " + collisionCandidates + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
- getServiceRegistry().notifyHooksPrivileged(new HookContext() {
- public void call(Object hook, ServiceRegistration<?> hookRegistration) throws Exception {
- if (hook instanceof CollisionHook) {
- ((CollisionHook) hook).filterCollisions(operationType, target, collisionCandidates);
- }
- }
-
- public String getHookClassName() {
- return collisionHookName;
- }
-
- public String getHookMethodName() {
- return "filterCollisions"; //$NON-NLS-1$
- }
- });
- }
-
- /**
- * Resume a bundle.
- *
- * @param bundle
- * Bundle to resume.
- */
- protected void resumeBundle(AbstractBundle bundle) {
- if (bundle.isActive()) {
- // if bundle is active.
- return;
- }
- try {
- if (Debug.DEBUG_GENERAL) {
- Debug.println("Trying to resume bundle " + bundle); //$NON-NLS-1$
- }
- bundle.resume();
- } catch (BundleException be) {
- if (Debug.DEBUG_GENERAL) {
- Debug.println("Bundle resume exception: " + be.getMessage()); //$NON-NLS-1$
- Debug.printStackTrace(be.getNestedException() == null ? be : be.getNestedException());
- }
- publishFrameworkEvent(FrameworkEvent.ERROR, bundle, be);
- }
- }
-
- /**
- * Suspend a bundle.
- *
- * @param bundle
- * Bundle to suspend.
- * @param lock
- * true if state change lock should be held when returning from
- * this method.
- * @return true if bundle was active and is now suspended.
- */
- protected boolean suspendBundle(AbstractBundle bundle, boolean lock) {
- boolean changed = false;
- if (!bundle.isActive() || bundle.isFragment()) {
- // if bundle is not active or is a fragment then do nothing.
- return changed;
- }
- try {
- if (Debug.DEBUG_GENERAL) {
- Debug.println("Trying to suspend bundle " + bundle); //$NON-NLS-1$
- }
- bundle.suspend(lock);
- } catch (BundleException be) {
- if (Debug.DEBUG_GENERAL) {
- Debug.println("Bundle suspend exception: " + be.getMessage()); //$NON-NLS-1$
- Debug.printStackTrace(be.getNestedException() == null ? be : be.getNestedException());
- }
- publishFrameworkEvent(FrameworkEvent.ERROR, bundle, be);
- }
- if (!bundle.isActive()) {
- changed = true;
- }
- return (changed);
- }
-
- /**
- * Locate an installed bundle with a given identity.
- *
- * @param location
- * string for the bundle
- * @return Bundle object for bundle with the specified location or null if
- * no bundle is installed with the specified location.
- */
- protected AbstractBundle getBundleByLocation(String location) {
- synchronized (bundles) {
- // this is not optimized; do not think it will get called
- // that much.
- final String finalLocation = location;
-
- //Bundle.getLocation requires AdminPermission (metadata)
- return AccessController.doPrivileged(new PrivilegedAction<AbstractBundle>() {
- public AbstractBundle run() {
- List<AbstractBundle> allBundles = bundles.getBundles();
- int size = allBundles.size();
- for (int i = 0; i < size; i++) {
- AbstractBundle bundle = allBundles.get(i);
- if (finalLocation.equals(bundle.getLocation())) {
- return bundle;
- }
- }
- return null;
- }
- });
- }
- }
-
- /**
- * Locate an installed bundle with a given symbolic name
- *
- * @param symbolicName
- * The symbolic name for the bundle
- * @return Bundle object for bundle with the specified Unique or null if no
- * bundle is installed with the specified symbolicName.
- */
- protected AbstractBundle[] getBundleBySymbolicName(String symbolicName) {
- synchronized (bundles) {
- return bundles.getBundles(symbolicName);
- }
- }
-
- /**
- * Creates a <code>File</code> 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 <code>null</code>.
- *
- * <p>
- * A <code>File</code> 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.
- */
- protected File getDataFile(final AbstractBundle bundle, final String filename) {
- return AccessController.doPrivileged(new GetDataFileAction(bundle, filename));
- }
-
- /**
- * Check for specific AdminPermission (RFC 73)
- */
- protected void checkAdminPermission(Bundle bundle, String action) {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null)
- sm.checkPermission(getAdminPermission(bundle, action));
- }
-
- // gets AdminPermission objects from a cache to reduce the number of AdminPermission
- // objects that are created.
- private AdminPermission getAdminPermission(Bundle bundle, String action) {
- synchronized (adminPermissions) {
- Long ID = new Long(bundle.getBundleId());
- Map<String, AdminPermission> bundlePermissions = adminPermissions.get(ID);
- if (bundlePermissions == null) {
- bundlePermissions = new HashMap<String, AdminPermission>();
- adminPermissions.put(ID, bundlePermissions);
- }
- AdminPermission result = bundlePermissions.get(action);
- if (result == null) {
- result = new AdminPermission(bundle, action);
- bundlePermissions.put(action, result);
- }
- return result;
- }
- }
-
- /**
- * This is necessary for running from a JXE, otherwise the SecurityManager
- * is set much later than we would like!
- */
- protected void installSecurityManager() {
- String securityManager = FrameworkProperties.getProperty(Constants.FRAMEWORK_SECURITY, FrameworkProperties.getProperty(PROP_EQUINOX_SECURITY, FrameworkProperties.getProperty("java.security.manager")));
- if (securityManager != null) {
- SecurityManager sm = System.getSecurityManager();
- if (sm == null) {
- if (securityManager.length() == 0)
- sm = new SecurityManager(); // use the default one from java
- else if (securityManager.equals(SECURITY_OSGI))
- sm = new EquinoxSecurityManager(); // use an OSGi enabled manager that understands postponed conditions
- else {
- // try to use a specific classloader by classname
- try {
- Class<?> clazz = Class.forName(securityManager);
- sm = (SecurityManager) clazz.newInstance();
- } catch (ClassNotFoundException e) {
- // do nothing
- } catch (ClassCastException e) {
- // do nothing
- } catch (InstantiationException e) {
- // do nothing
- } catch (IllegalAccessException e) {
- // do nothing
- }
- }
- if (sm == null)
- throw new NoClassDefFoundError(securityManager);
- if (Debug.DEBUG_SECURITY)
- Debug.println("Setting SecurityManager to: " + sm); //$NON-NLS-1$
- System.setSecurityManager(sm);
- return;
- }
- }
- }
-
- void addFrameworkListener(FrameworkListener listener, BundleContextImpl context) {
- synchronized (allFrameworkListeners) {
- CopyOnWriteIdentityMap<FrameworkListener, FrameworkListener> listeners = allFrameworkListeners.get(context);
- if (listeners == null) {
- listeners = new CopyOnWriteIdentityMap<FrameworkListener, FrameworkListener>();
- allFrameworkListeners.put(context, listeners);
- }
- listeners.put(listener, listener);
- }
- }
-
- void removeFrameworkListener(FrameworkListener listener, BundleContextImpl context) {
- synchronized (allFrameworkListeners) {
- CopyOnWriteIdentityMap<FrameworkListener, FrameworkListener> listeners = allFrameworkListeners.get(context);
- if (listeners != null)
- listeners.remove(listener);
- }
- }
-
- void removeAllListeners(BundleContextImpl context) {
- synchronized (allBundleListeners) {
- allBundleListeners.remove(context);
- }
- synchronized (allSyncBundleListeners) {
- allSyncBundleListeners.remove(context);
- }
- synchronized (allFrameworkListeners) {
- allFrameworkListeners.remove(context);
- }
- }
-
- /**
- * Deliver a FrameworkEvent.
- *
- * @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) {
- if (bundle == null)
- bundle = systemBundle;
- final FrameworkEvent event = new FrameworkEvent(type, bundle, throwable);
- if (System.getSecurityManager() == null) {
- publishFrameworkEventPrivileged(event, listeners);
- } else {
- AccessController.doPrivileged(new PrivilegedAction<Object>() {
- public Object run() {
- publishFrameworkEventPrivileged(event, listeners);
- return null;
- }
- });
- }
- }
-
- public void publishFrameworkEventPrivileged(FrameworkEvent event, FrameworkListener... callerListeners) {
- // Build the listener snapshot
- Map<BundleContextImpl, Set<Map.Entry<FrameworkListener, FrameworkListener>>> listenerSnapshot;
- synchronized (allFrameworkListeners) {
- listenerSnapshot = new HashMap<BundleContextImpl, Set<Map.Entry<FrameworkListener, FrameworkListener>>>(allFrameworkListeners.size());
- for (Map.Entry<BundleContextImpl, CopyOnWriteIdentityMap<FrameworkListener, FrameworkListener>> entry : allFrameworkListeners.entrySet()) {
- CopyOnWriteIdentityMap<FrameworkListener, FrameworkListener> listeners = entry.getValue();
- if (!listeners.isEmpty()) {
- listenerSnapshot.put(entry.getKey(), listeners.entrySet());
- }
- }
- }
- // If framework event hook were defined they would be called here
-
- // deliver the event to the snapshot
- ListenerQueue<FrameworkListener, FrameworkListener, FrameworkEvent> queue = newListenerQueue();
-
- // add the listeners specified by the caller first
- if (callerListeners != null && callerListeners.length > 0) {
- Map<FrameworkListener, FrameworkListener> listeners = new HashMap<FrameworkListener, FrameworkListener>();
- for (FrameworkListener listener : callerListeners) {
- if (listener != null)
- listeners.put(listener, listener);
- }
- // We use the system bundle context as the dispatcher
- if (listeners.size() > 0) {
- @SuppressWarnings({"rawtypes", "unchecked"})
- EventDispatcher<FrameworkListener, FrameworkListener, FrameworkEvent> dispatcher = (EventDispatcher) getSystemBundleContext();
- queue.queueListeners(listeners.entrySet(), dispatcher);
- }
- }
-
- for (Map.Entry<BundleContextImpl, Set<Map.Entry<FrameworkListener, FrameworkListener>>> entry : listenerSnapshot.entrySet()) {
- @SuppressWarnings({"rawtypes", "unchecked"})
- EventDispatcher<FrameworkListener, FrameworkListener, FrameworkEvent> dispatcher = (EventDispatcher) entry.getKey();
- Set<Map.Entry<FrameworkListener, FrameworkListener>> listeners = entry.getValue();
- queue.queueListeners(listeners, dispatcher);
- }
-
- queue.dispatchEventAsynchronous(FRAMEWORKEVENT, event);
- }
-
- void addBundleListener(BundleListener listener, BundleContextImpl context) {
- if (listener instanceof SynchronousBundleListener) {
- checkAdminPermission(context.getBundle(), AdminPermission.LISTENER);
- synchronized (allSyncBundleListeners) {
- CopyOnWriteIdentityMap<SynchronousBundleListener, SynchronousBundleListener> listeners = allSyncBundleListeners.get(context);
- if (listeners == null) {
- listeners = new CopyOnWriteIdentityMap<SynchronousBundleListener, SynchronousBundleListener>();
- allSyncBundleListeners.put(context, listeners);
- }
- listeners.put((SynchronousBundleListener) listener, (SynchronousBundleListener) listener);
- }
- } else {
- synchronized (allBundleListeners) {
- CopyOnWriteIdentityMap<BundleListener, BundleListener> listeners = allBundleListeners.get(context);
- if (listeners == null) {
- listeners = new CopyOnWriteIdentityMap<BundleListener, BundleListener>();
- allBundleListeners.put(context, listeners);
- }
- listeners.put(listener, listener);
- }
- }
- }
-
- void removeBundleListener(BundleListener listener, BundleContextImpl context) {
- if (listener instanceof SynchronousBundleListener) {
- checkAdminPermission(context.getBundle(), AdminPermission.LISTENER);
- synchronized (allSyncBundleListeners) {
- CopyOnWriteIdentityMap<SynchronousBundleListener, SynchronousBundleListener> listeners = allSyncBundleListeners.get(context);
- if (listeners != null)
- listeners.remove(listener);
- }
- } else {
- synchronized (allBundleListeners) {
- CopyOnWriteIdentityMap<BundleListener, BundleListener> listeners = allBundleListeners.get(context);
- if (listeners != null)
- listeners.remove(listener);
- }
- }
- }
-
- /**
- * Deliver a BundleEvent to SynchronousBundleListeners (synchronous). and
- * BundleListeners (asynchronous).
- *
- * @param type
- * BundleEvent type.
- * @param bundle
- * Affected bundle or null.
- */
- public void publishBundleEvent(int type, Bundle bundle) {
- publishBundleEvent(new BundleEvent(type, bundle));
- }
-
- private void publishBundleEvent(final BundleEvent event) {
- if (System.getSecurityManager() == null) {
- publishBundleEventPrivileged(event);
- } else {
- AccessController.doPrivileged(new PrivilegedAction<Object>() {
- public Object run() {
- publishBundleEventPrivileged(event);
- return null;
- }
- });
- }
- }
-
- public void publishBundleEventPrivileged(BundleEvent 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 */
- Map<BundleContextImpl, Set<Map.Entry<SynchronousBundleListener, SynchronousBundleListener>>> listenersSync;
- synchronized (allSyncBundleListeners) {
- listenersSync = new HashMap<BundleContextImpl, Set<Map.Entry<SynchronousBundleListener, SynchronousBundleListener>>>(allSyncBundleListeners.size());
- for (Map.Entry<BundleContextImpl, CopyOnWriteIdentityMap<SynchronousBundleListener, SynchronousBundleListener>> entry : allSyncBundleListeners.entrySet()) {
- CopyOnWriteIdentityMap<SynchronousBundleListener, SynchronousBundleListener> listeners = entry.getValue();
- if (!listeners.isEmpty()) {
- listenersSync.put(entry.getKey(), listeners.entrySet());
- }
- }
- }
- /* Collect snapshot of BundleListeners; only if the event is NOT STARTING or STOPPING or LAZY_ACTIVATION */
- Map<BundleContextImpl, Set<Map.Entry<BundleListener, BundleListener>>> listenersAsync = null;
- if ((event.getType() & (BundleEvent.STARTING | BundleEvent.STOPPING | BundleEvent.LAZY_ACTIVATION)) == 0) {
- synchronized (allBundleListeners) {
- listenersAsync = new HashMap<BundleContextImpl, Set<Map.Entry<BundleListener, BundleListener>>>(allBundleListeners.size());
- for (Map.Entry<BundleContextImpl, CopyOnWriteIdentityMap<BundleListener, BundleListener>> entry : allBundleListeners.entrySet()) {
- CopyOnWriteIdentityMap<BundleListener, BundleListener> listeners = entry.getValue();
- if (!listeners.isEmpty()) {
- listenersAsync.put(entry.getKey(), listeners.entrySet());
- }
- }
- }
- }
-
- /* 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<BundleContext> shrinkable;
- if (listenersAsync == null) {
- shrinkable = asBundleContexts(listenersSync.keySet());
- } else {
- shrinkable = new ShrinkableCollection<BundleContext>(asBundleContexts(listenersSync.keySet()), asBundleContexts(listenersAsync.keySet()));
- }
- notifyEventHooksPrivileged(event, shrinkable);
-
- /* Dispatch the event to the snapshot for sync listeners */
- if (!listenersSync.isEmpty()) {
- ListenerQueue<SynchronousBundleListener, SynchronousBundleListener, BundleEvent> queue = newListenerQueue();
- for (Map.Entry<BundleContextImpl, Set<Map.Entry<SynchronousBundleListener, SynchronousBundleListener>>> entry : listenersSync.entrySet()) {
- @SuppressWarnings({"rawtypes", "unchecked"})
- EventDispatcher<SynchronousBundleListener, SynchronousBundleListener, BundleEvent> dispatcher = (EventDispatcher) entry.getKey();
- Set<Map.Entry<SynchronousBundleListener, SynchronousBundleListener>> listeners = entry.getValue();
- queue.queueListeners(listeners, dispatcher);
- }
- queue.dispatchEventSynchronous(BUNDLEEVENTSYNC, event);
- }
-
- /* Dispatch the event to the snapshot for async listeners */
- if ((listenersAsync != null) && !listenersAsync.isEmpty()) {
- ListenerQueue<BundleListener, BundleListener, BundleEvent> queue = newListenerQueue();
- for (Map.Entry<BundleContextImpl, Set<Map.Entry<BundleListener, BundleListener>>> entry : listenersAsync.entrySet()) {
- @SuppressWarnings({"rawtypes", "unchecked"})
- EventDispatcher<BundleListener, BundleListener, BundleEvent> dispatcher = (EventDispatcher) entry.getKey();
- Set<Map.Entry<BundleListener, BundleListener>> listeners = entry.getValue();
- queue.queueListeners(listeners, dispatcher);
- }
- queue.dispatchEventAsynchronous(BUNDLEEVENT, event);
- }
- }
-
- /**
- * Coerce the generic type of a collection from Collection<BundleContextImpl>
- * to Collection<BundleContext>
- * @param c Collection to be coerced.
- * @return c coerced to Collection<BundleContext>
- */
- @SuppressWarnings("unchecked")
- public static Collection<BundleContext> asBundleContexts(Collection<? extends BundleContext> c) {
- return (Collection<BundleContext>) c;
- }
-
- private void notifyEventHooksPrivileged(final BundleEvent event, final Collection<BundleContext> result) {
- if (event.getType() == Framework.BATCHEVENT_BEGIN || event.getType() == Framework.BATCHEVENT_END)
- return; // we don't need to send this event; it is used to book case special listeners
- if (Debug.DEBUG_HOOKS) {
- Debug.println("notifyBundleEventHooks(" + event.getType() + ":" + event.getBundle() + ", " + result + " )"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
-
- getServiceRegistry().notifyHooksPrivileged(new HookContext() {
- public void call(Object hook, ServiceRegistration<?> hookRegistration) throws Exception {
- if (hook instanceof EventHook) {
- ((EventHook) hook).event(event, result);
- }
- }
-
- public String getHookClassName() {
- return eventHookName;
- }
-
- public String getHookMethodName() {
- return "event"; //$NON-NLS-1$
- }
- });
- }
-
- public <K, V, E> ListenerQueue<K, V, E> newListenerQueue() {
- return new ListenerQueue<K, V, E>(eventManager);
- }
-
- private void initializeContextFinder() {
- Thread current = Thread.currentThread();
- try {
- ClassLoader parent = null;
- // check property for specified parent
- String type = FrameworkProperties.getProperty(PROP_CONTEXTCLASSLOADER_PARENT);
- if (CONTEXTCLASSLOADER_PARENT_APP.equals(type))
- parent = ClassLoader.getSystemClassLoader();
- else if (CONTEXTCLASSLOADER_PARENT_BOOT.equals(type))
- parent = null;
- else if (CONTEXTCLASSLOADER_PARENT_FWK.equals(type))
- parent = Framework.class.getClassLoader();
- else if (CONTEXTCLASSLOADER_PARENT_EXT.equals(type)) {
- ClassLoader appCL = ClassLoader.getSystemClassLoader();
- if (appCL != null)
- parent = appCL.getParent();
- } else { // default is ccl (null or any other value will use ccl)
- parent = current.getContextClassLoader();
- }
- contextFinder = new ContextFinder(parent);
- current.setContextClassLoader(contextFinder);
- return;
- } catch (Exception e) {
- FrameworkLogEntry entry = new FrameworkLogEntry(FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME, FrameworkLogEntry.INFO, 0, NLS.bind(Msg.CANNOT_SET_CONTEXTFINDER, null), 0, e, null);
- adaptor.getFrameworkLog().log(entry);
- }
-
- }
-
- public static Field getField(Class<?> clazz, Class<?> type, boolean instance) {
- Field[] fields = clazz.getDeclaredFields();
- for (int i = 0; i < fields.length; i++) {
- boolean isStatic = Modifier.isStatic(fields[i].getModifiers());
- if (instance != isStatic && fields[i].getType().equals(type)) {
- fields[i].setAccessible(true);
- return fields[i];
- }
- }
- return null;
- }
-
- private void installContentHandlerFactory(BundleContext context, FrameworkAdaptor frameworkAdaptor) {
- ContentHandlerFactory chf = new ContentHandlerFactory(context, frameworkAdaptor);
- try {
- // first try the standard way
- URLConnection.setContentHandlerFactory(chf);
- } catch (Error err) {
- // ok we failed now use more drastic means to set the factory
- try {
- forceContentHandlerFactory(chf);
- } catch (Exception ex) {
- // this is unexpected, log the exception and throw the original error
- adaptor.getFrameworkLog().log(new FrameworkEvent(FrameworkEvent.ERROR, context.getBundle(), ex));
- throw err;
- }
- }
- contentHandlerFactory = chf;
- }
-
- private static void forceContentHandlerFactory(ContentHandlerFactory chf) throws Exception {
- Field factoryField = getField(URLConnection.class, java.net.ContentHandlerFactory.class, false);
- if (factoryField == null)
- 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,
- // 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});
- } catch (NoSuchMethodException e) {
- // current factory does not support multiplexing, ok we'll wrap it
- chf.setParentFactory(factory);
- factory = chf;
- }
- }
- // null out the field so that we can successfully call setContentHandlerFactory
- factoryField.set(null, null);
- // always attempt to clear the handlers cache
- // This allows an optomization for the single framework use-case
- resetContentHandlers();
- URLConnection.setContentHandlerFactory(factory);
- }
- }
-
- private void uninstallContentHandlerFactory() {
- try {
- Field factoryField = getField(URLConnection.class, java.net.ContentHandlerFactory.class, false);
- if (factoryField == null)
- return; // oh well, we tried.
- synchronized (URLConnection.class) {
- java.net.ContentHandlerFactory factory = (java.net.ContentHandlerFactory) factoryField.get(null);
-
- 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});
- }
- // null out the field so that we can successfully call setContentHandlerFactory
- factoryField.set(null, null);
- // always attempt to clear the handlers cache
- // This allows an optomization for the single framework use-case
- // Note that the call to setContentHandlerFactory below may clear this cache
- // but we want to be sure to clear it here just incase the parent is null.
- // In this case the call below would not occur.
- // Also it appears most java libraries actually do not clear the cache
- // when setContentHandlerFactory is called, go figure!!
- resetContentHandlers();
- if (factory != null)
- URLConnection.setContentHandlerFactory(factory);
- }
- } catch (Exception e) {
- // ignore and continue closing the framework
- }
- }
-
- private static void resetContentHandlers() throws IllegalAccessException {
- Field handlersField = getField(URLConnection.class, Hashtable.class, false);
- if (handlersField != null) {
- @SuppressWarnings("rawtypes")
- Hashtable<?, ?> handlers = (Hashtable) handlersField.get(null);
- if (handlers != null)
- handlers.clear();
- }
- }
-
- private void installURLStreamHandlerFactory(BundleContext context, FrameworkAdaptor frameworkAdaptor) {
- StreamHandlerFactory shf = new StreamHandlerFactory(context, frameworkAdaptor);
- try {
- // first try the standard way
- URL.setURLStreamHandlerFactory(shf);
- } catch (Error err) {
- try {
- // ok we failed now use more drastic means to set the factory
- forceURLStreamHandlerFactory(shf);
- } catch (Exception ex) {
- adaptor.getFrameworkLog().log(new FrameworkEvent(FrameworkEvent.ERROR, context.getBundle(), ex));
- throw err;
- }
- }
- streamHandlerFactory = shf;
- }
-
- private static void forceURLStreamHandlerFactory(StreamHandlerFactory shf) throws Exception {
- Field factoryField = getField(URL.class, URLStreamHandlerFactory.class, false);
- if (factoryField == null)
- throw new Exception("Could not find URLStreamHandlerFactory field"); //$NON-NLS-1$
- // look for a lock to synchronize on
- 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,
- // 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});
- } catch (NoSuchMethodException e) {
- // current factory does not support multiplexing, ok we'll wrap it
- shf.setParentFactory(factory);
- factory = shf;
- }
- }
- factoryField.set(null, null);
- // always attempt to clear the handlers cache
- // This allows an optomization for the single framework use-case
- resetURLStreamHandlers();
- URL.setURLStreamHandlerFactory(factory);
- }
- }
-
- private void uninstallURLStreamHandlerFactory() {
- try {
- Field factoryField = getField(URL.class, URLStreamHandlerFactory.class, false);
- if (factoryField == null)
- return; // oh well, we tried
- Object lock = getURLStreamHandlerFactoryLock();
- synchronized (lock) {
- URLStreamHandlerFactory factory = (URLStreamHandlerFactory) factoryField.get(null);
- if (factory == streamHandlerFactory) {
- factory = (URLStreamHandlerFactory) streamHandlerFactory.designateSuccessor();
- } else {
- Method unregister = factory.getClass().getMethod("unregister", new Class[] {Object.class}); //$NON-NLS-1$
- unregister.invoke(factory, new Object[] {streamHandlerFactory});
- }
- factoryField.set(null, null);
- // always attempt to clear the handlers cache
- // This allows an optomization for the single framework use-case
- // Note that the call to setURLStreamHandlerFactory below may clear this cache
- // but we want to be sure to clear it here just in case the parent is null.
- // In this case the call below would not occur.
- resetURLStreamHandlers();
- if (factory != null)
- URL.setURLStreamHandlerFactory(factory);
- }
- } catch (Exception e) {
- // ignore and continue closing the framework
- }
- }
-
- private static Object getURLStreamHandlerFactoryLock() throws IllegalAccessException {
- Object lock;
- try {
- Field streamHandlerLockField = URL.class.getDeclaredField("streamHandlerLock"); //$NON-NLS-1$
- streamHandlerLockField.setAccessible(true);
- lock = streamHandlerLockField.get(null);
- } catch (NoSuchFieldException noField) {
- // could not find the lock, lets sync on the class object
- lock = URL.class;
- }
- return lock;
- }
-
- private static void resetURLStreamHandlers() throws IllegalAccessException {
- Field handlersField = getField(URL.class, Hashtable.class, false);
- if (handlersField != null) {
- @SuppressWarnings("rawtypes")
- Hashtable<?, ?> handlers = (Hashtable) handlersField.get(null);
- if (handlers != null)
- handlers.clear();
- }
- }
-
- /*
- * (non-Javadoc)
- * @see java.lang.Runnable#run()
- * This thread monitors the framework active status and terminates when the framework is
- * shutdown. This is needed to ensure the VM does not exist because of the lack of a
- * non-daemon thread (bug 215730)
- */
- public void run() {
- synchronized (this) {
- while (active)
- try {
- this.wait(1000);
- } catch (InterruptedException e) {
- // do nothing
- }
- }
- }
-
- void setForcedRestart(boolean forcedRestart) {
- this.forcedRestart = forcedRestart;
- }
-
- boolean isForcedRestart() {
- return forcedRestart;
- }
-
- public FrameworkEvent waitForStop(long timeout) throws InterruptedException {
- boolean waitForEver = timeout == 0;
- long start = System.currentTimeMillis();
- long timeLeft = timeout;
- synchronized (this) {
- FrameworkEvent[] event = shutdownEvent;
- while (event != null && event[0] == null) {
- this.wait(timeLeft);
- if (!waitForEver) {
- timeLeft = start + timeout - System.currentTimeMillis();
- // break if we are passed the timeout
- if (timeLeft <= 0)
- break;
- }
- }
- if (event == null || event[0] == null)
- return new FrameworkEvent(FrameworkEvent.WAIT_TIMEDOUT, systemBundle, null);
- return event[0];
- }
- }
-
- /**
- * Used by ServiceReferenceImpl for isAssignableTo
- * @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
- * @return true if assignable given package wiring
- */
- public boolean isServiceAssignableTo(Bundle registrant, Bundle client, String className, Class<?> serviceClass) {
- // always return false for fragments
- AbstractBundle consumer = (AbstractBundle) client;
- if (consumer.isFragment())
- return false;
- // 1) if the registrant == consumer always return true
- AbstractBundle producer = (AbstractBundle) registrant;
- if (consumer == producer)
- return true;
- // 2) get the package name from the specified className
- String pkgName = BundleLoader.getPackageName(className);
- if (pkgName.startsWith("java.")) //$NON-NLS-1$
- return true;
- BundleLoader producerBL = producer.getBundleLoader();
- if (producerBL == null)
- return false;
- BundleLoader consumerBL = consumer.getBundleLoader();
- 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 = consumerBL.getPackageSource(pkgName);
- if (consumerSource == null)
- return true;
- // work around the issue when the package is in the EE and we delegate to boot for that package
- if (isBootDelegationPackage(pkgName)) {
- SystemBundleLoader systemLoader = (SystemBundleLoader) systemBundle.getBundleLoader();
- if (systemLoader.isEEPackage(pkgName))
- return true; // in this case we have a common source from the EE
- }
- // 4) For the registrant bundle, find the wiring for the package.
- PackageSource producerSource = producerBL.getPackageSource(pkgName);
- if (producerSource == null) {
- if (serviceClass != null && ServiceFactory.class.isAssignableFrom(serviceClass)) {
- Bundle bundle = packageAdmin.getBundle(serviceClass);
- if (bundle != null && bundle != registrant)
- // in this case we have a wacky ServiceFactory that is doing something we cannot
- // verify if it is correct. Instead of failing we allow the assignment and hope for the best
- // bug 326918
- return true;
- }
- // 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);
- if (producerSource == null)
- return false;
- }
- // 6) If the two wirings found are equal then return true; otherwise return false.
- return producerSource.hasCommonSource(consumerSource);
- }
-
- private PackageSource getPackageSource(Class<?> serviceClass, String pkgName) {
- if (serviceClass == null)
- return null;
- AbstractBundle serviceBundle = (AbstractBundle) packageAdmin.getBundle(serviceClass);
- if (serviceBundle == null)
- return null;
- BundleLoader producerBL = serviceBundle.getBundleLoader();
- if (producerBL == null)
- return null;
- PackageSource producerSource = producerBL.getPackageSource(pkgName);
- if (producerSource != null)
- return producerSource;
- // try the interfaces
- Class<?>[] interfaces = serviceClass.getInterfaces();
- // note that getInterfaces never returns null
- for (int i = 0; i < interfaces.length; i++) {
- producerSource = getPackageSource(interfaces[i], pkgName);
- if (producerSource != null)
- return producerSource;
- }
- // try super class
- return getPackageSource(serviceClass.getSuperclass(), pkgName);
- }
-
- public boolean isBootDelegationPackage(String name) {
- if (bootDelegateAll)
- return true;
- if (bootDelegation != null)
- for (int i = 0; i < bootDelegation.length; i++)
- if (name.equals(bootDelegation[i]))
- return true;
- if (bootDelegationStems != null)
- for (int i = 0; i < bootDelegationStems.length; i++)
- if (name.startsWith(bootDelegationStems[i]))
- return true;
- return false;
- }
-
- SignedContentFactory getSignedContentFactory() {
- ServiceTracker<SignedContentFactory, SignedContentFactory> currentTracker = signedContentFactory;
- return (currentTracker == null ? null : currentTracker.getService());
- }
-
- ContextFinder getContextFinder() {
- return contextFinder;
- }
-
- public boolean isRefreshDuplicateBSNAllowed() {
- return allowRefreshDuplicateBSN;
- }
-
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/InternalSystemBundle.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/InternalSystemBundle.java
deleted file mode 100644
index fb352f0de..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/InternalSystemBundle.java
+++ /dev/null
@@ -1,433 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2011 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.framework.internal.core;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URL;
-import java.security.Permission;
-import java.security.ProtectionDomain;
-import java.util.Dictionary;
-import java.util.Enumeration;
-import org.eclipse.osgi.framework.debug.Debug;
-import org.osgi.framework.*;
-import org.osgi.framework.startlevel.FrameworkStartLevel;
-import org.osgi.framework.wiring.FrameworkWiring;
-
-/**
- * This class subclasses Bundle to provide a system Bundle
- * so that the framework can be represented as a bundle and
- * can access the services provided by other bundles.
- */
-
-public class InternalSystemBundle extends BundleHost implements org.osgi.framework.launch.Framework {
- class SystemBundleHeaders extends Dictionary<String, String> {
- private final Dictionary<String, String> headers;
-
- public SystemBundleHeaders(Dictionary<String, String> headers) {
- this.headers = headers;
- }
-
- public Enumeration<String> elements() {
- return headers.elements();
- }
-
- public String get(Object key) {
- if (!(key instanceof String))
- return null;
- if (org.osgi.framework.Constants.EXPORT_PACKAGE.equalsIgnoreCase((String) key)) {
- return getExtra(org.osgi.framework.Constants.EXPORT_PACKAGE, org.osgi.framework.Constants.FRAMEWORK_SYSTEMPACKAGES, org.osgi.framework.Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA);
- } else if (org.osgi.framework.Constants.PROVIDE_CAPABILITY.equalsIgnoreCase((String) key)) {
- return getExtra(org.osgi.framework.Constants.PROVIDE_CAPABILITY, org.osgi.framework.Constants.FRAMEWORK_SYSTEMCAPABILITIES, org.osgi.framework.Constants.FRAMEWORK_SYSTEMCAPABILITIES_EXTRA);
- }
- return headers.get(key);
- }
-
- private String getExtra(String header, String systemProp, String systemExtraProp) {
- String systemValue = FrameworkProperties.getProperty(systemProp);
- String systemExtraValue = FrameworkProperties.getProperty(systemExtraProp);
- if (systemValue == null)
- systemValue = systemExtraValue;
- else if (systemExtraValue != null && systemExtraValue.trim().length() > 0)
- systemValue += ", " + systemExtraValue; //$NON-NLS-1$
- String result = headers.get(header);
- if (systemValue != null && systemValue.trim().length() > 0) {
- if (result != null)
- result += ", " + systemValue; //$NON-NLS-1$
- else
- result = systemValue;
- }
- return result;
- }
-
- public boolean isEmpty() {
- return headers.isEmpty();
- }
-
- public Enumeration<String> keys() {
- return headers.keys();
- }
-
- public String put(String key, String value) {
- return headers.put(key, value);
- }
-
- public String remove(Object key) {
- return headers.remove(key);
- }
-
- public int size() {
- return headers.size();
- }
-
- }
-
- private final FrameworkStartLevel fsl;
- ProtectionDomain systemDomain;
-
- /**
- * Private SystemBundle object constructor.
- * This method creates the SystemBundle and its BundleContext.
- * The SystemBundle's state is set to STARTING.
- * This method is called when the framework is constructed.
- *
- * @param framework Framework this bundle is running in
- */
- protected InternalSystemBundle(Framework framework) throws BundleException {
- super(framework.adaptor.createSystemBundleData(), framework); // startlevel=0 means framework stopped
- Constants.setInternalSymbolicName(bundledata.getSymbolicName());
- state = Bundle.RESOLVED;
- context = createContext();
- fsl = new EquinoxStartLevel();
- }
-
- /**
- * Load the bundle.
- * This methods overrides the Bundle method and does nothing.
- *
- */
- protected void load() {
- SecurityManager sm = System.getSecurityManager();
-
- if (sm != null) {
- systemDomain = getClass().getProtectionDomain();
- }
- }
-
- /**
- * Reload from a new bundle.
- * This methods overrides the Bundle method and does nothing.
- *
- * @param newBundle
- * @return false
- */
- protected boolean reload(AbstractBundle newBundle) {
- return (false);
- }
-
- /**
- * Refresh the bundle.
- * This methods overrides the Bundle method and does nothing.
- *
- */
- protected void refresh() {
- // do nothing
- }
-
- /**
- * Unload the bundle.
- * This methods overrides the Bundle method and does nothing.
- *
- * @return false
- */
- protected boolean unload() {
- return (false);
- }
-
- /**
- * Close the the Bundle's file.
- * This method closes the BundleContext for the SystemBundle.
- *
- */
- protected void close() {
- context.close();
- context = null;
- }
-
- /**
- * This method loads a class from the bundle.
- *
- * @param name the name of the desired Class.
- * @param checkPermission indicates whether a permission check should be done.
- * @return the resulting Class
- * @exception java.lang.ClassNotFoundException if the class definition was not found.
- */
- protected Class<?> loadClass(String name, boolean checkPermission) throws ClassNotFoundException {
- if (checkPermission) {
- framework.checkAdminPermission(this, AdminPermission.CLASS);
- checkValid();
- }
- return (Class.forName(name));
- }
-
- /**
- * Find the specified resource in this bundle.
- * This methods returns null for the system bundle.
- */
- public URL getResource(String name) {
- return (null);
- }
-
- /**
- * Indicate SystemBundle is resolved.
- *
- */
- protected boolean isUnresolved() {
- return (false);
- }
-
- /**
- * Start this bundle.
- * This methods overrides the Bundle method and does nothing.
- *
- */
- public void start() {
- framework.checkAdminPermission(this, AdminPermission.EXECUTE);
- }
-
- public void start(int options) {
- framework.checkAdminPermission(this, AdminPermission.EXECUTE);
- }
-
- /**
- * Start the SystemBundle.
- * This method launches the framework.
- *
- */
- protected void resume() {
- /* initialize the startlevel service */
- framework.startLevelManager.initialize();
-
- /* Load all installed bundles */
- loadInstalledBundles(framework.startLevelManager.getInstalledBundles(framework.bundles, false));
- /* Start the system bundle */
- try {
- framework.systemBundle.state = Bundle.STARTING;
- framework.systemBundle.context.start();
- framework.publishBundleEvent(BundleEvent.STARTING, framework.systemBundle);
- } catch (BundleException be) {
- if (Debug.DEBUG_STARTLEVEL) {
- Debug.println("SLL: Bundle resume exception: " + be.getMessage()); //$NON-NLS-1$
- Debug.printStackTrace(be.getNestedException() == null ? be : be.getNestedException());
- }
- framework.publishFrameworkEvent(FrameworkEvent.ERROR, framework.systemBundle, be);
- throw new RuntimeException(be.getMessage(), be);
- }
-
- }
-
- private void loadInstalledBundles(AbstractBundle[] installedBundles) {
-
- for (int i = 0; i < installedBundles.length; i++) {
- AbstractBundle bundle = installedBundles[i];
- if (Debug.DEBUG_STARTLEVEL) {
- Debug.println("SLL: Trying to load bundle " + bundle); //$NON-NLS-1$
- }
- bundle.load();
- }
- }
-
- /**
- * Stop the framework.
- * This method spawns a thread which will call framework.shutdown.
- *
- */
- public void stop() {
- framework.checkAdminPermission(this, AdminPermission.EXECUTE);
-
- if ((state & (ACTIVE | STARTING)) != 0) {
- Thread shutdown = framework.secureAction.createThread(new Runnable() {
- public void run() {
- try {
- framework.close();
- } catch (Throwable t) {
- // allow the adaptor to handle this unexpected error
- framework.adaptor.handleRuntimeError(t);
- }
- }
- }, "System Bundle Shutdown", framework.getContextFinder()); //$NON-NLS-1$
-
- shutdown.start();
- }
- }
-
- public void stop(int options) {
- stop();
- }
-
- /**
- * Stop the SystemBundle.
- * This method shuts down the framework.
- *
- */
- protected void suspend() {
-
- framework.startLevelManager.shutdown();
- framework.startLevelManager.cleanup();
-
- /* clean up the exporting loaders */
- framework.packageAdmin.cleanup();
-
- if (Debug.DEBUG_GENERAL) {
- Debug.println("->Framework shutdown"); //$NON-NLS-1$
- }
- // fire the STOPPED event here.
- // All bundles have been unloaded, but there may be a boot strap listener that is interested (bug 182742)
- framework.publishBundleEvent(BundleEvent.STOPPED, this);
- }
-
- protected void suspend(boolean lock) {
- // do nothing
- }
-
- /**
- * Update this bundle.
- * This method spawns a thread which will call framework.shutdown
- * followed by framework.launch.
- *
- */
- public void update() {
- framework.checkAdminPermission(this, AdminPermission.LIFECYCLE);
-
- if ((state & (ACTIVE | STARTING)) != 0) {
- Thread restart = framework.secureAction.createThread(new Runnable() {
- public void run() {
- int sl = framework.startLevelManager.getStartLevel();
- FrameworkProperties.setProperty(Constants.PROP_OSGI_RELAUNCH, ""); //$NON-NLS-1$
- framework.shutdown(FrameworkEvent.STOPPED_UPDATE);
- framework.launch();
- if (sl > 0)
- framework.startLevelManager.doSetStartLevel(sl);
- FrameworkProperties.clearProperty(Constants.PROP_OSGI_RELAUNCH);
- }
- }, "System Bundle Update", framework.getContextFinder()); //$NON-NLS-1$
-
- restart.start();
- }
- }
-
- /**
- * Update this bundle from an InputStream.
- * This methods overrides the Bundle method and does nothing.
- *
- * @param in The InputStream from which to read the new bundle.
- */
- public void update(InputStream in) {
- update();
-
- try {
- in.close();
- } catch (IOException e) {
- // do nothing
- }
- }
-
- /**
- * Uninstall this bundle.
- * This methods overrides the Bundle method and throws an exception.
- *
- */
- public void uninstall() throws BundleException {
- framework.checkAdminPermission(this, AdminPermission.LIFECYCLE);
-
- throw new BundleException(Msg.BUNDLE_SYSTEMBUNDLE_UNINSTALL_EXCEPTION, BundleException.INVALID_OPERATION);
- }
-
- /**
- * Determine whether the bundle has the requested
- * permission.
- * This methods overrides the Bundle method and returns <code>true</code>.
- *
- * @param permission The requested permission.
- * @return <code>true</code>
- */
- public boolean hasPermission(Object permission) {
- if (systemDomain != null) {
- if (permission instanceof Permission) {
- return systemDomain.implies((Permission) permission);
- }
-
- return false;
- }
-
- return true;
- }
-
- /**
- * No work to do for the SystemBundle.
- *
- * @param refreshedBundles
- * A list of bundles which have been refreshed as a result
- * of a packageRefresh
- */
- protected void unresolvePermissions(AbstractBundle[] refreshedBundles) {
- // Do nothing
- }
-
- public Dictionary<String, String> getHeaders(String localeString) {
- return new SystemBundleHeaders(super.getHeaders(localeString));
- }
-
- public void init() {
- // no op for internal representation
- }
-
- public FrameworkEvent waitForStop(long timeout) throws InterruptedException {
- return framework.waitForStop(timeout);
- }
-
- public ClassLoader getClassLoader() {
- return getClass().getClassLoader();
- }
-
- @SuppressWarnings("unchecked")
- @Override
- protected <A> A adapt0(Class<A> adapterType) {
- if (FrameworkStartLevel.class.equals(adapterType))
- return (A) fsl;
- else if (FrameworkWiring.class.equals(adapterType))
- return (A) framework.getPackageAdmin();
- return super.adapt0(adapterType);
- }
-
- class EquinoxStartLevel implements FrameworkStartLevel {
- public void setStartLevel(int startlevel, FrameworkListener... listeners) {
- framework.startLevelManager.setStartLevel(startlevel, InternalSystemBundle.this, listeners);
- }
-
- public int getInitialBundleStartLevel() {
- return framework.startLevelManager.getInitialBundleStartLevel();
- }
-
- public void setInitialBundleStartLevel(int startlevel) {
- framework.startLevelManager.setInitialBundleStartLevel(startlevel);
- }
-
- public Bundle getBundle() {
- return InternalSystemBundle.this;
- }
-
- public int getStartLevel() {
- return framework.startLevelManager.getStartLevel();
- }
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/ManifestLocalization.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/ManifestLocalization.java
deleted file mode 100644
index 5212b1733..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/ManifestLocalization.java
+++ /dev/null
@@ -1,241 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2004, 2011 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.osgi.framework.internal.core;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URL;
-import java.util.*;
-import org.eclipse.osgi.framework.util.Headers;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.Constants;
-
-/**
- * This class is used by the Bundle Class to localize manifest headers.
- */
-public class ManifestLocalization {
- final static String DEFAULT_ROOT = FrameworkProperties.getProperty("equinox.root.locale", "en"); //$NON-NLS-1$ //$NON-NLS-2$
- private final AbstractBundle bundle;
- private final Dictionary<String, String> rawHeaders;
- private Dictionary<String, String> defaultLocaleHeaders = null;
- private final Hashtable<String, BundleResourceBundle> cache = new Hashtable<String, BundleResourceBundle>(5);
-
- public ManifestLocalization(AbstractBundle bundle, Dictionary<String, String> rawHeaders) {
- this.bundle = bundle;
- this.rawHeaders = rawHeaders;
- }
-
- Dictionary<String, String> getHeaders(String localeString) {
- if (localeString.length() == 0)
- return rawHeaders;
- boolean isDefaultLocale = localeString.equals(Locale.getDefault().toString());
- Dictionary<String, String> currentDefault = defaultLocaleHeaders;
- if (isDefaultLocale && currentDefault != null) {
- return currentDefault;
- }
- try {
- bundle.checkValid();
- } catch (IllegalStateException ex) {
- // defaultLocaleHeaders should have been initialized on uninstall
- if (currentDefault != null)
- return currentDefault;
- return rawHeaders;
- }
- ResourceBundle localeProperties = getResourceBundle(localeString, isDefaultLocale);
- Enumeration<String> e = this.rawHeaders.keys();
- Headers<String, String> localeHeaders = new Headers<String, String>(this.rawHeaders.size());
- while (e.hasMoreElements()) {
- String key = e.nextElement();
- String value = this.rawHeaders.get(key);
- if (value.startsWith("%") && (value.length() > 1)) { //$NON-NLS-1$
- String propertiesKey = value.substring(1);
- try {
- value = localeProperties == null ? propertiesKey : (String) localeProperties.getObject(propertiesKey);
- } catch (MissingResourceException ex) {
- value = propertiesKey;
- }
- }
- localeHeaders.set(key, value);
- }
- localeHeaders.setReadOnly();
- if (isDefaultLocale) {
- defaultLocaleHeaders = localeHeaders;
- }
- return (localeHeaders);
- }
-
- private String[] buildNLVariants(String nl) {
- List<String> result = new ArrayList<String>();
- while (nl.length() > 0) {
- result.add(nl);
- int i = nl.lastIndexOf('_');
- nl = (i < 0) ? "" : nl.substring(0, i); //$NON-NLS-1$
- }
- result.add(""); //$NON-NLS-1$
- return result.toArray(new String[result.size()]);
- }
-
- /*
- * This method find the appropriate Manifest Localization file inside the
- * bundle. If not found, return null.
- */
- ResourceBundle getResourceBundle(String localeString, boolean isDefaultLocale) {
- BundleResourceBundle resourceBundle = lookupResourceBundle(localeString);
- if (isDefaultLocale)
- return (ResourceBundle) resourceBundle;
- // need to determine if this is resource bundle is an empty stem
- // if it is then the default locale should be used
- if (resourceBundle == null || resourceBundle.isStemEmpty())
- return (ResourceBundle) lookupResourceBundle(Locale.getDefault().toString());
- return (ResourceBundle) resourceBundle;
- }
-
- 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)
- String localizationHeader = rawHeaders.get(Constants.BUNDLE_LOCALIZATION);
- if (localizationHeader == null)
- localizationHeader = Constants.BUNDLE_LOCALIZATION_DEFAULT_BASENAME;
- synchronized (cache) {
- BundleResourceBundle result = cache.get(localeString);
- if (result != null)
- return result.isEmpty() ? null : result;
- String[] nlVarients = buildNLVariants(localeString);
- BundleResourceBundle parent = null;
- for (int i = nlVarients.length - 1; i >= 0; i--) {
- BundleResourceBundle varientBundle = null;
- URL varientURL = findResource(localizationHeader + (nlVarients[i].equals("") ? nlVarients[i] : '_' + nlVarients[i]) + ".properties"); //$NON-NLS-1$ //$NON-NLS-2$
- if (varientURL == null) {
- varientBundle = cache.get(nlVarients[i]);
- } else {
- InputStream resourceStream = null;
- try {
- resourceStream = varientURL.openStream();
- varientBundle = new LocalizationResourceBundle(resourceStream);
- } catch (IOException e) {
- // ignore and continue
- } finally {
- if (resourceStream != null) {
- try {
- resourceStream.close();
- } catch (IOException e3) {
- //Ignore exception
- }
- }
- }
- }
-
- if (varientBundle == null) {
- varientBundle = new EmptyResouceBundle(nlVarients[i]);
- }
- if (parent != null)
- varientBundle.setParent((ResourceBundle) parent);
- cache.put(nlVarients[i], varientBundle);
- parent = varientBundle;
- }
- result = cache.get(localeString);
- return result.isEmpty() ? null : result;
- }
- }
-
- private URL findResource(String resource) {
- AbstractBundle searchBundle = bundle;
- if (bundle.isResolved()) {
- if (bundle.isFragment() && bundle.getHosts() != null) {
- //if the bundle is a fragment, look in the host first
- searchBundle = bundle.getHosts()[0];
- if (searchBundle.getState() == Bundle.UNINSTALLED)
- searchBundle = bundle;
- }
- return findInResolved(resource, searchBundle);
- }
- return searchBundle.getEntry0(resource);
- }
-
- private static URL findInResolved(String filePath, AbstractBundle bundleHost) {
- URL result = bundleHost.getEntry0(filePath);
- if (result != null)
- return result;
- return findInFragments(filePath, bundleHost);
- }
-
- private static URL findInFragments(String filePath, AbstractBundle searchBundle) {
- BundleFragment[] fragments = searchBundle.getFragments();
- URL fileURL = null;
- for (int i = 0; fragments != null && i < fragments.length && fileURL == null; i++) {
- if (fragments[i].getState() != Bundle.UNINSTALLED)
- fileURL = fragments[i].getEntry0(filePath);
- }
- return fileURL;
- }
-
- private interface BundleResourceBundle {
- void setParent(ResourceBundle parent);
-
- boolean isEmpty();
-
- boolean isStemEmpty();
- }
-
- private class LocalizationResourceBundle extends PropertyResourceBundle implements BundleResourceBundle {
- public LocalizationResourceBundle(InputStream in) throws IOException {
- super(in);
- }
-
- public void setParent(ResourceBundle parent) {
- super.setParent(parent);
- }
-
- public boolean isEmpty() {
- return false;
- }
-
- public boolean isStemEmpty() {
- return parent == null;
- }
- }
-
- class EmptyResouceBundle extends ResourceBundle implements BundleResourceBundle {
- private final String localeString;
-
- public EmptyResouceBundle(String locale) {
- super();
- this.localeString = locale;
- }
-
- @SuppressWarnings("unchecked")
- public Enumeration<String> getKeys() {
- return Collections.enumeration(Collections.EMPTY_LIST);
- }
-
- protected Object handleGetObject(String arg0) throws MissingResourceException {
- return null;
- }
-
- public void setParent(ResourceBundle parent) {
- super.setParent(parent);
- }
-
- public boolean isEmpty() {
- if (parent == null)
- return true;
- return ((BundleResourceBundle) parent).isEmpty();
- }
-
- public boolean isStemEmpty() {
- if (DEFAULT_ROOT.equals(localeString))
- return false;
- if (parent == null)
- return true;
- return ((BundleResourceBundle) parent).isStemEmpty();
- }
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/PackageAdminImpl.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/PackageAdminImpl.java
deleted file mode 100644
index f9e14605d..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/PackageAdminImpl.java
+++ /dev/null
@@ -1,766 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2012 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.framework.internal.core;
-
-import java.io.IOException;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.util.*;
-import org.eclipse.osgi.framework.adaptor.*;
-import org.eclipse.osgi.framework.debug.Debug;
-import org.eclipse.osgi.internal.loader.BundleLoader;
-import org.eclipse.osgi.internal.loader.BundleLoaderProxy;
-import org.eclipse.osgi.internal.profile.Profile;
-import org.eclipse.osgi.service.resolver.*;
-import org.eclipse.osgi.service.resolver.VersionRange;
-import org.eclipse.osgi.util.NLS;
-import org.osgi.framework.*;
-import org.osgi.framework.wiring.FrameworkWiring;
-import org.osgi.service.packageadmin.*;
-
-/**
- * PackageAdmin service for the OSGi specification.
- *
- * Framework service which allows bundle programmers to inspect the packages
- * exported in the framework and eagerly update or uninstall bundles.
- *
- * If present, there will only be a single instance of this service
- * registered in the framework.
- *
- * <p> The term <i>exported package</i> (and the corresponding interface
- * {@link ExportedPackage}) refers to a package that has actually been
- * exported (as opposed to one that is available for export).
- *
- * <p> Note that the information about exported packages returned by this
- * service is valid only until the next time {@link #refreshPackages(org.osgi.framework.Bundle[])} is
- * called.
- * If an ExportedPackage becomes stale, (that is, the package it references
- * has been updated or removed as a result of calling
- * PackageAdmin.refreshPackages()),
- * its getName() and getSpecificationVersion() continue to return their
- * old values, isRemovalPending() returns true, and getExportingBundle()
- * and getImportingBundles() return null.
- */
-public class PackageAdminImpl implements PackageAdmin, FrameworkWiring {
- /** framework object */
- protected Framework framework;
-
- /*
- * We need to make sure that the GetBundleAction class loads early to prevent a ClassCircularityError when checking permissions.
- * See bug 161561
- */
- static {
- Class<?> c;
- c = GetBundleAction.class;
- c.getName(); // to prevent compiler warnings
- }
-
- static class GetBundleAction implements PrivilegedAction<Bundle> {
- private Class<?> clazz;
- private PackageAdminImpl impl;
-
- public GetBundleAction(PackageAdminImpl impl, Class<?> clazz) {
- this.impl = impl;
- this.clazz = clazz;
- }
-
- public Bundle run() {
- return impl.getBundlePriv(clazz);
- }
- }
-
- /**
- * Constructor.
- *
- * @param framework Framework object.
- */
- protected PackageAdminImpl(Framework framework) {
- this.framework = framework;
- }
-
- public ExportedPackage[] getExportedPackages(Bundle bundle) {
- List<ExportedPackage> allExports = new ArrayList<ExportedPackage>();
- FrameworkAdaptor adaptor = framework.adaptor;
- if (adaptor == null)
- return null;
- ExportPackageDescription[] allDescriptions = adaptor.getState().getExportedPackages();
- for (int i = 0; i < allDescriptions.length; i++) {
- ExportedPackageImpl exportedPackage = createExportedPackage(allDescriptions[i]);
- if (exportedPackage == null)
- continue;
- if (bundle == null || exportedPackage.getBundle() == bundle)
- allExports.add(exportedPackage);
- }
- return (allExports.size() == 0 ? null : allExports.toArray(new ExportedPackage[allExports.size()]));
- }
-
- private ExportedPackageImpl createExportedPackage(ExportPackageDescription description) {
- BundleDescription exporter = description.getExporter();
- if (exporter == null || exporter.getHost() != null)
- return null;
- Object userObject = exporter.getUserObject();
- if (!(userObject instanceof BundleLoaderProxy)) {
- BundleHost bundle = (BundleHost) framework.getBundle(exporter.getBundleId());
- if (bundle == null)
- return null;
- userObject = bundle.getLoaderProxy();
- }
- return new ExportedPackageImpl(description, (BundleLoaderProxy) userObject);
- }
-
- public ExportedPackage getExportedPackage(String name) {
- ExportedPackage[] allExports = getExportedPackages((Bundle) null);
- if (allExports == null)
- return null;
- ExportedPackage result = null;
- for (int i = 0; i < allExports.length; i++) {
- if (name.equals(allExports[i].getName())) {
- if (result == null) {
- result = allExports[i];
- } else {
- Version curVersion = result.getVersion();
- Version newVersion = allExports[i].getVersion();
- if (newVersion.compareTo(curVersion) >= 0)
- result = allExports[i];
- }
- }
- }
- return result;
- }
-
- public ExportedPackage[] getExportedPackages(String name) {
- ExportedPackage[] allExports = getExportedPackages((Bundle) null);
- if (allExports == null)
- return null;
- List<ExportedPackage> result = new ArrayList<ExportedPackage>(1); // rare to have more than one
- for (int i = 0; i < allExports.length; i++)
- if (name.equals(allExports[i].getName()))
- result.add(allExports[i]);
- return (result.size() == 0 ? null : result.toArray(new ExportedPackage[result.size()]));
- }
-
- public void refreshPackages(Bundle[] input) {
- refreshPackages(input, false, null);
- }
-
- public void refreshPackages(Bundle[] input, boolean synchronously, final FrameworkListener[] listeners) {
- framework.checkAdminPermission(framework.systemBundle, AdminPermission.RESOLVE);
-
- final AbstractBundle[] copy;
- if (input != null) {
- synchronized (input) {
- copy = new AbstractBundle[input.length];
- System.arraycopy(input, 0, copy, 0, input.length);
- }
- } else
- copy = null;
-
- if (synchronously) {
- doResolveBundles(copy, true, listeners);
- if (framework.isForcedRestart())
- framework.systemBundle.stop();
- } else {
- Thread refresh = framework.secureAction.createThread(new Runnable() {
- public void run() {
- doResolveBundles(copy, true, listeners);
- if (framework.isForcedRestart())
- framework.shutdown(FrameworkEvent.STOPPED_BOOTCLASSPATH_MODIFIED);
- }
- }, "Refresh Packages", framework.getContextFinder()); //$NON-NLS-1$
- refresh.start();
- }
- }
-
- public boolean resolveBundles(Bundle[] bundles) {
- return resolveBundles(bundles, false);
- }
-
- boolean resolveBundles(Bundle[] bundles, boolean propagateError) {
- framework.checkAdminPermission(framework.systemBundle, AdminPermission.RESOLVE);
- if (bundles == null)
- bundles = framework.getAllBundles();
- try {
- doResolveBundles(bundles, false, null);
- } catch (ResolverHookException e) {
- if (propagateError)
- throw e;
- }
- for (int i = 0; i < bundles.length; i++)
- if (!((AbstractBundle) bundles[i]).isResolved())
- return false;
-
- return true;
- }
-
- // This method is protected to enable a work around to bug 245251
- synchronized protected void doResolveBundles(Bundle[] bundles, boolean refreshPackages, FrameworkListener[] listeners) {
- try {
- if (Profile.PROFILE && Profile.STARTUP)
- Profile.logEnter("resolve bundles"); //$NON-NLS-1$
- framework.publishBundleEvent(Framework.BATCHEVENT_BEGIN, framework.systemBundle);
- State systemState = framework.adaptor.getState();
- BundleDescription[] descriptions = null;
- int numBundles = bundles == null ? 0 : bundles.length;
- if (!refreshPackages) {
- List<BundleDescription> resolving = new ArrayList<BundleDescription>();
- for (Bundle bundle : bundles) {
- BundleDescription description = ((AbstractBundle) bundle).getBundleDescription();
- if (((bundle.getState() & Bundle.INSTALLED) != 0) && description != null)
- resolving.add(description);
- }
- descriptions = resolving.toArray(new BundleDescription[resolving.size()]);
- } else if (numBundles > 0) {
- // populate the resolved hosts package sources first (do this outside sync block: bug 280929)
- populateLoaders(framework.getAllBundles());
- synchronized (framework.bundles) {
- // now collect the descriptions to refresh
- List<BundleDescription> results = new ArrayList<BundleDescription>(numBundles);
- for (int i = 0; i < numBundles; i++) {
- BundleDescription description = ((AbstractBundle) bundles[i]).getBundleDescription();
- if (description != null && description.getBundleId() != 0 && !results.contains(description))
- results.add(description);
- if (framework.isRefreshDuplicateBSNAllowed()) {
- // add in any bundles that have the same symbolic name see bug (169593)
- AbstractBundle[] sameNames = framework.bundles.getBundles(bundles[i].getSymbolicName());
- if (sameNames != null && sameNames.length > 1) {
- for (int j = 0; j < sameNames.length; j++)
- if (sameNames[j] != bundles[i]) {
- BundleDescription sameName = sameNames[j].getBundleDescription();
- if (sameName != null && sameName.getBundleId() != 0 && !results.contains(sameName)) {
- if (checkExtensionBundle(sameName))
- results.add(sameName);
- }
- }
- }
- }
- }
- descriptions = (results.size() == 0 ? null : results.toArray(new BundleDescription[results.size()]));
- }
- }
- StateDelta stateDelta = systemState.resolve(descriptions, refreshPackages);
- BundleDelta[] delta = stateDelta.getChanges();
- processDelta(delta, refreshPackages, systemState);
- if (stateDelta.getResovlerHookException() != null)
- throw stateDelta.getResovlerHookException();
- } catch (Throwable t) {
- if (Debug.DEBUG_PACKAGEADMIN) {
- Debug.println("PackageAdminImpl.doResolveBundles: Error occured :"); //$NON-NLS-1$
- Debug.printStackTrace(t);
- }
- if (t instanceof RuntimeException)
- throw (RuntimeException) t;
- if (t instanceof Error)
- throw (Error) t;
- } finally {
- if (Profile.PROFILE && Profile.STARTUP)
- Profile.logExit("resolve bundles"); //$NON-NLS-1$
- if (framework.isActive()) {
- framework.publishBundleEvent(Framework.BATCHEVENT_END, framework.systemBundle);
- if (refreshPackages)
- framework.publishFrameworkEvent(FrameworkEvent.PACKAGES_REFRESHED, framework.systemBundle, null, listeners);
- }
- }
- }
-
- private void populateLoaders(AbstractBundle[] bundles) {
- // populate all the loaders with their package source information
- // this is needed to fix bug 259903.
- for (int i = 0; i < bundles.length; i++) {
- // only need to do this for host bundles which are resolved
- if (bundles[i] instanceof BundleHost && bundles[i].isResolved()) {
- // getting the BundleLoader object populates the require-bundle sources
- BundleLoader loader = ((BundleHost) bundles[i]).getBundleLoader();
- if (loader != null)
- // need to explicitly get the import package sources
- loader.getImportedSources(null);
- }
- }
- }
-
- private boolean checkExtensionBundle(BundleDescription sameName) {
- if (sameName.getHost() == null || !sameName.isResolved())
- return true; // only do this extra check for resolved fragment bundles
- // only add fragments if they are not for the system bundle
- if (((BundleDescription) sameName.getHost().getSupplier()).getBundleId() != 0)
- return true;
- // never do this for resolved system bundle fragments
- return false;
- }
-
- private void resumeBundles(AbstractBundle[] bundles, boolean refreshPackages, int[] previousStates) {
- if (Debug.DEBUG_PACKAGEADMIN) {
- Debug.println("PackageAdminImpl: restart the bundles"); //$NON-NLS-1$
- }
- if (bundles == null)
- return;
- for (int i = 0; i < bundles.length; i++) {
- if (!bundles[i].isResolved() || (!refreshPackages && ((bundles[i].getBundleData().getStatus() & Constants.BUNDLE_LAZY_START) == 0 || bundles[i].testStateChanging(Thread.currentThread()))))
- // skip bundles that are not resolved or
- // if we are doing resolveBundles then skip non-lazy start bundles and bundles currently changing state by this thread
- continue;
- if (previousStates[i] == Bundle.ACTIVE)
- try {
- bundles[i].start(Bundle.START_TRANSIENT);
- } catch (BundleException e) {
- framework.publishFrameworkEvent(FrameworkEvent.ERROR, bundles[i], e);
- }
- else
- framework.resumeBundle(bundles[i]);
- }
- }
-
- private void suspendBundle(AbstractBundle bundle) {
- // attempt to suspend the bundle or obtain the state change lock
- // Note that this may fail but we cannot quit the
- // refreshPackages operation because of it. (bug 84169)
- if (bundle.isActive() && !bundle.isFragment()) {
- framework.suspendBundle(bundle, true);
- } else {
- if (bundle.getStateChanging() != Thread.currentThread())
- try {
- bundle.beginStateChange();
- } catch (BundleException e) {
- framework.publishFrameworkEvent(FrameworkEvent.ERROR, bundle, e);
- }
- }
-
- if (Debug.DEBUG_PACKAGEADMIN) {
- if (bundle.stateChanging == null) {
- Debug.println("Bundle state change lock is clear! " + bundle); //$NON-NLS-1$
- Debug.printStackTrace(new Exception("Stack trace")); //$NON-NLS-1$
- }
- }
- }
-
- private void applyRemovalPending(BundleDelta bundleDelta) throws BundleException {
- if ((bundleDelta.getType() & BundleDelta.REMOVAL_COMPLETE) != 0) {
- BundleDescription bundle = bundleDelta.getBundle();
- if (bundle.getDependents() != null && bundle.getDependents().length > 0) {
- /* Reaching here is an internal error */
- if (Debug.DEBUG_PACKAGEADMIN) {
- Debug.println("Bundles still depend on removed bundle! " + bundle); //$NON-NLS-1$
- Debug.printStackTrace(new Exception("Stack trace")); //$NON-NLS-1$
- }
- throw new BundleException(Msg.OSGI_INTERNAL_ERROR);
- }
- Object userObject = bundle.getUserObject();
- if (userObject instanceof BundleLoaderProxy) {
- BundleLoader.closeBundleLoader((BundleLoaderProxy) userObject);
- try {
- ((BundleLoaderProxy) userObject).getBundleData().close();
- } catch (IOException e) {
- // ignore
- }
- } else if (userObject instanceof BundleData) {
- try {
- ((BundleData) userObject).close();
- } catch (IOException e) {
- // ignore
- }
- }
- }
- }
-
- private AbstractBundle setResolved(BundleDescription bundleDescription) {
- if (!bundleDescription.isResolved())
- return null;
- AbstractBundle bundle = framework.getBundle(bundleDescription.getBundleId());
- if (bundle == null) {
- BundleException be = new BundleException(NLS.bind(Msg.BUNDLE_NOT_IN_FRAMEWORK, bundleDescription));
- framework.publishFrameworkEvent(FrameworkEvent.ERROR, framework.systemBundle, be);
- return null;
- }
- boolean resolve = true;
- if (bundle.isFragment()) {
- BundleDescription[] hosts = bundleDescription.getHost().getHosts();
- for (int i = 0; i < hosts.length; i++) {
- BundleHost host = (BundleHost) framework.getBundle(hosts[i].getBundleId());
- resolve = ((BundleFragment) bundle).addHost(host);
- }
- }
- if (resolve)
- bundle.resolve();
- return bundle;
- }
-
- private void applyDeltas(BundleDelta[] bundleDeltas) throws BundleException {
- Arrays.sort(bundleDeltas, new Comparator<BundleDelta>() {
- public int compare(BundleDelta delta0, BundleDelta delta1) {
- return (int) (delta0.getBundle().getBundleId() - delta1.getBundle().getBundleId());
- }
- });
- for (int i = 0; i < bundleDeltas.length; i++) {
- int type = bundleDeltas[i].getType();
- if ((type & (BundleDelta.REMOVAL_PENDING | BundleDelta.REMOVAL_COMPLETE)) != 0)
- applyRemovalPending(bundleDeltas[i]);
- if ((type & BundleDelta.RESOLVED) != 0) {
- AbstractBundle bundle = setResolved(bundleDeltas[i].getBundle());
- if (bundle != null && bundle.isResolved()) {
- NativeCodeSpecification nativeCode = bundleDeltas[i].getBundle().getNativeCodeSpecification();
- if (nativeCode != null && nativeCode.getSupplier() != null)
- try {
- BundleData data = bundle.getBundleData();
- data.installNativeCode(((NativeCodeDescription) nativeCode.getSupplier()).getNativePaths());
- } catch (BundleException e) {
- framework.publishFrameworkEvent(FrameworkEvent.ERROR, bundle, e);
- }
- }
- }
- }
- }
-
- private AbstractBundle[] processDelta(BundleDelta[] bundleDeltas, boolean refreshPackages, State systemState) {
- List<AbstractBundle> bundlesList = new ArrayList<AbstractBundle>(bundleDeltas.length);
- // get all the bundles that are going to be refreshed
- for (int i = 0; i < bundleDeltas.length; i++) {
- if ((bundleDeltas[i].getType() & BundleDelta.REMOVAL_COMPLETE) != 0 && (bundleDeltas[i].getType() & BundleDelta.REMOVED) == 0)
- // this means the bundle was previously pending removal; do not add to list because it was already removed from before.
- continue;
- AbstractBundle changedBundle = framework.getBundle(bundleDeltas[i].getBundle().getBundleId());
- if (changedBundle != null && !bundlesList.contains(changedBundle))
- bundlesList.add(changedBundle);
- }
- AbstractBundle[] refresh = bundlesList.toArray(new AbstractBundle[bundlesList.size()]);
- // first sort by id/start-level order
- Util.sort(refresh, 0, refresh.length);
- // then sort by dependency order
- framework.startLevelManager.sortByDependency(refresh);
- boolean[] previouslyResolved = new boolean[refresh.length];
- int[] previousStates = new int[refresh.length];
- try {
- try {
- if (Debug.DEBUG_PACKAGEADMIN) {
- Debug.println("refreshPackages: Suspend each bundle and acquire its state change lock"); //$NON-NLS-1$
- }
- // find which bundles were previously resolved and handle extension bundles
- boolean restart = false;
- for (int i = refresh.length - 1; i >= 0; i--) {
- previouslyResolved[i] = refresh[i].isResolved();
- if (refresh[i] == framework.systemBundle)
- restart = true;
- else if (((refresh[i].bundledata.getType() & BundleData.TYPE_FRAMEWORK_EXTENSION) != 0) && previouslyResolved[i])
- restart = true;
- else if ((refresh[i].bundledata.getType() & BundleData.TYPE_BOOTCLASSPATH_EXTENSION) != 0)
- restart = true;
- else if ((refresh[i].bundledata.getType() & BundleData.TYPE_EXTCLASSPATH_EXTENSION) != 0 && previouslyResolved[i])
- restart = true;
- }
- if (restart) {
- FrameworkProperties.setProperty("osgi.forcedRestart", "true"); //$NON-NLS-1$ //$NON-NLS-2$
- framework.setForcedRestart(true);
- // do not shutdown the framework while holding the PackageAdmin lock (bug 194149)
- return null;
- }
- // now suspend each bundle and grab its state change lock.
- if (refreshPackages)
- for (int i = refresh.length - 1; i >= 0; i--) {
- previousStates[i] = refresh[i].getState();
- suspendBundle(refresh[i]);
- }
- /*
- * Refresh the bundles which will unexport the packages.
- * This will move RESOLVED bundles to the INSTALLED state.
- */
- if (Debug.DEBUG_PACKAGEADMIN) {
- Debug.println("refreshPackages: refresh the bundles"); //$NON-NLS-1$
- }
-
- synchronized (framework.bundles) {
- for (int i = refresh.length - 1; i >= 0; i--)
- refresh[i].refresh();
- }
- // send out unresolved events outside synch block (defect #80610)
- // send out unresolved events in reverse dependency order (defect #207505)
- for (int i = refresh.length - 1; i >= 0; i--) {
- // send out unresolved events
- if (previouslyResolved[i])
- framework.publishBundleEvent(BundleEvent.UNRESOLVED, refresh[i]);
- }
-
- /*
- * apply Deltas.
- */
- if (Debug.DEBUG_PACKAGEADMIN) {
- Debug.println("refreshPackages: applying deltas to bundles"); //$NON-NLS-1$
- }
- synchronized (framework.bundles) {
- applyDeltas(bundleDeltas);
- }
-
- } finally {
- /*
- * Release the state change locks.
- */
- if (Debug.DEBUG_PACKAGEADMIN) {
- Debug.println("refreshPackages: release the state change locks"); //$NON-NLS-1$
- }
- if (refreshPackages)
- for (int i = 0; i < refresh.length; i++) {
- AbstractBundle changedBundle = refresh[i];
- changedBundle.completeStateChange();
- }
- }
- /*
- * Take this opportunity to clean up the adaptor storage.
- */
- if (refreshPackages) {
- if (Debug.DEBUG_PACKAGEADMIN)
- Debug.println("refreshPackages: clean up adaptor storage"); //$NON-NLS-1$
- try {
- framework.adaptor.compactStorage();
- } catch (IOException e) {
- if (Debug.DEBUG_PACKAGEADMIN) {
- Debug.println("refreshPackages exception: " + e.getMessage()); //$NON-NLS-1$
- Debug.printStackTrace(e);
- }
- framework.publishFrameworkEvent(FrameworkEvent.ERROR, framework.systemBundle, new BundleException(Msg.BUNDLE_REFRESH_FAILURE, e));
- }
- }
- } catch (BundleException e) {
- if (Debug.DEBUG_PACKAGEADMIN) {
- Debug.println("refreshPackages exception: " + e.getMessage()); //$NON-NLS-1$
- Debug.printStackTrace(e.getNestedException() == null ? e : e.getNestedException());
- }
- framework.publishFrameworkEvent(FrameworkEvent.ERROR, framework.systemBundle, new BundleException(Msg.BUNDLE_REFRESH_FAILURE, e));
- }
-
- // send out any resolved. This must be done after the state change locks have been release.
- if (Debug.DEBUG_PACKAGEADMIN)
- Debug.println("refreshPackages: send out RESOLVED events"); //$NON-NLS-1$
- for (int i = 0; i < refresh.length; i++)
- if (refresh[i].isResolved())
- framework.publishBundleEvent(BundleEvent.RESOLVED, refresh[i]);
-
- // if we end up refreshing the system bundle or one of its fragments the framework will be shutdown and
- // should be re-started. This call should return without doing further work.
- if (!framework.isActive())
- return refresh;
- if (refreshPackages) {
- // must clear permission class and condition cache
- framework.securityAdmin.clearCaches();
- // increment the system state timestamp if we are refreshing packages.
- // this is needed incase we suspended a bundle from processing the delta (bug 167483)
- if (bundleDeltas.length > 0)
- systemState.setTimeStamp(systemState.getTimeStamp() == Long.MAX_VALUE ? 0 : systemState.getTimeStamp() + 1);
- }
- // always resume bundles incase we have lazy-start bundles
- resumeBundles(refresh, refreshPackages, previousStates);
- return refresh;
- }
-
- public RequiredBundle[] getRequiredBundles(String symbolicName) {
- AbstractBundle[] bundles;
- if (symbolicName == null)
- bundles = framework.getAllBundles();
- else
- bundles = framework.getBundleBySymbolicName(symbolicName);
- if (bundles == null || bundles.length == 0)
- return null;
-
- List<RequiredBundle> result = new ArrayList<RequiredBundle>(bundles.length);
- for (int i = 0; i < bundles.length; i++) {
- if (bundles[i].isFragment() || !bundles[i].isResolved() || bundles[i].getSymbolicName() == null)
- continue;
- if (bundles[i].hasPermission(new BundlePermission(bundles[i].getSymbolicName(), BundlePermission.PROVIDE)))
- result.add(((BundleHost) bundles[i]).getLoaderProxy());
- }
- return result.size() == 0 ? null : result.toArray(new RequiredBundle[result.size()]);
- }
-
- public Bundle[] getBundles(String symbolicName, String versionRange) {
- if (symbolicName == null) {
- throw new IllegalArgumentException();
- }
- AbstractBundle bundles[] = framework.getBundleBySymbolicName(symbolicName);
- if (bundles == null)
- return null;
-
- if (versionRange == null) {
- AbstractBundle[] result = new AbstractBundle[bundles.length];
- System.arraycopy(bundles, 0, result, 0, result.length);
- return result;
- }
-
- // This code depends on the array of bundles being in descending
- // version order.
- List<AbstractBundle> result = new ArrayList<AbstractBundle>(bundles.length);
- VersionRange range = new VersionRange(versionRange);
- for (int i = 0; i < bundles.length; i++) {
- if (range.isIncluded(bundles[i].getVersion())) {
- result.add(bundles[i]);
- }
- }
-
- if (result.size() == 0)
- return null;
- return result.toArray(new AbstractBundle[result.size()]);
- }
-
- public Bundle[] getFragments(Bundle bundle) {
- return ((AbstractBundle) bundle).getFragments();
- }
-
- public Bundle[] getHosts(Bundle bundle) {
- BundleHost[] hosts = ((AbstractBundle) bundle).getHosts();
- if (hosts == null)
- return null;
- // copy the array to protect modification
- Bundle[] result = new Bundle[hosts.length];
- for (int i = 0; i < hosts.length; i++)
- result[i] = hosts[i];
- return result;
- }
-
- Bundle getBundlePriv(Class<?> clazz) {
- ClassLoader cl = clazz.getClassLoader();
- if (cl instanceof BundleClassLoader) {
- ClassLoaderDelegate delegate = ((BundleClassLoader) cl).getDelegate();
- if (delegate instanceof BundleLoader)
- return ((BundleLoader) delegate).getBundle();
- }
- if (cl == getClass().getClassLoader())
- return framework.systemBundle;
- return null;
- }
-
- public Bundle getBundle(@SuppressWarnings("rawtypes") final Class clazz) {
- if (System.getSecurityManager() == null)
- return getBundlePriv(clazz);
- return AccessController.doPrivileged(new GetBundleAction(this, clazz));
- }
-
- public int getBundleType(Bundle bundle) {
- return ((AbstractBundle) bundle).isFragment() ? PackageAdmin.BUNDLE_TYPE_FRAGMENT : 0;
- }
-
- protected void cleanup() {
- //This is only called when the framework is shutting down
- }
-
- protected void setResolvedBundles(InternalSystemBundle systemBundle) {
- checkSystemBundle(systemBundle);
- // Now set the actual state of the bundles from the persisted state.
- State state = framework.adaptor.getState();
- BundleDescription[] descriptions = state.getBundles();
- for (int i = 0; i < descriptions.length; i++) {
- if (descriptions[i].getBundleId() == 0)
- setFrameworkVersion(descriptions[i]);
- else
- setResolved(descriptions[i]);
- }
- }
-
- private void checkSystemBundle(InternalSystemBundle systemBundle) {
- try {
- // first check that the system bundle has not changed since last saved state.
- State state = framework.adaptor.getState();
- BundleDescription oldSystemBundle = state.getBundle(0);
- boolean different = false;
- if (oldSystemBundle == null || !systemBundle.getBundleData().getVersion().equals(oldSystemBundle.getVersion()))
- different = true;
- if (!different && FrameworkProperties.getProperty("osgi.dev") == null) //$NON-NLS-1$
- return; // return quick if not in dev mode; system bundle version changes with each build
- BundleDescription newSystemBundle = state.getFactory().createBundleDescription(state, systemBundle.getHeaders(""), systemBundle.getLocation(), 0); //$NON-NLS-1$
- if (newSystemBundle == null)
- throw new BundleException(Msg.OSGI_SYSTEMBUNDLE_DESCRIPTION_ERROR);
- if (!different) {
- // need to check to make sure the system bundle description is up to date in the state.
- ExportPackageDescription[] oldPackages = oldSystemBundle.getExportPackages();
- ExportPackageDescription[] newPackages = newSystemBundle.getExportPackages();
- if (oldPackages.length >= newPackages.length) {
- for (int i = 0; i < newPackages.length && !different; i++) {
- if (oldPackages[i].getName().equals(newPackages[i].getName())) {
- Object oldVersion = oldPackages[i].getVersion();
- Object newVersion = newPackages[i].getVersion();
- different = oldVersion == null ? newVersion != null : !oldVersion.equals(newVersion);
- } else {
- different = true;
- }
- }
- } else {
- different = true;
- }
- }
- if (different) {
- state.removeBundle(0);
- state.addBundle(newSystemBundle);
- // force resolution so packages are properly linked
- state.resolve(false);
- }
- } catch (BundleException e) /* fatal error */{
- e.printStackTrace();
- throw new RuntimeException(NLS.bind(Msg.OSGI_SYSTEMBUNDLE_CREATE_EXCEPTION, e.getMessage()), e);
- }
- }
-
- private void setFrameworkVersion(BundleDescription systemBundle) {
- ExportPackageDescription[] packages = systemBundle.getExportPackages();
- for (int i = 0; i < packages.length; i++)
- if (packages[i].getName().equals(Constants.OSGI_FRAMEWORK_PACKAGE)) {
- FrameworkProperties.setProperty(Constants.FRAMEWORK_VERSION, packages[i].getVersion().toString());
- break;
- }
- FrameworkProperties.setProperty(Constants.OSGI_IMPL_VERSION_KEY, systemBundle.getVersion().toString());
- }
-
- public Bundle getBundle() {
- return framework.getBundle(0);
- }
-
- public void refreshBundles(Collection<Bundle> bundles, FrameworkListener... listeners) {
- refreshPackages(bundles == null ? null : bundles.toArray(new Bundle[bundles.size()]), false, listeners);
- }
-
- public boolean resolveBundles(Collection<Bundle> bundles) {
- return resolveBundles(bundles == null ? null : bundles.toArray(new Bundle[bundles.size()]));
- }
-
- public Collection<Bundle> getRemovalPendingBundles() {
- // TODO need to consolidate our removal pending tracking.
- // We currently have three places this is kept (PackageAdminImpl, StateImpl and ResolverImpl)
- // Using the state's because it has easy access to the uninstalled Bundle objects
- BundleDescription[] removals = framework.adaptor.getState().getRemovalPending();
- Set<Bundle> result = new HashSet<Bundle>();
- for (int i = 0; i < removals.length; i++) {
- Object ref = removals[i].getUserObject();
- if (ref instanceof BundleReference)
- result.add(((BundleReference) ref).getBundle());
- }
- return result;
- }
-
- public Collection<Bundle> getDependencyClosure(Collection<Bundle> bundles) {
- Collection<BundleDescription> descriptions = getDescriptionClosure(bundles);
- Set<Bundle> result = new HashSet<Bundle>();
- for (BundleDescription description : descriptions) {
- Object userObject = description.getUserObject();
- if (userObject instanceof BundleReference) {
- Bundle bundle = ((BundleReference) userObject).getBundle();
- if (bundle != null)
- result.add(bundle);
- }
- }
- return result;
- }
-
- private Collection<BundleDescription> getDescriptionClosure(Collection<Bundle> bundles) {
- State state = framework.adaptor.getState();
- Collection<BundleDescription> descriptions = new ArrayList<BundleDescription>();
- for (Bundle bundle : bundles) {
- BundleDescription description = state.getBundle(bundle.getBundleId());
- if (description != null)
- descriptions.add(description);
- }
- return state.getDependencyClosure(descriptions);
- }
-
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/StartLevelEvent.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/StartLevelEvent.java
deleted file mode 100644
index 10636bc64..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/StartLevelEvent.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.framework.internal.core;
-
-import java.util.EventObject;
-import org.osgi.framework.FrameworkListener;
-
-/**
- * StartLevel Event for the OSGi framework.
- *
- * Event which signifies that a start level change has been requested for the framework or for a bundle.
- *
- */
-class StartLevelEvent extends EventObject {
- private static final long serialVersionUID = 3258125839085155891L;
- public final static int CHANGE_BUNDLE_SL = 0x00000000;
- public final static int CHANGE_FW_SL = 0x00000001;
-
- /**
- * Event Type
- */
- private final transient int type;
-
- /**
- * StartLevel - value depends on event type:
- * CHANGE_BUNDLE_SL - value is the new bundle startlevel
- * CHANGE_FW_SL - value is the new framework startlevel
- *
- */
- private final transient int newSl;
-
- /**
- * For a change in bundle startlevel, this is the bundle to be changed.
- * For a change in framework startlevel, this is the bundle requesting the change.
- */
- private final transient AbstractBundle bundle;
-
- /**
- * A list of framework listeners that must be called at the end of the operation.
- */
- private final transient FrameworkListener[] listeners;
-
- /**
- * Creates a StartLevel event regarding the specified bundle.
- *
- * @param type The type of startlevel event (inc or dec)
- * @param newSl the ultimate requested startlevel we are on our way to
- * @param bundle The affected bundle, or system bundle if it is for the framework
- */
- public StartLevelEvent(int type, int newSl, AbstractBundle bundle, FrameworkListener... listeners) {
- super(bundle);
- this.type = type;
- this.newSl = newSl;
- this.bundle = bundle;
- this.listeners = listeners;
- }
-
- public int getType() {
- return this.type;
- }
-
- public int getNewSL() {
- return this.newSl;
- }
-
- public AbstractBundle getBundle() {
- return this.bundle;
- }
-
- public FrameworkListener[] getListeners() {
- return listeners;
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/StartLevelManager.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/StartLevelManager.java
deleted file mode 100644
index efd697c99..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/StartLevelManager.java
+++ /dev/null
@@ -1,678 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2011 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.framework.internal.core;
-
-import java.io.IOException;
-import java.security.*;
-import java.util.*;
-import org.eclipse.osgi.framework.debug.Debug;
-import org.eclipse.osgi.framework.eventmgr.*;
-import org.eclipse.osgi.service.resolver.BundleDescription;
-import org.eclipse.osgi.util.NLS;
-import org.osgi.framework.*;
-import org.osgi.service.startlevel.StartLevel;
-
-/**
- * StartLevel service implementation for the OSGi specification.
- *
- * Framework service which allows management of framework and bundle startlevels.
- *
- * This class also acts as the StartLevel service factory class, providing StartLevel objects
- * to those requesting org.osgi.service.startlevel.StartLevel service.
- *
- * If present, there will only be a single instance of this service
- * registered in the framework.
- */
-public class StartLevelManager implements EventDispatcher<Object, Object, StartLevelEvent>, StartLevel {
- protected static EventManager eventManager;
- protected static Map<Object, Object> startLevelListeners;
-
- /** The initial bundle start level for newly installed bundles */
- protected int initialBundleStartLevel = 1;
- // default value is 1 for compatibility mode
-
- /** The currently active framework start level */
- private int activeSL = 0;
-
- /** An object used to lock the active startlevel while it is being referenced */
- private final Object lock = new Object();
- private final Framework framework;
-
- /** This constructor is called by the Framework */
- protected StartLevelManager(Framework framework) {
- this.framework = framework;
- }
-
- protected void initialize() {
- initialBundleStartLevel = framework.adaptor.getInitialBundleStartLevel();
-
- // create an event manager and a start level listener
- // note that we do not pass the ContextFinder because it is set each time doSetStartLevel is called
- eventManager = new EventManager("Start Level Event Dispatcher"); //$NON-NLS-1$
- startLevelListeners = new CopyOnWriteIdentityMap<Object, Object>();
- startLevelListeners.put(this, this);
- }
-
- protected void cleanup() {
- eventManager.close();
- eventManager = null;
- startLevelListeners.clear();
- startLevelListeners = null;
- }
-
- /**
- * Return the initial start level value that is assigned
- * to a Bundle when it is first installed.
- *
- * @return The initial start level value for Bundles.
- * @see #setInitialBundleStartLevel
- */
- public int getInitialBundleStartLevel() {
- return initialBundleStartLevel;
- }
-
- /**
- * Set the initial start level value that is assigned
- * to a Bundle when it is first installed.
- *
- * <p>The initial bundle start level will be set to the specified start level. The
- * initial bundle start level value will be persistently recorded
- * by the Framework.
- *
- * <p>When a Bundle is installed via <tt>BundleContext.installBundle</tt>,
- * it is assigned the initial bundle start level value.
- *
- * <p>The default initial bundle start level value is 1
- * unless this method has been
- * called to assign a different initial bundle
- * start level value.
- *
- * <p>This method does not change the start level values of installed
- * bundles.
- *
- * @param startlevel The initial start level for newly installed bundles.
- * @throws IllegalArgumentException If the specified start level is less than or
- * equal to zero.
- * @throws SecurityException if the caller does not have the
- * <tt>AdminPermission</tt> and the Java runtime environment supports
- * permissions.
- */
- public void setInitialBundleStartLevel(int startlevel) {
- framework.checkAdminPermission(framework.systemBundle, AdminPermission.STARTLEVEL);
- if (startlevel <= 0) {
- throw new IllegalArgumentException();
- }
- initialBundleStartLevel = startlevel;
- framework.adaptor.setInitialBundleStartLevel(startlevel);
- }
-
- /**
- * Return the active start level value of the Framework.
- *
- * If the Framework 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.
- */
- public int getStartLevel() {
- return activeSL;
- }
-
- /**
- * Modify the active start level of the Framework.
- *
- * <p>The Framework will move to the requested start level. This method
- * will return immediately to the caller and the start level
- * change will occur asynchronously on another thread.
- *
- * <p>If the specified start level is
- * higher than the active start level, the
- * Framework will continue to increase the start level
- * until the Framework has reached the specified start level,
- * starting bundles at each
- * start level which are persistently marked to be started as described in the
- * <tt>Bundle.start</tt> method.
- *
- * At each intermediate start level value on the
- * way to and including the target start level, the framework must:
- * <ol>
- * <li>Change the active start level to the intermediate start level value.
- * <li>Start bundles at the intermediate start level in
- * ascending order by <tt>Bundle.getBundleId</tt>.
- * </ol>
- * When this process completes after the specified start level is reached,
- * the Framework will broadcast a Framework event of
- * type <tt>FrameworkEvent.STARTLEVEL_CHANGED</tt> to announce it has moved to the specified
- * start level.
- *
- * <p>If the specified start level is lower than the active start level, the
- * Framework will continue to decrease the start level
- * until the Framework has reached the specified start level
- * stopping bundles at each
- * start level as described in the <tt>Bundle.stop</tt> method except that their
- * persistently recorded state indicates that they must be restarted in the
- * future.
- *
- * At each intermediate start level value on the
- * way to and including the specified start level, the framework must:
- * <ol>
- * <li>Stop bundles at the intermediate start level in
- * descending order by <tt>Bundle.getBundleId</tt>.
- * <li>Change the active start level to the intermediate start level value.
- * </ol>
- * When this process completes after the specified start level is reached,
- * the Framework will broadcast a Framework event of
- * type <tt>FrameworkEvent.STARTLEVEL_CHANGED</tt> to announce it has moved to the specified
- * start level.
- *
- * <p>If the specified start level is equal to the active start level, then
- * no bundles are started or stopped, however, the Framework must broadcast
- * a Framework event of type <tt>FrameworkEvent.STARTLEVEL_CHANGED</tt> to
- * announce it has finished moving to the specified start level. This
- * event may arrive before the this method return.
- *
- * @param newSL The requested start level for the Framework.
- * @throws IllegalArgumentException If the specified start level is less than or
- * equal to zero.
- * @throws SecurityException If the caller does not have the
- * <tt>AdminPermission</tt> and the Java runtime environment supports
- * permissions.
- */
- public void setStartLevel(int newSL, org.osgi.framework.Bundle callerBundle, FrameworkListener... listeners) {
- if (newSL <= 0) {
- throw new IllegalArgumentException(NLS.bind(Msg.STARTLEVEL_EXCEPTION_INVALID_REQUESTED_STARTLEVEL, "" + newSL)); //$NON-NLS-1$
- }
- framework.checkAdminPermission(framework.systemBundle, AdminPermission.STARTLEVEL);
-
- if (Debug.DEBUG_STARTLEVEL) {
- Debug.println("StartLevelImpl: setStartLevel: " + newSL + "; callerBundle = " + callerBundle.getBundleId()); //$NON-NLS-1$ //$NON-NLS-2$
- }
- issueEvent(new StartLevelEvent(StartLevelEvent.CHANGE_FW_SL, newSL, (AbstractBundle) callerBundle, listeners));
-
- }
-
- public void setStartLevel(int newSL) {
- setStartLevel(newSL, framework.systemBundle);
- }
-
- /**
- * Internal method to shut down the framework synchronously by setting the startlevel to zero
- * and calling the StartLevelListener worker calls directly
- *
- * This method does not return until all bundles are stopped and the framework is shut down.
- */
- protected void shutdown() {
- doSetStartLevel(0);
- }
-
- /**
- * Internal worker method to set the startlevel
- *
- * @param newSL start level value
- * @param callerBundle - the bundle initiating the change in start level
- */
- void doSetStartLevel(int newSL, FrameworkListener... listeners) {
- synchronized (lock) {
- ClassLoader previousTCCL = Thread.currentThread().getContextClassLoader();
- ClassLoader contextFinder = framework.getContextFinder();
- if (contextFinder == previousTCCL)
- contextFinder = null;
- else
- Thread.currentThread().setContextClassLoader(contextFinder);
- try {
- int tempSL = activeSL;
- if (newSL > tempSL) {
- boolean launching = tempSL == 0;
- for (int i = tempSL; i < newSL; i++) {
- if (Debug.DEBUG_STARTLEVEL) {
- Debug.println("sync - incrementing Startlevel from " + tempSL); //$NON-NLS-1$
- }
- tempSL++;
- // Note that we must get a new list of installed bundles each time;
- // this is because additional bundles could have been installed from the previous start-level
- incFWSL(i + 1, getInstalledBundles(framework.bundles, false));
- }
- if (launching) {
- framework.systemBundle.state = Bundle.ACTIVE;
- framework.publishBundleEvent(BundleEvent.STARTED, framework.systemBundle);
- framework.publishFrameworkEvent(FrameworkEvent.STARTED, framework.systemBundle, null);
- }
- } else {
- AbstractBundle[] sortedBundles = getInstalledBundles(framework.bundles, true);
- for (int i = tempSL; i > newSL; i--) {
- if (Debug.DEBUG_STARTLEVEL) {
- Debug.println("sync - decrementing Startlevel from " + tempSL); //$NON-NLS-1$
- }
- tempSL--;
- decFWSL(i - 1, sortedBundles);
- }
- if (newSL == 0) {
- // unload all bundles
- unloadAllBundles(framework.bundles);
- stopSystemBundle();
- }
- }
- framework.publishFrameworkEvent(FrameworkEvent.STARTLEVEL_CHANGED, framework.systemBundle, null, listeners);
- if (Debug.DEBUG_STARTLEVEL) {
- Debug.println("StartLevelImpl: doSetStartLevel: STARTLEVEL_CHANGED event published"); //$NON-NLS-1$
- }
- } catch (Error e) {
- framework.publishFrameworkEvent(FrameworkEvent.ERROR, framework.systemBundle, e, listeners);
- throw e;
- } catch (RuntimeException e) {
- framework.publishFrameworkEvent(FrameworkEvent.ERROR, framework.systemBundle, e, listeners);
- throw e;
- } finally {
- if (contextFinder != null)
- Thread.currentThread().setContextClassLoader(previousTCCL);
- }
- }
- }
-
- /**
- * This method is used within the package to save the actual active startlevel value for the framework.
- * Externally the setStartLevel method must be used.
- *
- * @param newSL - the new startlevel to save
- */
- protected void saveActiveStartLevel(int newSL) {
- synchronized (lock) {
- activeSL = newSL;
- }
- }
-
- /**
- * Return the persistent state of the specified bundle.
- *
- * <p>This method returns the persistent state of a bundle.
- * The persistent state of a bundle indicates whether a bundle
- * is persistently marked to be started when it's start level is
- * reached.
- *
- * @return <tt>true</tt> if the bundle is persistently marked to be started,
- * <tt>false</tt> if the bundle is not persistently marked to be started.
- * @exception java.lang.IllegalArgumentException If the specified bundle has been uninstalled.
- */
- public boolean isBundlePersistentlyStarted(org.osgi.framework.Bundle bundle) {
- return ((AbstractBundle) bundle).isPersistentlyStarted();
- }
-
- public boolean isBundleActivationPolicyUsed(Bundle bundle) {
- return ((AbstractBundle) bundle).isActivationPolicyUsed();
- }
-
- /**
- * Return the assigned start level value for the specified Bundle.
- *
- * @param bundle The target bundle.
- * @return The start level value of the specified Bundle.
- * @exception java.lang.IllegalArgumentException If the specified bundle has been uninstalled.
- */
- public int getBundleStartLevel(org.osgi.framework.Bundle bundle) {
- return ((AbstractBundle) bundle).getStartLevel();
- }
-
- /**
- * Assign a start level value to the specified Bundle.
- *
- * <p>The specified bundle will be assigned the specified start level. The
- * start level value assigned to the bundle will be persistently recorded
- * by the Framework.
- *
- * If the new start level for the bundle is lower than or equal to the active start level of
- * the Framework, the Framework will start the specified bundle as described
- * in the <tt>Bundle.start</tt> method if the bundle is persistently marked
- * to be started. The actual starting of this bundle must occur asynchronously.
- *
- * If the new start level for the bundle is higher than the active start level of
- * the Framework, the Framework will stop the specified bundle as described
- * in the <tt>Bundle.stop</tt> method except that the persistently recorded
- * state for the bundle indicates that the bundle must be restarted in the
- * future. The actual stopping of this bundle must occur asynchronously.
- *
- * @param bundle The target bundle.
- * @param newSL The new start level for the specified Bundle.
- * @throws IllegalArgumentException
- * If the specified bundle has been uninstalled or
- * if the specified start level is less than or equal to zero, or the specified bundle is
- * the system bundle.
- * @throws SecurityException if the caller does not have the
- * <tt>AdminPermission</tt> and the Java runtime environment supports
- * permissions.
- */
- public void setBundleStartLevel(org.osgi.framework.Bundle bundle, int newSL) {
-
- String exceptionText = null;
- if (bundle.getBundleId() == 0) { // system bundle has id=0
- exceptionText = Msg.STARTLEVEL_CANT_CHANGE_SYSTEMBUNDLE_STARTLEVEL;
- } else if (bundle.getState() == Bundle.UNINSTALLED) {
- exceptionText = NLS.bind(Msg.BUNDLE_UNINSTALLED_EXCEPTION, ((AbstractBundle) bundle).getBundleData().getLocation());
- } else if (newSL <= 0) {
- exceptionText = NLS.bind(Msg.STARTLEVEL_EXCEPTION_INVALID_REQUESTED_STARTLEVEL, "" + newSL); //$NON-NLS-1$
- }
- if (exceptionText != null)
- throw new IllegalArgumentException(exceptionText);
- // first check the permission of the caller
- framework.checkAdminPermission(bundle, AdminPermission.EXECUTE);
- try {
- // if the bundle's startlevel is not already at the requested startlevel
- if (newSL != ((org.eclipse.osgi.framework.internal.core.AbstractBundle) bundle).getInternalStartLevel()) {
- final AbstractBundle b = (AbstractBundle) bundle;
- b.getBundleData().setStartLevel(newSL);
- try {
- AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
- public Object run() throws Exception {
- b.getBundleData().save();
- return null;
- }
- });
- } catch (PrivilegedActionException e) {
- if (e.getException() instanceof IOException) {
- throw (IOException) e.getException();
- }
- throw (RuntimeException) e.getException();
- }
- // handle starting or stopping the bundle asynchronously
- issueEvent(new StartLevelEvent(StartLevelEvent.CHANGE_BUNDLE_SL, newSL, (AbstractBundle) bundle));
- }
- } catch (IOException e) {
- framework.publishFrameworkEvent(FrameworkEvent.ERROR, bundle, e);
- }
-
- }
-
- /**
- * This method sends the StartLevelEvent to the EventManager for dispatching
- *
- * @param sle The event to be queued to the Event Manager
- */
- private void issueEvent(StartLevelEvent sle) {
-
- /* queue to hold set of listeners */
- ListenerQueue<Object, Object, StartLevelEvent> queue = new ListenerQueue<Object, Object, StartLevelEvent>(eventManager);
-
- /* add set of StartLevelListeners to queue */
- queue.queueListeners(startLevelListeners.entrySet(), this);
-
- /* dispatch event to set of listeners */
- queue.dispatchEventAsynchronous(sle.getType(), sle);
- }
-
- /**
- * This method is the call back that is called once for each listener.
- * This method must cast the EventListener object to the appropriate listener
- * class for the event type and call the appropriate listener method.
- *
- * @param listener This listener must be cast to the appropriate listener
- * class for the events created by this source and the appropriate listener method
- * must then be called.
- * @param listenerObject This is the optional object that was passed to
- * EventListeners.addListener when the listener was added to the EventListeners.
- * @param eventAction This value was passed to the ListenerQueue object via one of its
- * dispatchEvent* method calls. It can provide information (such
- * as which listener method to call) so that this method
- * can complete the delivery of the event to the listener.
- * @param event This object was passed to the ListenerQueue object via one of its
- * dispatchEvent* method calls. This object was created by the event source and
- * is passed to this method. It should contain all the necessary information (such
- * as what event object to pass) so that this method
- * can complete the delivery of the event to the listener.
- */
- public void dispatchEvent(Object listener, Object listenerObject, int eventAction, StartLevelEvent event) {
- try {
- switch (eventAction) {
- case StartLevelEvent.CHANGE_BUNDLE_SL :
- setBundleSL(event);
- break;
- case StartLevelEvent.CHANGE_FW_SL :
- doSetStartLevel(event.getNewSL(), event.getListeners());
- break;
- }
- } catch (Throwable t) {
- // allow the adaptor to handle this unexpected error
- framework.adaptor.handleRuntimeError(t);
- }
- }
-
- /**
- * Increment the active startlevel by one
- */
- protected void incFWSL(int incToSL, AbstractBundle[] launchBundles) {
- if (Debug.DEBUG_STARTLEVEL) {
- Debug.println("SLL: incFWSL: saving activeSL of " + incToSL); //$NON-NLS-1$
- }
- // save the startlevel
- saveActiveStartLevel(incToSL);
- // resume all bundles at the startlevel
- resumeBundles(launchBundles, incToSL);
- }
-
- /**
- * Build an array of all installed bundles to be launch.
- * The returned array is sorted by increasing startlevel/id order.
- * @param bundles - the bundles installed in the framework
- * @return A sorted array of bundles
- */
- AbstractBundle[] getInstalledBundles(BundleRepository bundles, boolean sortByDependency) {
-
- /* make copy of bundles vector in case it is modified during launch */
- AbstractBundle[] installedBundles;
-
- synchronized (bundles) {
- List<AbstractBundle> allBundles = bundles.getBundles();
- installedBundles = new AbstractBundle[allBundles.size()];
- allBundles.toArray(installedBundles);
-
- /* sort bundle array in ascending startlevel / bundle id order
- * so that bundles are started in ascending order.
- */
- Util.sort(installedBundles, 0, installedBundles.length);
- if (sortByDependency)
- sortByDependency(installedBundles);
- }
- return installedBundles;
- }
-
- void sortByDependency(AbstractBundle[] bundles) {
- synchronized (framework.bundles) {
- if (bundles.length <= 1)
- return;
- int currentSL = bundles[0].getInternalStartLevel();
- int currentSLindex = 0;
- boolean lazy = false;
- for (int i = 0; i < bundles.length; i++) {
- if (currentSL != bundles[i].getInternalStartLevel()) {
- if (lazy)
- sortByDependencies(bundles, currentSLindex, i);
- currentSL = bundles[i].getInternalStartLevel();
- currentSLindex = i;
- lazy = false;
- }
- lazy |= (bundles[i].getBundleData().getStatus() & Constants.BUNDLE_LAZY_START) != 0;
- }
- // sort the last set of bundles
- if (lazy)
- sortByDependencies(bundles, currentSLindex, bundles.length);
- }
- }
-
- private void sortByDependencies(AbstractBundle[] bundles, int start, int end) {
- if (end - start <= 1)
- return;
- List<BundleDescription> descList = new ArrayList<BundleDescription>(end - start);
- List<AbstractBundle> missingDescs = new ArrayList<AbstractBundle>(0);
- for (int i = start; i < end; i++) {
- BundleDescription desc = bundles[i].getBundleDescription();
- if (desc != null)
- descList.add(desc);
- else
- missingDescs.add(bundles[i]);
- }
- if (descList.size() <= 1)
- return;
- BundleDescription[] descriptions = descList.toArray(new BundleDescription[descList.size()]);
- framework.adaptor.getPlatformAdmin().getStateHelper().sortBundles(descriptions);
- for (int i = start; i < descriptions.length + start; i++)
- bundles[i] = framework.bundles.getBundle(descriptions[i - start].getBundleId());
- if (missingDescs.size() > 0) {
- Iterator<AbstractBundle> missing = missingDescs.iterator();
- for (int i = start + descriptions.length; i < end && missing.hasNext(); i++)
- bundles[i] = missing.next();
- }
- }
-
- /**
- * Resume all bundles in the launch list at the specified start-level
- * @param launch a list of Bundle Objects to launch
- * @param currentSL the current start-level that the bundles must meet to be resumed
- */
- private void resumeBundles(AbstractBundle[] launch, int currentSL) {
- // Resume all bundles that were previously started and whose startlevel is <= the active startlevel
- // first resume the lazy activated bundles
- resumeBundles(launch, true, currentSL);
- // now resume all non lazy bundles
- resumeBundles(launch, false, currentSL);
- }
-
- private void resumeBundles(AbstractBundle[] launch, boolean lazyOnly, int currentSL) {
- for (int i = 0; i < launch.length && !framework.isForcedRestart(); i++) {
- int bsl = launch[i].getInternalStartLevel();
- if (bsl < currentSL) {
- // skip bundles who should have already been started
- continue;
- } else if (bsl == currentSL) {
- if (Debug.DEBUG_STARTLEVEL) {
- Debug.println("SLL: Active sl = " + currentSL + "; Bundle " + launch[i].getBundleId() + " sl = " + bsl); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- boolean isLazyStart = launch[i].isLazyStart();
- if (lazyOnly ? isLazyStart : !isLazyStart)
- framework.resumeBundle(launch[i]);
- } else {
- // can stop resuming bundles since any remaining bundles have a greater startlevel than the framework active startlevel
- break;
- }
- }
- }
-
- /**
- * Decrement the active startlevel by one
- * @param decToSL - the startlevel value to set the framework to
- */
- protected void decFWSL(int decToSL, AbstractBundle[] shutdown) {
- if (Debug.DEBUG_STARTLEVEL) {
- Debug.println("SLL: decFWSL: saving activeSL of " + decToSL); //$NON-NLS-1$
- }
-
- saveActiveStartLevel(decToSL);
-
- // just decrementing the active startlevel - framework is not shutting down
- // Do not check framework.isForcedRestart here because we want to stop the active bundles regardless.
- for (int i = shutdown.length - 1; i >= 0; i--) {
- int bsl = shutdown[i].getInternalStartLevel();
- if (bsl > decToSL + 1)
- // skip bundles who should have already been stopped
- continue;
- else if (bsl <= decToSL)
- // stopped all bundles we are going to for this start level
- break;
- else if (shutdown[i].isActive()) {
- // if bundle is active or starting, then stop the bundle
- if (Debug.DEBUG_STARTLEVEL)
- Debug.println("SLL: stopping bundle " + shutdown[i].getBundleId()); //$NON-NLS-1$
- framework.suspendBundle(shutdown[i], false);
- }
- }
- }
-
- /**
- * Stops the system bundle
- */
- private void stopSystemBundle() {
- try {
- framework.systemBundle.context.stop();
- } catch (BundleException sbe) {
- if (Debug.DEBUG_STARTLEVEL) {
- Debug.println("SLL: Bundle suspend exception: " + sbe.getMessage()); //$NON-NLS-1$
- Debug.printStackTrace(sbe.getNestedException() == null ? sbe : sbe.getNestedException());
- }
-
- framework.publishFrameworkEvent(FrameworkEvent.ERROR, framework.systemBundle, sbe);
- }
-
- framework.systemBundle.state = Bundle.RESOLVED;
- framework.publishBundleEvent(BundleEvent.STOPPED, framework.systemBundle);
- }
-
- /**
- * Unloads all bundles in the vector passed in.
- * @param bundles list of Bundle objects to be unloaded
- */
- private void unloadAllBundles(BundleRepository bundles) {
- synchronized (bundles) {
- /* unload all installed bundles */
- List<AbstractBundle> allBundles = bundles.getBundles();
- int size = allBundles.size();
-
- for (int i = 0; i < size; i++) {
- AbstractBundle bundle = allBundles.get(i);
-
- if (Debug.DEBUG_STARTLEVEL) {
- Debug.println("SLL: Trying to unload bundle " + bundle); //$NON-NLS-1$
- }
- bundle.refresh();
- try {
- // make sure we close all the bundle data objects
- bundle.getBundleData().close();
- } catch (IOException e) {
- // ignore, we are shutting down anyway
- }
- }
- }
- }
-
- /**
- * Set the bundle's startlevel to the new value
- * This may cause the bundle to start or stop based on the active framework startlevel
- * @param startLevelEvent - the event requesting change in bundle startlevel
- */
- protected void setBundleSL(StartLevelEvent startLevelEvent) {
- synchronized (lock) {
- int currentSL = getStartLevel();
- int newSL = startLevelEvent.getNewSL();
- AbstractBundle bundle = startLevelEvent.getBundle();
-
- if (Debug.DEBUG_STARTLEVEL) {
- Debug.print("SLL: bundle active=" + bundle.isActive()); //$NON-NLS-1$
- Debug.print("; newSL = " + newSL); //$NON-NLS-1$
- Debug.println("; activeSL = " + currentSL); //$NON-NLS-1$
- }
-
- if (bundle.isActive() && (newSL > currentSL)) {
- if (Debug.DEBUG_STARTLEVEL) {
- Debug.println("SLL: stopping bundle " + bundle.getBundleId()); //$NON-NLS-1$
- }
- framework.suspendBundle(bundle, false);
- } else {
- if (!bundle.isActive() && (newSL <= currentSL)) {
- if (Debug.DEBUG_STARTLEVEL) {
- Debug.println("SLL: starting bundle " + bundle.getBundleId()); //$NON-NLS-1$
- }
- framework.resumeBundle(bundle);
- }
- }
- if (Debug.DEBUG_STARTLEVEL) {
- Debug.println("SLL: Bundle Startlevel set to " + newSL); //$NON-NLS-1$
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/SystemBundleActivator.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/SystemBundleActivator.java
deleted file mode 100644
index f3233207d..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/SystemBundleActivator.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.framework.internal.core;
-
-import java.util.Dictionary;
-import java.util.Hashtable;
-import org.eclipse.osgi.framework.debug.FrameworkDebugOptions;
-import org.eclipse.osgi.internal.resolver.StateImpl;
-import org.eclipse.osgi.service.resolver.State;
-import org.osgi.framework.*;
-import org.osgi.service.condpermadmin.ConditionalPermissionAdmin;
-
-/**
- * This class activates the System Bundle.
- */
-
-public class SystemBundleActivator implements BundleActivator {
- private BundleContext context;
- private InternalSystemBundle bundle;
- private Framework framework;
- private ServiceRegistration<?> packageAdmin;
- private ServiceRegistration<?> securityAdmin;
- private ServiceRegistration<?> startLevel;
- private ServiceRegistration<?> debugOptions;
- private ServiceRegistration<?> contextFinder;
-
- public void start(BundleContext bc) throws Exception {
- this.context = bc;
- bundle = (InternalSystemBundle) bc.getBundle();
- framework = bundle.framework;
-
- if (framework.packageAdmin != null)
- packageAdmin = register(new String[] {Constants.OSGI_PACKAGEADMIN_NAME}, framework.packageAdmin, null);
- if (framework.securityAdmin != null)
- securityAdmin = register(new String[] {Constants.OSGI_PERMISSIONADMIN_NAME, ConditionalPermissionAdmin.class.getName()}, framework.securityAdmin, null);
- if (framework.startLevelManager != null)
- startLevel = register(new String[] {Constants.OSGI_STARTLEVEL_NAME}, framework.startLevelManager, null);
- FrameworkDebugOptions dbgOptions = null;
- if ((dbgOptions = FrameworkDebugOptions.getDefault()) != null) {
- dbgOptions.start(bc);
- debugOptions = register(new String[] {org.eclipse.osgi.service.debug.DebugOptions.class.getName()}, dbgOptions, null);
- }
- ClassLoader tccl = framework.getContextFinder();
- if (tccl != null) {
- Dictionary<String, Object> props = new Hashtable<String, Object>(7);
- props.put("equinox.classloader.type", "contextClassLoader"); //$NON-NLS-1$ //$NON-NLS-2$
- contextFinder = register(new String[] {ClassLoader.class.getName()}, tccl, props);
- }
-
- // Always call the adaptor.frameworkStart() at the end of this method.
- framework.adaptor.frameworkStart(bc);
- State state = framework.adaptor.getState();
- if (state instanceof StateImpl)
- ((StateImpl) state).setResolverHookFactory(new CoreResolverHookFactory((BundleContextImpl) context, framework.getServiceRegistry()));
- // attempt to resolve all bundles
- // this is done after the adaptor.frameworkStart has been called
- // this should be the first time the resolver State is accessed
- framework.packageAdmin.setResolvedBundles(bundle);
- // reinitialize the system bundles localization to take into account system bundle fragments
- framework.systemBundle.manifestLocalization = null;
- }
-
- public void stop(BundleContext bc) throws Exception {
- // Always call the adaptor.frameworkStop() at the begining of this method.
- framework.adaptor.frameworkStop(bc);
-
- if (packageAdmin != null)
- packageAdmin.unregister();
- if (securityAdmin != null)
- securityAdmin.unregister();
- if (startLevel != null)
- startLevel.unregister();
- if (debugOptions != null) {
- FrameworkDebugOptions dbgOptions = FrameworkDebugOptions.getDefault();
- if (dbgOptions != null)
- dbgOptions.stop(bc);
- debugOptions.unregister();
- }
- if (contextFinder != null)
- contextFinder.unregister();
-
- framework = null;
- bundle = null;
- this.context = null;
- }
-
- /**
- * Register a service object.
- *
- */
- private ServiceRegistration<?> register(String[] names, Object service, Dictionary<String, Object> properties) {
- if (properties == null)
- properties = new Hashtable<String, Object>(7);
- Dictionary<String, String> headers = bundle.getHeaders();
- properties.put(Constants.SERVICE_VENDOR, headers.get(Constants.BUNDLE_VENDOR));
- properties.put(Constants.SERVICE_RANKING, new Integer(Integer.MAX_VALUE));
- properties.put(Constants.SERVICE_PID, bundle.getBundleId() + "." + service.getClass().getName()); //$NON-NLS-1$
- return context.registerService(names, service, properties);
- }
-
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/UniversalUniqueIdentifier.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/UniversalUniqueIdentifier.java
deleted file mode 100644
index abeab38b1..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/UniversalUniqueIdentifier.java
+++ /dev/null
@@ -1,270 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2011 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.osgi.framework.internal.core;
-
-import java.io.*;
-import java.math.BigInteger;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.security.SecureRandom;
-import java.util.GregorianCalendar;
-import java.util.Random;
-
-public class UniversalUniqueIdentifier {
-
- /* INSTANCE FIELDS =============================================== */
-
- private byte[] fBits = new byte[BYTES_SIZE];
-
- /* NON-FINAL PRIVATE STATIC FIELDS =============================== */
-
- private volatile static BigInteger fgPreviousClockValue;
- private volatile static int fgClockAdjustment = 0;
- private volatile static int fgClockSequence = -1;
- private final static byte[] nodeAddress;
-
- static {
- nodeAddress = computeNodeAddress();
- }
-
- /* PRIVATE STATIC FINAL FIELDS =================================== */
-
- private final static Random fgRandomNumberGenerator = new Random();
-
- /* PUBLIC STATIC FINAL FIELDS ==================================== */
-
- public static final int BYTES_SIZE = 16;
- public static final byte[] UNDEFINED_UUID_BYTES = new byte[16];
- public static final int MAX_CLOCK_SEQUENCE = 0x4000;
- public static final int MAX_CLOCK_ADJUSTMENT = 0x7FFF;
- public static final int TIME_FIELD_START = 0;
- public static final int TIME_FIELD_STOP = 6;
- public static final int TIME_HIGH_AND_VERSION = 7;
- public static final int CLOCK_SEQUENCE_HIGH_AND_RESERVED = 8;
- public static final int CLOCK_SEQUENCE_LOW = 9;
- public static final int NODE_ADDRESS_START = 10;
- public static final int NODE_ADDRESS_BYTE_SIZE = 6;
-
- public static final int BYTE_MASK = 0xFF;
-
- public static final int HIGH_NIBBLE_MASK = 0xF0;
-
- public static final int LOW_NIBBLE_MASK = 0x0F;
-
- public static final int SHIFT_NIBBLE = 4;
-
- public static final int ShiftByte = 8;
-
- /**
- UniversalUniqueIdentifier default constructor returns a
- new instance that has been initialized to a unique value.
- */
- public UniversalUniqueIdentifier() {
- this.setVersion(1);
- this.setVariant(1);
- this.setTimeValues();
- this.setNode(getNodeAddress());
- }
-
- private void appendByteString(StringBuffer buffer, byte value) {
- String hexString;
-
- if (value < 0)
- hexString = Integer.toHexString(256 + value);
- else
- hexString = Integer.toHexString(value);
- if (hexString.length() == 1)
- buffer.append("0"); //$NON-NLS-1$
- buffer.append(hexString);
- }
-
- private static BigInteger clockValueNow() {
- GregorianCalendar now = new GregorianCalendar();
- BigInteger nowMillis = BigInteger.valueOf(now.getTime().getTime());
- BigInteger baseMillis = BigInteger.valueOf(now.getGregorianChange().getTime());
-
- return (nowMillis.subtract(baseMillis).multiply(BigInteger.valueOf(10000L)));
- }
-
- /**
- * Answers the node address attempting to mask the IP
- * address of this machine.
- *
- * @return byte[] the node address
- */
- private static byte[] computeNodeAddress() {
-
- byte[] address = new byte[NODE_ADDRESS_BYTE_SIZE];
-
- // Seed the secure randomizer with some oft-varying inputs
- int thread = Thread.currentThread().hashCode();
- long time = System.currentTimeMillis();
- int objectId = System.identityHashCode(new String());
- ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
- DataOutputStream out = new DataOutputStream(byteOut);
- byte[] ipAddress = getIPAddress();
-
- try {
- if (ipAddress != null)
- out.write(ipAddress);
- out.write(thread);
- out.writeLong(time);
- out.write(objectId);
- out.close();
- } catch (IOException exc) {
- //ignore the failure, we're just trying to come up with a random seed
- }
- byte[] rand = byteOut.toByteArray();
-
- SecureRandom randomizer = new SecureRandom(rand);
- randomizer.nextBytes(address);
-
- // set the MSB of the first octet to 1 to distinguish from IEEE node addresses
- address[0] = (byte) (address[0] | (byte) 0x80);
-
- return address;
- }
-
- /**
- Answers the IP address of the local machine using the
- Java API class <code>InetAddress</code>.
-
- @return byte[] the network address in network order
- @see java.net.InetAddress#getLocalHost()
- @see java.net.InetAddress#getAddress()
- */
- private static byte[] getIPAddress() {
- try {
- return InetAddress.getLocalHost().getAddress();
- } catch (UnknownHostException e) {
- //valid for this to be thrown be a machine with no IP connection
- //It is VERY important NOT to throw this exception
- return null;
- } catch (ArrayIndexOutOfBoundsException e) {
- // there appears to be a bug in the VM if there is an alias
- // see bug 354820. As above it is important not to throw this
- return null;
- }
- }
-
- private static byte[] getNodeAddress() {
- return nodeAddress;
- }
-
- private static int nextClockSequence() {
-
- if (fgClockSequence == -1)
- fgClockSequence = (int) (fgRandomNumberGenerator.nextDouble() * MAX_CLOCK_SEQUENCE);
-
- fgClockSequence = (fgClockSequence + 1) % MAX_CLOCK_SEQUENCE;
-
- return fgClockSequence;
- }
-
- private static BigInteger nextTimestamp() {
-
- BigInteger timestamp = clockValueNow();
- int timestampComparison;
-
- timestampComparison = timestamp.compareTo(fgPreviousClockValue);
-
- if (timestampComparison == 0) {
- if (fgClockAdjustment == MAX_CLOCK_ADJUSTMENT) {
- while (timestamp.compareTo(fgPreviousClockValue) == 0)
- timestamp = clockValueNow();
- timestamp = nextTimestamp();
- } else
- fgClockAdjustment++;
- } else {
- fgClockAdjustment = 0;
-
- if (timestampComparison < 0)
- nextClockSequence();
- }
-
- return timestamp;
- }
-
- private void setClockSequence(int clockSeq) {
- int clockSeqHigh = (clockSeq >>> ShiftByte) & LOW_NIBBLE_MASK;
- int reserved = fBits[CLOCK_SEQUENCE_HIGH_AND_RESERVED] & HIGH_NIBBLE_MASK;
-
- fBits[CLOCK_SEQUENCE_HIGH_AND_RESERVED] = (byte) (reserved | clockSeqHigh);
- fBits[CLOCK_SEQUENCE_LOW] = (byte) (clockSeq & BYTE_MASK);
- }
-
- private void setNode(byte[] bytes) {
-
- for (int index = 0; index < NODE_ADDRESS_BYTE_SIZE; index++)
- fBits[index + NODE_ADDRESS_START] = bytes[index];
- }
-
- private void setTimestamp(BigInteger timestamp) {
- BigInteger value = timestamp;
- BigInteger bigByte = BigInteger.valueOf(256L);
- BigInteger[] results;
- int version;
- int timeHigh;
-
- for (int index = TIME_FIELD_START; index < TIME_FIELD_STOP; index++) {
- results = value.divideAndRemainder(bigByte);
- value = results[0];
- fBits[index] = (byte) results[1].intValue();
- }
- version = fBits[TIME_HIGH_AND_VERSION] & HIGH_NIBBLE_MASK;
- timeHigh = value.intValue() & LOW_NIBBLE_MASK;
- fBits[TIME_HIGH_AND_VERSION] = (byte) (timeHigh | version);
- }
-
- private synchronized void setTimeValues() {
- this.setTimestamp(timestamp());
- this.setClockSequence(fgClockSequence);
- }
-
- private int setVariant(int variantIdentifier) {
- int clockSeqHigh = fBits[CLOCK_SEQUENCE_HIGH_AND_RESERVED] & LOW_NIBBLE_MASK;
- int variant = variantIdentifier & LOW_NIBBLE_MASK;
-
- fBits[CLOCK_SEQUENCE_HIGH_AND_RESERVED] = (byte) ((variant << SHIFT_NIBBLE) | clockSeqHigh);
- return (variant);
- }
-
- private void setVersion(int versionIdentifier) {
- int timeHigh = fBits[TIME_HIGH_AND_VERSION] & LOW_NIBBLE_MASK;
- int version = versionIdentifier & LOW_NIBBLE_MASK;
-
- fBits[TIME_HIGH_AND_VERSION] = (byte) (timeHigh | (version << SHIFT_NIBBLE));
- }
-
- private static BigInteger timestamp() {
- BigInteger timestamp;
-
- if (fgPreviousClockValue == null) {
- fgClockAdjustment = 0;
- nextClockSequence();
- timestamp = clockValueNow();
- } else
- timestamp = nextTimestamp();
-
- fgPreviousClockValue = timestamp;
- return fgClockAdjustment == 0 ? timestamp : timestamp.add(BigInteger.valueOf(fgClockAdjustment));
- }
-
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- for (int i = 0; i < fBits.length; i++) {
- if (i == 4 || i == 6 || i == 8 || i == 10)
- buffer.append('-');
- appendByteString(buffer, fBits[i]);
- }
- return buffer.toString();
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/Util.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/Util.java
deleted file mode 100644
index 63ccfd2d7..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/Util.java
+++ /dev/null
@@ -1,208 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.framework.internal.core;
-
-/**
- * This class contains utility functions.
- */
-public class Util {
- /**
- * Performs a quicksort of the given objects
- * by their string representation in ascending order.
- * <p>
- *
- * @param array The array of objects to sort
- */
- public static void sortByString(Object[] array) {
- qSortByString(array, 0, array.length - 1);
- }
-
- /**
- * Sorts the array of objects by their string representation
- * in ascending order.
- * <p>
- * This is a version of C.A.R Hoare's Quick Sort algorithm.
- *
- * @param array the array of objects to sort
- * @param start the start index to begin sorting
- * @param stop the end index to stop sorting
- *
- * @exception ArrayIndexOutOfBoundsException when <code>start < 0</code>
- * or <code>end >= array.length</code>
- */
- public static void qSortByString(Object[] array, int start, int stop) {
- if (start >= stop)
- return;
-
- int left = start; // left index
- int right = stop; // right index
- Object temp; // for swapping
-
- // arbitrarily establish a partition element as the midpoint of the array
- String mid = String.valueOf(array[(start + stop) / 2]);
-
- // loop through the array until indices cross
- while (left <= right) {
- // find the first element that is smaller than the partition element from the left
- while ((left < stop) && (String.valueOf(array[left]).compareTo(mid) < 0)) {
- ++left;
- }
- // find an element that is smaller than the partition element from the right
- while ((right > start) && (mid.compareTo(String.valueOf(array[right])) < 0)) {
- --right;
- }
- // if the indices have not crossed, swap
- if (left <= right) {
- temp = array[left];
- array[left] = array[right];
- array[right] = temp;
- ++left;
- --right;
- }
- }
- // sort the left partition, if the right index has not reached the left side of array
- if (start < right) {
- qSortByString(array, start, right);
- }
- // sort the right partition, if the left index has not reached the right side of array
- if (left < stop) {
- qSortByString(array, left, stop);
- }
- }
-
- /**
- * Sorts the specified range in the array in ascending order.
- *
- * @param array the Object array to be sorted
- * @param start the start index to sort
- * @param end the last + 1 index to sort
- *
- * @exception ClassCastException when an element in the array does not
- * implement Comparable or elements cannot be compared to each other
- * @exception IllegalArgumentException when <code>start > end</code>
- * @exception ArrayIndexOutOfBoundsException when <code>start < 0</code>
- * or <code>end > array.size()</code>
- */
- @SuppressWarnings("unchecked")
- public static void sort(Object[] array, int start, int end) {
- int middle = (start + end) / 2;
- if (start + 1 < middle)
- sort(array, start, middle);
- if (middle + 1 < end)
- sort(array, middle, end);
- if (start + 1 >= end)
- return; // this case can only happen when this method is called by the user
- if (((Comparable<Object>) array[middle - 1]).compareTo(array[middle]) <= 0)
- return;
- if (start + 2 == end) {
- Object temp = array[start];
- array[start] = array[middle];
- array[middle] = temp;
- return;
- }
- int i1 = start, i2 = middle, i3 = 0;
- Object[] merge = new Object[end - start];
- while (i1 < middle && i2 < end) {
- merge[i3++] = ((Comparable<Object>) array[i1]).compareTo(array[i2]) <= 0 ? array[i1++] : array[i2++];
- }
- if (i1 < middle)
- System.arraycopy(array, i1, merge, i3, middle - i1);
- System.arraycopy(merge, 0, array, start, i2 - start);
- }
-
- /**
- * Sorts the specified range in the array in descending order.
- *
- * @param array the Object array to be sorted
- * @param start the start index to sort
- * @param end the last + 1 index to sort
- *
- * @exception ClassCastException when an element in the array does not
- * implement Comparable or elements cannot be compared to each other
- * @exception IllegalArgumentException when <code>start > end</code>
- * @exception ArrayIndexOutOfBoundsException when <code>start < 0</code>
- * or <code>end > array.size()</code>
- */
- public static void dsort(Object[] array, int start, int end) {
- // first sort in ascending order
- sort(array, start, end);
- // then swap the elements in the array
- swap(array);
- }
-
- /**
- * Reverse the elements in the array.
- *
- * @param array the Object array to be reversed
- */
- public static void swap(Object[] array) {
- int start = 0;
- int end = array.length - 1;
- while (start < end) {
- Object temp = array[start];
- array[start++] = array[end];
- array[end--] = temp;
- }
- }
-
- /**
- * Returns a string representation of the object
- * in the given length.
- * If the string representation of the given object
- * is longer then it is truncated.
- * If it is shorter then it is padded with the blanks
- * to the given total length.
- * If the given object is a number then the padding
- * is done on the left, otherwise on the right.
- *
- * @param object the object to convert
- * @param length the length the output string
- */
- public static String toString(Object object, int length) {
- boolean onLeft = object instanceof Number;
- return toString(object, length, ' ', onLeft);
- }
-
- /**
- * Returns a string representation of the object
- * in the given length.
- * If the string representation of the given object
- * is longer then it is truncated.
- * If it is shorter then it is padded to the left or right
- * with the given character to the given total length.
- *
- * @param object the object to convert
- * @param length the length the output string
- * @param pad the pad character
- * @param onLeft if <code>true</code> pad on the left, otherwise an the right
- */
- public static String toString(Object object, int length, char pad, boolean onLeft) {
- String input = String.valueOf(object);
- int size = input.length();
- if (size >= length) {
- int start = (onLeft) ? size - length : 0;
- return input.substring(start, length);
- }
-
- StringBuffer padding = new StringBuffer(length - size);
- for (int i = size; i < length; i++)
- padding.append(pad);
-
- StringBuffer stringBuffer = new StringBuffer(length);
- if (onLeft)
- stringBuffer.append(padding.toString());
- stringBuffer.append(input);
- if (!onLeft)
- stringBuffer.append(padding.toString());
- return stringBuffer.toString();
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/osname.aliases b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/osname.aliases
deleted file mode 100644
index 0aff94e32..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/osname.aliases
+++ /dev/null
@@ -1,46 +0,0 @@
-########################################################################
-# Copyright (c) 2003, 2012 IBM Corporation and others.
-# All rights reserved. This program and the accompanying materials
-# are made available under the terms of the Eclipse Public License v1.0
-# which accompanies this distribution, and is available at
-# http://www.eclipse.org/legal/epl-v10.html
-#
-# Contributors:
-# IBM Corporation - initial API and implementation
-########################################################################
-
-# This file must be UTF8 encoded.
-
-#OS Aliases Description
-
-AIX # IBM
-DigitalUnix # Compaq
-embos # Segger Embedded Software Solutions
-Epoc32 SymbianOS # Symbian OS
-FreeBSD # Free BSD
-HPUX # Hewlett Packard
-IRIX # Sillicon Graphics
-Linux # Open source
-MacOS "Mac OS" # Apple
-MacOSX "Mac OS X" # Apple
-NetBSD # Open source
-Netware # Novell
-OpenBSD # Open source
-OS2 OS/2 # IBM
-QNX procnto # QNX Neutrino 2.1
-Solaris # Sun
-SunOS # Sun
-VxWorks # WindRiver Systems
-Windows95 "Windows 95" Win95 Win32 # Microsoft
-Windows98 "Windows 98" Win98 Win32 # Microsoft
-WindowsNT "Windows NT" WinNT Win32 # Microsoft
-WindowsCE "Windows CE" WinCE # Microsoft
-Windows2000 "Windows 2000" Win2000 Win32 # Microsoft
-WindowsXP "Windows XP" WinXP Win32 # Microsoft
-Windows2003 "Windows 2003" "Windows Server 2003" Win2003 Win32 # Microsoft
-WindowsVista WinVista "Windows Vista" Win32 # Microsoft
-Windows2008 "Windows 2008" "Windows Server 2008" Win2008 Win32 # Microsoft
-WindowsServer2008 "Windows 2008" "Windows Server 2008" Win2008 Win32 # Microsoft
-WindowsServer2008R2 "Windows 2008 R2" "Windows Server 2008 R2" Win2008R2 Win32 # Microsoft
-Windows7 "Windows 7" Win7 Win32 # Microsoft
-Windows8 "Windows 8" Win8 Win32 # Microsoft \ No newline at end of file
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/processor.aliases b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/processor.aliases
deleted file mode 100644
index 5fb0ff398..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/processor.aliases
+++ /dev/null
@@ -1,28 +0,0 @@
-########################################################################
-# Copyright (c) 2003, 2005 IBM Corporation and others.
-# All rights reserved. This program and the accompanying materials
-# are made available under the terms of the Eclipse Public License v1.0
-# which accompanies this distribution, and is available at
-# http://www.eclipse.org/legal/epl-v10.html
-#
-# Contributors:
-# IBM Corporation - initial API and implementation
-########################################################################
-
-# This file must be UTF8 encoded.
-
-#Processor Aliases Description
-
-68k # Motorola 68000 and up
-ARM # Intel Strong ARM
-Alpha # Compaq (ex DEC)
-Ignite psc1k # PTSC
-Mips # SGI
-PArisc # Hewlett Packard PA Risc
-PowerPC power ppc # Motorola/IBM Power PC
-Sparc # SUN
-x86 pentium i386 i486 i586 i686 # Intel
-s390 # IBM System 390
-s390x # IBM System 390 (64-bit)
-v850e # NEC V850E
-x86-64 amd64 em64t x86_64 # 64 bit x86 architecture
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/ContentHandlerFactory.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/ContentHandlerFactory.java
deleted file mode 100644
index c84f76da1..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/ContentHandlerFactory.java
+++ /dev/null
@@ -1,163 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.framework.internal.protocol;
-
-import java.lang.reflect.Method;
-import java.net.ContentHandler;
-import java.net.URLConnection;
-import java.util.*;
-import org.eclipse.osgi.framework.adaptor.FrameworkAdaptor;
-import org.eclipse.osgi.framework.internal.core.Msg;
-import org.eclipse.osgi.framework.log.FrameworkLogEntry;
-import org.eclipse.osgi.util.NLS;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.osgi.service.url.URLConstants;
-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.
- */
-// TODO rename this class!!! its really confusing to name the impl the same as the interface
-public class ContentHandlerFactory extends MultiplexingFactory implements java.net.ContentHandlerFactory {
- private ServiceTracker<ContentHandler, ContentHandler> contentHandlerTracker;
-
- private static final String contentHandlerClazz = "java.net.ContentHandler"; //$NON-NLS-1$
- 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"; //$NON-NLS-1$
-
- private static final List<Class<?>> ignoredClasses = Arrays.asList(new Class<?>[] {MultiplexingContentHandler.class, ContentHandlerFactory.class, URLConnection.class});
-
- private Map<String, ContentHandlerProxy> proxies;
- private java.net.ContentHandlerFactory parentFactory;
-
- public ContentHandlerFactory(BundleContext context, FrameworkAdaptor adaptor) {
- super(context, adaptor);
-
- proxies = new Hashtable<String, ContentHandlerProxy>(5);
-
- //We need to track content handler registrations
- contentHandlerTracker = new ServiceTracker<ContentHandler, ContentHandler>(context, contentHandlerClazz, null);
- contentHandlerTracker.open();
- }
-
- /**
- * @see java.net.ContentHandlerFactory#createContentHandler(String)
- */
- //TODO method is too long... consider reducing indentation (returning quickly) and moving complex steps to private methods
- 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
- String builtInHandlers = StreamHandlerFactory.secureAction.getProperty(CONTENT_HANDLER_PKGS);
- 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 '_'.
-
- // find all characters not allowed in java names
- String convertedContentType = contentType.replace('.', '_');
- convertedContentType = convertedContentType.replace('/', '.');
- convertedContentType = convertedContentType.replace('-', '_');
- StringTokenizer tok = new StringTokenizer(builtInHandlers, "|"); //$NON-NLS-1$
- while (tok.hasMoreElements()) {
- StringBuffer name = new StringBuffer();
- name.append(tok.nextToken());
- name.append("."); //$NON-NLS-1$
- name.append(convertedContentType);
- try {
- clazz = StreamHandlerFactory.secureAction.loadSystemClass(name.toString());
- if (clazz != null) {
- return (null); //this class exists, it is a built in handler, let the JVM handle it
- }
- } catch (ClassNotFoundException ex) {
- //keep looking
- }
- }
- }
-
- if (isMultiplexing())
- return new MultiplexingContentHandler(contentType, this);
-
- return createInternalContentHandler(contentType);
- }
-
- public ContentHandler createInternalContentHandler(String contentType) {
- //first check to see if the handler is in the cache
- ContentHandlerProxy proxy = proxies.get(contentType);
- if (proxy != null) {
- return (proxy);
- }
- ServiceReference<ContentHandler>[] serviceReferences = contentHandlerTracker.getServiceReferences();
- if (serviceReferences != null) {
- for (int i = 0; i < serviceReferences.length; i++) {
- Object prop = serviceReferences[i].getProperty(URLConstants.URL_CONTENT_MIMETYPE);
- if (prop instanceof String)
- 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, serviceReferences[i].getBundle()});
- adaptor.getFrameworkLog().log(new FrameworkLogEntry(FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME, FrameworkLogEntry.WARNING, 0, message, 0, null, null));
- continue;
- }
- String[] contentHandler = (String[]) prop;
- for (int j = 0; j < contentHandler.length; j++) {
- if (contentHandler[j].equals(contentType)) {
- proxy = new ContentHandlerProxy(contentType, serviceReferences[i], context);
- proxies.put(contentType, proxy);
- return (proxy);
- }
- }
- }
- }
- // if parent is present do parent lookup before returning a proxy
- if (parentFactory != null) {
- ContentHandler parentHandler = parentFactory.createContentHandler(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.
- proxy = new ContentHandlerProxy(contentType, null, context);
- proxies.put(contentType, proxy);
- return (proxy);
- }
-
- public synchronized ContentHandler findAuthorizedContentHandler(String contentType) {
- Object factory = findAuthorizedFactory(ignoredClasses);
- if (factory == null)
- return null;
-
- if (factory == this)
- 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});
- } catch (Exception e) {
- adaptor.getFrameworkLog().log(new FrameworkLogEntry(ContentHandlerFactory.class.getName(), FrameworkLogEntry.ERROR, 0, "findAuthorizedContentHandler-loop", 0, e, null)); //$NON-NLS-1$
- throw new RuntimeException(e.getMessage(), e);
- }
- }
-
- public Object getParentFactory() {
- return parentFactory;
- }
-
- public void setParentFactory(Object parentFactory) {
- if (this.parentFactory == null) // only allow it to be set once
- this.parentFactory = (java.net.ContentHandlerFactory) parentFactory;
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/ContentHandlerProxy.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/ContentHandlerProxy.java
deleted file mode 100644
index b60b7940c..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/ContentHandlerProxy.java
+++ /dev/null
@@ -1,152 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.framework.internal.protocol;
-
-import java.io.IOException;
-import java.net.ContentHandler;
-import java.net.URLConnection;
-import org.osgi.framework.*;
-import org.osgi.service.url.URLConstants;
-import org.osgi.util.tracker.ServiceTracker;
-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.
- */
-public class ContentHandlerProxy extends ContentHandler implements ServiceTrackerCustomizer<ContentHandler, ServiceReference<ContentHandler>> {
- protected ContentHandler realHandler;
-
- //TODO avoid type-based names
- protected ServiceTracker<ContentHandler, ServiceReference<ContentHandler>> contentHandlerServiceTracker;
-
- protected BundleContext context;
- protected ServiceReference<ContentHandler> contentHandlerServiceReference;
-
- protected String contentType;
-
- protected int ranking = Integer.MIN_VALUE;
-
- public ContentHandlerProxy(String contentType, ServiceReference<ContentHandler> reference, BundleContext context) {
- this.context = context;
- this.contentType = contentType;
-
- // 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));
-
- contentHandlerServiceTracker = new ServiceTracker<ContentHandler, ServiceReference<ContentHandler>>(context, ContentHandler.class.getName(), this);
- StreamHandlerFactory.secureAction.open(contentHandlerServiceTracker);
- }
-
- private void setNewHandler(ServiceReference<ContentHandler> reference, int rank) {
- if (contentHandlerServiceReference != null)
- context.ungetService(contentHandlerServiceReference);
-
- contentHandlerServiceReference = reference;
- ranking = rank;
-
- if (reference == null)
- realHandler = new DefaultContentHandler();
- else
- realHandler = StreamHandlerFactory.secureAction.getService(reference, context);
- }
-
- /**
- * @see org.osgi.util.tracker.ServiceTrackerCustomizer#addingService(ServiceReference)
- */
- public ServiceReference<ContentHandler> addingService(ServiceReference<ContentHandler> reference) {
- //check to see if our contentType is being registered by another service
- Object prop = reference.getProperty(URLConstants.URL_CONTENT_MIMETYPE);
- if (!(prop instanceof String[]))
- return null;
- String[] contentTypes = (String[]) prop;
- for (int i = 0; i < contentTypes.length; i++) {
- if (contentTypes[i].equals(contentType)) {
- //If our contentType is registered by another service, check the service ranking and switch URLStreamHandlers if nessecary.
- int newServiceRanking = getRank(reference);
- if (newServiceRanking > ranking || contentHandlerServiceReference == null)
- setNewHandler(reference, newServiceRanking);
- return (reference);
- }
- }
-
- //we don't want to continue hearing events about a ContentHandler service not registered under our contentType
- return (null);
- }
-
- /**
- * @see org.osgi.util.tracker.ServiceTrackerCustomizer#modifiedService(ServiceReference, Object)
- */
-
- public void modifiedService(ServiceReference<ContentHandler> reference, ServiceReference<ContentHandler> service) {
- 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.
- // this should get us the highest ranked service, if available
- ServiceReference<ContentHandler> newReference = contentHandlerServiceTracker.getServiceReference();
- if (newReference != contentHandlerServiceReference && newReference != null) {
- setNewHandler(newReference, ((Integer) newReference.getProperty(Constants.SERVICE_RANKING)).intValue());
- }
- }
- } else if (newrank > ranking) {
- // the service changed is another URLHandler that we are not currently using
- // If it's ranking is higher, we must swap it in.
- setNewHandler(reference, newrank);
- }
- }
-
- /**
- * @see org.osgi.util.tracker.ServiceTrackerCustomizer#removedService(ServiceReference, Object)
- */
- public void removedService(ServiceReference<ContentHandler> reference, ServiceReference<ContentHandler> service) {
- //check to see if our URLStreamHandler was unregistered.
- if (reference != contentHandlerServiceReference)
- return;
- // If so, look for a lower ranking URLHandler
- // this should get us the highest ranking service left, if available
- ServiceReference<ContentHandler> newReference = contentHandlerServiceTracker.getServiceReference();
- // if newReference == null then we will use the DefaultContentHandler here
- setNewHandler(newReference, getRank(newReference));
- }
-
- /**
- * @see java.net.ContentHandler#getContent(URLConnection)
- */
-
- public Object getContent(URLConnection uConn) throws IOException {
- return realHandler.getContent(uConn);
- }
-
- private int getRank(ServiceReference<?> reference) {
- if (reference == null)
- return Integer.MIN_VALUE;
- Object property = reference.getProperty(Constants.SERVICE_RANKING);
- return (property instanceof Integer) ? ((Integer) property).intValue() : 0;
- }
-
- class DefaultContentHandler extends ContentHandler {
-
- /**
- * @see java.net.ContentHandler#getContent(URLConnection)
- */
- public Object getContent(URLConnection uConn) throws IOException {
- return uConn.getInputStream();
- }
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/MultiplexingContentHandler.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/MultiplexingContentHandler.java
deleted file mode 100644
index 3a49caa9f..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/MultiplexingContentHandler.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006 Cognos Incorporated, IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- *******************************************************************************/
-package org.eclipse.osgi.framework.internal.protocol;
-
-import java.io.IOException;
-import java.net.ContentHandler;
-import java.net.URLConnection;
-
-public class MultiplexingContentHandler extends ContentHandler {
-
- private String contentType;
- private ContentHandlerFactory factory;
-
- public MultiplexingContentHandler(String contentType, ContentHandlerFactory factory) {
- this.contentType = contentType;
- this.factory = factory;
- }
-
- public Object getContent(URLConnection uConn) throws IOException {
- ContentHandler handler = factory.findAuthorizedContentHandler(contentType);
- if (handler != null)
- return handler.getContent(uConn);
-
- return uConn.getInputStream();
- }
-
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/MultiplexingFactory.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/MultiplexingFactory.java
deleted file mode 100644
index 648292324..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/MultiplexingFactory.java
+++ /dev/null
@@ -1,173 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2010 Cognos Incorporated, IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- *******************************************************************************/
-package org.eclipse.osgi.framework.internal.protocol;
-
-import java.lang.reflect.Method;
-import java.util.LinkedList;
-import java.util.List;
-import org.eclipse.osgi.framework.adaptor.FrameworkAdaptor;
-import org.eclipse.osgi.framework.log.FrameworkLogEntry;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.osgi.service.packageadmin.PackageAdmin;
-import org.osgi.util.tracker.ServiceTracker;
-
-/*
- * An abstract class for handler factory impls (Stream and Content) that can
- * handle environments running multiple osgi frameworks with the same VM.
- */
-public abstract class MultiplexingFactory {
-
- protected static final String PACKAGEADMINCLASS = "org.osgi.service.packageadmin.PackageAdmin"; //$NON-NLS-1$
- protected BundleContext context;
- protected FrameworkAdaptor adaptor;
- private List<Object> factories; // list of multiplexed factories
- private ServiceTracker<ServiceReference<?>, PackageAdmin> packageAdminTracker;
-
- // used to get access to the protected SecurityManager#getClassContext method
- static class InternalSecurityManager extends SecurityManager {
- public Class<?>[] getClassContext() {
- return super.getClassContext();
- }
- }
-
- private static InternalSecurityManager internalSecurityManager = new InternalSecurityManager();
-
- MultiplexingFactory(BundleContext context, FrameworkAdaptor adaptor) {
- this.context = context;
- this.adaptor = adaptor;
- packageAdminTracker = new ServiceTracker<ServiceReference<?>, PackageAdmin>(context, PACKAGEADMINCLASS, null);
- packageAdminTracker.open();
- }
-
- abstract public void setParentFactory(Object parentFactory);
-
- abstract public Object getParentFactory();
-
- public boolean isMultiplexing() {
- return getFactories() != null;
- }
-
- 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()});
- } catch (Exception e) {
- adaptor.getFrameworkLog().log(new FrameworkLogEntry(MultiplexingFactory.class.getName(), FrameworkLogEntry.ERROR, 0, "register", FrameworkLogEntry.ERROR, e, null)); //$NON-NLS-1$
- throw new RuntimeException(e.getMessage(), e);
- }
- addFactory(factory);
- }
-
- 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$
- closeTracker.setAccessible(true); // its a private method
- closeTracker.invoke(factory, (Object[]) null);
- } catch (Exception e) {
- adaptor.getFrameworkLog().log(new FrameworkLogEntry(MultiplexingFactory.class.getName(), FrameworkLogEntry.ERROR, 0, "unregister", FrameworkLogEntry.ERROR, e, null)); //$NON-NLS-1$
- throw new RuntimeException(e.getMessage(), e);
- }
- }
-
- public Object designateSuccessor() {
- List<Object> released = releaseFactories();
- // 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:
- // Framework.installURLStreamHandlerFactory(BundleContext, FrameworkAdaptor)
- // Framework.installContentHandlerFactory(BundleContext, FrameworkAdaptor)
- // Framework.uninstallURLStreamHandlerFactory
- // Framework.uninstallContentHandlerFactory()
- if (released == null || released.isEmpty())
- return getParentFactory();
- Object successor = released.remove(0);
- try {
- Class<?> clazz = successor.getClass();
- Method register = clazz.getMethod("register", new Class[] {Object.class}); //$NON-NLS-1$
- for (Object r : released) {
- register.invoke(successor, new Object[] {r});
- }
- } catch (Exception e) {
- adaptor.getFrameworkLog().log(new FrameworkLogEntry(MultiplexingFactory.class.getName(), FrameworkLogEntry.ERROR, 0, "designateSuccessor", FrameworkLogEntry.ERROR, e, null)); //$NON-NLS-1$
- throw new RuntimeException(e.getMessage(), e);
- }
- closePackageAdminTracker(); // close tracker
- return successor;
- }
-
- private void closePackageAdminTracker() {
- packageAdminTracker.close();
- }
-
- public Object findAuthorizedFactory(List<Class<?>> ignoredClasses) {
- List<Object> current = getFactories();
- Class<?>[] classStack = internalSecurityManager.getClassContext();
- for (int i = 0; i < classStack.length; i++) {
- Class<?> clazz = classStack[i];
- if (clazz == InternalSecurityManager.class || clazz == MultiplexingFactory.class || ignoredClasses.contains(clazz))
- continue;
- if (hasAuthority(clazz))
- return this;
- if (current == null)
- 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()) {
- return factory;
- }
- } catch (Exception e) {
- adaptor.getFrameworkLog().log(new FrameworkLogEntry(MultiplexingFactory.class.getName(), FrameworkLogEntry.ERROR, 0, "findAuthorizedURLStreamHandler-loop", FrameworkLogEntry.ERROR, e, null)); //$NON-NLS-1$
- throw new RuntimeException(e.getMessage(), e);
- }
- }
- }
- return null;
- }
-
- public boolean hasAuthority(Class<?> clazz) {
- PackageAdmin packageAdminService = packageAdminTracker.getService();
- if (packageAdminService != null) {
- return packageAdminService.getBundle(clazz) != null;
- }
- return false;
- }
-
- private synchronized List<Object> getFactories() {
- return factories;
- }
-
- private synchronized List<Object> releaseFactories() {
- if (factories == null)
- return null;
-
- List<Object> released = new LinkedList<Object>(factories);
- factories = null;
- return released;
- }
-
- private synchronized void addFactory(Object factory) {
- List<Object> updated = (factories == null) ? new LinkedList<Object>() : new LinkedList<Object>(factories);
- updated.add(factory);
- factories = updated;
- }
-
- private synchronized void removeFactory(Object factory) {
- List<Object> updated = new LinkedList<Object>(factories);
- updated.remove(factory);
- factories = updated.isEmpty() ? null : updated;
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/MultiplexingURLStreamHandler.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/MultiplexingURLStreamHandler.java
deleted file mode 100644
index 4bc71a844..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/MultiplexingURLStreamHandler.java
+++ /dev/null
@@ -1,247 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2010 Cognos Incorporated, IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- *******************************************************************************/
-package org.eclipse.osgi.framework.internal.protocol;
-
-import java.io.IOException;
-import java.lang.reflect.*;
-import java.net.*;
-import org.eclipse.osgi.framework.internal.core.Framework;
-import org.eclipse.osgi.framework.log.FrameworkLogEntry;
-
-public class MultiplexingURLStreamHandler extends URLStreamHandler {
- private static Method openConnectionMethod;
- private static Method equalsMethod;
- private static Method getDefaultPortMethod;
- private static Method getHostAddressMethod;
- private static Method hashCodeMethod;
- private static Method hostsEqualMethod;
- private static Method parseURLMethod;
- private static Method sameFileMethod;
- private static Method setURLMethod;
- private static Method toExternalFormMethod;
- private static Field handlerField;
- private static boolean methodsInitialized = false;
-
- private String protocol;
- private StreamHandlerFactory factory;
-
- private static synchronized void initializeMethods(StreamHandlerFactory factory) {
- if (methodsInitialized)
- return;
- try {
- openConnectionMethod = URLStreamHandler.class.getDeclaredMethod("openConnection", new Class[] {URL.class}); //$NON-NLS-1$
- openConnectionMethod.setAccessible(true);
-
- equalsMethod = URLStreamHandler.class.getDeclaredMethod("equals", new Class[] {URL.class, URL.class}); //$NON-NLS-1$
- equalsMethod.setAccessible(true);
-
- getDefaultPortMethod = URLStreamHandler.class.getDeclaredMethod("getDefaultPort", (Class[]) null); //$NON-NLS-1$
- getDefaultPortMethod.setAccessible(true);
-
- getHostAddressMethod = URLStreamHandler.class.getDeclaredMethod("getHostAddress", new Class[] {URL.class}); //$NON-NLS-1$
- getHostAddressMethod.setAccessible(true);
-
- hashCodeMethod = URLStreamHandler.class.getDeclaredMethod("hashCode", new Class[] {URL.class}); //$NON-NLS-1$
- hashCodeMethod.setAccessible(true);
-
- hostsEqualMethod = URLStreamHandler.class.getDeclaredMethod("hostsEqual", new Class[] {URL.class, URL.class}); //$NON-NLS-1$
- hostsEqualMethod.setAccessible(true);
-
- parseURLMethod = URLStreamHandler.class.getDeclaredMethod("parseURL", new Class[] {URL.class, String.class, Integer.TYPE, Integer.TYPE}); //$NON-NLS-1$
- parseURLMethod.setAccessible(true);
-
- sameFileMethod = URLStreamHandler.class.getDeclaredMethod("sameFile", new Class[] {URL.class, URL.class}); //$NON-NLS-1$
- sameFileMethod.setAccessible(true);
-
- 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.setAccessible(true);
-
- toExternalFormMethod = URLStreamHandler.class.getDeclaredMethod("toExternalForm", new Class[] {URL.class}); //$NON-NLS-1$
- toExternalFormMethod.setAccessible(true);
-
- try {
- handlerField = URL.class.getDeclaredField("handler"); //$NON-NLS-1$
- } catch (NoSuchFieldException e) {
- handlerField = Framework.getField(URL.class, URLStreamHandler.class, true);
- if (handlerField == null)
- throw e;
- }
- handlerField.setAccessible(true);
- } catch (Exception e) {
- factory.adaptor.getFrameworkLog().log(new FrameworkLogEntry(MultiplexingURLStreamHandler.class.getName(), FrameworkLogEntry.ERROR, 0, "initializeMethods", 0, e, null)); //$NON-NLS-1$
- throw new RuntimeException(e.getMessage(), e);
- }
- methodsInitialized = true;
- }
-
- public MultiplexingURLStreamHandler(String protocol, StreamHandlerFactory factory) {
- this.protocol = protocol;
- this.factory = factory;
- initializeMethods(factory);
- }
-
- protected URLConnection openConnection(URL url) throws IOException {
- URLStreamHandler handler = factory.findAuthorizedURLStreamHandler(protocol);
- if (handler != null) {
- try {
- 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.adaptor.getFrameworkLog().log(new FrameworkLogEntry(MultiplexingURLStreamHandler.class.getName(), FrameworkLogEntry.ERROR, 0, "openConnection", 0, e, null)); //$NON-NLS-1$
- throw new RuntimeException(e.getMessage(), e);
- }
- }
- throw new MalformedURLException();
- }
-
- protected boolean equals(URL url1, URL url2) {
- URLStreamHandler handler = factory.findAuthorizedURLStreamHandler(protocol);
- if (handler != null) {
- try {
- return ((Boolean) equalsMethod.invoke(handler, new Object[] {url1, url2})).booleanValue();
- } catch (InvocationTargetException e) {
- throw (RuntimeException) e.getTargetException();
- } catch (Exception e) {
- factory.adaptor.getFrameworkLog().log(new FrameworkLogEntry(MultiplexingURLStreamHandler.class.getName(), FrameworkLogEntry.ERROR, 0, "equals", 0, e, null)); //$NON-NLS-1$
- throw new RuntimeException(e.getMessage(), e);
- }
- }
- throw new IllegalStateException();
- }
-
- protected int getDefaultPort() {
- URLStreamHandler handler = factory.findAuthorizedURLStreamHandler(protocol);
- if (handler != null) {
- try {
- return ((Integer) getDefaultPortMethod.invoke(handler, (Object[]) null)).intValue();
- } catch (InvocationTargetException e) {
- throw (RuntimeException) e.getTargetException();
- } catch (Exception e) {
- factory.adaptor.getFrameworkLog().log(new FrameworkLogEntry(MultiplexingURLStreamHandler.class.getName(), FrameworkLogEntry.ERROR, 0, "getDefaultPort", 0, e, null)); //$NON-NLS-1$
- throw new RuntimeException(e.getMessage(), e);
- }
- }
- throw new IllegalStateException();
- }
-
- protected InetAddress getHostAddress(URL url) {
- URLStreamHandler handler = factory.findAuthorizedURLStreamHandler(protocol);
- if (handler != null) {
- try {
- return (InetAddress) getHostAddressMethod.invoke(handler, new Object[] {url});
- } catch (InvocationTargetException e) {
- throw (RuntimeException) e.getTargetException();
- } catch (Exception e) {
- factory.adaptor.getFrameworkLog().log(new FrameworkLogEntry(MultiplexingURLStreamHandler.class.getName(), FrameworkLogEntry.ERROR, 0, "hashCode", 0, e, null)); //$NON-NLS-1$
- throw new RuntimeException(e.getMessage(), e);
- }
- }
- throw new IllegalStateException();
- }
-
- protected int hashCode(URL url) {
- URLStreamHandler handler = factory.findAuthorizedURLStreamHandler(protocol);
- if (handler != null) {
- try {
- return ((Integer) hashCodeMethod.invoke(handler, new Object[] {url})).intValue();
- } catch (InvocationTargetException e) {
- throw (RuntimeException) e.getTargetException();
- } catch (Exception e) {
- factory.adaptor.getFrameworkLog().log(new FrameworkLogEntry(MultiplexingURLStreamHandler.class.getName(), FrameworkLogEntry.ERROR, 0, "hashCode", 0, e, null)); //$NON-NLS-1$
- throw new RuntimeException(e.getMessage(), e);
- }
- }
- throw new IllegalStateException();
- }
-
- protected boolean hostsEqual(URL url1, URL url2) {
- URLStreamHandler handler = factory.findAuthorizedURLStreamHandler(protocol);
- if (handler != null) {
- try {
- return ((Boolean) hostsEqualMethod.invoke(handler, new Object[] {url1, url2})).booleanValue();
- } catch (InvocationTargetException e) {
- throw (RuntimeException) e.getTargetException();
- } catch (Exception e) {
- factory.adaptor.getFrameworkLog().log(new FrameworkLogEntry(MultiplexingURLStreamHandler.class.getName(), FrameworkLogEntry.ERROR, 0, "hostsEqual", 0, e, null)); //$NON-NLS-1$
- throw new RuntimeException(e.getMessage(), e);
- }
- }
- throw new IllegalStateException();
- }
-
- protected void parseURL(URL arg0, String arg1, int arg2, int arg3) {
- URLStreamHandler handler = factory.findAuthorizedURLStreamHandler(protocol);
- if (handler != null) {
- try {
- // set the real handler for the URL
- handlerField.set(arg0, handler);
- parseURLMethod.invoke(handler, new Object[] {arg0, arg1, new Integer(arg2), new Integer(arg3)});
- return;
- } catch (InvocationTargetException e) {
- throw (RuntimeException) e.getTargetException();
- } catch (Exception e) {
- factory.adaptor.getFrameworkLog().log(new FrameworkLogEntry(MultiplexingURLStreamHandler.class.getName(), FrameworkLogEntry.ERROR, 0, "parseURL", 0, e, null)); //$NON-NLS-1$
- throw new RuntimeException(e.getMessage(), e);
- }
- }
- throw new IllegalStateException();
- }
-
- protected boolean sameFile(URL url1, URL url2) {
- URLStreamHandler handler = factory.findAuthorizedURLStreamHandler(protocol);
- if (handler != null) {
- try {
- return ((Boolean) sameFileMethod.invoke(handler, new Object[] {url1, url2})).booleanValue();
- } catch (InvocationTargetException e) {
- throw (RuntimeException) e.getTargetException();
- } catch (Exception e) {
- factory.adaptor.getFrameworkLog().log(new FrameworkLogEntry(MultiplexingURLStreamHandler.class.getName(), FrameworkLogEntry.ERROR, 0, "sameFile", 0, e, null)); //$NON-NLS-1$
- throw new RuntimeException(e.getMessage(), e);
- }
- }
- throw new IllegalStateException();
- }
-
- protected void setURL(URL arg0, String arg1, String arg2, int arg3, String arg4, String arg5, String arg6, String arg7, String arg8) {
- URLStreamHandler handler = factory.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, new Integer(arg3), arg4, arg5, arg6, arg7, arg8});
- return;
- } catch (InvocationTargetException e) {
- throw (RuntimeException) e.getTargetException();
- } catch (Exception e) {
- factory.adaptor.getFrameworkLog().log(new FrameworkLogEntry(MultiplexingURLStreamHandler.class.getName(), FrameworkLogEntry.ERROR, 0, "setURL", 0, e, null)); //$NON-NLS-1$
- throw new RuntimeException(e.getMessage(), e);
- }
- }
- throw new IllegalStateException();
- }
-
- protected String toExternalForm(URL url) {
- URLStreamHandler handler = factory.findAuthorizedURLStreamHandler(protocol);
- if (handler != null) {
- try {
- return (String) toExternalFormMethod.invoke(handler, new Object[] {url});
- } catch (InvocationTargetException e) {
- throw (RuntimeException) e.getTargetException();
- } catch (Exception e) {
- factory.adaptor.getFrameworkLog().log(new FrameworkLogEntry(MultiplexingURLStreamHandler.class.getName(), FrameworkLogEntry.ERROR, 0, "toExternalForm", 0, e, null)); //$NON-NLS-1$
- throw new RuntimeException(e.getMessage(), e);
- }
- }
- throw new IllegalStateException();
- }
-
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/NullURLStreamHandlerService.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/NullURLStreamHandlerService.java
deleted file mode 100644
index 4cca4f943..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/NullURLStreamHandlerService.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2006 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.framework.internal.protocol;
-
-import java.io.IOException;
-import java.net.*;
-import org.osgi.service.url.URLStreamHandlerService;
-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.
- */
-
-public class NullURLStreamHandlerService implements URLStreamHandlerService {
-
- public URLConnection openConnection(URL u) throws IOException {
- throw new MalformedURLException();
- }
-
- public boolean equals(URL url1, URL url2) {
- throw new IllegalStateException();
- }
-
- public int getDefaultPort() {
- throw new IllegalStateException();
- }
-
- public InetAddress getHostAddress(URL url) {
- throw new IllegalStateException();
- }
-
- public int hashCode(URL url) {
- throw new IllegalStateException();
- }
-
- public boolean hostsEqual(URL url1, URL url2) {
- throw new IllegalStateException();
- }
-
- 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) {
- throw new IllegalStateException();
- }
-
- public void setURL(URL u, String protocol, String host, int port, String file, String ref) {
- throw new IllegalStateException();
- }
-
- public String toExternalForm(URL url) {
- throw new IllegalStateException();
- }
-
- public void parseURL(URLStreamHandlerSetter realHandler, URL u, String spec, int start, int limit) {
- throw new IllegalStateException();
- }
-
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/ProtocolActivator.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/ProtocolActivator.java
deleted file mode 100644
index 39043c01e..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/ProtocolActivator.java
+++ /dev/null
@@ -1,22 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2006 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.framework.internal.protocol;
-
-import org.eclipse.osgi.framework.adaptor.FrameworkAdaptor;
-import org.osgi.framework.BundleContext;
-
-//TODO this is non-API, and has no internal clients - do we really need it? at least explain why
-public interface ProtocolActivator {
-
- public void start(BundleContext context, FrameworkAdaptor adaptor);
-
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/StreamHandlerFactory.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/StreamHandlerFactory.java
deleted file mode 100644
index 3e38687f7..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/StreamHandlerFactory.java
+++ /dev/null
@@ -1,223 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2004, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.framework.internal.protocol;
-
-import java.lang.reflect.Method;
-import java.net.*;
-import java.security.AccessController;
-import java.util.*;
-import org.eclipse.osgi.framework.adaptor.FrameworkAdaptor;
-import org.eclipse.osgi.framework.internal.core.Constants;
-import org.eclipse.osgi.framework.internal.core.Msg;
-import org.eclipse.osgi.framework.log.FrameworkLogEntry;
-import org.eclipse.osgi.framework.util.SecureAction;
-import org.eclipse.osgi.util.NLS;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.osgi.service.url.URLConstants;
-import org.osgi.service.url.URLStreamHandlerService;
-import org.osgi.util.tracker.ServiceTracker;
-
-/**
- * This class contains the URL stream handler factory for the OSGi framework.
- */
-public class StreamHandlerFactory extends MultiplexingFactory implements URLStreamHandlerFactory {
- static final SecureAction secureAction = AccessController.doPrivileged(SecureAction.createSecureAction());
-
- private ServiceTracker<URLStreamHandlerService, URLStreamHandlerService> handlerTracker;
-
- protected static final String URLSTREAMHANDLERCLASS = "org.osgi.service.url.URLStreamHandlerService"; //$NON-NLS-1$
- protected static final String PROTOCOL_HANDLER_PKGS = "java.protocol.handler.pkgs"; //$NON-NLS-1$
- protected static final String INTERNAL_PROTOCOL_HANDLER_PKG = "org.eclipse.osgi.framework.internal.protocol"; //$NON-NLS-1$
-
- private static final List<Class<?>> ignoredClasses = Arrays.asList(new Class<?>[] {MultiplexingURLStreamHandler.class, StreamHandlerFactory.class, URL.class});
- private static final boolean useNetProxy;
- static {
- Class<?> clazz = null;
- try {
- clazz = Class.forName("java.net.Proxy"); //$NON-NLS-1$
- } catch (ClassNotFoundException e) {
- // expected on JRE < 1.5
- }
- useNetProxy = clazz != null;
- }
- private Map<String, URLStreamHandler> proxies;
- private URLStreamHandlerFactory parentFactory;
- private ThreadLocal<List<String>> creatingProtocols = new ThreadLocal<List<String>>();
-
- /**
- * Create the factory.
- *
- * @param context BundleContext for the system bundle
- */
- public StreamHandlerFactory(BundleContext context, FrameworkAdaptor adaptor) {
- super(context, adaptor);
-
- proxies = new Hashtable<String, URLStreamHandler>(15);
- handlerTracker = new ServiceTracker<URLStreamHandlerService, URLStreamHandlerService>(context, URLSTREAMHANDLERCLASS, null);
- handlerTracker.open();
- }
-
- private Class<?> getBuiltIn(String protocol, String builtInHandlers, boolean fromFramework) {
- if (builtInHandlers == null)
- return null;
- Class<?> clazz;
- StringTokenizer tok = new StringTokenizer(builtInHandlers, "|"); //$NON-NLS-1$
- while (tok.hasMoreElements()) {
- StringBuffer name = new StringBuffer();
- name.append(tok.nextToken());
- name.append("."); //$NON-NLS-1$
- name.append(protocol);
- name.append(".Handler"); //$NON-NLS-1$
- try {
- if (fromFramework)
- clazz = secureAction.forName(name.toString());
- else
- clazz = secureAction.loadSystemClass(name.toString());
- if (clazz != null)
- return clazz; //this class exists, it is a built in handler
- } catch (ClassNotFoundException ex) {
- // keep looking
- }
- }
- return null;
- }
-
- /**
- * Creates a new URLStreamHandler instance for the specified
- * protocol.
- *
- * @param protocol The desired protocol
- * @return a URLStreamHandler for the specific protocol.
- */
- public URLStreamHandler createURLStreamHandler(String protocol) {
- // Check if we are recursing
- if (isRecursive(protocol))
- return null;
- try {
- //first check for built in handlers
- String builtInHandlers = secureAction.getProperty(PROTOCOL_HANDLER_PKGS);
- Class<?> clazz = getBuiltIn(protocol, builtInHandlers, false);
- if (clazz != null)
- return null; // let the VM handle it
- URLStreamHandler result = null;
- if (isMultiplexing()) {
- if (findAuthorizedURLStreamHandler(protocol) != null)
- result = new MultiplexingURLStreamHandler(protocol, this);
- } else {
- result = createInternalURLStreamHandler(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.*)
- } catch (Throwable t) {
- adaptor.getFrameworkLog().log(new FrameworkLogEntry(StreamHandlerFactory.class.getName(), FrameworkLogEntry.ERROR, 0, "Unexpected error in factory.", 0, t, null)); //$NON-NLS-1$
- return null;
- } finally {
- releaseRecursive(protocol);
- }
- }
-
- private boolean isRecursive(String protocol) {
- List<String> protocols = creatingProtocols.get();
- if (protocols == null) {
- protocols = new ArrayList<String>(1);
- creatingProtocols.set(protocols);
- }
- if (protocols.contains(protocol))
- return true;
- protocols.add(protocol);
- return false;
- }
-
- private void releaseRecursive(String protocol) {
- List<String> protocols = creatingProtocols.get();
- protocols.remove(protocol);
- }
-
- public URLStreamHandler createInternalURLStreamHandler(String protocol) {
- //internal protocol handlers
- String internalHandlerPkgs = secureAction.getProperty(Constants.INTERNAL_HANDLER_PKGS);
- internalHandlerPkgs = internalHandlerPkgs == null ? INTERNAL_PROTOCOL_HANDLER_PKG : internalHandlerPkgs + '|' + INTERNAL_PROTOCOL_HANDLER_PKG;
- Class<?> clazz = getBuiltIn(protocol, internalHandlerPkgs, true);
-
- if (clazz == null) {
- //Now we check the service registry
- //first check to see if the handler is in the cache
- URLStreamHandlerProxy handler = (URLStreamHandlerProxy) proxies.get(protocol);
- if (handler != null)
- return (handler);
- //look through the service registry for a URLStramHandler registered for this protocol
- ServiceReference<URLStreamHandlerService>[] serviceReferences = handlerTracker.getServiceReferences();
- if (serviceReferences == null)
- return null;
- for (int i = 0; i < serviceReferences.length; i++) {
- Object prop = serviceReferences[i].getProperty(URLConstants.URL_HANDLER_PROTOCOL);
- if (prop instanceof String)
- 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_HANDLER_PROTOCOL, URLSTREAMHANDLERCLASS, serviceReferences[i].getBundle()});
- adaptor.getFrameworkLog().log(new FrameworkLogEntry(FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME, FrameworkLogEntry.WARNING, 0, message, 0, null, null));
- continue;
- }
- String[] protocols = (String[]) prop;
- for (int j = 0; j < protocols.length; j++)
- if (protocols[j].equals(protocol)) {
- handler = useNetProxy ? new URLStreamHandlerFactoryProxyFor15(protocol, serviceReferences[i], context) : new URLStreamHandlerProxy(protocol, serviceReferences[i], context);
- proxies.put(protocol, handler);
- return (handler);
- }
- }
- return null;
- }
-
- // must be a built-in handler
- try {
- URLStreamHandler handler = (URLStreamHandler) clazz.newInstance();
-
- if (handler instanceof ProtocolActivator) {
- ((ProtocolActivator) handler).start(context, adaptor);
- }
-
- return handler;
- } catch (Exception e) {
- return null;
- }
- }
-
- protected URLStreamHandler findAuthorizedURLStreamHandler(String protocol) {
- Object factory = findAuthorizedFactory(ignoredClasses);
- if (factory == null)
- return null;
-
- if (factory == this)
- 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});
- } catch (Exception e) {
- adaptor.getFrameworkLog().log(new FrameworkLogEntry(StreamHandlerFactory.class.getName(), FrameworkLogEntry.ERROR, 0, "findAuthorizedURLStreamHandler-loop", 0, e, null)); //$NON-NLS-1$
- throw new RuntimeException(e.getMessage(), e);
- }
- }
-
- public Object getParentFactory() {
- return parentFactory;
- }
-
- public void setParentFactory(Object parentFactory) {
- if (this.parentFactory == null) // only allow it to be set once
- this.parentFactory = (URLStreamHandlerFactory) parentFactory;
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/URLStreamHandlerFactoryProxyFor15.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/URLStreamHandlerFactoryProxyFor15.java
deleted file mode 100644
index ddfaf80f3..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/URLStreamHandlerFactoryProxyFor15.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.framework.internal.protocol;
-
-import java.io.IOException;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.net.*;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.osgi.service.url.URLStreamHandlerService;
-
-public class URLStreamHandlerFactoryProxyFor15 extends URLStreamHandlerProxy {
-
- public URLStreamHandlerFactoryProxyFor15(String protocol, ServiceReference<URLStreamHandlerService> reference, BundleContext context) {
- super(protocol, reference, context);
- }
-
- protected URLConnection openConnection(URL u, Proxy p) throws IOException {
- try {
- Method openConn = realHandlerService.getClass().getMethod("openConnection", new Class[] {URL.class, Proxy.class}); //$NON-NLS-1$
- return (URLConnection) openConn.invoke(realHandlerService, new Object[] {u, p});
- } catch (InvocationTargetException e) {
- if (e.getTargetException() instanceof IOException)
- throw (IOException) e.getTargetException();
- throw (RuntimeException) e.getTargetException();
- } catch (Exception e) {
- // expected on JRE < 1.5
- throw (UnsupportedOperationException) new UnsupportedOperationException().initCause(e);
- }
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/URLStreamHandlerProxy.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/URLStreamHandlerProxy.java
deleted file mode 100644
index cb0dc57ae..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/URLStreamHandlerProxy.java
+++ /dev/null
@@ -1,218 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.framework.internal.protocol;
-
-import java.io.IOException;
-import java.net.*;
-import org.osgi.framework.*;
-import org.osgi.service.url.URLConstants;
-import org.osgi.service.url.URLStreamHandlerService;
-import org.osgi.util.tracker.ServiceTracker;
-import org.osgi.util.tracker.ServiceTrackerCustomizer;
-
-/**
- * The URLStreamHandlerProxy is a URLStreamHandler that acts as a proxy for registered
- * URLStreamHandlerServices. When a URLStreamHandler is requested from the URLStreamHandlerFactory
- * and it exists in the service registry, a URLStreamHandlerProxy is created which will pass all the
- * requests from the requestor to the real URLStreamHandlerService. We can't return the real
- * URLStreamHandlerService from the URLStreamHandlerFactory because the JVM caches URLStreamHandlers
- * and therefore would not support a dynamic environment of URLStreamHandlerServices being registered
- * and unregistered.
- */
-
-public class URLStreamHandlerProxy extends URLStreamHandler implements ServiceTrackerCustomizer<URLStreamHandlerService, ServiceReference<URLStreamHandlerService>> {
- // TODO lots of type-based names
- protected URLStreamHandlerService realHandlerService;
-
- protected URLStreamHandlerSetter urlSetter;
-
- protected ServiceTracker<URLStreamHandlerService, ServiceReference<URLStreamHandlerService>> urlStreamHandlerServiceTracker;
-
- protected BundleContext context;
- protected ServiceReference<URLStreamHandlerService> urlStreamServiceReference;
-
- protected String protocol;
-
- protected int ranking = Integer.MIN_VALUE;
-
- public URLStreamHandlerProxy(String protocol, ServiceReference<URLStreamHandlerService> reference, BundleContext context) {
- this.context = context;
- this.protocol = protocol;
-
- urlSetter = new URLStreamHandlerSetter(this);
-
- //set the handler and ranking
- setNewHandler(reference, getRank(reference));
-
- urlStreamHandlerServiceTracker = new ServiceTracker<URLStreamHandlerService, ServiceReference<URLStreamHandlerService>>(context, StreamHandlerFactory.URLSTREAMHANDLERCLASS, this);
- StreamHandlerFactory.secureAction.open(urlStreamHandlerServiceTracker);
- }
-
- private void setNewHandler(ServiceReference<URLStreamHandlerService> reference, int rank) {
- if (urlStreamServiceReference != null)
- context.ungetService(urlStreamServiceReference);
-
- urlStreamServiceReference = reference;
- ranking = rank;
-
- if (reference == null)
- realHandlerService = new NullURLStreamHandlerService();
- else
- realHandlerService = StreamHandlerFactory.secureAction.getService(reference, context);
- }
-
- /**
- * @see java.net.URLStreamHandler#equals(URL, URL)
- */
- protected boolean equals(URL url1, URL url2) {
- return realHandlerService.equals(url1, url2);
- }
-
- /**
- * @see java.net.URLStreamHandler#getDefaultPort()
- */
- protected int getDefaultPort() {
- return realHandlerService.getDefaultPort();
- }
-
- /**
- * @see java.net.URLStreamHandler#getHostAddress(URL)
- */
- protected InetAddress getHostAddress(URL url) {
- return realHandlerService.getHostAddress(url);
- }
-
- /**
- * @see java.net.URLStreamHandler#hashCode(URL)
- */
- protected int hashCode(URL url) {
- return realHandlerService.hashCode(url);
- }
-
- /**
- * @see java.net.URLStreamHandler#hostsEqual(URL, URL)
- */
- protected boolean hostsEqual(URL url1, URL url2) {
- return realHandlerService.hostsEqual(url1, url2);
- }
-
- /**
- * @see java.net.URLStreamHandler#openConnection(URL)
- */
- protected URLConnection openConnection(URL url) throws IOException {
- return realHandlerService.openConnection(url);
- }
-
- /**
- * @see java.net.URLStreamHandler#parseURL(URL, String, int, int)
- */
- protected void parseURL(URL url, String str, int start, int end) {
- realHandlerService.parseURL(urlSetter, url, str, start, end);
- }
-
- /**
- * @see java.net.URLStreamHandler#sameFile(URL, URL)
- */
- protected boolean sameFile(URL url1, URL url2) {
- return realHandlerService.sameFile(url1, url2);
- }
-
- /**
- * @see java.net.URLStreamHandler#toExternalForm(URL)
- */
- protected String toExternalForm(URL url) {
- return realHandlerService.toExternalForm(url);
- }
-
- /**
- * @see java.net.URLStreamHandler#setURL(URL, String, String, int, String, String, String, String, String)
- */
- public void setURL(URL u, String protocol, String host, int port, String authority, String userInfo, String file, String query, String ref) {
- super.setURL(u, protocol, host, port, authority, userInfo, file, query, ref);
- }
-
- @SuppressWarnings("deprecation")
- public void setURL(URL url, String protocol, String host, int port, String file, String ref) {
-
- //using non-deprecated URLStreamHandler.setURL method.
- //setURL(URL u, String protocol, String host, int port, String authority, String userInfo, String file, String query, String ref)
- super.setURL(url, protocol, host, port, null, null, file, null, ref);
- }
-
- /**
- * @see org.osgi.util.tracker.ServiceTrackerCustomizer#addingService(ServiceReference)
- */
- public ServiceReference<URLStreamHandlerService> addingService(ServiceReference<URLStreamHandlerService> reference) {
- //check to see if our protocol is being registered by another service
- Object prop = reference.getProperty(URLConstants.URL_HANDLER_PROTOCOL);
- if (!(prop instanceof String[]))
- return null;
- String[] protocols = (String[]) prop;
- for (int i = 0; i < protocols.length; i++) {
- if (protocols[i].equals(protocol)) {
- //If our protocol is registered by another service, check the service ranking and switch URLStreamHandlers if nessecary.
- int newServiceRanking = getRank(reference);
- if (newServiceRanking > ranking || urlStreamServiceReference == null)
- setNewHandler(reference, newServiceRanking);
- return reference;
- }
- }
-
- //we don't want to continue hearing events about a URLStreamHandlerService not registered under our protocol
- return null;
- }
-
- /**
- * @see org.osgi.util.tracker.ServiceTrackerCustomizer#modifiedService(ServiceReference, Object)
- */
- // check to see if the ranking has changed. If so, re-select a new URLHandler
- public void modifiedService(ServiceReference<URLStreamHandlerService> reference, ServiceReference<URLStreamHandlerService> service) {
- int newRank = getRank(reference);
- if (reference == urlStreamServiceReference) {
- if (newRank < ranking) {
- // The URLHandler we are currently using has dropped it's ranking below a URLHandler registered
- // for the same protocol. We need to swap out URLHandlers.
- // this should get us the highest ranked service, if available
- ServiceReference<URLStreamHandlerService> newReference = urlStreamHandlerServiceTracker.getServiceReference();
- if (newReference != urlStreamServiceReference && newReference != null) {
- setNewHandler(newReference, ((Integer) newReference.getProperty(Constants.SERVICE_RANKING)).intValue());
- }
- }
- } else if (newRank > ranking) {
- // the service changed is another URLHandler that we are not currently using
- // If it's ranking is higher, we must swap it in.
- setNewHandler(reference, newRank);
- }
- }
-
- /**
- * @see org.osgi.util.tracker.ServiceTrackerCustomizer#removedService(ServiceReference, Object)
- */
- public void removedService(ServiceReference<URLStreamHandlerService> reference, ServiceReference<URLStreamHandlerService> service) {
- // check to see if our URLStreamHandler was unregistered.
- if (reference != urlStreamServiceReference)
- return;
- // If so, look for a lower ranking URLHandler
- // this should get us the highest ranking service left, if available
- ServiceReference<URLStreamHandlerService> newReference = urlStreamHandlerServiceTracker.getServiceReference();
- // if newReference == null then we will use the NullURLStreamHandlerService here
- setNewHandler(newReference, getRank(newReference));
- }
-
- private int getRank(ServiceReference<?> reference) {
- if (reference == null)
- return Integer.MIN_VALUE;
- Object property = reference.getProperty(Constants.SERVICE_RANKING);
- return (property instanceof Integer) ? ((Integer) property).intValue() : 0;
- }
-
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/URLStreamHandlerSetter.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/URLStreamHandlerSetter.java
deleted file mode 100644
index c576b5a2b..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/URLStreamHandlerSetter.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2006 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.framework.internal.protocol;
-
-import java.net.URL;
-
-public class URLStreamHandlerSetter implements org.osgi.service.url.URLStreamHandlerSetter {
-
- protected URLStreamHandlerProxy handlerProxy;
-
- public URLStreamHandlerSetter(URLStreamHandlerProxy handler) {
- this.handlerProxy = handler;
- }
-
- /**
- * @see org.osgi.service.url.URLStreamHandlerSetter#setURL(URL, String, String, int, String, String)
- * @deprecated
- */
- public void setURL(URL url, String protocol, String host, int port, String file, String ref) {
- handlerProxy.setURL(url, protocol, host, port, file, ref);
- }
-
- /**
- * @see org.osgi.service.url.URLStreamHandlerSetter#setURL(URL, String, String, int, String, String, String, String, String)
- */
- 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/core/framework/org/eclipse/osgi/internal/loader/BundleLoader.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/BundleLoader.java
deleted file mode 100644
index f972160de..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/BundleLoader.java
+++ /dev/null
@@ -1,1270 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2004, 2011 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.internal.loader;
-
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.net.URL;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.util.*;
-import org.eclipse.osgi.framework.adaptor.*;
-import org.eclipse.osgi.framework.debug.Debug;
-import org.eclipse.osgi.framework.internal.core.*;
-import org.eclipse.osgi.framework.internal.core.Constants;
-import org.eclipse.osgi.framework.util.KeyedElement;
-import org.eclipse.osgi.framework.util.KeyedHashSet;
-import org.eclipse.osgi.internal.loader.buddy.PolicyHandler;
-import org.eclipse.osgi.internal.resolver.StateBuilder;
-import org.eclipse.osgi.service.resolver.*;
-import org.eclipse.osgi.util.ManifestElement;
-import org.osgi.framework.*;
-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.
- * @see org.eclipse.osgi.internal.loader.BundleLoaderProxy
- */
-public class BundleLoader implements ClassLoaderDelegate {
- public final static String DEFAULT_PACKAGE = "."; //$NON-NLS-1$
- public final static String JAVA_PACKAGE = "java."; //$NON-NLS-1$
- public final static byte FLAG_IMPORTSINIT = 0x01;
- public final static byte FLAG_HASDYNAMICIMPORTS = 0x02;
- public final static byte FLAG_HASDYNAMICEIMPORTALL = 0x04;
- public final static byte FLAG_CLOSED = 0x08;
- public final static byte FLAG_LAZYTRIGGER = 0x10;
-
- public final static ClassContext CLASS_CONTEXT = AccessController.doPrivileged(new PrivilegedAction<ClassContext>() {
- public ClassContext run() {
- return new ClassContext();
- }
- });
- public final static ClassLoader FW_CLASSLOADER = getClassLoader(Framework.class);
-
- private static final int PRE_CLASS = 1;
- private static final int POST_CLASS = 2;
- private static final int PRE_RESOURCE = 3;
- private static final int POST_RESOURCE = 4;
- private static final int PRE_RESOURCES = 5;
- private static final int POST_RESOURCES = 6;
- private static final int PRE_LIBRARY = 7;
- private static final int POST_LIBRARY = 8;
-
- /* the proxy */
- final private BundleLoaderProxy proxy;
- /* Bundle object */
- final BundleHost bundle;
- final private PolicyHandler policy;
- /* List of package names that are exported by this BundleLoader */
- final private Collection<String> exportedPackages;
- final private Collection<String> substitutedPackages;
- /* List of required bundle BundleLoaderProxy objects */
- final BundleLoaderProxy[] requiredBundles;
- /* List of indexes into the requiredBundles list of reexported bundles */
- final int[] reexportTable;
- /* cache of required package sources. Key is packagename, value is PackageSource */
- final private KeyedHashSet requiredSources;
-
- // note that the following non-final must be access using synchronization
- /* cache of imported packages. Key is packagename, Value is PackageSource */
- private KeyedHashSet importedSources;
- /* If not null, list of package stems to import dynamically. */
- private String[] dynamicImportPackageStems;
- /* If not null, list of package names to import dynamically. */
- private String[] dynamicImportPackages;
- /* loader flags */
- private byte loaderFlags = 0;
- /* The is the BundleClassLoader for the bundle */
- private BundleClassLoader classloader;
- private ClassLoader parent;
-
- /**
- * 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.
- */
- public final static String getPackageName(String name) {
- if (name != null) {
- int index = name.lastIndexOf('.'); /* find last period in class name */
- if (index > 0)
- return name.substring(0, index);
- }
- return DEFAULT_PACKAGE;
- }
-
- /**
- * 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.
- */
- public final static String getResourcePackageName(String name) {
- if (name != null) {
- /* 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)
- return name.substring(begin, end).replace('/', '.');
- }
- return DEFAULT_PACKAGE;
- }
-
- /**
- * BundleLoader runtime constructor. This object is created lazily
- * when the first request for a resource is made to this bundle.
- *
- * @param bundle Bundle object for this loader.
- * @param proxy the BundleLoaderProxy for this loader.
- * @exception org.osgi.framework.BundleException
- */
- protected BundleLoader(BundleHost bundle, BundleLoaderProxy proxy) throws BundleException {
- this.bundle = bundle;
- this.proxy = proxy;
- try {
- bundle.getBundleData().open(); /* make sure the BundleData is open */
- } catch (IOException e) {
- throw new BundleException(Msg.BUNDLE_READ_EXCEPTION, e);
- }
- BundleDescription description = proxy.getBundleDescription();
- // init the require bundles list.
- BundleDescription[] required = description.getResolvedRequires();
- if (required.length > 0) {
- // get a list of re-exported symbolic names
- Set<String> reExportSet = new HashSet<String>(required.length);
- BundleSpecification[] requiredSpecs = description.getRequiredBundles();
- if (requiredSpecs != null && requiredSpecs.length > 0)
- for (int i = 0; i < requiredSpecs.length; i++)
- if (requiredSpecs[i].isExported())
- reExportSet.add(requiredSpecs[i].getName());
-
- requiredBundles = new BundleLoaderProxy[required.length];
- int[] reexported = new int[required.length];
- int reexportIndex = 0;
- for (int i = 0; i < required.length; i++) {
- requiredBundles[i] = getLoaderProxy(required[i]);
- if (reExportSet.contains(required[i].getSymbolicName()))
- reexported[reexportIndex++] = i;
- }
- if (reexportIndex > 0) {
- reexportTable = new int[reexportIndex];
- System.arraycopy(reexported, 0, reexportTable, 0, reexportIndex);
- } else {
- reexportTable = null;
- }
- requiredSources = new KeyedHashSet(10, false);
- } else {
- requiredBundles = null;
- reexportTable = null;
- requiredSources = null;
- }
-
- // init the provided packages set
- ExportPackageDescription[] exports = description.getSelectedExports();
- if (exports != null && exports.length > 0) {
- exportedPackages = Collections.synchronizedCollection(exports.length > 10 ? new HashSet<String>(exports.length) : new ArrayList<String>(exports.length));
- initializeExports(exports, exportedPackages);
- } else {
- exportedPackages = Collections.synchronizedCollection(new ArrayList<String>(0));
- }
-
- ExportPackageDescription substituted[] = description.getSubstitutedExports();
- if (substituted.length > 0) {
- substitutedPackages = substituted.length > 10 ? new HashSet<String>(substituted.length) : new ArrayList<String>(substituted.length);
- for (int i = 0; i < substituted.length; i++)
- substitutedPackages.add(substituted[i].getName());
- } else {
- substitutedPackages = null;
- }
-
- //This is the fastest way to access to the description for fragments since the hostdescription.getFragments() is slow
- BundleFragment[] fragmentObjects = bundle.getFragments();
- BundleDescription[] fragments = new BundleDescription[fragmentObjects == null ? 0 : fragmentObjects.length];
- for (int i = 0; i < fragments.length; i++)
- fragments[i] = fragmentObjects[i].getBundleDescription();
- // init the dynamic imports tables
- if (description.hasDynamicImports())
- addDynamicImportPackage(description.getImportPackages());
- // ...and its fragments
- for (int i = 0; i < fragments.length; i++)
- if (fragments[i].isResolved() && fragments[i].hasDynamicImports())
- addDynamicImportPackage(fragments[i].getImportPackages());
-
- //Initialize the policy handler
- String buddyList = null;
- try {
- buddyList = bundle.getBundleData().getManifest().get(Constants.BUDDY_LOADER);
- } catch (BundleException e) {
- // do nothing; buddyList == null
- }
- policy = buddyList != null ? new PolicyHandler(this, buddyList, bundle.getFramework().getPackageAdmin()) : null;
- if (policy != null)
- policy.open(bundle.getFramework().getSystemBundleContext());
- }
-
- private void initializeExports(ExportPackageDescription[] exports, Collection<String> exportNames) {
- for (int i = 0; i < exports.length; i++) {
- if (proxy.forceSourceCreation(exports[i])) {
- if (!exportNames.contains(exports[i].getName())) {
- // must force filtered and reexport sources to be created early
- // to prevent lazy normal package source creation.
- // We only do this for the first export of a package name.
- proxy.createPackageSource(exports[i], true);
- }
- }
- exportNames.add(exports[i].getName());
- }
- }
-
- public synchronized KeyedHashSet getImportedSources(KeyedHashSet visited) {
- if ((loaderFlags & FLAG_IMPORTSINIT) != 0)
- return importedSources;
- BundleDescription bundleDesc = proxy.getBundleDescription();
- ExportPackageDescription[] packages = bundleDesc.getResolvedImports();
- if (packages != null && packages.length > 0) {
- if (importedSources == null)
- importedSources = new KeyedHashSet(packages.length, false);
- for (int i = 0; i < packages.length; i++) {
- if (packages[i].getExporter() == bundleDesc)
- continue; // ignore imports resolved to this bundle
- PackageSource source = createExportPackageSource(packages[i], visited);
- if (source != null)
- importedSources.add(source);
- }
- }
- loaderFlags |= FLAG_IMPORTSINIT;
- return importedSources;
- }
-
- public synchronized boolean isLazyTriggerSet() {
- return (loaderFlags & FLAG_LAZYTRIGGER) != 0;
- }
-
- public void setLazyTrigger() throws BundleException {
- synchronized (this) {
- loaderFlags |= FLAG_LAZYTRIGGER;
- }
- BundleLoaderProxy.secureAction.start(bundle, Bundle.START_TRANSIENT | BundleHost.LAZY_TRIGGER);
- }
-
- final PackageSource createExportPackageSource(ExportPackageDescription export, KeyedHashSet visited) {
- BundleLoaderProxy exportProxy = getLoaderProxy(export.getExporter());
- if (exportProxy == null)
- // TODO log error!!
- return null;
- PackageSource requiredSource = exportProxy.getBundleLoader().findRequiredSource(export.getName(), visited);
- PackageSource exportSource = exportProxy.createPackageSource(export, false);
- if (requiredSource == null)
- return exportSource;
- return createMultiSource(export.getName(), new PackageSource[] {requiredSource, exportSource});
- }
-
- private static PackageSource createMultiSource(String packageName, PackageSource[] sources) {
- if (sources.length == 1)
- return sources[0];
- List<SingleSourcePackage> sourceList = new ArrayList<SingleSourcePackage>(sources.length);
- for (int i = 0; i < sources.length; i++) {
- SingleSourcePackage[] innerSources = sources[i].getSuppliers();
- for (int j = 0; j < innerSources.length; j++)
- if (!sourceList.contains(innerSources[j]))
- sourceList.add(innerSources[j]);
- }
- return new MultiSourcePackage(packageName, sourceList.toArray(new SingleSourcePackage[sourceList.size()]));
- }
-
- /*
- * get the loader proxy for a bundle description
- */
- public final BundleLoaderProxy getLoaderProxy(BundleDescription source) {
- Object userObject = source.getUserObject();
- if (!(userObject instanceof BundleLoaderProxy)) {
- // may need to force the proxy to be created
- long exportingID = source.getBundleId();
- BundleHost exportingBundle = (BundleHost) bundle.getFramework().getBundle(exportingID);
- if (exportingBundle == null)
- return null;
- userObject = exportingBundle.getLoaderProxy();
- }
- return (BundleLoaderProxy) userObject;
- }
-
- public BundleLoaderProxy getLoaderProxy() {
- return proxy;
- }
-
- /*
- * Close the the BundleLoader.
- *
- */
- synchronized void close() {
- if ((loaderFlags & FLAG_CLOSED) != 0)
- return;
- if (classloader != null)
- classloader.close();
- if (policy != null)
- policy.close(bundle.getFramework().getSystemBundleContext());
- loaderFlags |= FLAG_CLOSED; /* This indicates the BundleLoader is destroyed */
- }
-
- /**
- * This method loads a class from the bundle. The class 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 Class.
- * @return the resulting Class
- * @exception java.lang.ClassNotFoundException if the class definition was not found.
- */
- final public Class<?> loadClass(String name) throws ClassNotFoundException {
- BundleClassLoader bcl = createClassLoader();
- // The instanceof check here is just to be safe. The javadoc contract stated in BundleClassLoader
- // mandate that BundleClassLoaders be an instance of ClassLoader.
- if (name.length() > 0 && name.charAt(0) == '[' && bcl instanceof ClassLoader)
- return Class.forName(name, false, (ClassLoader) bcl);
- return bcl.loadClass(name);
- }
-
- /**
- * 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.
- */
- final URL getResource(String name) {
- return createClassLoader().getResource(name);
- }
-
- public final synchronized ClassLoader getParentClassLoader() {
- if (parent != null)
- return parent;
- createClassLoader();
- return parent;
- }
-
- final public synchronized BundleClassLoader createClassLoader() {
- if (classloader != null)
- return classloader;
- String[] classpath;
- try {
- classpath = bundle.getBundleData().getClassPath();
- } catch (BundleException e) {
- // no classpath
- classpath = new String[0];
- bundle.getFramework().publishFrameworkEvent(FrameworkEvent.ERROR, bundle, e);
- }
- if (classpath == null) {
- // no classpath
- classpath = new String[0];
- bundle.getFramework().publishFrameworkEvent(FrameworkEvent.ERROR, bundle, new BundleException(Msg.BUNDLE_NO_CLASSPATH_MATCH, BundleException.MANIFEST_ERROR));
- }
- BundleClassLoader bcl = createBCLPrevileged(bundle.getProtectionDomain(), classpath);
- parent = getParentPrivileged(bcl);
- classloader = bcl;
- return classloader;
- }
-
- /**
- * 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
- */
- Class<?> findLocalClass(String name) throws ClassNotFoundException {
- if (Debug.DEBUG_LOADER)
- Debug.println("BundleLoader[" + this + "].findLocalClass(" + name + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- try {
- Class<?> clazz = createClassLoader().findLocalClass(name);
- if (Debug.DEBUG_LOADER && clazz != null)
- Debug.println("BundleLoader[" + this + "] found local class " + name); //$NON-NLS-1$ //$NON-NLS-2$
- return clazz;
- } catch (ClassNotFoundException e) {
- if (e instanceof StatusException) {
- if ((((StatusException) e).getStatusCode() & StatusException.CODE_ERROR) != 0)
- throw e;
- }
- return null;
- }
- }
-
- /**
- * 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 findClass(name, true);
- }
-
- Class<?> findClass(String name, boolean checkParent) throws ClassNotFoundException {
- ClassLoader parentCL = getParentClassLoader();
- if (checkParent && parentCL != 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.
- return parentCL.loadClass(name);
- return findClassInternal(name, checkParent, parentCL);
- }
-
- private Class<?> findClassInternal(String name, boolean checkParent, ClassLoader parentCL) throws ClassNotFoundException {
- if (Debug.DEBUG_LOADER)
- Debug.println("BundleLoader[" + this + "].loadBundleClass(" + name + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- String pkgName = getPackageName(name);
- boolean bootDelegation = false;
- // follow the OSGi delegation model
- if (checkParent && parentCL != null && bundle.getFramework().isBootDelegationPackage(pkgName))
- // 2) if part of the bootdelegation list then delegate to parent and continue of failure
- try {
- return parentCL.loadClass(name);
- } catch (ClassNotFoundException cnfe) {
- // we want to continue
- bootDelegation = true;
- }
- Class<?> result = null;
- try {
- result = (Class<?>) searchHooks(name, PRE_CLASS);
- } catch (ClassNotFoundException e) {
- throw e;
- } catch (FileNotFoundException e) {
- // will not happen
- }
- if (result != null)
- return result;
- // 3) search the imported packages
- PackageSource source = findImportedSource(pkgName, null);
- if (source != null) {
- // 3) found import source terminate search at the source
- result = source.loadClass(name);
- if (result != null)
- return result;
- throw new ClassNotFoundException(name);
- }
- // 4) search the required bundles
- source = findRequiredSource(pkgName, null);
- if (source != null)
- // 4) attempt to load from source but continue on failure
- result = source.loadClass(name);
- // 5) search the local bundle
- if (result == null)
- 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
- if (source == null) {
- source = findDynamicSource(pkgName);
- if (source != null) {
- result = source.loadClass(name);
- if (result != null)
- return result;
- // must throw CNFE if dynamic import source does not have the class
- throw new ClassNotFoundException(name);
- }
- }
-
- if (result == null)
- try {
- result = (Class<?>) searchHooks(name, POST_CLASS);
- } catch (ClassNotFoundException e) {
- throw e;
- } catch (FileNotFoundException e) {
- // will not happen
- }
- // do buddy policy loading
- if (result == null && policy != null)
- result = policy.doBuddyClassLoading(name);
- if (result != null)
- return result;
- // hack to support backwards compatibiility for bootdelegation
- // or last resort; do class context trick to work around VM bugs
- if (parentCL != null && !bootDelegation && ((checkParent && bundle.getFramework().compatibiltyBootDelegation) || isRequestFromVM()))
- // we don't need to continue if a CNFE is thrown here.
- try {
- return parentCL.loadClass(name);
- } catch (ClassNotFoundException e) {
- // we want to generate our own exception below
- }
- throw new ClassNotFoundException(name);
- }
-
- @SuppressWarnings("unchecked")
- private <E> E searchHooks(String name, int type) throws ClassNotFoundException, FileNotFoundException {
- ClassLoaderDelegateHook[] delegateHooks = bundle.getFramework().getDelegateHooks();
- if (delegateHooks == null)
- return null;
- E result = null;
- for (int i = 0; i < delegateHooks.length && result == null; i++) {
- switch (type) {
- case PRE_CLASS :
- result = (E) delegateHooks[i].preFindClass(name, createClassLoader(), bundle.getBundleData());
- break;
- case POST_CLASS :
- result = (E) delegateHooks[i].postFindClass(name, createClassLoader(), bundle.getBundleData());
- break;
- case PRE_RESOURCE :
- result = (E) delegateHooks[i].preFindResource(name, createClassLoader(), bundle.getBundleData());
- break;
- case POST_RESOURCE :
- result = (E) delegateHooks[i].postFindResource(name, createClassLoader(), bundle.getBundleData());
- break;
- case PRE_RESOURCES :
- result = (E) delegateHooks[i].preFindResources(name, createClassLoader(), bundle.getBundleData());
- break;
- case POST_RESOURCES :
- result = (E) delegateHooks[i].postFindResources(name, createClassLoader(), bundle.getBundleData());
- break;
- case PRE_LIBRARY :
- result = (E) delegateHooks[i].preFindLibrary(name, createClassLoader(), bundle.getBundleData());
- break;
- case POST_LIBRARY :
- result = (E) delegateHooks[i].postFindLibrary(name, createClassLoader(), bundle.getBundleData());
- break;
- }
- }
- return result;
- }
-
- private boolean isRequestFromVM() {
- if (bundle.getFramework().isBootDelegationPackage("*") || !bundle.getFramework().contextBootDelegation) //$NON-NLS-1$
- return false;
- // 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++)
- // find the first class in the context which is not BundleLoader or instanceof ClassLoader
- if (context[i] != BundleLoader.class && !ClassLoader.class.isAssignableFrom(context[i])) {
- // only find in parent if the class is not "Class" (Class#forName case) or if the class is not loaded with a BundleClassLoader
- ClassLoader cl = getClassLoader(context[i]);
- if (cl != FW_CLASSLOADER) { // extra check incase an adaptor adds another class into the stack besides an instance of ClassLoader
- if (Class.class != context[i] && !(cl instanceof BundleClassLoader))
- return true;
- break;
- }
- }
- return false;
- }
-
- private static ClassLoader getClassLoader(final Class<?> clazz) {
- if (System.getSecurityManager() == null)
- return clazz.getClassLoader();
- return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
- public ClassLoader run() {
- return clazz.getClassLoader();
- }
- });
- }
-
- /**
- * Finds the resource for a bundle. This method is used for delegation by the bundle's classloader.
- */
- public URL findResource(String name) {
- return findResource(name, true);
- }
-
- URL findResource(String name, boolean checkParent) {
- 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);
- boolean bootDelegation = false;
- ClassLoader parentCL = getParentClassLoader();
- // follow the OSGi delegation model
- // First check the parent classloader for system resources, if it is a java resource.
- if (checkParent && parentCL != 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 parentCL.getResource(name);
- else if (bundle.getFramework().isBootDelegationPackage(pkgName)) {
- // 2) if part of the bootdelegation list then delegate to parent and continue of failure
- URL result = parentCL.getResource(name);
- if (result != null)
- return result;
- bootDelegation = true;
- }
- }
-
- URL result = null;
- try {
- result = (URL) searchHooks(name, PRE_RESOURCE);
- } catch (FileNotFoundException e) {
- return null;
- } catch (ClassNotFoundException e) {
- // will not happen
- }
- if (result != null)
- return result;
- // 3) search the imported packages
- PackageSource source = findImportedSource(pkgName, null);
- if (source != null)
- // 3) found import source terminate search at the source
- return source.getResource(name);
- // 4) search the required bundles
- source = findRequiredSource(pkgName, null);
- if (source != null)
- // 4) attempt to load from source but continue on failure
- result = source.getResource(name);
- // 5) search the local bundle
- if (result == null)
- 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
- if (source == null) {
- source = findDynamicSource(pkgName);
- if (source != null)
- // must return the result of the dynamic import and do not continue
- return source.getResource(name);
- }
-
- if (result == null)
- try {
- result = (URL) searchHooks(name, POST_RESOURCE);
- } catch (FileNotFoundException e) {
- return null;
- } catch (ClassNotFoundException e) {
- // will not happen
- }
- // do buddy policy loading
- if (result == null && policy != null)
- result = policy.doBuddyResourceLoading(name);
- if (result != null)
- return result;
- // hack to support backwards compatibiility for bootdelegation
- // or last resort; do class context trick to work around VM bugs
- if (parentCL != null && !bootDelegation && ((checkParent && bundle.getFramework().compatibiltyBootDelegation) || isRequestFromVM()))
- // we don't need to continue if the resource is not found here
- return parentCL.getResource(name);
- return result;
- }
-
- /**
- * Finds the resources for a bundle. This method is used for delegation by the bundle's classloader.
- */
- public Enumeration<URL> findResources(String name) throws IOException {
- // 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<URL> result = null;
- try {
- result = searchHooks(name, PRE_RESOURCES);
- } catch (ClassNotFoundException e) {
- // will not happen
- } catch (FileNotFoundException e) {
- return null;
- }
- if (result != null)
- return result;
- // start at step 3 because of the comment above about ClassLoader#getResources
- // 3) search the imported packages
- PackageSource source = findImportedSource(pkgName, null);
- if (source != null)
- // 3) found import source terminate search at the source
- return source.getResources(name);
- // 4) search the required bundles
- source = findRequiredSource(pkgName, null);
- if (source != null)
- // 4) attempt to load from source but continue on failure
- result = source.getResources(name);
-
- // 5) search the local bundle
- // compound the required source results with the local ones
- Enumeration<URL> 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
- if (result == null && source == null) {
- source = findDynamicSource(pkgName);
- if (source != null)
- return source.getResources(name);
- }
- if (result == null)
- try {
- result = searchHooks(name, POST_RESOURCES);
- } catch (ClassNotFoundException e) {
- // will not happen
- } catch (FileNotFoundException e) {
- return null;
- }
- if (policy != null) {
- Enumeration<URL> buddyResult = policy.doBuddyResourcesLoading(name);
- result = compoundEnumerations(result, buddyResult);
- }
- return result;
- }
-
- private boolean isSubPackage(String parentPackage, String subPackage) {
- String prefix = (parentPackage.length() == 0 || parentPackage.equals(DEFAULT_PACKAGE)) ? "" : parentPackage + '.'; //$NON-NLS-1$
- return subPackage.startsWith(prefix);
- }
-
- public Collection<String> listResources(String path, String filePattern, int options) {
- String pkgName = getResourcePackageName(path.endsWith("/") ? path : path + '/'); //$NON-NLS-1$
- if ((path.length() > 1) && (path.charAt(0) == '/')) /* if name has a leading slash */
- path = path.substring(1); /* remove leading slash before search */
- boolean subPackages = (options & BundleWiring.LISTRESOURCES_RECURSE) != 0;
- List<String> packages = new ArrayList<String>();
- // search imported package names
- KeyedHashSet importSources = getImportedSources(null);
- if (importSources != null) {
- KeyedElement[] imports = importSources.elements();
- for (KeyedElement keyedElement : imports) {
- String id = ((PackageSource) keyedElement).getId();
- if (id.equals(pkgName) || (subPackages && isSubPackage(pkgName, id)))
- packages.add(id);
- }
- }
-
- // now add package names from required bundles
- if (requiredBundles != null) {
- KeyedHashSet visited = new KeyedHashSet(false);
- visited.add(bundle); // always add ourselves so we do not recurse back to ourselves
- for (BundleLoaderProxy requiredProxy : requiredBundles) {
- BundleLoader requiredLoader = requiredProxy.getBundleLoader();
- requiredLoader.addProvidedPackageNames(requiredProxy.getSymbolicName(), pkgName, packages, subPackages, visited);
- }
- }
-
- boolean localSearch = (options & BundleWiring.LISTRESOURCES_LOCAL) != 0;
- List<String> result = new ArrayList<String>();
- Set<String> importedPackages = new HashSet<String>(0);
- for (String name : packages) {
- // look for import source
- PackageSource externalSource = findImportedSource(name, null);
- if (externalSource != null) {
- // record this package is imported
- importedPackages.add(name);
- } else {
- // look for require bundle source
- externalSource = findRequiredSource(name, null);
- }
- // only add the content of the external source if this is not a localSearch
- if (externalSource != null && !localSearch) {
- String packagePath = name.replace('.', '/');
- Collection<String> 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
- result.add(resource);
- }
- }
- }
-
- // now search locally
- Collection<String> localResources = createClassLoader().listLocalResources(path, filePattern, options);
- for (String resource : localResources) {
- String resourcePkg = getResourcePackageName(resource);
- if (!importedPackages.contains(resourcePkg) && !result.contains(resource))
- result.add(resource);
- }
- return result;
- }
-
- /*
- * This method is used by Bundle.getResources to do proper parent delegation.
- */
- public Enumeration<URL> getResources(String name) throws IOException {
- 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);
- // follow the OSGi delegation model
- // First check the parent classloader for system resources, if it is a java resource.
- Enumeration<URL> result = null;
- if (pkgName.startsWith(JAVA_PACKAGE) || bundle.getFramework().isBootDelegationPackage(pkgName)) {
- // 1) if startsWith "java." delegate to parent and terminate search
- // 2) if part of the bootdelegation list then delegate to parent and continue of failure
- ClassLoader parentCL = getParentClassLoader();
- result = parentCL == null ? null : parentCL.getResources(name);
- if (pkgName.startsWith(JAVA_PACKAGE))
- return result;
- }
- return compoundEnumerations(result, findResources(name));
- }
-
- public static <E> Enumeration<E> compoundEnumerations(Enumeration<E> list1, Enumeration<E> list2) {
- if (list2 == null || !list2.hasMoreElements())
- return list1;
- if (list1 == null || !list1.hasMoreElements())
- return list2;
- List<E> compoundResults = new ArrayList<E>();
- while (list1.hasMoreElements())
- compoundResults.add(list1.nextElement());
- while (list2.hasMoreElements()) {
- E item = list2.nextElement();
- 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.
- * @param name The name of the resource to find.
- * @return The URL to the resource or null if the resource is not found.
- */
- URL findLocalResource(final String name) {
- return createClassLoader().findLocalResource(name);
- }
-
- /**
- * 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
- * @return an Enumeration of URLs for the resources
- */
- Enumeration<URL> findLocalResources(String name) {
- return createClassLoader().findLocalResources(name);
- }
-
- /**
- * Returns the absolute path name of a native library.
- *
- * @param name the library name
- * @return the absolute path of the native library or null if not found
- */
- public String findLibrary(final String name) {
- if (System.getSecurityManager() == null)
- return findLocalLibrary(name);
- return AccessController.doPrivileged(new PrivilegedAction<String>() {
- public String run() {
- return findLocalLibrary(name);
- }
- });
- }
-
- final String findLocalLibrary(final String name) {
- String result = null;
- try {
- result = (String) searchHooks(name, PRE_LIBRARY);
- } catch (FileNotFoundException e) {
- return null;
- } catch (ClassNotFoundException e) {
- // will not happen
- }
- if (result != null)
- return result;
- result = bundle.getBundleData().findLibrary(name);
- if (result != null)
- return result;
-
- // look in fragments imports ...
- BundleFragment[] fragments = bundle.getFragments();
- if (fragments != null)
- for (int i = 0; i < fragments.length; i++) {
- result = fragments[i].getBundleData().findLibrary(name);
- if (result != null)
- return result;
- }
- try {
- return (String) searchHooks(name, POST_LIBRARY);
- } catch (FileNotFoundException e) {
- return null; // this is not necessary; but being consistent in case another step is added below
- } catch (ClassNotFoundException e) {
- // will not happen
- }
- return null;
- }
-
- /*
- * Return the bundle we are associated with.
- */
- public final AbstractBundle getBundle() {
- return bundle;
- }
-
- private BundleClassLoader createBCLPrevileged(final BundleProtectionDomain pd, final String[] cp) {
- // Create the classloader as previleged code if security manager is present.
- if (System.getSecurityManager() == null)
- return createBCL(pd, cp);
-
- return AccessController.doPrivileged(new PrivilegedAction<BundleClassLoader>() {
- public BundleClassLoader run() {
- return createBCL(pd, cp);
- }
- });
-
- }
-
- BundleClassLoader createBCL(final BundleProtectionDomain pd, final String[] cp) {
- BundleClassLoader bcl = bundle.getBundleData().createClassLoader(BundleLoader.this, pd, cp);
- // attach existing fragments to classloader
- BundleFragment[] fragments = bundle.getFragments();
- if (fragments != null)
- for (int i = 0; i < fragments.length; i++) {
- try {
- bcl.attachFragment(fragments[i].getBundleData(), fragments[i].getProtectionDomain(), fragments[i].getBundleData().getClassPath());
- } catch (BundleException be) {
- bundle.getFramework().publishFrameworkEvent(FrameworkEvent.ERROR, bundle, be);
- }
- }
-
- // finish the initialization of the classloader.
- bcl.initialize();
- return bcl;
- }
-
- /**
- * Return a string representation of this loader.
- * @return String
- */
- public final String toString() {
- BundleData result = bundle.getBundleData();
- return result == null ? "BundleLoader.bundledata == null!" : result.toString(); //$NON-NLS-1$
- }
-
- /**
- * 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.
- */
- private final synchronized boolean isDynamicallyImported(String pkgname) {
- if (this instanceof SystemBundleLoader)
- return false; // system bundle cannot dynamically import
- // must check for startsWith("java.") to satisfy R3 section 4.7.2
- if (pkgname.startsWith("java.")) //$NON-NLS-1$
- return true;
-
- /* quick shortcut check */
- if ((loaderFlags & FLAG_HASDYNAMICIMPORTS) == 0)
- return false;
-
- /* "*" shortcut */
- if ((loaderFlags & FLAG_HASDYNAMICEIMPORTALL) != 0)
- return true;
-
- /* match against specific names */
- if (dynamicImportPackages != null)
- for (int i = 0; i < dynamicImportPackages.length; i++)
- if (pkgname.equals(dynamicImportPackages[i]))
- return true;
-
- /* match against names with trailing wildcards */
- if (dynamicImportPackageStems != null)
- for (int i = 0; i < dynamicImportPackageStems.length; i++)
- if (pkgname.startsWith(dynamicImportPackageStems[i]))
- return true;
-
- return false;
- }
-
- final void addExportedProvidersFor(String symbolicName, String packageName, List<PackageSource> result, KeyedHashSet visited) {
- if (!visited.add(bundle))
- return;
-
- // See if we locally provide the package.
- PackageSource local = null;
- if (isExportedPackage(packageName))
- local = proxy.getPackageSource(packageName);
- else if (isSubstitutedExport(packageName)) {
- result.add(findImportedSource(packageName, visited));
- return; // should not continue to required bundles in this case
- }
- // Must search required bundles that are exported first.
- if (requiredBundles != null) {
- int size = reexportTable == null ? 0 : reexportTable.length;
- int reexportIndex = 0;
- for (int i = 0; i < requiredBundles.length; i++) {
- if (local != null) {
- // 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.
- requiredBundles[i].getBundleLoader().addExportedProvidersFor(symbolicName, packageName, result, visited);
- } else if (reexportIndex < size && reexportTable[reexportIndex] == i) {
- reexportIndex++;
- requiredBundles[i].getBundleLoader().addExportedProvidersFor(symbolicName, packageName, result, visited);
- }
- }
- }
-
- // now add the locally provided package.
- if (local != null && local.isFriend(symbolicName))
- result.add(local);
- }
-
- final void addProvidedPackageNames(String symbolicName, String packageName, List<String> result, boolean subPackages, KeyedHashSet visitied) {
- if (!visitied.add(bundle))
- return;
- for (String exported : exportedPackages) {
- if (exported.equals(packageName) || (subPackages && isSubPackage(packageName, exported))) {
- if (!result.contains(exported))
- result.add(exported);
- }
- }
- if (substitutedPackages != null)
- for (String substituted : substitutedPackages) {
- if (substituted.equals(packageName) || (subPackages && isSubPackage(packageName, substituted))) {
- if (!result.contains(substituted))
- result.add(substituted);
- }
- }
- if (requiredBundles != null) {
- int size = reexportTable == null ? 0 : reexportTable.length;
- int reexportIndex = 0;
- for (int i = 0; i < requiredBundles.length; i++) {
- if (reexportIndex < size && reexportTable[reexportIndex] == i) {
- reexportIndex++;
- requiredBundles[i].getBundleLoader().addProvidedPackageNames(symbolicName, packageName, result, subPackages, visitied);
- }
- }
- }
- }
-
- final boolean isExportedPackage(String name) {
- return exportedPackages.contains(name);
- }
-
- final boolean isSubstitutedExport(String name) {
- return substitutedPackages == null ? false : substitutedPackages.contains(name);
- }
-
- private void addDynamicImportPackage(ImportPackageSpecification[] packages) {
- if (packages == null)
- return;
- List<String> dynamicImports = new ArrayList<String>(packages.length);
- for (int i = 0; i < packages.length; i++)
- if (ImportPackageSpecification.RESOLUTION_DYNAMIC.equals(packages[i].getDirective(Constants.RESOLUTION_DIRECTIVE)))
- dynamicImports.add(packages[i].getName());
- if (dynamicImports.size() > 0)
- addDynamicImportPackage(dynamicImports.toArray(new String[dynamicImports.size()]));
- }
-
- /**
- * 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) {
- if (packages == null)
- return;
-
- loaderFlags |= FLAG_HASDYNAMICIMPORTS;
- int size = packages.length;
- List<String> stems;
- if (dynamicImportPackageStems == null) {
- stems = new ArrayList<String>(size);
- } else {
- stems = new ArrayList<String>(size + dynamicImportPackageStems.length);
- for (int i = 0; i < dynamicImportPackageStems.length; i++) {
- stems.add(dynamicImportPackageStems[i]);
- }
- }
-
- List<String> names;
- if (dynamicImportPackages == null) {
- names = new ArrayList<String>(size);
- } else {
- names = new ArrayList<String>(size + dynamicImportPackages.length);
- for (int i = 0; i < dynamicImportPackages.length; i++) {
- names.add(dynamicImportPackages[i]);
- }
- }
-
- for (int i = 0; i < size; i++) {
- String name = packages[i];
- if (isDynamicallyImported(name))
- continue;
- if (name.equals("*")) { /* shortcut *///$NON-NLS-1$
- loaderFlags |= FLAG_HASDYNAMICEIMPORTALL;
- return;
- }
-
- if (name.endsWith(".*")) //$NON-NLS-1$
- stems.add(name.substring(0, name.length() - 1));
- else
- names.add(name);
- }
-
- size = stems.size();
- if (size > 0)
- dynamicImportPackageStems = stems.toArray(new String[size]);
-
- size = names.size();
- if (size > 0)
- dynamicImportPackages = names.toArray(new String[size]);
- }
-
- /**
- * 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 synchronized void addDynamicImportPackage(ManifestElement[] packages) {
- if (packages == null)
- return;
- List<String> dynamicImports = new ArrayList<String>(packages.length);
- List<ImportPackageSpecification> dynamicImportSpecs = new ArrayList<ImportPackageSpecification>(packages.length);
- for (ManifestElement dynamicImportElement : packages) {
- String[] names = dynamicImportElement.getValueComponents();
- for (String name : names)
- dynamicImports.add(name);
- StateBuilder.addImportPackages(dynamicImportElement, dynamicImportSpecs, 2, true);
- }
- if (dynamicImports.size() > 0) {
- addDynamicImportPackage(dynamicImports.toArray(new String[dynamicImports.size()]));
- BundleDescription revision = getLoaderProxy().getBundleDescription();
- State state = revision.getContainingState();
- state.addDynamicImportPackages(revision, dynamicImportSpecs.toArray(new ImportPackageSpecification[dynamicImportSpecs.size()]));
- }
- }
-
- synchronized public void attachFragment(BundleFragment fragment) throws BundleException {
- ExportPackageDescription[] exports = proxy.getBundleDescription().getSelectedExports();
- if (classloader == null) {
- initializeExports(exports, exportedPackages);
- return;
- }
- String[] classpath = fragment.getBundleData().getClassPath();
- if (classpath != null)
- classloader.attachFragment(fragment.getBundleData(), fragment.getProtectionDomain(), classpath);
- initializeExports(exports, exportedPackages);
- }
-
- /*
- * 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)
- return null;
- PackageSource result = findImportedSource(pkgName, null);
- if (result != null)
- return result;
- // Note that dynamic imports are not checked to avoid aggressive wiring (bug 105779)
- return findRequiredSource(pkgName, null);
- }
-
- private PackageSource findImportedSource(String pkgName, KeyedHashSet visited) {
- KeyedHashSet imports = getImportedSources(visited);
- if (imports == null)
- return null;
- synchronized (imports) {
- return (PackageSource) imports.getByKey(pkgName);
- }
- }
-
- private PackageSource findDynamicSource(String pkgName) {
- if (isDynamicallyImported(pkgName)) {
- ExportPackageDescription exportPackage = bundle.getFramework().getAdaptor().getState().linkDynamicImport(proxy.getBundleDescription(), pkgName);
- if (exportPackage != null) {
- PackageSource source = createExportPackageSource(exportPackage, null);
- synchronized (this) {
- if (importedSources == null)
- importedSources = new KeyedHashSet(false);
- }
- synchronized (importedSources) {
- importedSources.add(source);
- }
- return source;
- }
- }
- return null;
- }
-
- private PackageSource findRequiredSource(String pkgName, KeyedHashSet visited) {
- if (requiredBundles == null)
- return null;
- synchronized (requiredSources) {
- PackageSource result = (PackageSource) requiredSources.getByKey(pkgName);
- if (result != null)
- return result.isNullSource() ? null : result;
- }
- if (visited == null)
- visited = new KeyedHashSet(false);
- visited.add(bundle); // always add ourselves so we do not recurse back to ourselves
- List<PackageSource> result = new ArrayList<PackageSource>(3);
- for (int i = 0; i < requiredBundles.length; i++) {
- BundleLoader requiredLoader = requiredBundles[i].getBundleLoader();
- requiredLoader.addExportedProvidersFor(proxy.getSymbolicName(), pkgName, result, visited);
- }
- // found some so cache the result for next time and return
- PackageSource source;
- if (result.size() == 0) {
- // did not find it in our required bundles lets record the failure
- // so we do not have to do the search again for this package.
- source = NullPackageSource.getNullPackageSource(pkgName);
- } else if (result.size() == 1) {
- // if there is just one source, remember just the single source
- source = result.get(0);
- } else {
- // if there was more than one source, build a multisource and cache that.
- PackageSource[] srcs = result.toArray(new PackageSource[result.size()]);
- source = createMultiSource(pkgName, srcs);
- }
- synchronized (requiredSources) {
- requiredSources.add(source);
- }
- return source.isNullSource() ? null : source;
- }
-
- /*
- * Gets the package source for the pkgName. This will include the local package source
- * if the bundle exports the package. This is used to compare the PackageSource of a
- * package from two different bundles.
- */
- public final PackageSource getPackageSource(String pkgName) {
- PackageSource result = findSource(pkgName);
- if (!isExportedPackage(pkgName))
- return result;
- // if the package is exported then we need to get the local source
- PackageSource localSource = proxy.getPackageSource(pkgName);
- if (result == null)
- return localSource;
- if (localSource == null)
- return result;
- return createMultiSource(pkgName, new PackageSource[] {result, localSource});
- }
-
- private ClassLoader getParentPrivileged(final BundleClassLoader bcl) {
- if (System.getSecurityManager() == null)
- return bcl.getParent();
-
- return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
- public ClassLoader run() {
- return bcl.getParent();
- }
- });
- }
-
- static final class ClassContext extends SecurityManager {
- // need to make this method public
- public Class<?>[] getClassContext() {
- return super.getClassContext();
- }
- }
-
- static public void closeBundleLoader(BundleLoaderProxy proxy) {
- if (proxy == null)
- return;
- // First close the BundleLoader
- BundleLoader loader = proxy.getBasicBundleLoader();
- if (loader != null)
- loader.close();
- proxy.setStale();
- // if proxy is not null then make sure to unset user object
- // associated with the proxy in the state
- BundleDescription description = proxy.getBundleDescription();
- // must set it back to the bundle object; not null
- // need to make sure the user object is a BundleReference
- description.setUserObject(proxy.getBundleData());
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/BundleLoaderProxy.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/BundleLoaderProxy.java
deleted file mode 100644
index a9612a91b..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/BundleLoaderProxy.java
+++ /dev/null
@@ -1,247 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.osgi.internal.loader;
-
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.util.ArrayList;
-import java.util.List;
-import org.eclipse.osgi.framework.adaptor.BundleData;
-import org.eclipse.osgi.framework.internal.core.*;
-import org.eclipse.osgi.framework.internal.core.Constants;
-import org.eclipse.osgi.framework.util.KeyedHashSet;
-import org.eclipse.osgi.framework.util.SecureAction;
-import org.eclipse.osgi.service.resolver.BundleDescription;
-import org.eclipse.osgi.service.resolver.ExportPackageDescription;
-import org.osgi.framework.*;
-import org.osgi.service.packageadmin.RequiredBundle;
-
-/*
- * The BundleLoaderProxy proxies a BundleLoader object for a Bundle. This
- * allows for a Bundle's depedencies to be linked without forcing the
- * creating of the BundleLoader or BundleClassLoader objects. This class
- * keeps track of the depedencies between the bundles installed in the
- * Framework.
- */
-public class BundleLoaderProxy implements RequiredBundle, BundleReference {
- static SecureAction secureAction = AccessController.doPrivileged(SecureAction.createSecureAction());
- // The BundleLoader that this BundleLoaderProxy is managing
- private BundleLoader loader;
- // The Bundle that this BundleLoaderProxy is for
- final private BundleHost bundle;
- // the BundleDescription for the Bundle
- final private BundleDescription description;
- // the BundleData for the bundle revision
- final private BundleData data;
- // Indicates if this BundleLoaderProxy is stale;
- // this is true when the bundle is updated or uninstalled.
- private boolean stale = false;
- // cached of package sources for the bundle
- final private KeyedHashSet pkgSources;
-
- public BundleLoaderProxy(BundleHost bundle, BundleDescription description) {
- this.bundle = bundle;
- this.description = description;
- this.pkgSources = new KeyedHashSet(false);
- this.data = bundle.getBundleData();
- }
-
- public BundleLoader getBundleLoader() {
- if (System.getSecurityManager() == null)
- return getBundleLoader0();
- return AccessController.doPrivileged(new PrivilegedAction<BundleLoader>() {
- public BundleLoader run() {
- return getBundleLoader0();
- }
- });
- }
-
- synchronized BundleLoader getBundleLoader0() {
- if (loader != null)
- return loader;
- if (bundle.isResolved()) {
- try {
- if (bundle.getBundleId() == 0) // this is the system bundle
- loader = new SystemBundleLoader(bundle, this);
- else
- loader = new BundleLoader(bundle, this);
- } catch (BundleException e) {
- bundle.getFramework().publishFrameworkEvent(FrameworkEvent.ERROR, bundle, e);
- return null;
- }
- }
- return loader;
- }
-
- public BundleLoader getBasicBundleLoader() {
- return loader;
- }
-
- public AbstractBundle getBundleHost() {
- return bundle;
- }
-
- void setStale() {
- stale = true;
- }
-
- public boolean isStale() {
- return stale;
- }
-
- public String toString() {
- String symbolicName = bundle.getSymbolicName();
- StringBuffer sb = new StringBuffer(symbolicName == null ? bundle.getBundleData().getLocation() : symbolicName);
- sb.append("; ").append(Constants.BUNDLE_VERSION_ATTRIBUTE); //$NON-NLS-1$
- sb.append("=\"").append(description.getVersion().toString()).append("\""); //$NON-NLS-1$//$NON-NLS-2$
- return sb.toString();
- }
-
- public org.osgi.framework.Bundle getBundle() {
- if (isStale())
- return null;
-
- return bundle;
- }
-
- public BundleData getBundleData() {
- return data;
- }
-
- public Bundle[] getRequiringBundles() {
- if (isStale())
- return null;
- // This is VERY slow; but never gets called in regular execution.
- BundleDescription[] dependents = description.getDependents();
- if (dependents == null || dependents.length == 0)
- return new Bundle[0];
- List<Bundle> result = new ArrayList<Bundle>(dependents.length);
- for (int i = 0; i < dependents.length; i++)
- addRequirers(dependents[i], result);
- return result.toArray(new org.osgi.framework.Bundle[result.size()]);
- }
-
- void addRequirers(BundleDescription dependent, List<Bundle> result) {
- if (dependent.getHost() != null) // don't look in fragments.
- return;
- BundleLoaderProxy dependentProxy = getBundleLoader().getLoaderProxy(dependent);
- if (dependentProxy == null)
- return; // bundle must have been uninstalled
- if (result.contains(dependentProxy.bundle))
- return; // prevent endless recusion
- BundleLoader dependentLoader = dependentProxy.getBundleLoader();
- BundleLoaderProxy[] requiredBundles = dependentLoader.requiredBundles;
- int[] reexportTable = dependentLoader.reexportTable;
- if (requiredBundles == null)
- return;
- int size = reexportTable == null ? 0 : reexportTable.length;
- int reexportIndex = 0;
- for (int i = 0; i < requiredBundles.length; i++) {
- if (requiredBundles[i] == this) {
- result.add(dependentProxy.bundle);
- if (reexportIndex < size && reexportTable[reexportIndex] == i) {
- reexportIndex++;
- BundleDescription[] dependents = dependent.getDependents();
- if (dependents == null)
- return;
- for (int j = 0; j < dependents.length; j++)
- dependentProxy.addRequirers(dependents[j], result);
- }
- return;
- }
- }
- return;
- }
-
- public String getSymbolicName() {
- return description.getSymbolicName();
- }
-
- public Version getVersion() {
- return description.getVersion();
- }
-
- public boolean isRemovalPending() {
- return description.isRemovalPending();
- }
-
- public BundleDescription getBundleDescription() {
- return description;
- }
-
- PackageSource getPackageSource(String pkgName) {
- // getByKey is called outside of a synch block because we really do not
- // care too much of duplicates getting created. Only the first one will
- // successfully get stored into pkgSources
- PackageSource pkgSource = (PackageSource) pkgSources.getByKey(pkgName);
- if (pkgSource == null) {
- pkgSource = new SingleSourcePackage(pkgName, this);
- synchronized (pkgSources) {
- pkgSources.add(pkgSource);
- }
- }
- return pkgSource;
- }
-
- public boolean inUse() {
- return (description.getDependents().length > 0);
- }
-
- boolean forceSourceCreation(ExportPackageDescription export) {
- boolean strict = Constants.STRICT_MODE.equals(secureAction.getProperty(Constants.OSGI_RESOLVER_MODE));
- return (export.getDirective(Constants.INCLUDE_DIRECTIVE) != null) || (export.getDirective(Constants.EXCLUDE_DIRECTIVE) != null) || (strict && export.getDirective(Constants.FRIENDS_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
- // (i.e. it will be created lazily)
- public PackageSource createPackageSource(ExportPackageDescription export, boolean storeSource) {
- PackageSource pkgSource = null;
-
- // check to see if it is a filtered export
- String includes = (String) export.getDirective(Constants.INCLUDE_DIRECTIVE);
- String excludes = (String) export.getDirective(Constants.EXCLUDE_DIRECTIVE);
- String[] friends = (String[]) export.getDirective(Constants.FRIENDS_DIRECTIVE);
- if (friends != null) {
- boolean strict = Constants.STRICT_MODE.equals(secureAction.getProperty(Constants.OSGI_RESOLVER_MODE));
- if (!strict)
- friends = null; // do not pay attention to friends if not in strict mode
- }
- if (includes != null || excludes != null || friends != null) {
- pkgSource = new FilteredSourcePackage(export.getName(), this, includes, excludes, friends);
- }
-
- if (storeSource) {
- // if the package source is not null then store the source only if it is not already present;
- // getByKey is called outside of a synch block because we really do not
- // care too much of duplicates getting created. Only the first one will
- // successfully get stored into pkgSources
- if (pkgSource != null && pkgSources.getByKey(export.getName()) == null)
- synchronized (pkgSources) {
- pkgSources.add(pkgSource);
- }
- } else {
- // 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(export.getName());
- // the first export cached may not be a simple single source like we need.
- if (pkgSource.getClass() != SingleSourcePackage.class)
- return new SingleSourcePackage(export.getName(), this);
- }
- }
-
- return pkgSource;
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/FilteredSourcePackage.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/FilteredSourcePackage.java
deleted file mode 100644
index 287f9eb7a..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/FilteredSourcePackage.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2004, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.osgi.internal.loader;
-
-import java.net.URL;
-import java.util.*;
-import org.eclipse.osgi.util.ManifestElement;
-
-public class FilteredSourcePackage extends SingleSourcePackage {
- private static final char ALL = '*';
- String[] includes;
- String[] excludes;
- String[] friends;
-
- public FilteredSourcePackage(String name, BundleLoaderProxy supplier, String includes, String excludes, String[] friends) {
- super(name, supplier);
- if (includes != null)
- this.includes = ManifestElement.getArrayFromList(includes);
- if (excludes != null)
- this.excludes = ManifestElement.getArrayFromList(excludes);
- this.friends = friends;
- }
-
- public boolean isFriend(String symbolicName) {
- if (friends == null)
- return true;
- for (int i = 0; i < friends.length; i++)
- if (friends[i].equals(symbolicName))
- return true;
- return false;
- }
-
- public URL getResource(String name) {
- if (isFiltered(name, getId()))
- return null;
- return super.getResource(name);
- }
-
- public Enumeration<URL> getResources(String name) {
- if (isFiltered(name, getId()))
- return null;
- return super.getResources(name);
- }
-
- public Class<?> loadClass(String name) throws ClassNotFoundException {
- if (isFiltered(name, getId()))
- return null;
- return super.loadClass(name);
- }
-
- private boolean isFiltered(String name, String pkgName) {
- String lastName = getName(name, pkgName);
- return !isIncluded(lastName) || isExcluded(lastName);
- }
-
- private String getName(String name, String pkgName) {
- if (!BundleLoader.DEFAULT_PACKAGE.equals(pkgName) && pkgName.length() + 1 <= name.length())
- return name.substring(pkgName.length() + 1);
- return name;
- }
-
- private boolean isIncluded(String name) {
- if (includes == null)
- return true;
- return isInList(name, includes);
- }
-
- private boolean isExcluded(String name) {
- if (excludes == null)
- return false;
- return isInList(name, excludes);
- }
-
- private boolean isInList(String name, String[] list) {
- for (int i = 0; i < list.length; i++) {
- int len = list[i].length();
- if (len == 0)
- continue;
- if (list[i].charAt(0) == ALL && len == 1)
- return true; // handles "*" wild card
- if (list[i].charAt(len - 1) == ALL)
- if (name.startsWith(list[i].substring(0, len - 1)))
- return true;
- if (name.equals(list[i]))
- return true;
-
- }
- return false;
- }
-
- @Override
- public Collection<String> listResources(String path, String filePattern) {
- Collection<String> result = super.listResources(path, filePattern);
- for (Iterator<String> resources = result.iterator(); resources.hasNext();) {
- String resource = resources.next();
- int lastSlash = resource.lastIndexOf('/');
- String fileName = lastSlash >= 0 ? resource.substring(lastSlash + 1) : resource;
- if (!isIncluded(fileName) || isExcluded(fileName))
- resources.remove();
- }
- return result;
- }
-
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/MultiSourcePackage.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/MultiSourcePackage.java
deleted file mode 100644
index 83eefc6c5..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/MultiSourcePackage.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.osgi.internal.loader;
-
-import java.net.URL;
-import java.util.*;
-
-public class MultiSourcePackage extends PackageSource {
- SingleSourcePackage[] suppliers;
-
- MultiSourcePackage(String id, SingleSourcePackage[] suppliers) {
- super(id);
- this.suppliers = suppliers;
- }
-
- public SingleSourcePackage[] getSuppliers() {
- return suppliers;
- }
-
- public Class<?> loadClass(String name) throws ClassNotFoundException {
- Class<?> result = null;
- for (int i = 0; i < suppliers.length; i++) {
- result = suppliers[i].loadClass(name);
- if (result != null)
- return result;
- }
- return result;
- }
-
- public URL getResource(String name) {
- URL result = null;
- for (int i = 0; i < suppliers.length; i++) {
- result = suppliers[i].getResource(name);
- if (result != null)
- return result;
- }
- return result;
- }
-
- public Enumeration<URL> getResources(String name) {
- Enumeration<URL> results = null;
- for (int i = 0; i < suppliers.length; i++)
- results = BundleLoader.compoundEnumerations(results, suppliers[i].getResources(name));
- return results;
- }
-
- @Override
- public Collection<String> listResources(String path, String filePattern) {
- List<String> result = new ArrayList<String>();
- for (SingleSourcePackage source : suppliers) {
- Collection<String> sourceResources = source.listResources(path, filePattern);
- for (String resource : sourceResources) {
- if (!result.contains(resource))
- result.add(resource);
- }
- }
- return result;
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/NullPackageSource.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/NullPackageSource.java
deleted file mode 100644
index 796432ba8..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/NullPackageSource.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.osgi.internal.loader;
-
-import java.net.URL;
-import java.util.*;
-import org.eclipse.osgi.framework.util.KeyedHashSet;
-
-/**
- * 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 KeyedHashSet sources;
-
- private NullPackageSource(String name) {
- super(name);
- }
-
- public SingleSourcePackage[] getSuppliers() {
- return null;
- }
-
- public boolean isNullSource() {
- return true;
- }
-
- public String toString() {
- return id + " -> null"; //$NON-NLS-1$
- }
-
- public Class<?> loadClass(String name) {
- return null;
- }
-
- public URL getResource(String name) {
- return null;
- }
-
- public Enumeration<URL> getResources(String name) {
- return null;
- }
-
- public static synchronized NullPackageSource getNullPackageSource(String name) {
- if (sources == null)
- sources = new KeyedHashSet();
- NullPackageSource result = (NullPackageSource) sources.getByKey(name);
- if (result != null)
- return result;
- result = new NullPackageSource(name);
- sources.add(result);
- return result;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public List<String> listResources(String path, String filePattern) {
- return Collections.EMPTY_LIST;
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/PackageSource.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/PackageSource.java
deleted file mode 100644
index 0f2d98835..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/PackageSource.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.osgi.internal.loader;
-
-import java.io.IOException;
-import java.net.URL;
-import java.util.Collection;
-import java.util.Enumeration;
-import org.eclipse.osgi.framework.util.KeyedElement;
-
-public abstract class PackageSource implements KeyedElement {
- protected String id;
-
- public PackageSource(String id) {
- // others depend on the id being interned; see SingleSourcePackage.equals
- this.id = id.intern();
- }
-
- public String getId() {
- return id;
- }
-
- public abstract SingleSourcePackage[] getSuppliers();
-
- public boolean compare(KeyedElement other) {
- return id.equals(((PackageSource) other).getId());
- }
-
- public int getKeyHashCode() {
- return id.hashCode();
- }
-
- public Object getKey() {
- return id;
- }
-
- public boolean isNullSource() {
- return false;
- }
-
- public boolean isFriend(String symbolicName) {
- return true;
- }
-
- public abstract Class<?> loadClass(String name) throws ClassNotFoundException;
-
- public abstract URL getResource(String name);
-
- public abstract Enumeration<URL> getResources(String name) throws IOException;
-
- //TODO See how this relates with FilteredSourcePackage. Overwriting or doing a double dispatch might be good.
- // 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;
- if (this == other)
- return true;
- SingleSourcePackage[] suppliers1 = getSuppliers();
- SingleSourcePackage[] suppliers2 = other.getSuppliers();
- if (suppliers1 == null || suppliers2 == null)
- return false;
- // This will return true if the specified source has at least one
- // of the suppliers of this source.
- for (int i = 0; i < suppliers1.length; i++)
- for (int j = 0; j < suppliers2.length; j++)
- if (suppliers2[j].equals(suppliers1[i]))
- return true;
- return false;
- }
-
- public abstract Collection<String> listResources(String path, String filePattern);
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/SingleSourcePackage.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/SingleSourcePackage.java
deleted file mode 100644
index 533c99676..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/SingleSourcePackage.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.osgi.internal.loader;
-
-import java.net.URL;
-import java.util.Collection;
-import java.util.Enumeration;
-import org.eclipse.osgi.framework.adaptor.BundleClassLoader;
-
-public class SingleSourcePackage extends PackageSource {
- BundleLoaderProxy supplier;
-
- public SingleSourcePackage(String id, BundleLoaderProxy supplier) {
- super(id);
- this.supplier = supplier;
- }
-
- public SingleSourcePackage[] getSuppliers() {
- return new SingleSourcePackage[] {this};
- }
-
- public String toString() {
- return id + " -> " + supplier; //$NON-NLS-1$
- }
-
- public Class<?> loadClass(String name) throws ClassNotFoundException {
- return supplier.getBundleLoader().findLocalClass(name);
- }
-
- public URL getResource(String name) {
- return supplier.getBundleLoader().findLocalResource(name);
- }
-
- public Enumeration<URL> getResources(String name) {
- return supplier.getBundleLoader().findLocalResources(name);
- }
-
- public boolean equals(Object source) {
- if (this == source)
- return true;
- 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
- return supplier == singleSource.supplier && id == singleSource.getId();
- }
-
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + id.hashCode();
- result = prime * result + supplier.hashCode();
- return result;
- }
-
- @Override
- public Collection<String> listResources(String path, String filePattern) {
- BundleClassLoader bcl = supplier.getBundleLoader().createClassLoader();
- return bcl.listLocalResources(path, filePattern, 0);
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/SystemBundleLoader.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/SystemBundleLoader.java
deleted file mode 100644
index 252fdb2cb..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/SystemBundleLoader.java
+++ /dev/null
@@ -1,277 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.internal.loader;
-
-import java.io.IOException;
-import java.net.URL;
-import java.security.ProtectionDomain;
-import java.util.*;
-import org.eclipse.osgi.framework.adaptor.*;
-import org.eclipse.osgi.framework.internal.core.BundleFragment;
-import org.eclipse.osgi.framework.internal.core.BundleHost;
-import org.eclipse.osgi.service.resolver.ExportPackageDescription;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleException;
-import org.osgi.framework.wiring.BundleWiring;
-
-/**
- * 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$
- final ClassLoader classLoader;
- private final Set<String> eePackages;
- private final Set<String> extPackages;
- private final ClassLoader extClassLoader;
-
- /**
- * @param bundle The system bundle.
- * @param proxy The BundleLoaderProxy for the system bundle
- * @throws BundleException On any error.
- */
- protected SystemBundleLoader(BundleHost bundle, BundleLoaderProxy proxy) throws BundleException {
- super(bundle, proxy);
- ExportPackageDescription[] exports = proxy.getBundleDescription().getSelectedExports();
- if (exports == null || exports.length == 0)
- eePackages = null;
- else {
- eePackages = new HashSet<String>(exports.length);
- for (int i = 0; i < exports.length; i++)
- if (((Integer) exports[i].getDirective(EQUINOX_EE)).intValue() >= 0)
- eePackages.add(exports[i].getName());
- }
- this.classLoader = getClass().getClassLoader();
- extPackages = new HashSet<String>(0); // not common; start with 0
- BundleFragment[] fragments = bundle.getFragments();
- if (fragments != null)
- for (int i = 0; i < fragments.length; i++)
- addExtPackages(fragments[i]);
- ClassLoader extCL = ClassLoader.getSystemClassLoader();
- if (extCL == null)
- extClassLoader = null;
- else {
- while (extCL.getParent() != null)
- extCL = extCL.getParent();
- // make sure extCL is not already on the parent chain of the system classloader
- boolean found = false;
- ClassLoader systemExtCL = this.classLoader;
- while (systemExtCL.getParent() != null && !found) {
- if (systemExtCL.getParent() == extCL)
- found = true;
- else
- systemExtCL = systemExtCL.getParent();
- }
- extClassLoader = found ? null : extCL;
- }
- }
-
- private void addExtPackages(BundleFragment fragment) {
- if ((fragment.getBundleData().getType() & BundleData.TYPE_EXTCLASSPATH_EXTENSION) == 0)
- return;
- ExportPackageDescription[] extExports = fragment.getBundleDescription().getExportPackages();
- for (int j = 0; j < extExports.length; j++)
- extPackages.add(extExports[j].getName());
- }
-
- synchronized public void attachFragment(BundleFragment fragment) throws BundleException {
- super.attachFragment(fragment);
- synchronized (extPackages) {
- addExtPackages(fragment);
- }
- }
-
- /**
- * 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.
- */
- public Class<?> findClass(String name) throws ClassNotFoundException {
- Class<?> result = findLocalClass(name);
- if (result == null)
- throw new ClassNotFoundException(name);
- return result;
- }
-
- /**
- * This method will always return null.
- * This method never gets called because there is no BundleClassLoader for the framework.
- */
- public String findLibrary(String name) {
- return null;
- }
-
- /**
- * The ClassLoader that loads OSGi framework classes is used to find the class.
- */
- Class<?> findLocalClass(String name) {
- try {
- return classLoader.loadClass(name);
- } catch (ClassNotFoundException e) {
- if (extClassLoader != null)
- synchronized (extPackages) {
- if (extPackages.size() > 0 && extPackages.contains(BundleLoader.getPackageName(name)))
- try {
- return extClassLoader.loadClass(name);
- } catch (ClassNotFoundException e2) {
- return null;
- }
- }
- }
- return null;
- }
-
- /**
- * The ClassLoader that loads OSGi framework classes is used to find the resource.
- */
- URL findLocalResource(String name) {
- URL result = classLoader.getResource(name);
- if (result == null && extClassLoader != null)
- synchronized (extPackages) {
- if (extPackages.size() > 0 && extPackages.contains(BundleLoader.getResourcePackageName(name)))
- result = extClassLoader.getResource(name);
- }
- return result;
- }
-
- /**
- * The ClassLoader that loads OSGi framework classes is used to find the resource.
- */
- Enumeration<URL> findLocalResources(String name) {
- Enumeration<URL> result = null;
- try {
- result = classLoader.getResources(name);
- } catch (IOException e) {
- // do nothing
- }
- if ((result == null || !result.hasMoreElements()) && extClassLoader != null)
- synchronized (extPackages) {
- if (extPackages.size() > 0 && extPackages.contains(BundleLoader.getResourcePackageName(name)))
- try {
- result = extClassLoader.getResources(name);
- } catch (IOException e) {
- // do nothing
- }
- }
- return result;
- }
-
- /**
- * The ClassLoader that loads OSGi framework classes is used to find the resource.
- * This method never gets called because there is no BundleClassLoader for the framework.
- */
- public URL findResource(String name) {
- return findLocalResource(name);
- }
-
- /**
- * The ClassLoader that loads OSGi framework classes is used to find the resource.
- * This method never gets called because there is no BundleClassLoader for the framework.
- * @throws IOException
- */
- public Enumeration<URL> findResources(String name) throws IOException {
- return findLocalResources(name);
- }
-
- /**
- * Do nothing on a close.
- */
- protected void close() {
- // Do nothing.
- }
-
- public boolean isEEPackage(String pkgName) {
- return eePackages.contains(pkgName);
- }
-
- BundleClassLoader createBCL(BundleProtectionDomain pd, String[] cp) {
- return new BundleClassLoader() {
-
- public Bundle getBundle() {
- return SystemBundleLoader.this.getBundle();
- }
-
- public Class<?> loadClass(String name) throws ClassNotFoundException {
- return SystemBundleLoader.this.loadClass(name);
- }
-
- public void initialize() {
- // nothing
- }
-
- /**
- * @throws IOException
- */
- public Enumeration<URL> getResources(String name) throws IOException {
- return findLocalResources(name);
- }
-
- public URL getResource(String name) {
- return SystemBundleLoader.this.findLocalResource(name);
- }
-
- public ClassLoader getParent() {
- return SystemBundleLoader.this.classLoader.getParent();
- }
-
- public ClassLoaderDelegate getDelegate() {
- return SystemBundleLoader.this;
- }
-
- public Enumeration<URL> findLocalResources(String resource) {
- return SystemBundleLoader.this.findLocalResources(resource);
- }
-
- public URL findLocalResource(String resource) {
- return getResource(resource);
- }
-
- /**
- * @throws ClassNotFoundException
- */
- public Class<?> findLocalClass(String classname) throws ClassNotFoundException {
- return SystemBundleLoader.this.findLocalClass(classname);
- }
-
- public void close() {
- // nothing
- }
-
- public void attachFragment(BundleData bundledata, ProtectionDomain domain, String[] classpath) {
- // nothing
- }
-
- public List<URL> findEntries(String path, String filePattern, int options) {
- Bundle systemBundle = SystemBundleLoader.this.getBundle();
- boolean recurse = (options & BundleWiring.FINDENTRIES_RECURSE) != 0;
- @SuppressWarnings("unchecked")
- List<URL> result = Collections.EMPTY_LIST;
- Enumeration<URL> entries = systemBundle.findEntries(path, filePattern, recurse);
- if (entries != null) {
- result = new ArrayList<URL>();
- while (entries.hasMoreElements())
- result.add(entries.nextElement());
- }
- return Collections.unmodifiableList(result);
- }
-
- @SuppressWarnings("unchecked")
- public Collection<String> listResources(String path, String filePattern, int options) {
- return Collections.EMPTY_LIST;
- }
-
- @SuppressWarnings("unchecked")
- public Collection<String> listLocalResources(String path, String filePattern, int options) {
- return Collections.EMPTY_LIST;
- }
- };
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/buddy/DependentPolicy.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/buddy/DependentPolicy.java
deleted file mode 100644
index 74121aeaa..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/buddy/DependentPolicy.java
+++ /dev/null
@@ -1,119 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.internal.loader.buddy;
-
-import java.io.IOException;
-import java.net.URL;
-import java.util.*;
-import org.eclipse.osgi.internal.loader.BundleLoader;
-import org.eclipse.osgi.internal.loader.BundleLoaderProxy;
-import org.eclipse.osgi.service.resolver.BundleDescription;
-
-/**
- * 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<BundleDescription> 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
- allDependents = new ArrayList<BundleDescription>();
- basicAddImmediateDependents(buddyRequester.getBundle().getBundleDescription());
- //If there is no dependent, reset to null
- if (allDependents.size() == 0)
- allDependents = null;
- }
-
- public Class<?> loadClass(String name) {
- if (allDependents == null)
- return null;
-
- Class<?> result = null;
- //size may change, so we must check it every time
- for (int i = 0; i < allDependents.size() && result == null; i++) {
- BundleDescription searchedBundle = allDependents.get(i);
- try {
- BundleLoaderProxy proxy = buddyRequester.getLoaderProxy(searchedBundle);
- if (proxy == null)
- continue;
- result = proxy.getBundleLoader().findClass(name);
- } catch (ClassNotFoundException e) {
- if (result == null)
- addDependent(i, searchedBundle);
- }
- }
- return result;
- }
-
- private synchronized void addDependent(int i, BundleDescription searchedBundle) {
- if (i > lastDependentOfAdded) {
- lastDependentOfAdded = i;
- basicAddImmediateDependents(searchedBundle);
- }
- }
-
- public URL loadResource(String name) {
- if (allDependents == null)
- return null;
-
- URL result = null;
- //size may change, so we must check it every time
- for (int i = 0; i < allDependents.size() && result == null; i++) {
- BundleDescription searchedBundle = allDependents.get(i);
- BundleLoaderProxy proxy = buddyRequester.getLoaderProxy(searchedBundle);
- if (proxy == null)
- continue;
- result = proxy.getBundleLoader().findResource(name);
- if (result == null) {
- addDependent(i, searchedBundle);
- }
- }
- return result;
- }
-
- public Enumeration<URL> loadResources(String name) {
- if (allDependents == null)
- return null;
-
- Enumeration<URL> results = null;
- //size may change, so we must check it every time
- for (int i = 0; i < allDependents.size(); i++) {
- BundleDescription searchedBundle = allDependents.get(i);
- try {
- BundleLoaderProxy proxy = buddyRequester.getLoaderProxy(searchedBundle);
- if (proxy == null)
- continue;
- results = BundleLoader.compoundEnumerations(results, proxy.getBundleLoader().findResources(name));
- addDependent(i, searchedBundle);
- } catch (IOException e) {
- //Ignore and keep looking
- }
- }
- return results;
- }
-
- private void basicAddImmediateDependents(BundleDescription root) {
- BundleDescription[] dependents = root.getDependents();
- for (int i = 0; i < dependents.length; i++) {
- BundleDescription toAdd = dependents[i];
- if (toAdd.getHost() == null && !allDependents.contains(toAdd)) {
- allDependents.add(toAdd);
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/buddy/GlobalPolicy.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/buddy/GlobalPolicy.java
deleted file mode 100644
index 1985ff87a..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/buddy/GlobalPolicy.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.osgi.internal.loader.buddy;
-
-import java.io.IOException;
-import java.net.URL;
-import java.util.Enumeration;
-import org.eclipse.osgi.internal.loader.BundleLoader;
-import org.osgi.service.packageadmin.ExportedPackage;
-import org.osgi.service.packageadmin.PackageAdmin;
-
-/**
- * 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.
- */
-public class GlobalPolicy implements IBuddyPolicy {
- private PackageAdmin admin;
-
- public GlobalPolicy(PackageAdmin admin) {
- this.admin = admin;
- }
-
- public Class<?> loadClass(String name) {
- ExportedPackage pkg = admin.getExportedPackage(BundleLoader.getPackageName(name));
- if (pkg == null)
- return null;
- try {
- return pkg.getExportingBundle().loadClass(name);
- } catch (ClassNotFoundException e) {
- return null;
- }
- }
-
- public URL loadResource(String name) {
- //get all exported packages that match the resource's package
- ExportedPackage pkg = admin.getExportedPackage(BundleLoader.getResourcePackageName(name));
- if (pkg == null)
- return null;
- return pkg.getExportingBundle().getResource(name);
- }
-
- public Enumeration<URL> loadResources(String name) {
- //get all exported packages that match the resource's package
- ExportedPackage[] pkgs = admin.getExportedPackages(BundleLoader.getResourcePackageName(name));
- if (pkgs == null || pkgs.length == 0)
- return null;
-
- //get all matching resources for each package
- Enumeration<URL> results = null;
- for (int i = 0; i < pkgs.length; i++) {
- try {
- results = BundleLoader.compoundEnumerations(results, pkgs[i].getExportingBundle().getResources(name));
- } catch (IOException e) {
- //ignore IO problems and try next package
- }
- }
-
- return results;
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/buddy/IBuddyPolicy.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/buddy/IBuddyPolicy.java
deleted file mode 100644
index a4066eeea..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/buddy/IBuddyPolicy.java
+++ /dev/null
@@ -1,22 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.osgi.internal.loader.buddy;
-
-import java.net.URL;
-import java.util.Enumeration;
-
-public interface IBuddyPolicy {
- public Class<?> loadClass(String name);
-
- public URL loadResource(String name);
-
- public Enumeration<URL> loadResources(String name);
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/buddy/PolicyHandler.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/buddy/PolicyHandler.java
deleted file mode 100644
index 0795902e1..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/buddy/PolicyHandler.java
+++ /dev/null
@@ -1,219 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.osgi.internal.loader.buddy;
-
-import java.net.URL;
-import java.util.*;
-import org.eclipse.osgi.framework.internal.core.Constants;
-import org.eclipse.osgi.internal.loader.BundleLoader;
-import org.osgi.framework.*;
-import org.osgi.service.packageadmin.PackageAdmin;
-
-public class PolicyHandler implements SynchronousBundleListener {
- //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$
- private final static String APP_POLICY = "app"; //$NON-NLS-1$
- private final static String EXT_POLICY = "ext"; //$NON-NLS-1$
- 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.
- private final BundleLoader policedLoader;
- //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
- private final ThreadLocal<Set<String>> beingLoaded;
- private final PackageAdmin packageAdmin;
-
- public PolicyHandler(BundleLoader loader, String buddyList, PackageAdmin packageAdmin) {
- policedLoader = loader;
- policies = getArrayFromList(buddyList);
- beingLoaded = new ThreadLocal<Set<String>>();
- this.packageAdmin = packageAdmin;
- }
-
- static Object[] getArrayFromList(String stringList) {
- if (stringList == null || stringList.trim().equals("")) //$NON-NLS-1$
- return null;
- List<Object> list = new ArrayList<Object>();
- StringTokenizer tokens = new StringTokenizer(stringList, ","); //$NON-NLS-1$
- while (tokens.hasMoreTokens()) {
- String token = tokens.nextToken().trim();
- if (!token.equals("")) //$NON-NLS-1$
- list.add(token);
- }
- return list.isEmpty() ? new Object[0] : list.toArray(new Object[list.size()]);
- }
-
- private IBuddyPolicy getPolicyImplementation(Object[] policiesSnapshot, int policyOrder) {
- synchronized (policiesSnapshot) {
- if (policyOrder >= policiesSnapshot.length)
- return null;
- if (policiesSnapshot[policyOrder] instanceof String) {
- String buddyName = (String) policiesSnapshot[policyOrder];
-
- if (REGISTERED_POLICY.equals(buddyName)) {
- policiesSnapshot[policyOrder] = new RegisteredPolicy(policedLoader);
- return (IBuddyPolicy) policiesSnapshot[policyOrder];
- }
- if (BOOT_POLICY.equals(buddyName)) {
- policiesSnapshot[policyOrder] = SystemPolicy.getInstance(SystemPolicy.BOOT);
- return (IBuddyPolicy) policiesSnapshot[policyOrder];
- }
- if (APP_POLICY.equals(buddyName)) {
- policiesSnapshot[policyOrder] = SystemPolicy.getInstance(SystemPolicy.APP);
- return (IBuddyPolicy) policiesSnapshot[policyOrder];
- }
- if (EXT_POLICY.equals(buddyName)) {
- policiesSnapshot[policyOrder] = SystemPolicy.getInstance(SystemPolicy.EXT);
- return (IBuddyPolicy) policiesSnapshot[policyOrder];
- }
- if (DEPENDENT_POLICY.equals(buddyName)) {
- policiesSnapshot[policyOrder] = new DependentPolicy(policedLoader);
- return (IBuddyPolicy) policiesSnapshot[policyOrder];
- }
- if (GLOBAL_POLICY.equals(buddyName)) {
- policiesSnapshot[policyOrder] = new GlobalPolicy(packageAdmin);
- return (IBuddyPolicy) policiesSnapshot[policyOrder];
- }
- if (PARENT_POLICY.equals(buddyName)) {
- policiesSnapshot[policyOrder] = new SystemPolicy(policedLoader.getParentClassLoader());
- return (IBuddyPolicy) policiesSnapshot[policyOrder];
- }
-
- // //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 Enumeration loadResources(String name) {
- // return null;
- // }
- // };
- //
- // //The policies loaded through service are not cached
- // return ((IBuddyPolicy) fwkCtx.getService(matchingBuddies[0]));
- }
- return (IBuddyPolicy) policiesSnapshot[policyOrder];
- }
- }
-
- public Class<?> doBuddyClassLoading(String name) {
- if (startLoading(name) == false)
- return null;
-
- Class<?> result = null;
- Object[] policiesSnapshot = policies;
- int policyCount = (policiesSnapshot == null) ? 0 : policiesSnapshot.length;
- for (int i = 0; i < policyCount && result == null; i++) {
- IBuddyPolicy policy = getPolicyImplementation(policiesSnapshot, i);
- if (policy != null)
- result = policy.loadClass(name);
- }
- stopLoading(name);
- return result;
- }
-
- public URL doBuddyResourceLoading(String name) {
- if (startLoading(name) == false)
- return null;
-
- URL result = null;
- Object[] policiesSnapshot = policies;
- int policyCount = (policiesSnapshot == null) ? 0 : policiesSnapshot.length;
- for (int i = 0; i < policyCount && result == null; i++) {
- IBuddyPolicy policy = getPolicyImplementation(policiesSnapshot, i);
- if (policy != null)
- result = policy.loadResource(name);
- }
- stopLoading(name);
- return result;
- }
-
- public Enumeration<URL> doBuddyResourcesLoading(String name) {
- if (startLoading(name) == false)
- return null;
-
- List<URL> results = null;
- Object[] policiesSnapshot = policies;
- int policyCount = (policiesSnapshot == null) ? 0 : policiesSnapshot.length;
- for (int i = 0; i < policyCount; i++) {
- IBuddyPolicy policy = getPolicyImplementation(policiesSnapshot, i);
- if (policy == null)
- continue;
- Enumeration<URL> result = policy.loadResources(name);
- if (result != null) {
- if (results == null)
- results = new ArrayList<URL>(policyCount);
- while (result.hasMoreElements()) {
- URL url = result.nextElement();
- if (!results.contains(url)) //only add if not already added
- results.add(url);
- }
- }
- }
- stopLoading(name);
- return results == null || results.isEmpty() ? null : Collections.enumeration(results);
- }
-
- private boolean startLoading(String name) {
- Set<String> classesAndResources = beingLoaded.get();
- if (classesAndResources != null && classesAndResources.contains(name))
- return false;
-
- if (classesAndResources == null) {
- classesAndResources = new HashSet<String>(3);
- beingLoaded.set(classesAndResources);
- }
- classesAndResources.add(name);
- return true;
- }
-
- private void stopLoading(String name) {
- beingLoaded.get().remove(name);
- }
-
- public void open(BundleContext context) {
- context.addBundleListener(this);
- }
-
- public void close(BundleContext context) {
- context.removeBundleListener(this);
- }
-
- public void bundleChanged(BundleEvent event) {
- if ((event.getType() & (BundleEvent.RESOLVED | BundleEvent.UNRESOLVED)) == 0)
- return;
- // reinitialize the policies
- try {
- String list = policedLoader.getBundle().getBundleData().getManifest().get(Constants.BUDDY_LOADER);
- policies = getArrayFromList(list);
- } catch (BundleException e) {
- //Ignore
- }
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/buddy/RegisteredPolicy.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/buddy/RegisteredPolicy.java
deleted file mode 100644
index bf59610c1..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/buddy/RegisteredPolicy.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.osgi.internal.loader.buddy;
-
-import java.io.IOException;
-import java.net.URL;
-import java.util.Enumeration;
-import java.util.Iterator;
-import org.eclipse.osgi.framework.internal.core.AbstractBundle;
-import org.eclipse.osgi.framework.internal.core.Constants;
-import org.eclipse.osgi.internal.loader.BundleLoader;
-import org.eclipse.osgi.internal.loader.BundleLoaderProxy;
-import org.eclipse.osgi.service.resolver.BundleDescription;
-import org.eclipse.osgi.util.ManifestElement;
-import org.osgi.framework.BundleException;
-
-/**
- *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;
- if (allDependents == null)
- return;
-
- for (Iterator<BundleDescription> iter = allDependents.iterator(); iter.hasNext();) {
- BundleLoaderProxy proxy = buddyRequester.getLoaderProxy(iter.next());
- if (proxy == null)
- iter.remove();
-
- try {
- String[] allContributions = ManifestElement.getArrayFromList(((AbstractBundle) proxy.getBundle()).getBundleData().getManifest().get(Constants.REGISTERED_POLICY));
- if (allContributions == null) {
- iter.remove();
- continue;
- }
- boolean contributes = false;
- for (int j = 0; j < allContributions.length && contributes == false; j++) {
- if (allContributions[j].equals(buddyRequester.getBundle().getSymbolicName()))
- contributes = true;
- }
- if (!contributes)
- iter.remove();
-
- } catch (BundleException e) {
- iter.remove();
- }
- }
-
- //After the filtering, if nothing is left then null out the variable for optimization
- if (allDependents.size() == 0)
- allDependents = null;
- }
-
- public Class<?> loadClass(String name) {
- if (allDependents == null)
- return null;
-
- Class<?> result = null;
- int size = allDependents.size();
- for (int i = 0; i < size && result == null; i++) {
- try {
- BundleLoaderProxy proxy = buddyRequester.getLoaderProxy(allDependents.get(i));
- if (proxy == null)
- continue;
- result = proxy.getBundleLoader().findClass(name);
- } catch (ClassNotFoundException e) {
- //Nothing to do, just keep looking
- continue;
- }
- }
- return result;
- }
-
- public URL loadResource(String name) {
- if (allDependents == null)
- return null;
-
- URL result = null;
- int size = allDependents.size();
- for (int i = 0; i < size && result == null; i++) {
- BundleLoaderProxy proxy = buddyRequester.getLoaderProxy(allDependents.get(i));
- if (proxy == null)
- continue;
- result = proxy.getBundleLoader().findResource(name);
- }
- return result;
- }
-
- public Enumeration<URL> loadResources(String name) {
- if (allDependents == null)
- return null;
-
- Enumeration<URL> results = null;
- int size = allDependents.size();
- for (int i = 0; i < size; i++) {
- try {
- BundleLoaderProxy proxy = buddyRequester.getLoaderProxy(allDependents.get(i));
- if (proxy == null)
- continue;
- results = BundleLoader.compoundEnumerations(results, proxy.getBundleLoader().findResources(name));
- } catch (IOException e) {
- //Ignore and keep looking
- }
- }
- return results;
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/buddy/SystemPolicy.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/buddy/SystemPolicy.java
deleted file mode 100644
index a72e6ac15..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/loader/buddy/SystemPolicy.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.osgi.internal.loader.buddy;
-
-import java.io.IOException;
-import java.net.URL;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.util.Enumeration;
-
-public class SystemPolicy implements IBuddyPolicy {
-
- private static class ParentClassLoader extends ClassLoader {
- protected ParentClassLoader() {
- super(Object.class.getClassLoader());
- }
- }
-
- public static final byte BOOT = 0;
- public static final byte EXT = 1;
- public static final byte APP = 2;
-
- private static SystemPolicy[] instances = new SystemPolicy[3];
-
- private ClassLoader classLoader;
-
- public static SystemPolicy getInstance(final byte type) {
- if (instances[type] == null) {
- instances[type] = new SystemPolicy();
- instances[type].classLoader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
- public ClassLoader run() {
- return createClassLoader(type);
- }
- });
- }
- return instances[type];
- }
-
- public SystemPolicy() {
- //Nothing to do
- }
-
- public SystemPolicy(ClassLoader parent) {
- classLoader = parent;
- }
-
- static ClassLoader createClassLoader(byte type) {
- switch (type) {
- case APP :
- if (ClassLoader.getSystemClassLoader() != null)
- return ClassLoader.getSystemClassLoader();
- return new ParentClassLoader();
-
- case BOOT :
- return new ParentClassLoader();
-
- case EXT :
- if (ClassLoader.getSystemClassLoader() != null)
- return ClassLoader.getSystemClassLoader().getParent();
- return new ParentClassLoader();
- }
- return null;
- }
-
- public Class<?> loadClass(String name) {
- try {
- return classLoader.loadClass(name);
- } catch (ClassNotFoundException e) {
- return null;
- }
- }
-
- public URL loadResource(String name) {
- return classLoader.getResource(name);
- }
-
- public Enumeration<URL> loadResources(String name) {
- try {
- return classLoader.getResources(name);
- } catch (IOException e) {
- return null;
- }
- }
-
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/BundlePermissions.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/BundlePermissions.java
deleted file mode 100644
index 5ade23ff0..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/BundlePermissions.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.osgi.internal.permadmin;
-
-import java.security.Permission;
-import java.security.PermissionCollection;
-import java.util.Enumeration;
-import java.util.NoSuchElementException;
-import org.osgi.framework.Bundle;
-
-public final class BundlePermissions extends PermissionCollection {
- private static final long serialVersionUID = -5443618108312606612L;
-
- // Note that this forces the Enumeration inner class to be loaded as soon as possible (see bug 119069)
- static final Enumeration<Permission> EMPTY_ENUMERATION = new Enumeration<Permission>() {
- public boolean hasMoreElements() {
- return false;
- }
-
- public Permission nextElement() {
- throw new NoSuchElementException();
- }
- };
-
- private final Bundle bundle;
- private final SecurityAdmin securityAdmin;
- private final PermissionInfoCollection impliedPermissions;
- private final PermissionInfoCollection restrictedPermissions;
-
- public BundlePermissions(Bundle bundle, SecurityAdmin securityAdmin, PermissionInfoCollection impliedPermissions, PermissionInfoCollection restrictedPermissions) {
- this.bundle = bundle;
- this.securityAdmin = securityAdmin;
- this.impliedPermissions = impliedPermissions;
- this.restrictedPermissions = restrictedPermissions;
- setReadOnly(); // collections are managed with ConditionalPermissionAdmin
- }
-
- public void add(Permission permission) {
- throw new SecurityException();
- }
-
- public Enumeration<Permission> elements() {
- // TODO return an empty enumeration for now;
- // It does not seem possible to do this properly with multiple exports and conditional permissions.
- // When looking to fix this be sure the Enumeration class is loaded as soon as possible (see bug 119069)
- return EMPTY_ENUMERATION;
- }
-
- public boolean implies(Permission permission) {
- // first check implied permissions
- if ((impliedPermissions != null) && impliedPermissions.implies(permission))
- return true;
- // We must be allowed by the restricted permissions to have any hope of passing the check
- if ((restrictedPermissions != null) && !restrictedPermissions.implies(permission))
- return false;
- return securityAdmin.checkPermission(permission, this);
- }
-
- public Bundle getBundle() {
- return bundle;
- }
-
- void clearPermissionCache() {
- if (impliedPermissions != null)
- impliedPermissions.clearPermissionCache();
- if (restrictedPermissions != null)
- restrictedPermissions.clearPermissionCache();
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/EquinoxSecurityManager.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/EquinoxSecurityManager.java
deleted file mode 100644
index 10d5ce78e..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/EquinoxSecurityManager.java
+++ /dev/null
@@ -1,192 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.internal.permadmin;
-
-import java.security.*;
-import java.util.*;
-import org.eclipse.osgi.internal.permadmin.SecurityRow.Decision;
-import org.osgi.service.condpermadmin.Condition;
-
-/**
- *
- * This security manager implements the ConditionalPermission processing for
- * OSGi. It is to be used with ConditionalPermissionAdmin.
- *
- */
-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.
- */
- static {
- Class<?> c;
- c = CheckPermissionAction.class;
- c = CheckContext.class;
- c.getName(); // to prevent compiler warnings
- }
-
- static class CheckContext {
- // A non zero depth indicates that we are doing a recursive permission check.
- List<List<Decision[]>> depthCondSets = new ArrayList<List<Decision[]>>(2);
- List<AccessControlContext> accs = new ArrayList<AccessControlContext>(2);
- List<Class<?>> CondClassSet;
-
- public int getDepth() {
- return depthCondSets.size() - 1;
- }
- }
-
- static class CheckPermissionAction implements PrivilegedAction<Object> {
- Permission perm;
- Object context;
- EquinoxSecurityManager fsm;
-
- CheckPermissionAction(EquinoxSecurityManager fsm, Permission perm, Object context) {
- this.fsm = fsm;
- this.perm = perm;
- this.context = context;
- }
-
- public Object run() {
- fsm.internalCheckPermission(perm, context);
- return null;
- }
- }
-
- private final ThreadLocal<CheckContext> localCheckContext = new ThreadLocal<CheckContext>();
-
- boolean addConditionsForDomain(Decision[] results) {
- CheckContext cc = localCheckContext.get();
- if (cc == null) {
- // We are being invoked in a weird way. Perhaps the ProtectionDomain is
- // getting invoked directly.
- return false;
- }
- List<Decision[]> condSets = cc.depthCondSets.get(cc.getDepth());
- if (condSets == null) {
- condSets = new ArrayList<Decision[]>(1);
- cc.depthCondSets.set(cc.getDepth(), condSets);
- }
- condSets.add(results);
- return true;
- }
-
- boolean inCheckPermission() {
- return localCheckContext.get() != null;
- }
-
- public void checkPermission(Permission perm, Object context) {
- AccessController.doPrivileged(new CheckPermissionAction(this, perm, context));
- }
-
- /**
- * 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.
- */
- public AccessControlContext getContextToBeChecked() {
- CheckContext cc = localCheckContext.get();
- if (cc != null && cc.accs != null && !cc.accs.isEmpty())
- return cc.accs.get(cc.accs.size() - 1);
- return null;
- }
-
- void internalCheckPermission(Permission perm, Object context) {
- AccessControlContext acc = (AccessControlContext) context;
- CheckContext cc = localCheckContext.get();
- if (cc == null) {
- cc = new CheckContext();
- localCheckContext.set(cc);
- }
- cc.depthCondSets.add(null); // initialize postponed condition set to null
- cc.accs.add(acc);
- try {
- acc.checkPermission(perm);
- // We want to pop the first set of postponed conditions and process them
- List<Decision[]> conditionSets = cc.depthCondSets.get(cc.getDepth());
- if (conditionSets == null)
- return;
- // TODO the spec seems impossible to implement just doing the simple thing for now
- Map<Class<? extends Condition>, Dictionary<Object, Object>> conditionDictionaries = new HashMap<Class<? extends Condition>, Dictionary<Object, Object>>();
- for (Decision[] domainDecisions : conditionSets) {
- boolean grant = false;
- for (int i = 0; i < domainDecisions.length; i++) {
- if (domainDecisions[i] == null)
- break;
- if ((domainDecisions[i].decision & SecurityTable.ABSTAIN) != 0)
- continue;
- if ((domainDecisions[i].decision & SecurityTable.POSTPONED) == 0) {
- // hit an immediate decision; use it
- if ((domainDecisions[i].decision & SecurityTable.GRANTED) != 0)
- grant = true;
- break;
- }
- int decision = getPostponedDecision(domainDecisions[i], conditionDictionaries, cc);
- if ((decision & SecurityTable.ABSTAIN) != 0)
- continue;
- if ((decision & SecurityTable.GRANTED) != 0)
- grant = true;
- break;
- }
- if (!grant)
- // did not find a condition to grant the permission for this domain
- throw new SecurityException("Conditions not satisfied"); //$NON-NLS-1$
- // continue to next domain
- }
-
- } finally {
- cc.depthCondSets.remove(cc.getDepth());
- cc.accs.remove(cc.accs.size() - 1);
- }
- }
-
- private int getPostponedDecision(Decision decision, Map<Class<? extends Condition>, Dictionary<Object, Object>> conditionDictionaries, CheckContext cc) {
- Condition[] postponed = decision.postponed;
- for (int i = 0; i < postponed.length; i++) {
- Dictionary<Object, Object> condContext = conditionDictionaries.get(postponed[i].getClass());
- if (condContext == null) {
- condContext = new Hashtable<Object, Object>();
- conditionDictionaries.put(postponed[i].getClass(), condContext);
- }
- // prevent recursion into Condition
- if (cc.CondClassSet == null)
- cc.CondClassSet = new ArrayList<Class<?>>(2);
- if (cc.CondClassSet.contains(postponed[i].getClass()))
- return SecurityTable.ABSTAIN;
- cc.CondClassSet.add(postponed[i].getClass());
- try {
- // must call isMutable before calling isSatisfied according to the specification
- boolean mutable = postponed[i].isMutable();
- boolean isSatisfied = postponed[i].isSatisfied(new Condition[] {postponed[i]}, condContext);
- decision.handleImmutable(postponed[i], isSatisfied, mutable);
- if (!isSatisfied)
- return SecurityTable.ABSTAIN;
- } finally {
- cc.CondClassSet.remove(postponed[i].getClass());
- }
- }
- // call postponed conditions are satisfied return the decision
- return decision.decision;
- }
-
- public void checkPermission(Permission perm) {
- checkPermission(perm, getSecurityContext());
- }
-
- public Object getSecurityContext() {
- return AccessController.getContext();
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/PermissionAdminTable.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/PermissionAdminTable.java
deleted file mode 100644
index 472c35009..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/PermissionAdminTable.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.osgi.internal.permadmin;
-
-import java.util.HashMap;
-import java.util.Map;
-import org.osgi.service.permissionadmin.PermissionInfo;
-
-public class PermissionAdminTable {
- private final Map<String, PermissionInfoCollection> locations = new HashMap<String, PermissionInfoCollection>();
-
- String[] getLocations() {
- return locations.keySet().toArray(new String[locations.size()]);
- }
-
- PermissionInfo[] getPermissions(String location) {
- PermissionInfoCollection collection = locations.get(location);
- if (collection != null)
- return collection.getPermissionInfos();
- return null;
- }
-
- void setPermissions(String location, PermissionInfo[] permissions) {
- if (permissions == null) {
- locations.remove(location);
- return;
- }
- locations.put(location, new PermissionInfoCollection(permissions));
- }
-
- PermissionInfoCollection getCollection(String location) {
- return locations.get(location);
- }
-
- PermissionInfoCollection[] getCollections() {
- String[] currentLocations = getLocations();
- PermissionInfoCollection[] results = new PermissionInfoCollection[currentLocations.length];
- for (int i = 0; i < results.length; i++)
- results[i] = getCollection(currentLocations[i]);
- return results;
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/PermissionInfoCollection.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/PermissionInfoCollection.java
deleted file mode 100644
index 8d72ff1cd..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/PermissionInfoCollection.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.osgi.internal.permadmin;
-
-import java.io.File;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.security.*;
-import java.util.*;
-import org.osgi.service.permissionadmin.PermissionInfo;
-
-public final class PermissionInfoCollection extends PermissionCollection {
- private static final long serialVersionUID = 3140511562980923957L;
- /* Used to find permission constructors in addPermissions */
- 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};
-
- /* @GuardedBy(cachedPermisssionCollections) */
- private final Map<Class<? extends Permission>, PermissionCollection> cachedPermissionCollections = new HashMap<Class<? extends Permission>, PermissionCollection>();
- private final boolean hasAllPermission;
- private final PermissionInfo[] permInfos;
-
- public PermissionInfoCollection(PermissionInfo[] permInfos) {
- this.permInfos = permInfos;
- boolean tempAllPermissions = false;
- for (int i = 0; i < permInfos.length && !tempAllPermissions; i++)
- if (permInfos[i].getType().equals(AllPermission.class.getName()))
- tempAllPermissions = true;
- this.hasAllPermission = tempAllPermissions;
- setReadOnly(); // collections are managed with ConditionalPermissionAdmin
- }
-
- public void add(Permission arg0) {
- throw new SecurityException();
- }
-
- public Enumeration<Permission> elements() {
- // TODO return an empty enumeration for now;
- return BundlePermissions.EMPTY_ENUMERATION;
- }
-
- public boolean implies(Permission perm) {
- if (hasAllPermission)
- return true;
- Class<? extends Permission> permClass = perm.getClass();
- PermissionCollection collection;
- synchronized (cachedPermissionCollections) {
- collection = cachedPermissionCollections.get(permClass);
- }
- // must populate the collection outside of the lock to prevent class loader deadlock
- if (collection == null) {
- collection = perm.newPermissionCollection();
- if (collection == null)
- collection = new PermissionsHash();
- try {
- addPermissions(collection, permClass);
- } catch (Exception e) {
- throw (SecurityException) new SecurityException("Exception creating permissions: " + permClass + ": " + e.getMessage()).initCause(e); //$NON-NLS-1$ //$NON-NLS-2$
- }
- synchronized (cachedPermissionCollections) {
- // check to see if another thread beat this thread at adding the collection
- PermissionCollection exists = cachedPermissionCollections.get(permClass);
- if (exists != null)
- collection = exists;
- else
- cachedPermissionCollections.put(permClass, collection);
- }
- }
- return collection.implies(perm);
- }
-
- PermissionInfo[] getPermissionInfos() {
- return permInfos;
- }
-
- private void addPermissions(PermissionCollection collection, Class<? extends Permission> permClass) throws NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
- String permClassName = permClass.getName();
- Constructor<? extends Permission> constructor = null;
- int numArgs = -1;
- for (int i = permClassArrayArgs.length - 1; i >= 0; i--) {
- try {
- constructor = permClass.getConstructor(permClassArrayArgs[i]);
- numArgs = i;
- break;
- } catch (NoSuchMethodException e) {
- // ignore
- }
- }
- if (constructor == null)
- throw new NoSuchMethodException(permClass.getName() + ".<init>()"); //$NON-NLS-1$
- /*
- * TODO: We need to cache the permission constructors to enhance performance (see bug 118813).
- */
- for (int i = 0; i < permInfos.length; i++) {
- if (permInfos[i].getType().equals(permClassName)) {
- String args[] = new String[numArgs];
- if (numArgs > 0)
- args[0] = permInfos[i].getName();
- if (numArgs > 1)
- args[1] = permInfos[i].getActions();
-
- if (permInfos[i].getType().equals("java.io.FilePermission")) { //$NON-NLS-1$
- // map FilePermissions for relative names to the bundle's data area
- if (!args[0].equals("<<ALL FILES>>")) { //$NON-NLS-1$
- File file = new File(args[0]);
- if (!file.isAbsolute()) { // relative name
- // TODO need to figure out how to do relative FilePermissions from the dataFile
- continue;
- }
- }
- }
- collection.add(constructor.newInstance((Object[]) args));
- }
- }
- }
-
- void clearPermissionCache() {
- synchronized (cachedPermissionCollections) {
- cachedPermissionCollections.clear();
- }
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/PermissionsHash.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/PermissionsHash.java
deleted file mode 100644
index 667f23e01..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/PermissionsHash.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.osgi.internal.permadmin;
-
-import java.security.Permission;
-import java.security.PermissionCollection;
-import java.util.Enumeration;
-import java.util.Hashtable;
-
-/**
- * A simple Hashtable based collection of Permission objects.
- * <p>
- * 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.
- * <p>
- * 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 {
- private static final long serialVersionUID = 3258408426341284153L;
- /**
- * A hashtable to store the elements of the collection.
- */
- Hashtable<Permission, Permission> perms = new Hashtable<Permission, Permission>(8);
-
- /**
- * Constructs a new instance of this class.
- *
- */
- public PermissionsHash() {
- super();
- }
-
- /**
- * 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.
- */
- public void add(Permission perm) {
- if (isReadOnly()) {
- throw new SecurityException();
- }
-
- perms.put(perm, perm);
- }
-
- /**
- * Answers an enumeration of the permissions
- * in the receiver.
- *
- * @return Enumeration
- * the permissions in the receiver.
- */
- public Enumeration<Permission> elements() {
- return perms.keys();
- }
-
- /**
- * Indicates whether the argument permission is implied
- * by the permissions contained in the receiver.
- *
- * @return boolean
- * <code>true</code> if the argument permission
- * is implied by the permissions in the receiver,
- * and <code>false</code> if it is not.
- * @param perm java.security.Permission
- * the permission to check
- */
- public boolean implies(Permission perm) {
- Permission p = perms.get(perm);
-
- if ((p != null) && p.implies(perm)) {
- return true;
- }
-
- Enumeration<Permission> permsEnum = elements();
-
- while (permsEnum.hasMoreElements()) {
- if (permsEnum.nextElement().implies(perm)) {
- return true;
- }
- }
-
- return false;
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/SecurePermissionStorage.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/SecurePermissionStorage.java
deleted file mode 100644
index 270212b85..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/SecurePermissionStorage.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.internal.permadmin;
-
-import java.io.IOException;
-import java.security.*;
-import org.eclipse.osgi.framework.adaptor.PermissionStorage;
-
-/**
- * PermissionStorage privileged action class. This class is not thread safe. Callers
- * must ensure multiple threads do not call methods on this class at the same time.
- */
-public class SecurePermissionStorage implements PermissionStorage, PrivilegedExceptionAction<String[]> {
- private final PermissionStorage storage;
- private String location;
- private String[] data;
- private String[] infos;
- private int action;
- private static final int GET = 1;
- private static final int SET = 2;
- private static final int LOCATION = 3;
- private static final int GET_INFOS = 4;
- private static final int SAVE_INFOS = 5;
-
- public SecurePermissionStorage(PermissionStorage storage) {
- this.storage = storage;
- }
-
- public String[] run() throws IOException {
- switch (action) {
- case GET :
- return storage.getPermissionData(location);
- case SET :
- storage.setPermissionData(location, data);
- return null;
- case LOCATION :
- return storage.getLocations();
- case SAVE_INFOS :
- storage.saveConditionalPermissionInfos(infos);
- return null;
- case GET_INFOS :
- return storage.getConditionalPermissionInfos();
- }
-
- throw new UnsupportedOperationException();
- }
-
- public String[] getPermissionData(String loc) throws IOException {
- this.location = loc;
- this.action = GET;
-
- try {
- return AccessController.doPrivileged(this);
- } catch (PrivilegedActionException e) {
- throw (IOException) e.getException();
- }
- }
-
- public String[] getLocations() throws IOException {
- this.action = LOCATION;
-
- try {
- return AccessController.doPrivileged(this);
- } catch (PrivilegedActionException e) {
- throw (IOException) e.getException();
- }
- }
-
- public void setPermissionData(String location, String[] data) throws IOException {
- this.location = location;
- this.data = data;
- this.action = SET;
-
- try {
- AccessController.doPrivileged(this);
- } catch (PrivilegedActionException e) {
- throw (IOException) e.getException();
- }
- }
-
- public void saveConditionalPermissionInfos(String[] updatedInfos) throws IOException {
- this.action = SAVE_INFOS;
- this.infos = updatedInfos;
- try {
- AccessController.doPrivileged(this);
- } catch (PrivilegedActionException e) {
- throw (IOException) e.getException();
- }
-
- }
-
- public String[] getConditionalPermissionInfos() throws IOException {
- this.action = GET_INFOS;
- try {
- return AccessController.doPrivileged(this);
- } catch (PrivilegedActionException e) {
- throw (IOException) e.getException();
- }
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/SecurityAdmin.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/SecurityAdmin.java
deleted file mode 100644
index d59644242..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/SecurityAdmin.java
+++ /dev/null
@@ -1,874 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008, 2012 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.osgi.internal.permadmin;
-
-import java.io.*;
-import java.math.BigInteger;
-import java.net.URL;
-import java.security.*;
-import java.security.cert.*;
-import java.util.*;
-import org.eclipse.osgi.framework.adaptor.BundleProtectionDomain;
-import org.eclipse.osgi.framework.adaptor.PermissionStorage;
-import org.eclipse.osgi.framework.internal.core.*;
-import org.eclipse.osgi.framework.internal.core.Constants;
-import org.osgi.framework.*;
-import org.osgi.service.condpermadmin.*;
-import org.osgi.service.permissionadmin.PermissionAdmin;
-import org.osgi.service.permissionadmin.PermissionInfo;
-
-public final class SecurityAdmin implements PermissionAdmin, ConditionalPermissionAdmin {
- private static final PermissionCollection DEFAULT_DEFAULT;
- static {
- AllPermission allPerm = new AllPermission();
- DEFAULT_DEFAULT = allPerm.newPermissionCollection();
- if (DEFAULT_DEFAULT != null)
- DEFAULT_DEFAULT.add(allPerm);
- }
-
- private static final String ADMIN_IMPLIED_ACTIONS = AdminPermission.RESOURCE + ',' + AdminPermission.METADATA + ',' + AdminPermission.CLASS + ',' + AdminPermission.CONTEXT;
- private static final PermissionInfo[] EMPTY_PERM_INFO = new PermissionInfo[0];
- /* @GuardedBy(lock) */
- private final PermissionAdminTable permAdminTable = new PermissionAdminTable();
- /* @GuardedBy(lock) */
- private SecurityTable condAdminTable;
- /* @GuardedBy(lock) */
- private PermissionInfoCollection permAdminDefaults;
- /* @GuardedBy(lock) */
- private long timeStamp = 0;
- /* @GuardedBy(lock) */
- private long nextID = System.currentTimeMillis();
- /* @GuardedBy(lock) */
- private final PermissionStorage permissionStorage;
- private final Object lock = new Object();
- private final Framework framework;
- private final PermissionInfo[] impliedPermissionInfos;
- private final EquinoxSecurityManager supportedSecurityManager;
-
- private SecurityAdmin(EquinoxSecurityManager supportedSecurityManager, Framework framework, PermissionInfo[] impliedPermissionInfos, PermissionInfoCollection permAdminDefaults) {
- this.supportedSecurityManager = supportedSecurityManager;
- this.framework = framework;
- this.impliedPermissionInfos = impliedPermissionInfos;
- this.permAdminDefaults = permAdminDefaults;
- this.permissionStorage = null;
- }
-
- public SecurityAdmin(EquinoxSecurityManager supportedSecurityManager, Framework framework, PermissionStorage permissionStorage) throws IOException {
- this.supportedSecurityManager = supportedSecurityManager;
- this.framework = framework;
- this.permissionStorage = new SecurePermissionStorage(permissionStorage);
- this.impliedPermissionInfos = SecurityAdmin.getPermissionInfos(getClass().getResource(Constants.OSGI_BASE_IMPLIED_PERMISSIONS), framework);
- String[] encodedDefaultInfos = permissionStorage.getPermissionData(null);
- PermissionInfo[] defaultInfos = getPermissionInfos(encodedDefaultInfos);
- if (defaultInfos != null)
- permAdminDefaults = new PermissionInfoCollection(defaultInfos);
- String[] locations = permissionStorage.getLocations();
- if (locations != null) {
- for (int i = 0; i < locations.length; i++) {
- String[] encodedLocationInfos = permissionStorage.getPermissionData(locations[i]);
- if (encodedLocationInfos != null) {
- PermissionInfo[] locationInfos = getPermissionInfos(encodedLocationInfos);
- permAdminTable.setPermissions(locations[i], locationInfos);
- }
- }
- }
- String[] encodedCondPermInfos = permissionStorage.getConditionalPermissionInfos();
- if (encodedCondPermInfos == null)
- condAdminTable = new SecurityTable(this, new SecurityRow[0]);
- else {
- SecurityRow[] rows = new SecurityRow[encodedCondPermInfos.length];
- try {
- for (int i = 0; i < rows.length; i++)
- rows[i] = SecurityRow.createSecurityRow(this, encodedCondPermInfos[i]);
- } catch (IllegalArgumentException e) {
- // TODO should log
- // bad format persisted in storage; start clean
- rows = new SecurityRow[0];
- }
- condAdminTable = new SecurityTable(this, rows);
- }
- }
-
- private static PermissionInfo[] getPermissionInfos(String[] encodedInfos) {
- if (encodedInfos == null)
- return null;
- PermissionInfo[] results = new PermissionInfo[encodedInfos.length];
- for (int i = 0; i < results.length; i++)
- results[i] = new PermissionInfo(encodedInfos[i]);
- return results;
- }
-
- boolean checkPermission(Permission permission, BundlePermissions bundlePermissions) {
- // check permissions by location
- PermissionInfoCollection locationCollection;
- SecurityTable curCondAdminTable;
- PermissionInfoCollection curPermAdminDefaults;
- // save off the current state of the world while holding the lock
- synchronized (lock) {
- // get location the hard way to avoid permission check
- Bundle bundle = bundlePermissions.getBundle();
- locationCollection = bundle instanceof AbstractBundle ? permAdminTable.getCollection(((AbstractBundle) bundle).getBundleData().getLocation()) : null;
- curCondAdminTable = condAdminTable;
- curPermAdminDefaults = permAdminDefaults;
- }
- if (locationCollection != null)
- return locationCollection.implies(permission);
- // if conditional admin table is empty the fall back to defaults
- if (curCondAdminTable.isEmpty())
- return curPermAdminDefaults != null ? curPermAdminDefaults.implies(permission) : DEFAULT_DEFAULT.implies(permission);
- // check the condition table
- int result = curCondAdminTable.evaluate(bundlePermissions, permission);
- if ((result & SecurityTable.GRANTED) != 0)
- return true;
- if ((result & SecurityTable.DENIED) != 0)
- return false;
- if ((result & SecurityTable.POSTPONED) != 0)
- return true;
- return false;
- }
-
- public PermissionInfo[] getDefaultPermissions() {
- synchronized (lock) {
- if (permAdminDefaults == null)
- return null;
- return permAdminDefaults.getPermissionInfos();
- }
- }
-
- public String[] getLocations() {
- synchronized (lock) {
- String[] results = permAdminTable.getLocations();
- return results.length == 0 ? null : results;
- }
- }
-
- public PermissionInfo[] getPermissions(String location) {
- synchronized (lock) {
- return permAdminTable.getPermissions(location);
- }
- }
-
- public void setDefaultPermissions(PermissionInfo[] permissions) {
- checkAllPermission();
- synchronized (lock) {
- if (permissions == null)
- permAdminDefaults = null;
- else
- permAdminDefaults = new PermissionInfoCollection(permissions);
- try {
- permissionStorage.setPermissionData(null, getEncodedPermissionInfos(permissions));
- } catch (IOException e) {
- // log
- e.printStackTrace();
- }
- }
- }
-
- private static void checkAllPermission() {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null)
- sm.checkPermission(new AllPermission());
- }
-
- private static String[] getEncodedPermissionInfos(PermissionInfo[] permissions) {
- if (permissions == null)
- return null;
- String[] encoded = new String[permissions.length];
- for (int i = 0; i < encoded.length; i++)
- encoded[i] = permissions[i].getEncoded();
- return encoded;
- }
-
- public void setPermissions(String location, PermissionInfo[] permissions) {
- checkAllPermission();
- synchronized (lock) {
- permAdminTable.setPermissions(location, permissions);
- try {
- permissionStorage.setPermissionData(location, getEncodedPermissionInfos(permissions));
- } catch (IOException e) {
- // TODO log
- e.printStackTrace();
- }
- }
- }
-
- void delete(SecurityRow securityRow, boolean firstTry) {
- ConditionalPermissionUpdate update = newConditionalPermissionUpdate();
- @SuppressWarnings("unchecked")
- List<ConditionalPermissionInfo> rows = update.getConditionalPermissionInfos();
- for (Iterator<ConditionalPermissionInfo> iRows = rows.iterator(); iRows.hasNext();) {
- ConditionalPermissionInfo info = iRows.next();
- if (securityRow.getName().equals(info.getName())) {
- iRows.remove();
- synchronized (lock) {
- if (!update.commit()) {
- if (firstTry)
- // try again
- delete(securityRow, false);
- }
- }
- break;
- }
- }
- }
-
- /**
- * @deprecated
- */
- public ConditionalPermissionInfo addConditionalPermissionInfo(ConditionInfo[] conds, PermissionInfo[] perms) {
- return setConditionalPermissionInfo(null, conds, perms, true);
- }
-
- public ConditionalPermissionInfo newConditionalPermissionInfo(String name, ConditionInfo[] conditions, PermissionInfo[] permissions, String decision) {
- return new SecurityRowSnapShot(name, conditions, permissions, decision);
- }
-
- public ConditionalPermissionInfo newConditionalPermissionInfo(String encoded) {
- return SecurityRow.createSecurityRowSnapShot(encoded);
- }
-
- public ConditionalPermissionUpdate newConditionalPermissionUpdate() {
- synchronized (lock) {
- return new SecurityTableUpdate(this, condAdminTable.getRows(), timeStamp);
- }
- }
-
- public AccessControlContext getAccessControlContext(String[] signers) {
- SecurityAdmin snapShot = getSnapShot();
- return new AccessControlContext(new ProtectionDomain[] {createProtectionDomain(createMockBundle(signers), snapShot)});
- }
-
- /**
- * @deprecated
- */
- public ConditionalPermissionInfo getConditionalPermissionInfo(String name) {
- synchronized (lock) {
- return condAdminTable.getRow(name);
- }
- }
-
- /**
- * @deprecated
- */
- public Enumeration<ConditionalPermissionInfo> getConditionalPermissionInfos() {
- // could implement our own Enumeration, but we don't care about performance here. Just do something simple:
- synchronized (lock) {
- SecurityRow[] rows = condAdminTable.getRows();
- List<ConditionalPermissionInfo> vRows = new ArrayList<ConditionalPermissionInfo>(rows.length);
- for (int i = 0; i < rows.length; i++)
- vRows.add(rows[i]);
- return Collections.enumeration(vRows);
- }
- }
-
- /**
- * @deprecated
- */
- public ConditionalPermissionInfo setConditionalPermissionInfo(String name, ConditionInfo[] conds, PermissionInfo[] perms) {
- return setConditionalPermissionInfo(name, conds, perms, true);
- }
-
- private SecurityAdmin getSnapShot() {
- SecurityAdmin sa;
- synchronized (lock) {
- sa = new SecurityAdmin(supportedSecurityManager, framework, impliedPermissionInfos, permAdminDefaults);
- SecurityRow[] rows = condAdminTable.getRows();
- SecurityRow[] rowsSnapShot = new SecurityRow[rows.length];
- for (int i = 0; i < rows.length; i++)
- rowsSnapShot[i] = new SecurityRow(sa, rows[i].getName(), rows[i].getConditionInfos(), rows[i].getPermissionInfos(), rows[i].getAccessDecision());
- sa.condAdminTable = new SecurityTable(sa, rowsSnapShot);
- }
- return sa;
- }
-
- private ConditionalPermissionInfo setConditionalPermissionInfo(String name, ConditionInfo[] conds, PermissionInfo[] perms, boolean firstTry) {
- ConditionalPermissionUpdate update = newConditionalPermissionUpdate();
- @SuppressWarnings("unchecked")
- List<ConditionalPermissionInfo> rows = update.getConditionalPermissionInfos();
- ConditionalPermissionInfo newInfo = newConditionalPermissionInfo(name, conds, perms, ConditionalPermissionInfo.ALLOW);
- int index = -1;
- if (name != null) {
- for (int i = 0; i < rows.size() && index < 0; i++) {
- ConditionalPermissionInfo info = rows.get(i);
- if (name.equals(info.getName())) {
- index = i;
- }
- }
- }
- if (index < 0) {
- // must always add to the beginning (bug 303930)
- rows.add(0, newInfo);
- index = 0;
- } else {
- rows.set(index, newInfo);
- }
- synchronized (lock) {
- if (!update.commit()) {
- if (firstTry)
- // try again
- setConditionalPermissionInfo(name, conds, perms, false);
- }
- return condAdminTable.getRow(index);
- }
- }
-
- boolean commit(List<ConditionalPermissionInfo> rows, long updateStamp) {
- checkAllPermission();
- synchronized (lock) {
- if (updateStamp != timeStamp)
- return false;
- SecurityRow[] newRows = new SecurityRow[rows.size()];
- Collection<String> names = new ArrayList<String>();
- for (int i = 0; i < newRows.length; i++) {
- Object rowObj = rows.get(i);
- if (!(rowObj instanceof ConditionalPermissionInfo))
- throw new IllegalStateException("Invalid type \"" + rowObj.getClass().getName() + "\" at row: " + i); //$NON-NLS-1$//$NON-NLS-2$
- ConditionalPermissionInfo infoBaseRow = (ConditionalPermissionInfo) rowObj;
- String name = infoBaseRow.getName();
- if (name == null)
- name = generateName();
- if (names.contains(name))
- throw new IllegalStateException("Duplicate name \"" + name + "\" at row: " + i); //$NON-NLS-1$//$NON-NLS-2$
- names.add(name);
- newRows[i] = new SecurityRow(this, name, infoBaseRow.getConditionInfos(), infoBaseRow.getPermissionInfos(), infoBaseRow.getAccessDecision());
- }
- condAdminTable = new SecurityTable(this, newRows);
- try {
- permissionStorage.saveConditionalPermissionInfos(condAdminTable.getEncodedRows());
- } catch (IOException e) {
- // TODO log
- e.printStackTrace();
- }
- timeStamp += 1;
- return true;
- }
- }
-
- /* GuardedBy(lock) */
- private String generateName() {
- return "generated_" + Long.toString(nextID++); //$NON-NLS-1$;
- }
-
- public BundleProtectionDomain createProtectionDomain(Bundle bundle) {
- return createProtectionDomain(bundle, this);
- }
-
- private BundleProtectionDomain createProtectionDomain(Bundle bundle, SecurityAdmin sa) {
- PermissionInfoCollection impliedPermissions = getImpliedPermission(bundle);
- PermissionInfo[] restrictedInfos = getFileRelativeInfos(SecurityAdmin.getPermissionInfos(bundle.getEntry("OSGI-INF/permissions.perm"), framework), bundle); //$NON-NLS-1$
- PermissionInfoCollection restrictedPermissions = restrictedInfos == null ? null : new PermissionInfoCollection(restrictedInfos);
- BundlePermissions bundlePermissions = new BundlePermissions(bundle, sa, impliedPermissions, restrictedPermissions);
- return new BundleProtectionDomain(bundlePermissions, null, bundle);
- }
-
- private PermissionInfoCollection getImpliedPermission(Bundle bundle) {
- if (impliedPermissionInfos == null)
- return null;
- // create the implied AdminPermission actions for this bundle
- PermissionInfo impliedAdminPermission = new PermissionInfo(AdminPermission.class.getName(), "(id=" + bundle.getBundleId() + ")", ADMIN_IMPLIED_ACTIONS); //$NON-NLS-1$ //$NON-NLS-2$
- PermissionInfo[] bundleImpliedInfos = new PermissionInfo[impliedPermissionInfos.length + 1];
- System.arraycopy(impliedPermissionInfos, 0, bundleImpliedInfos, 0, impliedPermissionInfos.length);
- bundleImpliedInfos[impliedPermissionInfos.length] = impliedAdminPermission;
- return new PermissionInfoCollection(getFileRelativeInfos(bundleImpliedInfos, bundle));
- }
-
- private PermissionInfo[] getFileRelativeInfos(PermissionInfo[] permissionInfos, Bundle bundle) {
- if (permissionInfos == null || !(bundle instanceof AbstractBundle))
- return permissionInfos;
- PermissionInfo[] results = new PermissionInfo[permissionInfos.length];
- for (int i = 0; i < permissionInfos.length; i++) {
- results[i] = permissionInfos[i];
- if ("java.io.FilePermission".equals(permissionInfos[i].getType())) { //$NON-NLS-1$
- if (!"<<ALL FILES>>".equals(permissionInfos[i].getName())) { //$NON-NLS-1$
- File file = new File(permissionInfos[i].getName());
- if (!file.isAbsolute()) { // relative name
- File target = ((AbstractBundle) bundle).getBundleData().getDataFile(permissionInfos[i].getName());
- if (target != null)
- results[i] = new PermissionInfo(permissionInfos[i].getType(), target.getPath(), permissionInfos[i].getActions());
- }
- }
- }
- }
- return results;
- }
-
- public void clearCaches() {
- PermissionInfoCollection[] permAdminCollections;
- SecurityRow[] condAdminRows;
- synchronized (lock) {
- permAdminCollections = permAdminTable.getCollections();
- condAdminRows = condAdminTable.getRows();
- }
- for (int i = 0; i < permAdminCollections.length; i++)
- permAdminCollections[i].clearPermissionCache();
- for (int i = 0; i < condAdminRows.length; i++)
- condAdminRows[i].clearCaches();
- }
-
- EquinoxSecurityManager getSupportedSecurityManager() {
- return supportedSecurityManager != null ? supportedSecurityManager : getSupportedSystemSecurityManager();
- }
-
- static private EquinoxSecurityManager getSupportedSystemSecurityManager() {
- try {
- EquinoxSecurityManager equinoxManager = (EquinoxSecurityManager) System.getSecurityManager();
- return equinoxManager != null && equinoxManager.inCheckPermission() ? equinoxManager : null;
- } catch (ClassCastException e) {
- return null;
- }
- }
-
- private static PermissionInfo[] getPermissionInfos(URL resource, Framework framework) {
- if (resource == null)
- return null;
- PermissionInfo[] info = EMPTY_PERM_INFO;
- DataInputStream in = null;
- try {
- in = new DataInputStream(resource.openStream());
- List<PermissionInfo> permissions = new ArrayList<PermissionInfo>();
- BufferedReader reader;
- try {
- reader = new BufferedReader(new InputStreamReader(in, "UTF8")); //$NON-NLS-1$
- } catch (UnsupportedEncodingException e) {
- reader = new BufferedReader(new InputStreamReader(in));
- }
-
- while (true) {
- String line = reader.readLine();
- if (line == null) /* EOF */
- break;
- line = line.trim();
- if ((line.length() == 0) || line.startsWith("#") || line.startsWith("//")) /* comments *///$NON-NLS-1$ //$NON-NLS-2$
- continue;
-
- try {
- permissions.add(new PermissionInfo(line));
- } catch (IllegalArgumentException iae) {
- /* incorrectly encoded permission */
- if (framework != null)
- framework.publishFrameworkEvent(FrameworkEvent.ERROR, framework.getBundle(0), iae);
- }
- }
- int size = permissions.size();
- if (size > 0)
- info = permissions.toArray(new PermissionInfo[size]);
- } catch (IOException e) {
- // do nothing
- } finally {
- try {
- if (in != null)
- in.close();
- } catch (IOException ee) {
- // do nothing
- }
- }
- return info;
- }
-
- private static Bundle createMockBundle(String[] signers) {
- Map<X509Certificate, List<X509Certificate>> signersMap = new HashMap<X509Certificate, List<X509Certificate>>();
- for (int i = 0; i < signers.length; i++) {
- List<String> chain = parseDNchain(signers[i]);
- List<X509Certificate> signersList = new ArrayList<X509Certificate>();
- Principal subject = null, issuer = null;
- X509Certificate first = null;
- for (Iterator<String> iChain = chain.iterator(); iChain.hasNext();) {
- subject = issuer == null ? new MockPrincipal(iChain.next()) : issuer;
- issuer = iChain.hasNext() ? new MockPrincipal(iChain.next()) : subject;
- X509Certificate cert = new MockX509Certificate(subject, issuer);
- if (first == null)
- first = cert;
- signersList.add(cert);
- }
- if (subject != issuer)
- signersList.add(new MockX509Certificate(issuer, issuer));
- signersMap.put(first, signersList);
- }
- return new MockBundle(signersMap);
- }
-
- static class MockBundle implements Bundle {
- private final Map<X509Certificate, List<X509Certificate>> signers;
-
- MockBundle(Map<X509Certificate, List<X509Certificate>> signers) {
- this.signers = signers;
- }
-
- public Enumeration<URL> findEntries(String path, String filePattern, boolean recurse) {
- return null;
- }
-
- public BundleContext getBundleContext() {
- return null;
- }
-
- public long getBundleId() {
- return -1;
- }
-
- public URL getEntry(String path) {
- return null;
- }
-
- public Enumeration<String> getEntryPaths(String path) {
- return null;
- }
-
- public Dictionary<String, String> getHeaders() {
- return new Hashtable<String, String>();
- }
-
- public Dictionary<String, String> getHeaders(String locale) {
- return getHeaders();
- }
-
- public long getLastModified() {
- return 0;
- }
-
- public String getLocation() {
- return ""; //$NON-NLS-1$
- }
-
- public ServiceReference<?>[] getRegisteredServices() {
- return null;
- }
-
- public URL getResource(String name) {
- return null;
- }
-
- /**
- * @throws IOException
- */
- public Enumeration<URL> getResources(String name) throws IOException {
- return null;
- }
-
- public ServiceReference<?>[] getServicesInUse() {
- return null;
- }
-
- public Map<X509Certificate, List<X509Certificate>> getSignerCertificates(int signersType) {
- return new HashMap<X509Certificate, List<X509Certificate>>(signers);
- }
-
- public int getState() {
- return Bundle.UNINSTALLED;
- }
-
- public String getSymbolicName() {
- return null;
- }
-
- public Version getVersion() {
- return Version.emptyVersion;
- }
-
- public boolean hasPermission(Object permission) {
- return false;
- }
-
- /**
- * @throws ClassNotFoundException
- */
- public Class<?> loadClass(String name) throws ClassNotFoundException {
- throw new IllegalStateException();
- }
-
- /**
- * @throws BundleException
- */
- public void start(int options) throws BundleException {
- throw new IllegalStateException();
- }
-
- /**
- * @throws BundleException
- */
- public void start() throws BundleException {
- throw new IllegalStateException();
- }
-
- /**
- * @throws BundleException
- */
- public void stop(int options) throws BundleException {
- throw new IllegalStateException();
- }
-
- /**
- * @throws BundleException
- */
- public void stop() throws BundleException {
- throw new IllegalStateException();
- }
-
- /**
- * @throws BundleException
- */
- public void uninstall() throws BundleException {
- throw new IllegalStateException();
- }
-
- /**
- * @throws BundleException
- */
- public void update() throws BundleException {
- throw new IllegalStateException();
- }
-
- /**
- * @throws BundleException
- */
- public void update(InputStream in) throws BundleException {
- throw new IllegalStateException();
- }
-
- public int compareTo(Bundle o) {
- return 0;
- }
-
- public <A> A adapt(Class<A> type) {
- throw new IllegalStateException();
- }
-
- public File getDataFile(String filename) {
- return null;
- }
- }
-
- private static class MockX509Certificate extends X509Certificate {
- private final Principal subject;
- private final Principal issuer;
-
- MockX509Certificate(Principal subject, Principal issuer) {
- this.subject = subject;
- this.issuer = issuer;
- }
-
- public Principal getSubjectDN() {
- return subject;
- }
-
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj instanceof MockX509Certificate)
- return subject.equals(((MockX509Certificate) obj).subject) && issuer.equals(((MockX509Certificate) obj).issuer);
- return false;
- }
-
- public int hashCode() {
- return subject.hashCode() + issuer.hashCode();
- }
-
- public String toString() {
- return subject.toString();
- }
-
- /**
- * @throws CertificateExpiredException
- * @throws java.security.cert.CertificateNotYetValidException
- */
- public void checkValidity() throws CertificateExpiredException, java.security.cert.CertificateNotYetValidException {
- throw new UnsupportedOperationException();
- }
-
- /**
- * @throws java.security.cert.CertificateExpiredException
- * @throws java.security.cert.CertificateNotYetValidException
- */
- public void checkValidity(Date var0) throws java.security.cert.CertificateExpiredException, java.security.cert.CertificateNotYetValidException {
- throw new UnsupportedOperationException();
- }
-
- public int getBasicConstraints() {
- throw new UnsupportedOperationException();
- }
-
- public Principal getIssuerDN() {
- return issuer;
- }
-
- public boolean[] getIssuerUniqueID() {
- throw new UnsupportedOperationException();
- }
-
- public boolean[] getKeyUsage() {
- throw new UnsupportedOperationException();
- }
-
- public Date getNotAfter() {
- throw new UnsupportedOperationException();
- }
-
- public Date getNotBefore() {
- throw new UnsupportedOperationException();
- }
-
- public BigInteger getSerialNumber() {
- throw new UnsupportedOperationException();
- }
-
- public String getSigAlgName() {
- throw new UnsupportedOperationException();
- }
-
- public String getSigAlgOID() {
- throw new UnsupportedOperationException();
- }
-
- public byte[] getSigAlgParams() {
- throw new UnsupportedOperationException();
- }
-
- public byte[] getSignature() {
- throw new UnsupportedOperationException();
- }
-
- public boolean[] getSubjectUniqueID() {
- throw new UnsupportedOperationException();
- }
-
- /**
- * @throws CertificateEncodingException
- */
- public byte[] getTBSCertificate() throws CertificateEncodingException {
- throw new UnsupportedOperationException();
- }
-
- public int getVersion() {
- throw new UnsupportedOperationException();
- }
-
- /**
- * @throws CertificateEncodingException
- */
- public byte[] getEncoded() throws CertificateEncodingException {
- throw new UnsupportedOperationException();
- }
-
- public PublicKey getPublicKey() {
- throw new UnsupportedOperationException();
- }
-
- /**
- * @throws java.security.InvalidKeyException
- * @throws java.security.NoSuchAlgorithmException
- * @throws java.security.NoSuchProviderException
- * @throws java.security.SignatureException
- * @throws java.security.cert.CertificateException
- */
- public void verify(PublicKey var0) throws java.security.InvalidKeyException, java.security.NoSuchAlgorithmException, java.security.NoSuchProviderException, java.security.SignatureException, java.security.cert.CertificateException {
- throw new UnsupportedOperationException();
- }
-
- /**
- * @throws InvalidKeyException
- * @throws NoSuchAlgorithmException
- * @throws NoSuchProviderException
- * @throws SignatureException
- * @throws CertificateException
- */
- public void verify(PublicKey var0, String var1) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException, CertificateException {
- throw new UnsupportedOperationException();
- }
-
- public Set<String> getCriticalExtensionOIDs() {
- throw new UnsupportedOperationException();
- }
-
- public byte[] getExtensionValue(String var0) {
- throw new UnsupportedOperationException();
- }
-
- public Set<String> getNonCriticalExtensionOIDs() {
- throw new UnsupportedOperationException();
- }
-
- public boolean hasUnsupportedCriticalExtension() {
- throw new UnsupportedOperationException();
- }
- }
-
- private static class MockPrincipal implements Principal {
- private final String name;
-
- MockPrincipal(String name) {
- this.name = name;
- }
-
- public String getName() {
- return name;
- }
-
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj instanceof MockPrincipal) {
- return name.equals(((MockPrincipal) obj).name);
- }
- return false;
- }
-
- public int hashCode() {
- return name.hashCode();
- }
-
- public String toString() {
- return getName();
- }
- }
-
- private static List<String> parseDNchain(String dnChain) {
- if (dnChain == null) {
- throw new IllegalArgumentException("The DN chain must not be null."); //$NON-NLS-1$
- }
- List<String> parsed = new ArrayList<String>();
- int startIndex = 0;
- startIndex = skipSpaces(dnChain, startIndex);
- while (startIndex < dnChain.length()) {
- int endIndex = startIndex;
- boolean inQuote = false;
- out: while (endIndex < dnChain.length()) {
- char c = dnChain.charAt(endIndex);
- switch (c) {
- case '"' :
- inQuote = !inQuote;
- break;
- case '\\' :
- endIndex++; // skip the escaped char
- break;
- case ';' :
- if (!inQuote)
- break out;
- }
- endIndex++;
- }
- if (endIndex > dnChain.length()) {
- throw new IllegalArgumentException("unterminated escape"); //$NON-NLS-1$
- }
- parsed.add(dnChain.substring(startIndex, endIndex));
- startIndex = endIndex + 1;
- startIndex = skipSpaces(dnChain, startIndex);
- }
- return parsed;
- }
-
- private static int skipSpaces(String dnChain, int startIndex) {
- while (startIndex < dnChain.length() && dnChain.charAt(startIndex) == ' ') {
- startIndex++;
- }
- return startIndex;
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/SecurityRow.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/SecurityRow.java
deleted file mode 100644
index 25d269449..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/SecurityRow.java
+++ /dev/null
@@ -1,457 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.osgi.internal.permadmin;
-
-import java.lang.reflect.*;
-import java.security.Permission;
-import java.util.*;
-import org.osgi.framework.Bundle;
-import org.osgi.service.condpermadmin.*;
-import org.osgi.service.permissionadmin.PermissionInfo;
-
-public final class SecurityRow implements ConditionalPermissionInfo {
- /* Used to find condition constructors getConditions */
- 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);
- static final Decision DECISION_GRANTED = new Decision(SecurityTable.GRANTED, null, null, null);
- static final Decision DECISION_DENIED = new Decision(SecurityTable.DENIED, null, null, null);
-
- private final SecurityAdmin securityAdmin;
- private final String name;
- private final ConditionInfo[] conditionInfos;
- private final PermissionInfoCollection permissionInfoCollection;
- private final boolean deny;
- /* GuardedBy(bundleConditions) */
- final Map<BundlePermissions, Condition[]> bundleConditions;
-
- 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;
- this.conditionInfos = conditionInfos == null ? new ConditionInfo[0] : conditionInfos;
- decision = decision.toLowerCase();
- boolean d = ConditionalPermissionInfo.DENY.equals(decision);
- boolean a = ConditionalPermissionInfo.ALLOW.equals(decision);
- if (!(d | a))
- throw new IllegalArgumentException("Invalid decision: " + decision); //$NON-NLS-1$
- this.deny = d;
- this.name = name;
- this.permissionInfoCollection = new PermissionInfoCollection(permissionInfos);
- if (conditionInfos == null || conditionInfos.length == 0)
- bundleConditions = null;
- else
- bundleConditions = new HashMap<BundlePermissions, Condition[]>();
- }
-
- static SecurityRowSnapShot createSecurityRowSnapShot(String encoded) {
- return (SecurityRowSnapShot) createConditionalPermissionInfo(null, encoded);
- }
-
- static SecurityRow createSecurityRow(SecurityAdmin securityAdmin, String encoded) {
- return (SecurityRow) createConditionalPermissionInfo(securityAdmin, 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$
- char[] chars = encoded.toCharArray();
- int end = encoded.length() - 1;
- char lastChar = chars[end];
- if (lastChar != '}' && lastChar != '"')
- throw new IllegalArgumentException(encoded);
- String encodedName = null;
- if (lastChar == '"') {
- // we have a name: an empty name must have at least 2 chars for the quotes
- if (chars.length < 2)
- throw new IllegalArgumentException(encoded);
- int endName = encoded.length() - 1;
- int startName = endName - 1;
- while (startName > 0) {
- if (chars[startName] == '"') {
- startName--;
- if (startName > 0 && chars[startName] == '\\')
- startName--;
- else {
- startName++;
- break;
- }
- }
- startName--;
- }
- if (chars[startName] != '"')
- throw new IllegalArgumentException(encoded);
- encodedName = unescapeString(encoded.substring(startName + 1, endName));
- end = encoded.lastIndexOf('}', startName);
- }
- int start = encoded.indexOf('{');
- if (start < 0 || end < start)
- throw new IllegalArgumentException(encoded);
-
- String decision = encoded.substring(0, start);
- decision = decision.trim();
- if (decision.length() == 0 || (!ConditionalPermissionInfo.DENY.equalsIgnoreCase(decision) && !ConditionalPermissionInfo.ALLOW.equalsIgnoreCase(decision)))
- throw new IllegalArgumentException(encoded);
-
- List<ConditionInfo> condList = new ArrayList<ConditionInfo>();
- List<PermissionInfo> permList = new ArrayList<PermissionInfo>();
- int pos = start + 1;
- while (pos < end) {
- while (pos < end && chars[pos] != '[' && chars[pos] != '(')
- pos++;
- if (pos == end)
- break; // no perms or conds left
- int startPos = pos;
- char endChar = chars[startPos] == '[' ? ']' : ')';
- while (pos < end && chars[pos] != endChar) {
- if (chars[pos] == '"') {
- pos++;
- while (chars[pos] != '"') {
- if (chars[pos] == '\\')
- pos++;
- pos++;
- }
- }
- pos++;
- }
- int endPos = pos;
- String token = new String(chars, startPos, endPos - startPos + 1);
- if (endChar == ']')
- condList.add(new ConditionInfo(token));
- else
- permList.add(new PermissionInfo(token));
- pos++;
- }
- if (permList.size() == 0)
- throw new IllegalArgumentException("No Permission infos: " + encoded); //$NON-NLS-1$
- ConditionInfo[] conds = condList.toArray(new ConditionInfo[condList.size()]);
- PermissionInfo[] perms = permList.toArray(new PermissionInfo[permList.size()]);
- if (securityAdmin == null)
- return new SecurityRowSnapShot(encodedName, conds, perms, decision);
- return new SecurityRow(securityAdmin, encodedName, conds, perms, decision);
- }
-
- static Object cloneArray(Object[] array) {
- if (array == null)
- return null;
- Object result = Array.newInstance(array.getClass().getComponentType(), array.length);
- System.arraycopy(array, 0, result, 0, array.length);
- return result;
- }
-
- private static void escapeString(String str, StringBuffer output) {
- int len = str.length();
- 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;
- }
- }
- }
-
- private static String unescapeString(String str) {
- StringBuffer output = new StringBuffer(str.length());
- int end = str.length();
- for (int i = 0; i < end; i++) {
- char c = str.charAt(i);
- if (c == '\\') {
- i++;
- 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;
- }
- }
- }
- output.append(c);
- }
-
- return output.toString();
- }
-
- public String getName() {
- return name;
- }
-
- public ConditionInfo[] getConditionInfos() {
- // must make a copy for the public API method to prevent modification
- return (ConditionInfo[]) cloneArray(conditionInfos);
- }
-
- ConditionInfo[] internalGetConditionInfos() {
- return conditionInfos;
- }
-
- public String getAccessDecision() {
- return deny ? ConditionalPermissionInfo.DENY : ConditionalPermissionInfo.ALLOW;
- }
-
- public PermissionInfo[] getPermissionInfos() {
- // must make a copy for the public API method to prevent modification
- return (PermissionInfo[]) cloneArray(permissionInfoCollection.getPermissionInfos());
- }
-
- PermissionInfo[] internalGetPermissionInfos() {
- return permissionInfoCollection.getPermissionInfos();
- }
-
- /**
- * @deprecated
- */
- public void delete() {
- securityAdmin.delete(this, true);
- }
-
- Condition[] getConditions(Bundle bundle) {
- Condition[] conditions = new Condition[conditionInfos.length];
- for (int i = 0; i < conditionInfos.length; i++) {
- /*
- * TODO: Can we pre-get the Constructors in our own constructor
- */
- Class<?> clazz;
- try {
- clazz = Class.forName(conditionInfos[i].getType());
- } catch (ClassNotFoundException e) {
- /* If the class isn't there, we fail */
- return null;
- }
- Constructor<?> constructor = null;
- Method method = null;
- try {
- method = clazz.getMethod("getCondition", conditionMethodArgs); //$NON-NLS-1$
- if ((method.getModifiers() & Modifier.STATIC) == 0)
- method = null;
- } catch (NoSuchMethodException e) {
- // This is a normal case
- }
- if (method == null)
- try {
- constructor = clazz.getConstructor(conditionMethodArgs);
- } catch (NoSuchMethodException e) {
- // TODO should post a FrameworkEvent of type error here
- conditions[i] = Condition.FALSE;
- continue;
- }
-
- Object args[] = {bundle, conditionInfos[i]};
- try {
- if (method != null)
- conditions[i] = (Condition) method.invoke(null, args);
- else
- conditions[i] = (Condition) constructor.newInstance(args);
- } catch (Throwable t) {
- // TODO should post a FrameworkEvent of type error here
- conditions[i] = Condition.FALSE;
- }
- }
- return conditions;
- }
-
- Decision evaluate(BundlePermissions bundlePermissions, Permission permission) {
- if (bundleConditions == null || bundlePermissions == null)
- return evaluatePermission(permission);
- Condition[] conditions;
- synchronized (bundleConditions) {
- conditions = bundleConditions.get(bundlePermissions);
- if (conditions == null) {
- conditions = getConditions(bundlePermissions.getBundle());
- bundleConditions.put(bundlePermissions, conditions);
- }
- }
- if (conditions == ABSTAIN_LIST)
- return DECISION_ABSTAIN;
- if (conditions == SATISFIED_LIST)
- return evaluatePermission(permission);
-
- boolean empty = true;
- List<Condition> postponedConditions = null;
- Decision postponedPermCheck = null;
- for (int i = 0; i < conditions.length; i++) {
- Condition condition = conditions[i];
- 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.
- 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
- synchronized (bundleConditions) {
- bundleConditions.put(bundlePermissions, ABSTAIN_LIST);
- }
- return DECISION_ABSTAIN;
- }
- } else { // postponed case
- if (postponedPermCheck == null)
- // perform a permission check now
- postponedPermCheck = evaluatePermission(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
- if (postponedConditions == null)
- postponedConditions = new ArrayList<Condition>(1);
- postponedConditions.add(condition);
- }
- empty &= conditions[i] == null;
- }
- if (empty) {
- synchronized (bundleConditions) {
- bundleConditions.put(bundlePermissions, SATISFIED_LIST);
- }
- }
- if (postponedPermCheck != null)
- return new Decision(postponedPermCheck.decision | SecurityTable.POSTPONED, postponedConditions.toArray(new Condition[postponedConditions.size()]), this, bundlePermissions);
- return evaluatePermission(permission);
- }
-
- private boolean isPostponed(Condition condition) {
- // postponed checks can only happen if we are using a supported security manager
- return condition.isPostponed() && securityAdmin.getSupportedSecurityManager() != null;
- }
-
- private Decision evaluatePermission(Permission permission) {
- return permissionInfoCollection.implies(permission) ? (deny ? DECISION_DENIED : DECISION_GRANTED) : DECISION_ABSTAIN;
- }
-
- public String toString() {
- return getEncoded();
- }
-
- public String getEncoded() {
- return getEncoded(name, conditionInfos, internalGetPermissionInfos(), deny);
- }
-
- public boolean equals(Object obj) {
- // doing the simple (slow) thing for now
- if (obj == this)
- return true;
- if (!(obj instanceof ConditionalPermissionInfo))
- return false;
- // we assume the encoded string provides a canonical (comparable) form
- return getEncoded().equals(((ConditionalPermissionInfo) obj).getEncoded());
- }
-
- public int hashCode() {
- return getHashCode(name, internalGetConditionInfos(), internalGetPermissionInfos(), getAccessDecision());
- }
-
- static int getHashCode(String name, ConditionInfo[] conds, PermissionInfo[] perms, String decision) {
- int h = 31 * 17 + decision.hashCode();
- for (int i = 0; i < conds.length; i++)
- h = 31 * h + conds[i].hashCode();
- for (int i = 0; i < perms.length; i++)
- h = 31 * h + perms[i].hashCode();
- if (name != null)
- h = 31 * h + name.hashCode();
- return h;
- }
-
- static String getEncoded(String name, ConditionInfo[] conditionInfos, PermissionInfo[] permissionInfos, boolean deny) {
- StringBuffer result = new StringBuffer();
- if (deny)
- result.append(ConditionalPermissionInfo.DENY);
- else
- result.append(ConditionalPermissionInfo.ALLOW);
- result.append(" { "); //$NON-NLS-1$
- if (conditionInfos != null)
- for (int i = 0; i < conditionInfos.length; i++)
- result.append(conditionInfos[i].getEncoded()).append(' ');
- if (permissionInfos != null)
- for (int i = 0; i < permissionInfos.length; i++)
- result.append(permissionInfos[i].getEncoded()).append(' ');
- result.append('}');
- if (name != null) {
- result.append(" \""); //$NON-NLS-1$
- escapeString(name, result);
- result.append('"');
- }
- return result.toString();
- }
-
- PermissionInfoCollection getPermissionInfoCollection() {
- return permissionInfoCollection;
- }
-
- void clearCaches() {
- permissionInfoCollection.clearPermissionCache();
- if (bundleConditions != null)
- synchronized (bundleConditions) {
- bundleConditions.clear();
- }
- }
-
- static class Decision {
- final int decision;
- final Condition[] postponed;
- private final SecurityRow row;
- private final BundlePermissions bundlePermissions;
-
- Decision(int decision, Condition[] postponed, SecurityRow row, BundlePermissions bundlePermissions) {
- this.decision = decision;
- this.postponed = postponed;
- this.row = row;
- this.bundlePermissions = bundlePermissions;
- }
-
- void handleImmutable(Condition condition, boolean isSatisfied, boolean mutable) {
- if (mutable || !condition.isPostponed())
- return; // do nothing
- if (isSatisfied) {
- synchronized (row.bundleConditions) {
- Condition[] rowConditions = row.bundleConditions.get(bundlePermissions);
- boolean isEmpty = true;
- for (int i = 0; i < rowConditions.length; i++) {
- if (rowConditions[i] == condition)
- if (isSatisfied)
- rowConditions[i] = null;
- isEmpty &= rowConditions[i] == null;
- }
- if (isEmpty)
- row.bundleConditions.put(bundlePermissions, SATISFIED_LIST);
- }
- } else {
- synchronized (row.bundleConditions) {
- row.bundleConditions.put(bundlePermissions, ABSTAIN_LIST);
- }
- }
- }
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/SecurityRowSnapShot.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/SecurityRowSnapShot.java
deleted file mode 100644
index 79767716f..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/SecurityRowSnapShot.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008, 2009 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.osgi.internal.permadmin;
-
-import org.osgi.service.condpermadmin.ConditionInfo;
-import org.osgi.service.condpermadmin.ConditionalPermissionInfo;
-import org.osgi.service.permissionadmin.PermissionInfo;
-
-public class SecurityRowSnapShot implements ConditionalPermissionInfo {
-
- private final String name;
- private final ConditionInfo[] conditionInfos;
- private final PermissionInfo[] permissionInfos;
- private final 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();
- boolean d = ConditionalPermissionInfo.DENY.equals(decision);
- boolean a = ConditionalPermissionInfo.ALLOW.equals(decision);
- if (!(d | a))
- throw new IllegalArgumentException("Invalid decision: " + decision); //$NON-NLS-1$
- conditionInfos = conditionInfos == null ? new ConditionInfo[0] : conditionInfos;
- this.name = name;
- // must create copies of the passed in arrays to prevent changes
- this.conditionInfos = (ConditionInfo[]) SecurityRow.cloneArray(conditionInfos);
- this.permissionInfos = (PermissionInfo[]) SecurityRow.cloneArray(permissionInfos);
- this.decision = decision;
- }
-
- public ConditionInfo[] getConditionInfos() {
- return (ConditionInfo[]) SecurityRow.cloneArray(conditionInfos);
- }
-
- public String getAccessDecision() {
- return decision;
- }
-
- public String getName() {
- return name;
- }
-
- public PermissionInfo[] getPermissionInfos() {
- return (PermissionInfo[]) SecurityRow.cloneArray(permissionInfos);
- }
-
- /**
- * @deprecated
- */
- public void delete() {
- throw new UnsupportedOperationException();
- }
-
- public String toString() {
- return getEncoded();
- }
-
- public String getEncoded() {
- return SecurityRow.getEncoded(name, conditionInfos, permissionInfos, DENY.equalsIgnoreCase(decision));
- }
-
- public boolean equals(Object obj) {
- // doing the simple (slow) thing for now
- if (obj == this)
- return true;
- if (!(obj instanceof ConditionalPermissionInfo))
- return false;
- // we assume the encoded string provides a canonical (comparable) form
- return getEncoded().equals(((ConditionalPermissionInfo) obj).getEncoded());
- }
-
- public int hashCode() {
- return SecurityRow.getHashCode(name, conditionInfos, permissionInfos, getAccessDecision());
- }
-
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/SecurityTable.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/SecurityTable.java
deleted file mode 100644
index 72d587d48..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/SecurityTable.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.osgi.internal.permadmin;
-
-import java.security.Permission;
-import java.security.PermissionCollection;
-import java.util.Enumeration;
-import org.eclipse.osgi.internal.permadmin.SecurityRow.Decision;
-
-public class SecurityTable extends PermissionCollection {
- private static final long serialVersionUID = -1800193310096318060L;
- static final int GRANTED = 0x0001;
- static final int DENIED = 0x0002;
- static final int ABSTAIN = 0x0004;
- static final int POSTPONED = 0x0008;
-
- private final SecurityRow[] rows;
- private final SecurityAdmin securityAdmin;
-
- public SecurityTable(SecurityAdmin securityAdmin, SecurityRow[] rows) {
- if (rows == null)
- throw new NullPointerException("rows cannot be null!!"); //$NON-NLS-1$
- this.rows = rows;
- this.securityAdmin = securityAdmin;
- }
-
- boolean isEmpty() {
- return rows.length == 0;
- }
-
- int evaluate(BundlePermissions bundlePermissions, Permission permission) {
- if (isEmpty())
- return ABSTAIN;
- boolean postponed = false;
- Decision[] results = new Decision[rows.length];
- int immediateDecisionIdx = -1;
- // evaluate each row
- for (int i = 0; i < rows.length; i++) {
- try {
- results[i] = rows[i].evaluate(bundlePermissions, permission);
- } catch (Throwable t) {
- // TODO log?
- results[i] = SecurityRow.DECISION_ABSTAIN;
- }
- if ((results[i].decision & ABSTAIN) != 0)
- continue; // ignore this row and continue to next row
- if ((results[i].decision & POSTPONED) != 0) {
- // row is postponed; we can no longer return quickly on a denied decision
- postponed = true;
- continue; // continue to next row
- }
- if (!postponed)
- // no postpones encountered yet; we can return the decision quickly
- return results[i].decision; // return GRANTED or DENIED
- // got an immediate answer; but it is after a postponed condition.
- // no need to process the rest of the rows
- immediateDecisionIdx = i;
- break;
- }
- 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
- boolean allSameDecision = true;
- int i = immediateDecisionIdx < 0 ? results.length - 1 : immediateDecisionIdx - 1;
- for (; i >= 0 && allSameDecision; i--) {
- if (results[i] == null)
- continue;
- if ((results[i].decision & POSTPONED) != 0) {
- 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
- }
- }
- if (allSameDecision)
- return immediateDecision;
-
- // 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
- return ABSTAIN;
- equinoxManager.addConditionsForDomain(results);
- }
- return postponed ? POSTPONED : ABSTAIN;
- }
-
- SecurityRow getRow(int i) {
- return rows.length <= i || i < 0 ? null : rows[i];
- }
-
- SecurityRow getRow(String name) {
- for (int i = 0; i < rows.length; i++) {
- if (name.equals(rows[i].getName()))
- return rows[i];
- }
- return null;
- }
-
- SecurityRow[] getRows() {
- return rows;
- }
-
- String[] getEncodedRows() {
- String[] encoded = new String[rows.length];
- for (int i = 0; i < rows.length; i++)
- encoded[i] = rows[i].getEncoded();
- return encoded;
- }
-
- public void add(Permission permission) {
- throw new SecurityException();
- }
-
- public Enumeration<Permission> elements() {
- return BundlePermissions.EMPTY_ENUMERATION;
- }
-
- public boolean implies(Permission permission) {
- return (evaluate(null, permission) & SecurityTable.GRANTED) != 0;
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/SecurityTableUpdate.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/SecurityTableUpdate.java
deleted file mode 100644
index 286e328cc..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/SecurityTableUpdate.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.osgi.internal.permadmin;
-
-import java.util.ArrayList;
-import java.util.List;
-import org.osgi.service.condpermadmin.ConditionalPermissionInfo;
-import org.osgi.service.condpermadmin.ConditionalPermissionUpdate;
-
-public class SecurityTableUpdate implements ConditionalPermissionUpdate {
-
- private final SecurityAdmin securityAdmin;
- private final List<ConditionalPermissionInfo> rows;
- private final long timeStamp;
-
- public SecurityTableUpdate(SecurityAdmin securityAdmin, SecurityRow[] rows, long timeStamp) {
- this.securityAdmin = securityAdmin;
- this.timeStamp = timeStamp;
- // must make a snap shot of the security rows.
- this.rows = new ArrayList<ConditionalPermissionInfo>(rows.length);
- for (int i = 0; i < rows.length; i++)
- // Use SecurityRowSnapShot to prevent modification before commit
- // and to throw exceptions from delete
- this.rows.add(new SecurityRowSnapShot(rows[i].getName(), rows[i].internalGetConditionInfos(), rows[i].internalGetPermissionInfos(), rows[i].getAccessDecision()));
- }
-
- public boolean commit() {
- return securityAdmin.commit(rows, timeStamp);
- }
-
- public List<ConditionalPermissionInfo> getConditionalPermissionInfos() {
- // 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/core/framework/org/eclipse/osgi/internal/permadmin/default.permissions b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/default.permissions
deleted file mode 100644
index e04a88990..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/default.permissions
+++ /dev/null
@@ -1,25 +0,0 @@
-########################################################################
-# Copyright (c) 2003, 2005 IBM Corporation and others.
-# All rights reserved. This program and the accompanying materials
-# are made available under the terms of the Eclipse Public License v1.0
-# which accompanies this distribution, and is available at
-# http://www.eclipse.org/legal/epl-v10.html
-#
-# Contributors:
-# IBM Corporation - initial API and implementation
-########################################################################
-
-# Lines beginning with '#' or '//' are comments
-#
-# This file contains the default permissions to be granted
-# to bundles with no specific permission if there are no
-# default permission set. This file must be UTF8 encoded.
-#
-# In this file, FilePermissions with relative names are not
-# mapped to an individual bundle's data directory.
-#
-# The permissions are listed one per
-# line in PermissionInfo encoded format.
-# See org.osgi.service.permissionadmin.PermissionInfo
-
-(java.security.AllPermission)
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/implied.permissions b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/implied.permissions
deleted file mode 100644
index 1ddcfe994..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/permadmin/implied.permissions
+++ /dev/null
@@ -1,50 +0,0 @@
-########################################################################
-# Copyright (c) 2003, 2010 IBM Corporation and others.
-# All rights reserved. This program and the accompanying materials
-# are made available under the terms of the Eclipse Public License v1.0
-# which accompanies this distribution, and is available at
-# http://www.eclipse.org/legal/epl-v10.html
-#
-# Contributors:
-# IBM Corporation - initial API and implementation
-########################################################################
-
-# Lines beginning with '#' or '//' are comments
-#
-# This file contains the implied permissions to be granted
-# to all bundles. This file must be UTF8 encoded.
-#
-# In this file, FilePermissions with relative names are
-# mapped to an individual bundle's data directory.
-#
-# The permissions are listed one per
-# line in PermissionInfo encoded format.
-# See org.osgi.service.permissionadmin.PermissionInfo
-
-(java.util.PropertyPermission "java.vendor" "read")
-(java.util.PropertyPermission "java.specification.version" "read")
-(java.util.PropertyPermission "line.separator" "read")
-(java.util.PropertyPermission "java.class.version" "read")
-(java.util.PropertyPermission "java.specification.name" "read")
-(java.util.PropertyPermission "java.vendor.url" "read")
-(java.util.PropertyPermission "java.vm.version" "read")
-(java.util.PropertyPermission "os.name" "read")
-(java.util.PropertyPermission "os.arch" "read")
-(java.util.PropertyPermission "os.version" "read")
-(java.util.PropertyPermission "java.version" "read")
-(java.util.PropertyPermission "java.vm.specification.version" "read")
-(java.util.PropertyPermission "java.vm.specification.name" "read")
-(java.util.PropertyPermission "java.specification.vendor" "read")
-(java.util.PropertyPermission "java.vm.vendor" "read")
-(java.util.PropertyPermission "file.separator" "read")
-(java.util.PropertyPermission "path.separator" "read")
-(java.util.PropertyPermission "java.vm.name" "read")
-(java.util.PropertyPermission "java.vm.specification.vendor" "read")
-(java.util.PropertyPermission "org.osgi.framework.*" "read")
-(java.io.FilePermission "" "read")
-(java.io.FilePermission "-" "read,write,delete")
-
-# Added for OSGi SP R3 - this likely is not needed any more
-(org.osgi.framework.PackagePermission "java.*" "import")
-# Added for OSGi R4.3
-(org.osgi.framework.CapabilityPermission "osgi.ee" "require")
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/profile/DefaultProfileLogger.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/profile/DefaultProfileLogger.java
deleted file mode 100644
index 00d60d93d..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/profile/DefaultProfileLogger.java
+++ /dev/null
@@ -1,391 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.internal.profile;
-
-import java.io.*;
-import java.util.*;
-import org.eclipse.osgi.framework.debug.FrameworkDebugOptions;
-import org.eclipse.osgi.framework.internal.core.FrameworkProperties;
-
-public class DefaultProfileLogger implements ProfileLogger {
- protected static final String DEFAULTPROFILE_PROP = "osgi.defaultprofile."; //$NON-NLS-1$
- protected static final String PROP_FILENAME = DEFAULTPROFILE_PROP + "logfilename"; //$NON-NLS-1$
- protected static final String PROP_LOGSYNCHRONOUSLY = DEFAULTPROFILE_PROP + "logsynchronously"; //$NON-NLS-1$
- protected static final String PROP_BUFFERSIZE = DEFAULTPROFILE_PROP + "buffersize"; //$NON-NLS-1$
-
- protected static final String DEFAULTPROFILE_OPTION = "org.eclipse.osgi/defaultprofile/"; //$NON-NLS-1$
- protected static final String OPTION_FILENAME = DEFAULTPROFILE_OPTION + "logfilename"; //$NON-NLS-1$
- protected static final String OPTION_LOGSYNCHRONOUSLY = DEFAULTPROFILE_OPTION + "logsynchronously"; //$NON-NLS-1$
- protected static final String OPTION_BUFFERSIZE = DEFAULTPROFILE_OPTION + "buffersize"; //$NON-NLS-1$
-
- protected boolean logSynchronously = false;
- protected long startTime = 0;
- protected static final int DEFAULT_BUFFER_SIZE = 256;
-
- protected TimeEntry[] timeLogEntries = null;
- protected int timeEntriesIndex = 0;
- protected StringBuffer timelog = null;
-
- protected long launchTime = -1;
- protected int bufferSize = DEFAULT_BUFFER_SIZE;
- protected String logFileName = null;
- protected File logFile = null;
- private StringBuffer entryReport = new StringBuffer(120);
- private StringBuffer padsb = new StringBuffer(16); // to prevent creating this over and over
- protected int indent;
- protected int timePaddingLength;
- protected Stack<AccumPerfScope> scopeStack;
- protected Map<String, AccumPerfData> scopeToAccumPerfDataMap;
-
- public DefaultProfileLogger() {
- initProps();
-
- int size = getBufferSize();
- timeLogEntries = new TimeEntry[size];
- timelog = new StringBuffer(4096);
- for (int i = 0; i < size; i++) {
- timeLogEntries[i] = timeEntryFactory();
- }
- timeEntriesIndex = 0;
-
- launchTime = getLaunchTime();
- if (launchTime == -1) {
- startTime = getMainStartTime();
- } else {
- startTime = launchTime;
- }
-
- long freq = getTimerFrequency();
- for (timePaddingLength = 3; freq > 9; timePaddingLength++) {
- freq /= 10;
- }
-
- logInitMessages();
- }
-
- protected void logInitMessages() {
- int index = 0;
- if (launchTime != -1L) {
- logTime(Profile.FLAG_NONE, "DefaultProfileLogger.init()", "launch time initialized", null); //$NON-NLS-1$//$NON-NLS-2$
- timeLogEntries[index++].time = launchTime;
- }
-
- logTime(Profile.FLAG_NONE, "DefaultProfileLogger.init()", "start time initialized", null); //$NON-NLS-1$//$NON-NLS-2$
- timeLogEntries[index++].time = getMainStartTime();
- }
-
- protected long getLaunchTime() {
- String launchTimeString = FrameworkProperties.getProperty("launch.startMillis"); //$NON-NLS-1$
- if (launchTimeString != null) {
- return Long.parseLong(launchTimeString);
- }
- return -1L;
- }
-
- protected long getMainStartTime() {
- String timeString = FrameworkProperties.getProperty("eclipse.startTime"); //$NON-NLS-1$
- if (timeString != null)
- return Long.parseLong(timeString);
-
- return System.currentTimeMillis();
- }
-
- public void initProps() {
- String prop;
- FrameworkDebugOptions dbgOptions = null;
- // if osgi.debug is not available, don't force DebugOptions
- // to init as this variable may be set later on where
- // DebugOptions will succeed.
- if (FrameworkProperties.getProperty("osgi.debug") != null) { //$NON-NLS-1$
- dbgOptions = FrameworkDebugOptions.getDefault();
- if (dbgOptions != null) {
- logFileName = dbgOptions.getOption(OPTION_FILENAME);
- logSynchronously = dbgOptions.getBooleanOption(OPTION_LOGSYNCHRONOUSLY, false);
- int size = dbgOptions.getIntegerOption(OPTION_BUFFERSIZE, 0);
- if (size > 0)
- bufferSize = size;
- }
- }
-
- if ((prop = FrameworkProperties.getProperty(PROP_FILENAME)) != null) {
- logFileName = prop;
- if (dbgOptions != null)
- dbgOptions.setOption(OPTION_FILENAME, logFileName);
- }
- if ((prop = FrameworkProperties.getProperty(PROP_LOGSYNCHRONOUSLY)) != null) {
- logSynchronously = Boolean.valueOf(prop).booleanValue();
- if (dbgOptions != null)
- dbgOptions.setOption(OPTION_LOGSYNCHRONOUSLY, new Boolean(logSynchronously).toString());
- }
- if ((prop = FrameworkProperties.getProperty(PROP_BUFFERSIZE)) != null) {
- try {
- int value = Integer.parseInt(prop);
- if (value > 0) {
- bufferSize = value;
- if (dbgOptions != null)
- dbgOptions.setOption(OPTION_BUFFERSIZE, Integer.toString(bufferSize));
- }
- } catch (NumberFormatException e) {
- // do nothing
- }
- }
- }
-
- public synchronized void logTime(int flag, String id, String msg, String description) {
- if (timeEntriesIndex == timeLogEntries.length) {
- makeLog();
- logTime(Profile.FLAG_NONE, "Profile.logTime()", "log entries rolled", null); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- TimeEntry entry = timeLogEntries[timeEntriesIndex++];
- entry.time = getTime();
- entry.id = id;
- entry.msg = msg;
- entry.flag = flag;
- entry.description = description;
-
- if (logSynchronously) {
- System.out.print(getProfileLog().substring(2));
- }
- }
-
- public synchronized String getProfileLog() {
- String log;
- log = getProfileLogReport();
- writeToProfileLogFile(log);
- return log;
- }
-
- public synchronized void accumLogEnter(String scope) {
- // Initialize our data structures
- if (scopeStack == null)
- scopeStack = new Stack<AccumPerfScope>();
- if (scopeToAccumPerfDataMap == null)
- scopeToAccumPerfDataMap = new TreeMap<String, AccumPerfData>();
-
- // We want getTime() to evaluate as late as possible
- scopeStack.push(new AccumPerfScope(scope, getTime()));
- }
-
- public synchronized void accumLogExit(String scope) {
- // What time is it?
- long exit = getTime();
-
- // Initialize our data structures
- if (scopeStack == null)
- scopeStack = new Stack<AccumPerfScope>();
- if (scopeToAccumPerfDataMap == null)
- scopeToAccumPerfDataMap = new TreeMap<String, AccumPerfData>();
-
- // Do our calculations
- AccumPerfScope then = scopeStack.pop();
- if (then == null)
- System.err.println("ACCUM PERF ERROR: Scope stack empty: " + scope); //$NON-NLS-1$
- else {
- if (!then.scope.equals(scope))
- System.err.println("ACCUM PERF ERROR: Scope mismatch: then='" + then.scope + "', now='" + scope + "'"); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
-
- AccumPerfData now = scopeToAccumPerfDataMap.get(scope);
- if (now == null) {
- now = new AccumPerfData(scope);
- scopeToAccumPerfDataMap.put(scope, now);
- }
-
- now.time += exit - then.enter;
- now.enters++;
- }
- }
-
- protected long getTime() {
- return System.currentTimeMillis();
- }
-
- protected long getTimerFrequency() {
- return 1000L; // millisecond
- }
-
- protected TimeEntry findCompareEntry(int index, String id, int flag) {
- if (index > 0)
- index--;
- int prev = index;
- if (flag != Profile.FLAG_ENTER) {
- while (index >= 0) {
- TimeEntry entry = timeLogEntries[index];
- if (entry.id.equals(id)) {
- switch (flag) {
- case Profile.FLAG_NONE :
- return entry;
- case Profile.FLAG_EXIT :
- if (entry.flag == Profile.FLAG_ENTER)
- return entry;
- break;
- }
- }
- index--;
- }
- }
- return timeLogEntries[prev];
- }
-
- protected String entryReport(TimeEntry entry, TimeEntry compareWith) {
- // indent level:
- entryReport.setLength(0);
- if (entry.flag == Profile.FLAG_ENTER)
- indent++;
- long zeroTime = getRelativeTime(getStartTime());
-
- entryReport.append('-');
- long entryTime = getRelativeTime(entry.time);
- long diff = entryTime - zeroTime;
- entryReport.append(pad(Long.toString(diff), timePaddingLength));
- entryReport.append(" :"); //$NON-NLS-1$
- diff = entry.time - compareWith.time;
- entryReport.append(pad(Long.toString(diff), timePaddingLength));
- entryReport.append(pad("", indent * 2)); // indent before displaying the entry.id //$NON-NLS-1$
-
- if (entry.flag == Profile.FLAG_ENTER)
- entryReport.append(" >> "); //$NON-NLS-1$
- else if (entry.flag == Profile.FLAG_EXIT)
- entryReport.append(" << "); //$NON-NLS-1$
- else if (entry.flag == Profile.FLAG_NONE)
- entryReport.append(" -- "); //$NON-NLS-1$
-
- entryReport.append(entry.id);
- entryReport.append(" > "); //$NON-NLS-1$
- entryReport.append(entry.msg);
- if (entry.description != null) {
- entryReport.append(" :: "); //$NON-NLS-1$
- entryReport.append(entry.description);
- }
- entryReport.append("\r\n"); //$NON-NLS-1$
-
- if (entry.flag == Profile.FLAG_EXIT)
- indent -= 1;
- return entryReport.toString();
- }
-
- protected String accumEntryReport(AccumPerfData d) {
- return (" " + d.scope + ":enters=" + d.enters + ";time=" + d.time + ";\r\n"); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$
- }
-
- protected void makeLog() {
- indent = 0;
- timelog.append("\r\n"); //$NON-NLS-1$
- for (int i = 0; i < timeEntriesIndex; i++) {
- TimeEntry entry = timeLogEntries[i];
- TimeEntry cmpEntry = findCompareEntry(i, entry.id, entry.flag);
- timelog.append(entryReport(entry, cmpEntry));
- }
- timeEntriesIndex = 0;
-
- if (scopeToAccumPerfDataMap == null || scopeToAccumPerfDataMap.isEmpty())
- return; // No data; nothing to do
- timelog.append("\r\n"); //$NON-NLS-1$
- timelog.append("Cumulative Log:\r\n"); //$NON-NLS-1$
- for (AccumPerfData d : scopeToAccumPerfDataMap.values()) {
- timelog.append(accumEntryReport(d));
- }
- scopeToAccumPerfDataMap.clear();
- }
-
- protected String pad(String str, int size) {
- padsb.setLength(0);
- int len = str.length();
- int count = size - len;
- for (int i = 0; i < count; i++)
- padsb.append(' ');
- padsb.append(str);
- return padsb.toString();
- }
-
- protected String getProfileLogReport() {
- if (timelog == null)
- return ""; //$NON-NLS-1$
- makeLog();
- String log = timelog.toString();
- timelog.setLength(0);
- return log;
- }
-
- protected void writeToProfileLogFile(String log) {
- File profileLog = getProfileLogFile();
- if (profileLog == null)
- return;
- FileWriter fw = null;
- try {
- fw = new FileWriter(profileLog.getAbsolutePath(), true);
- fw.write(log);
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if (fw != null)
- try {
- fw.close();
- } catch (IOException e) {
- // do nothing
- }
- }
- }
-
- protected File getProfileLogFile() {
- if (logFile == null)
- if ((logFileName != null) && (logFileName.length() > 0))
- logFile = new File(logFileName);
- return logFile;
- }
-
- protected long getStartTime() {
- return startTime;
- }
-
- protected long getRelativeTime(long absoluteTime) {
- return absoluteTime;
- }
-
- protected int getBufferSize() {
- if (bufferSize < 2)
- return DEFAULT_BUFFER_SIZE;
- return bufferSize;
- }
-
- protected TimeEntry timeEntryFactory() {
- return new TimeEntry();
- }
-
- protected class TimeEntry {
- public long time;
- public String id;
- public String msg;
- public String description;
- public int flag;
- }
-
- protected static class AccumPerfData {
- public AccumPerfData(String scope) {
- this.scope = scope;
- }
-
- public String scope;
- public long time;
- public long enters;
- }
-
- protected static class AccumPerfScope {
- public AccumPerfScope(String scope, long enter) {
- this.scope = scope;
- this.enter = enter;
- }
-
- public String scope;
- public long enter;
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/profile/Profile.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/profile/Profile.java
deleted file mode 100644
index aed3e7eca..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/profile/Profile.java
+++ /dev/null
@@ -1,268 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.internal.profile;
-
-import org.eclipse.osgi.framework.debug.FrameworkDebugOptions;
-import org.eclipse.osgi.framework.internal.core.FrameworkProperties;
-
-/**
- * This class is a development tool that provides a simple way to log
- * programmer defined timmings for performance evaluations. This profiling
- * allows logging of a timestamp with a corresponding message to a trace
- * buffer.
- */
-
-public class Profile {
- /**
- * Profiling is enabled and available.
- */
- public static final boolean PROFILE = true; // enable profile compiling
- /**
- * The logging state of <tt>STARTUP</tt> messages
- */
- public static boolean STARTUP = false; // enable startup profiling
- /**
- * The logging state of <tt>BENCHMARK</tt> messages
- */
- public static boolean BENCHMARK = false; // enable all benchmarking
- /**
- * The logging state of <tt>DEBUG</tt> messages
- */
- public static boolean DEBUG = false; // enable general debug profiling
-
- private static final String OSGI_PROP = "osgi.profile."; //$NON-NLS-1$
- private static final String PROP_STARTUP = OSGI_PROP + "startup"; //$NON-NLS-1$
- private static final String PROP_BENCHMARK = OSGI_PROP + "benchmark"; //$NON-NLS-1$
- private static final String PROP_DEBUG = OSGI_PROP + "debug"; //$NON-NLS-1$
- private static final String PROP_IMPL = OSGI_PROP + "impl"; //$NON-NLS-1$
-
- private static final String OSGI_OPTION = "org.eclipse.osgi/profile/"; //$NON-NLS-1$
- private static final String OPTION_STARTUP = OSGI_OPTION + "startup"; //$NON-NLS-1$
- private static final String OPTION_BENCHMARK = OSGI_OPTION + "benchmark"; //$NON-NLS-1$
- private static final String OPTION_DEBUG = OSGI_OPTION + "debug"; //$NON-NLS-1$
- private static final String OPTION_IMPL = OSGI_OPTION + "impl"; //$NON-NLS-1$
-
- /**
- * The default logging flag.
- */
- public static final int FLAG_NONE = 0;
- /**
- * The logging flag for <strong>method enter</strong>
- */
- public static final int FLAG_ENTER = 1;
- /**
- * The logging flag for <strong>method exit</strong>
- */
- public static final int FLAG_EXIT = 2;
- /**
- * The description for <strong>method enter</strong>
- */
- public static final String ENTER_DESCRIPTION = "enter"; //$NON-NLS-1$
- /**
- * The description for <strong>method exit</strong>
- */
- public static final String EXIT_DESCRIPTION = "exit"; //$NON-NLS-1$
-
- private static ProfileLogger profileLogger = null;
- private static String profileLoggerClassName = null;
-
- static {
- initProps();
- }
-
- /**
- * Initialize/update profiling properties.
- *
- * If profiling properties are updated, this method is called to update
- * the profile states.
- */
- public static void initProps() {
- String prop;
- FrameworkDebugOptions dbgOptions = null;
-
- // if osgi.debug is not available, don't force DebugOptions
- // to init as this variable may be set later on where
- // DebugOptions will succeed.
- if (FrameworkProperties.getProperty("osgi.debug") != null) { //$NON-NLS-1$
- dbgOptions = FrameworkDebugOptions.getDefault();
- if (dbgOptions != null) {
- STARTUP = dbgOptions.getBooleanOption(OPTION_STARTUP, false);
- BENCHMARK = dbgOptions.getBooleanOption(OPTION_BENCHMARK, false);
- DEBUG = dbgOptions.getBooleanOption(OPTION_DEBUG, false);
- if (profileLogger == null)
- profileLoggerClassName = dbgOptions.getOption(OPTION_IMPL);
- }
- }
-
- // System properties will always override anything in .options file
- if ((prop = FrameworkProperties.getProperty(PROP_STARTUP)) != null) {
- STARTUP = Boolean.valueOf(prop).booleanValue();
- if (dbgOptions != null)
- dbgOptions.setOption(OPTION_STARTUP, new Boolean(STARTUP).toString());
- }
- if ((prop = FrameworkProperties.getProperty(PROP_BENCHMARK)) != null) {
- BENCHMARK = Boolean.valueOf(prop).booleanValue();
- if (dbgOptions != null)
- dbgOptions.setOption(OPTION_BENCHMARK, new Boolean(BENCHMARK).toString());
- }
- if ((prop = FrameworkProperties.getProperty(PROP_DEBUG)) != null) {
- DEBUG = Boolean.valueOf(prop).booleanValue();
- if (dbgOptions != null)
- dbgOptions.setOption(OPTION_DEBUG, new Boolean(DEBUG).toString());
- }
-
- if (profileLogger == null) {
- if ((prop = FrameworkProperties.getProperty(PROP_IMPL)) != null) {
- profileLoggerClassName = prop;
- if (dbgOptions != null)
- dbgOptions.setOption(OPTION_IMPL, profileLoggerClassName);
- }
- } else {
- profileLogger.initProps();
- }
- }
-
- /**
- * Log a method enter.
- *
- * @param id The method's unique identification (e.g. org.eclipse.class#name).
- */
- public static void logEnter(String id) {
- logTime(FLAG_ENTER, id, ENTER_DESCRIPTION, null);
- }
-
- /**
- * Log a method enter.
- *
- * @param id The method's unique identification (e.g. org.eclipse.class#name).
- * @param description A description of the method.
- */
- public static void logEnter(String id, String description) {
- logTime(FLAG_ENTER, id, ENTER_DESCRIPTION, description);
- }
-
- /**
- * Log a method exit.
- *
- * @param id The method's unique identification (e.g. org.eclipse.class#name).
- */
- public static void logExit(String id) {
- logTime(FLAG_EXIT, id, EXIT_DESCRIPTION, null);
- }
-
- /**
- * Log a method exit.
- *
- * @param id The method's unique identification (e.g. org.eclipse.class#name).
- * @param description A description of the method.
- */
- public static void logExit(String id, String description) {
- logTime(FLAG_EXIT, id, EXIT_DESCRIPTION, description);
- }
-
- /**
- * Log a message.
- *
- * @param id The method's unique identification (e.g. org.eclipse.class#name).
- * @param msg The message.
- */
- public static void logTime(String id, String msg) {
- logTime(FLAG_NONE, id, msg, null);
- }
-
- /**
- * Log a message.
- *
- * @param id The method's unique identification (e.g. org.eclipse.class#name).
- * @param msg The message.
- * @param description A description of the method.
- */
- public static void logTime(String id, String msg, String description) {
- logTime(FLAG_NONE, id, msg, description);
- }
-
- /**
- * Log a message.
- *
- * @param flag A profile logging flag.
- * @param id The method's unique identification (e.g. org.eclipse.class#name).
- * @param msg The message.
- * @param description A description of the method.
- *
- * @see #FLAG_ENTER
- * @see #FLAG_EXIT
- * @see #FLAG_NONE
- */
- public static void logTime(int flag, String id, String msg, String description) {
- if (profileLogger == null)
- profileLogger = createProfileLogger();
- profileLogger.logTime(flag, id, msg, description);
- }
-
- /**
- * Use cumulative logging to record the entrance from this scope.
- *
- * @param scope The entering scope
- */
- public static void accumLogEnter(String scope) {
- if (profileLogger == null)
- profileLogger = createProfileLogger();
- profileLogger.accumLogEnter(scope);
- }
-
- /**
- * Use cumulative logging to record the exit from this scope.
- *
- * @param scope The exiting scope
- */
- public static void accumLogExit(String scope) {
- if (profileLogger == null)
- profileLogger = createProfileLogger();
- profileLogger.accumLogExit(scope);
- }
-
- /**
- * Get the profiling log report and reset the trace buffer.
- *
- * @return The profiling log report.
- */
- public static String getProfileLog() {
- if (profileLogger != null)
- return profileLogger.getProfileLog();
- return ""; //$NON-NLS-1$
- }
-
- /**
- * Create an instance of the appropriate profile logger
- */
- private static ProfileLogger createProfileLogger() {
- ProfileLogger result = null;
-
- // Try to create it by class name
- if (profileLoggerClassName != null) {
- Class<?> profileImplClass = null;
- try {
- profileImplClass = Class.forName(profileLoggerClassName);
- result = (ProfileLogger) profileImplClass.newInstance();
- } catch (Exception e) {
- // could not find the class
- e.printStackTrace();
- }
- }
-
- // Use the default
- if (result == null)
- result = new DefaultProfileLogger();
-
- return (result);
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/profile/ProfileLogger.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/profile/ProfileLogger.java
deleted file mode 100644
index 31cab05ea..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/profile/ProfileLogger.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.internal.profile;
-
-public interface ProfileLogger {
-
- /**
- *
- *@see Profile#initProps()
- */
- public void initProps();
-
- /**
- *@see Profile#logTime(int, String, String, String)
- */
- public void logTime(int flag, String id, String msg, String description);
-
- /**
- * @see Profile#accumLogEnter(String)
- */
- public void accumLogEnter(String scope);
-
- /**
- * @see Profile#accumLogExit(String)
- */
- public void accumLogExit(String scope);
-
- /**
- *
- * @see Profile#getProfileLog()
- */
- public String getProfileLog();
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/FilteredServiceListener.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/FilteredServiceListener.java
deleted file mode 100644
index 528d8d2e6..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/FilteredServiceListener.java
+++ /dev/null
@@ -1,205 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.internal.serviceregistry;
-
-import org.eclipse.osgi.framework.debug.Debug;
-import org.eclipse.osgi.framework.internal.core.BundleContextImpl;
-import org.eclipse.osgi.framework.internal.core.FilterImpl;
-import org.osgi.framework.*;
-import org.osgi.framework.hooks.service.ListenerHook;
-
-/**
- * Service Listener delegate.
- */
-class FilteredServiceListener implements ServiceListener, ListenerHook.ListenerInfo {
- /** Filter for listener. */
- private final FilterImpl filter;
- /** Real listener. */
- private final ServiceListener listener;
- /** The bundle context */
- private final BundleContextImpl context;
- /** is this an AllServiceListener */
- private final boolean allservices;
- /** is this an UnfilteredServiceListener */
- private final boolean unfiltered;
- /** an objectClass required by the filter */
- private final String objectClass;
- /** indicates whether the listener has been removed */
- private volatile boolean removed;
-
- /**
- * 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.
- * @exception InvalidSyntaxException if the filter is invalid.
- */
- FilteredServiceListener(final BundleContextImpl context, final ServiceListener listener, final String filterstring) throws InvalidSyntaxException {
- this.unfiltered = (listener instanceof UnfilteredServiceListener);
- if (filterstring == null) {
- this.filter = null;
- this.objectClass = null;
- } else {
- FilterImpl filterImpl = FilterImpl.newInstance(filterstring);
- 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.filter = filterstring.equals(getObjectClassFilterString(this.objectClass)) ? null : filterImpl;
- }
- }
- this.removed = false;
- this.listener = listener;
- this.context = context;
- this.allservices = (listener instanceof AllServiceListener);
- }
-
- /**
- * Receives notification that a service has had a lifecycle change.
- *
- * @param event The <code>ServiceEvent</code> object.
- */
- 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
- 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
- break objectClassCheck;
- }
- 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.
-
- 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$
- }
-
- event = filterMatch(event);
- if (event == null) {
- return;
- }
- if (allservices || ServiceRegistry.isAssignableTo(context, reference)) {
- if (Debug.DEBUG_EVENTS) {
- String listenerName = listener.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(listener)); //$NON-NLS-1$
- Debug.println("dispatchFilteredServiceEvent(" + listenerName + ")"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- listener.serviceChanged(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.
- *
- * @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.
- */
- private ServiceEvent filterMatch(ServiceEvent delivered) {
- boolean modified = delivered.getType() == ServiceEvent.MODIFIED;
- ServiceEvent event = modified ? ((ModifiedServiceEvent) delivered).getModifiedEvent() : delivered;
- if (unfiltered || (filter == null)) {
- return event;
- }
- ServiceReference<?> reference = event.getServiceReference();
- if (filter.match(reference)) {
- return event;
- }
- if (modified) {
- ModifiedServiceEvent modifiedServiceEvent = (ModifiedServiceEvent) delivered;
- if (modifiedServiceEvent.matchPreviousProperties(filter)) {
- return modifiedServiceEvent.getModifiedEndMatchEvent();
- }
- }
- // does not match and did not match previous properties; do not send event
- return null;
- }
-
- /**
- * The string representation of this Filtered listener.
- *
- * @return The string representation of this listener.
- */
- public String toString() {
- String filterString = getFilter();
- if (filterString == null) {
- filterString = ""; //$NON-NLS-1$
- }
- return listener.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(listener)) + filterString; //$NON-NLS-1$
- }
-
- /**
- * 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()
- */
- public BundleContext getBundleContext() {
- return context;
- }
-
- /**
- * Return the filter string for the ListenerHook.
- * @return The filter string with which the listener was added. This may
- * be <code>null</code> if the listener was added without a filter.
- * @see org.osgi.framework.hooks.service.ListenerHook.ListenerInfo#getFilter()
- */
- public String getFilter() {
- if (filter != null) {
- return filter.toString();
- }
- return getObjectClassFilterString(objectClass);
- }
-
- /**
- * Return the state of the listener for this addition and removal life
- * cycle. Initially this method will return <code>false</code>
- * indicating the listener has been added but has not been removed.
- * After the listener has been removed, this method must always return
- * <code>true</code>.
- *
- * @return <code>false</code> if the listener has not been been removed,
- * <code>true</code> otherwise.
- */
- public boolean isRemoved() {
- return removed;
- }
-
- /**
- * Mark the service listener registration as removed.
- */
- void markRemoved() {
- removed = true;
- }
-
- /**
- * Returns an objectClass filter string for the specified class name.
- * @return A filter string for the specified class name or <code>null</code> if the
- * specified class name is <code>null</code>.
- */
- private static String getObjectClassFilterString(String className) {
- if (className == null) {
- return null;
- }
- return "(" + Constants.OBJECTCLASS + "=" + className + ")"; //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/HookContext.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/HookContext.java
deleted file mode 100644
index 74610341a..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/HookContext.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.internal.serviceregistry;
-
-import org.osgi.framework.ServiceRegistration;
-
-/**
- * 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.
- *
- */
-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 hookRegistration the registration for the hook object
- * @throws Exception An exception thrown by the hook object.
- */
- public void call(Object hook, ServiceRegistration<?> hookRegistration) throws Exception;
-
- /**
- * Return the class name of the hook type supported by this hook context.
- *
- * @return The class name of the hook type supported by this hook context.
- */
- public String getHookClassName();
-
- /**
- * Return the hook method name called by this hook context.
- *
- * @return The hook method name called by this hook context.
- */
- public String getHookMethodName();
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ModifiedServiceEvent.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ModifiedServiceEvent.java
deleted file mode 100644
index b3e62c2af..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ModifiedServiceEvent.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2009, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.internal.serviceregistry;
-
-import org.osgi.framework.*;
-
-/**
- * ServiceEvent subtype for MODIFIED_ENDMATCH computation.
- *
- */
-class ModifiedServiceEvent extends ServiceEvent {
- private static final long serialVersionUID = -5373850978543026102L;
- private final ServiceEvent modified;
- private final ServiceEvent modifiedEndMatch;
- private final ServiceProperties previousProperties;
-
- /**
- * Create a ServiceEvent containing the service properties prior to modification.
- *
- * @param reference Reference to service with modified properties.
- * @param previousProperties Service properties prior to modification.
- */
- ModifiedServiceEvent(ServiceReference<?> reference, ServiceProperties previousProperties) {
- super(ServiceEvent.MODIFIED, reference);
- this.modified = new ServiceEvent(ServiceEvent.MODIFIED, reference);
- this.modifiedEndMatch = new ServiceEvent(ServiceEvent.MODIFIED_ENDMATCH, reference);
- this.previousProperties = previousProperties;
- }
-
- /**
- * Return the service event of type MODIFIED.
- *
- * @return The service event of type MODIFIED.
- */
- ServiceEvent getModifiedEvent() {
- return modified;
- }
-
- /**
- * Return the service event of type MODIFIED_ENDMATCH.
- *
- * @return The service event of type MODIFIED_ENDMATCH.
- */
- ServiceEvent getModifiedEndMatchEvent() {
- return modifiedEndMatch;
- }
-
- /**
- * Return if the specified filter matches 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 matchCase here since ServiceProperties already
- * does case insensitive lookup.
- */
- return filter.matchCase(previousProperties);
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ServiceProperties.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ServiceProperties.java
deleted file mode 100644
index a829d2697..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ServiceProperties.java
+++ /dev/null
@@ -1,186 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.internal.serviceregistry;
-
-import java.lang.reflect.Array;
-import java.util.*;
-import org.eclipse.osgi.framework.util.Headers;
-import org.osgi.framework.Constants;
-
-/**
- * Hashtable for service properties.
- *
- * Supports case-insensitive key lookup.
- */
-class ServiceProperties extends Headers<String, Object> {
- /**
- * Create a properties object for the service.
- *
- * @param props The properties for this service.
- */
- private ServiceProperties(int size, Dictionary<String, ?> props) {
- super(size);
-
- if (props == null) {
- return;
- }
- synchronized (props) {
- Enumeration<?> keysEnum = props.keys();
-
- while (keysEnum.hasMoreElements()) {
- Object key = keysEnum.nextElement();
-
- if (key instanceof String) {
- String header = (String) key;
-
- setProperty(header, props.get(header));
- }
- }
- }
- }
-
- /**
- * Create a properties object for the service.
- *
- * @param props The properties for this service.
- */
- ServiceProperties(Dictionary<String, ?> props) {
- this((props == null) ? 2 : props.size() + 2, props);
- }
-
- /**
- * Get a clone of the value of a service's property.
- *
- * @param key header name.
- * @return Clone of the value of the property or <code>null</code> if there is
- * no property by that name.
- */
- Object getProperty(String key) {
- return cloneValue(get(key));
- }
-
- /**
- * Get the list of key names for the service's properties.
- *
- * @return The list of property key names.
- */
- synchronized String[] getPropertyKeys() {
- int size = size();
-
- String[] keynames = new String[size];
-
- Enumeration<String> keysEnum = keys();
-
- for (int i = 0; i < size; i++) {
- keynames[i] = keysEnum.nextElement();
- }
-
- return keynames;
- }
-
- /**
- * Put a clone of the property value into this property object.
- *
- * @param key Name of property.
- * @param value Value of property.
- * @return previous property value.
- */
- synchronized Object setProperty(String key, Object value) {
- return set(key, cloneValue(value));
- }
-
- /**
- * Attempt to clone the value if necessary and possible.
- *
- * For some strange reason, you can test to see of 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.
- */
- private static Object cloneValue(Object value) {
- if (value == null)
- return null;
- if (value instanceof String) /* shortcut String */
- return value;
- if (value instanceof Number) /* shortcut Number */
- return value;
- if (value instanceof Character) /* shortcut Character */
- return value;
- if (value instanceof Boolean) /* shortcut Boolean */
- return value;
-
- Class<?> clazz = value.getClass();
- if (clazz.isArray()) {
- // Do an array copy
- Class<?> type = clazz.getComponentType();
- int len = Array.getLength(value);
- Object clonedArray = Array.newInstance(type, len);
- System.arraycopy(value, 0, clonedArray, 0, len);
- return clonedArray;
- }
- // must use reflection because Object clone method is protected!!
- try {
- return clazz.getMethod("clone", (Class<?>[]) null).invoke(value, (Object[]) null); //$NON-NLS-1$
- } catch (Exception e) {
- /* clone is not a public method on value's class */
- } catch (Error e) {
- /* JCL does not support reflection; try some well known types */
- if (value instanceof Vector<?>)
- return ((Vector<?>) value).clone();
- if (value instanceof Hashtable<?, ?>)
- return ((Hashtable<?, ?>) value).clone();
- }
- return value;
- }
-
- public synchronized String toString() {
- String keys[] = getPropertyKeys();
-
- int size = keys.length;
-
- StringBuffer sb = new StringBuffer(20 * size);
-
- sb.append('{');
-
- int n = 0;
- for (int i = 0; i < size; i++) {
- String key = keys[i];
- if (!key.equals(Constants.OBJECTCLASS)) {
- if (n > 0)
- sb.append(", "); //$NON-NLS-1$
-
- sb.append(key);
- sb.append('=');
- Object value = get(key);
- if (value.getClass().isArray()) {
- sb.append('[');
- int length = Array.getLength(value);
- for (int j = 0; j < length; j++) {
- if (j > 0)
- sb.append(',');
- sb.append(Array.get(value, j));
- }
- sb.append(']');
- } else {
- sb.append(value);
- }
- n++;
- }
- }
-
- sb.append('}');
-
- return sb.toString();
- }
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ServiceReferenceImpl.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ServiceReferenceImpl.java
deleted file mode 100644
index e6784ca0a..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ServiceReferenceImpl.java
+++ /dev/null
@@ -1,275 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.internal.serviceregistry;
-
-import org.osgi.framework.*;
-
-/**
- * A reference to a service.
- *
- * <p>
- * The Framework returns <code>ServiceReference</code> objects from the
- * <code>BundleContext.getServiceReference</code> and
- * <code>BundleContext.getServiceReferences</code> methods.
- * <p>
- * A <code>ServiceReference</code> object may be shared between bundles and
- * can be used to examine the properties of the service and to get the service
- * object.
- * <p>
- * Every service registered in the Framework has a unique
- * <code>ServiceRegistration</code> object and may have multiple, distinct
- * <code>ServiceReference</code> objects referring to it.
- * <code>ServiceReference</code> objects associated with a
- * <code>ServiceRegistration</code> object have the same <code>hashCode</code>
- * and are considered equal (more specifically, their <code>equals()</code>
- * method will return <code>true</code> when compared).
- * <p>
- * If the same service object is registered multiple times,
- * <code>ServiceReference</code> objects associated with different
- * <code>ServiceRegistration</code> objects are not equal.
- *
- * @see BundleContext#getServiceReference
- * @see BundleContext#getServiceReferences
- * @see BundleContext#getService
- * @ThreadSafe
- */
-public class ServiceReferenceImpl<S> implements ServiceReference<S> {
- /** Registered Service object. */
- private final ServiceRegistrationImpl<S> registration;
-
- /**
- * Construct a reference.
- *
- */
- ServiceReferenceImpl(ServiceRegistrationImpl<S> registration) {
- this.registration = registration;
- /* 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 <code>Dictionary</code> object of the service
- * referenced by this <code>ServiceReference</code> object.
- *
- * <p>
- * Property keys are case-insensitive.
- *
- * <p>
- * This method must continue to return property values after the service has
- * been unregistered. This is so references to unregistered services (for
- * example, <code>ServiceReference</code> objects stored in the log) can
- * still be interrogated.
- *
- * @param key The property key.
- * @return The property value to which the key is mapped; <code>null</code>
- * if there is no property named after the key.
- */
- public Object getProperty(String key) {
- return registration.getProperty(key);
- }
-
- /**
- * Returns an array of the keys in the properties <code>Dictionary</code>
- * object of the service referenced by this <code>ServiceReference</code>
- * object.
- *
- * <p>
- * This method will continue to return the keys after the service has been
- * unregistered. This is so references to unregistered services (for
- * example, <code>ServiceReference</code> objects stored in the log) can
- * still be interrogated.
- *
- * <p>
- * This method is <i>case-preserving </i>; this means that every key in the
- * returned array must have the same case as the corresponding key in the
- * properties <code>Dictionary</code> that was passed to the
- * {@link BundleContext#registerService(String[],Object,java.util.Dictionary)}
- * or {@link ServiceRegistration#setProperties} methods.
- *
- * @return An array of property keys.
- */
- public String[] getPropertyKeys() {
- return registration.getPropertyKeys();
- }
-
- /**
- * Returns the bundle that registered the service referenced by this
- * <code>ServiceReference</code> object.
- *
- * <p>
- * This method must return <code>null</code> when the service has been
- * unregistered. This can be used to determine if the service has been
- * unregistered.
- *
- * @return The bundle that registered the service referenced by this
- * <code>ServiceReference</code> object; <code>null</code> if
- * that service has already been unregistered.
- * @see BundleContext#registerService(String[],Object,java.util.Dictionary)
- */
- public Bundle getBundle() {
- return registration.getBundle();
- }
-
- /**
- * Returns the bundles that are using the service referenced by this
- * <code>ServiceReference</code> 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 <code>ServiceReference</code> object is greater than
- * zero; <code>null</code> if no bundles are currently using that
- * service.
- *
- * @since 1.1
- */
- public Bundle[] getUsingBundles() {
- return registration.getUsingBundles();
- }
-
- /**
- * Tests if the bundle that registered the service referenced by this
- * <code>ServiceReference</code> and the specified bundle use the same
- * source for the package of the specified class name.
- * <p>
- * This method performs the following checks:
- * <ol>
- * <li>Get the package name from the specified class name.</li>
- * <li>For the bundle that registered the service referenced by this
- * <code>ServiceReference</code> (registrant bundle); find the source for
- * the package. If no source is found then return <code>true</code> if the
- * registrant bundle is equal to the specified bundle; otherwise return
- * <code>false</code>.</li>
- * <li>If the package source of the registrant bundle is equal to the
- * package source of the specified bundle then return <code>true</code>;
- * otherwise return <code>false</code>.</li>
- * </ol>
- *
- * @param bundle The <code>Bundle</code> object to check.
- * @param className The class name to check.
- * @return <code>true</code> if the bundle which registered the service
- * referenced by this <code>ServiceReference</code> and the
- * specified bundle use the same source for the package of the
- * specified class name. Otherwise <code>false</code> is returned.
- *
- * @since 1.3
- */
- public boolean isAssignableTo(Bundle bundle, String className) {
- return registration.isAssignableTo(bundle, className);
- }
-
- /**
- * Compares this <code>ServiceReference</code> with the specified
- * <code>ServiceReference</code> for order.
- *
- * <p>
- * If this <code>ServiceReference</code> and the specified
- * <code>ServiceReference</code> have the same
- * {@link Constants#SERVICE_ID service id} they are equal. This
- * <code>ServiceReference</code> is less than the specified
- * <code>ServiceReference</code> if it has a lower
- * {@link Constants#SERVICE_RANKING service ranking} and greater if it has a
- * higher service ranking. Otherwise, if this <code>ServiceReference</code>
- * and the specified <code>ServiceReference</code> have the same
- * {@link Constants#SERVICE_RANKING service ranking}, this
- * <code>ServiceReference</code> is less than the specified
- * <code>ServiceReference</code> if it has a higher
- * {@link Constants#SERVICE_ID service id} and greater if it has a lower
- * service id.
- *
- * @param object The <code>ServiceReference</code> to be compared.
- * @return Returns a negative integer, zero, or a positive integer if this
- * <code>ServiceReference</code> is less than, equal to, or
- * greater than the specified <code>ServiceReference</code>.
- * @since 1.4
- */
- public int compareTo(Object object) {
- ServiceRegistrationImpl<?> other = ((ServiceReferenceImpl<?>) object).registration;
-
- final int thisRanking = registration.getRanking();
- final int otherRanking = other.getRanking();
- if (thisRanking != otherRanking) {
- if (thisRanking < otherRanking) {
- return -1;
- }
- return 1;
- }
- final long thisId = registration.getId();
- final long otherId = other.getId();
- if (thisId == otherId) {
- return 0;
- }
- if (thisId < otherId) {
- return 1;
- }
- return -1;
- }
-
- /**
- * Returns a hash code value for the object.
- *
- * @return a hash code value for this object.
- */
- public int hashCode() {
- return registration.hashCode();
- }
-
- /**
- * Indicates whether some other object is "equal to" this one.
- *
- * @param obj the reference object with which to compare.
- * @return <code>true</code> if this object is the same as the obj
- * argument; <code>false</code> otherwise.
- */
- public boolean equals(Object obj) {
- if (obj == this) {
- return true;
- }
-
- if (!(obj instanceof ServiceReferenceImpl<?>)) {
- return false;
- }
-
- ServiceReferenceImpl<?> other = (ServiceReferenceImpl<?>) obj;
-
- return registration == other.registration;
- }
-
- /**
- * Return a string representation of this reference.
- *
- * @return String
- */
- public String toString() {
- return registration.toString();
- }
-
- /**
- * Return the ServiceRegistrationImpl for this ServiceReferenceImpl.
- *
- * @return The ServiceRegistrationImpl for this ServiceReferenceImpl.
- */
- public ServiceRegistrationImpl<S> getRegistration() {
- return registration;
- }
-
- /**
- * Return the classes under which the referenced service was registered.
- *
- * @return array of class names.
- */
- String[] getClasses() {
- return registration.getClasses();
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ServiceRegistrationImpl.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ServiceRegistrationImpl.java
deleted file mode 100644
index 3821f9f53..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ServiceRegistrationImpl.java
+++ /dev/null
@@ -1,650 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.internal.serviceregistry;
-
-import java.util.*;
-import org.eclipse.osgi.framework.debug.Debug;
-import org.eclipse.osgi.framework.internal.core.*;
-import org.osgi.framework.*;
-import org.osgi.framework.Constants;
-
-/**
- * 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.
- * <p>The ServiceRegistration object may be used to update the properties
- * for the service or to unregister the service.
- *
- * <p>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
- */
-public class ServiceRegistrationImpl<S> implements ServiceRegistration<S>, Comparable<ServiceRegistrationImpl<?>> {
- /** Internal framework object. */
- private final Framework framework;
-
- private final ServiceRegistry registry;
-
- /** context which registered this service. */
- private final BundleContextImpl context;
-
- /** bundle which registered this service. */
- private final Bundle bundle;
-
- /** service classes for this registration. */
- private final String[] clazzes;
-
- /** service object for this registration. */
- private final S service;
-
- /** Reference to this registration. */
- /* @GuardedBy("registrationLock") */
- private ServiceReferenceImpl<S> reference;
-
- /** List of contexts using the service.
- * List&lt;BundleContextImpl&gt;.
- * */
- /* @GuardedBy("registrationLock") */
- private final List<BundleContextImpl> contextsUsing;
-
- /** properties for this registration. */
- /* @GuardedBy("registrationLock") */
- private ServiceProperties properties;
-
- /** service id. */
- private final long serviceid;
-
- /** service ranking. */
- /* @GuardedBy("registrationLock") */
- private int serviceranking;
-
- /* internal object to use for synchronization */
- private final Object registrationLock = new Object();
-
- /** The registration state */
- /* @GuardedBy("registrationLock") */
- private int state;
- private static final int REGISTERED = 0x00;
- private static final int UNREGISTERING = 0x01;
- private static final int UNREGISTERED = 0x02;
-
- /**
- * Construct a ServiceRegistration and register the service
- * in the framework's service registry.
- *
- */
- ServiceRegistrationImpl(ServiceRegistry registry, BundleContextImpl context, String[] clazzes, S service) {
- this.registry = registry;
- this.context = context;
- this.bundle = context.getBundleImpl();
- this.framework = context.getFramework();
- this.clazzes = clazzes; /* must be set before calling createProperties. */
- this.service = service;
- this.serviceid = registry.getNextServiceId(); /* must be set before calling createProperties. */
- this.contextsUsing = new ArrayList<BundleContextImpl>(10);
-
- 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.
- */
- this.reference = new ServiceReferenceImpl<S>(this);
- }
- }
-
- /**
- * Call after constructing this object to complete the registration.
- */
- void register(Dictionary<String, ?> props) {
- final ServiceReferenceImpl<S> ref;
- synchronized (registry) {
- context.checkValid();
- synchronized (registrationLock) {
- ref = reference; /* used to publish event outside sync */
- this.properties = createProperties(props); /* must be valid after unregister is called. */
- }
- if (Debug.DEBUG_SERVICES) {
- Debug.println("registerService[" + bundle + "](" + this + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- registry.addServiceRegistration(context, this);
- }
-
- /* must not hold the registrations lock when this event is published */
- registry.publishServiceEvent(new ServiceEvent(ServiceEvent.REGISTERED, ref));
- }
-
- /**
- * Update the properties associated with this service.
- *
- * <p>The key "objectClass" cannot be modified by this method. It's
- * value is set when the service is registered.
- *
- * <p>The following steps are followed to modify a service's properties:
- * <ol>
- * <li>The service's properties are replaced with the provided properties.
- * <li>A {@link ServiceEvent} of type {@link ServiceEvent#MODIFIED}
- * is synchronously sent.
- * </ol>
- *
- * @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 <tt>properties</tt>
- * parameter contains case variants of the same key name.
- */
- public void setProperties(Dictionary<String, ?> props) {
- final ServiceReferenceImpl<S> ref;
- final ServiceProperties previousProperties;
- synchronized (registry) {
- synchronized (registrationLock) {
- if (state != REGISTERED) { /* in the process of unregisterING */
- throw new IllegalStateException(Msg.SERVICE_ALREADY_UNREGISTERED_EXCEPTION);
- }
-
- ref = reference; /* used to publish event outside sync */
- previousProperties = this.properties;
- this.properties = createProperties(props);
- }
- registry.modifyServiceRegistration(context, this);
- }
- /* must not hold the registrationLock when this event is published */
- registry.publishServiceEvent(new ModifiedServiceEvent(ref, previousProperties));
- }
-
- /**
- * 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.
- *
- * <p>The following steps are followed to unregister a service:
- * <ol>
- * <li>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.
- * <li>A {@link ServiceEvent} of type {@link ServiceEvent#UNREGISTERING}
- * is synchronously sent so that bundles using this service
- * may release their use of the service.
- * <li>For each bundle whose use count for this service is greater
- * than zero:
- * <ol>
- * <li>The bundle's use count for this service is set to zero.
- * <li>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.
- * </ol>
- * </ol>
- *
- * @exception java.lang.IllegalStateException If
- * this ServiceRegistration has already been unregistered.
- * @see BundleContextImpl#ungetService
- */
- public void unregister() {
- final ServiceReferenceImpl<S> ref;
- synchronized (registry) {
- synchronized (registrationLock) {
- if (state != REGISTERED) { /* in the process of unregisterING */
- throw new IllegalStateException(Msg.SERVICE_ALREADY_UNREGISTERED_EXCEPTION);
- }
-
- /* remove this object from the service registry */
- if (Debug.DEBUG_SERVICES) {
- Debug.println("unregisterService[" + bundle + "](" + this + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- registry.removeServiceRegistration(context, this);
-
- state = UNREGISTERING; /* mark unregisterING */
- ref = reference; /* used to publish event outside sync */
- }
- }
-
- /* must not hold the registrationLock when this event is published */
- registry.publishServiceEvent(new ServiceEvent(ServiceEvent.UNREGISTERING, ref));
-
- int size = 0;
- BundleContextImpl[] users = null;
-
- synchronized (registrationLock) {
- /* we have published the ServiceEvent, now mark the service fully unregistered */
- state = UNREGISTERED;
-
- size = contextsUsing.size();
- if (size > 0) {
- if (Debug.DEBUG_SERVICES) {
- Debug.println("unregisterService: releasing users"); //$NON-NLS-1$
- }
- users = contextsUsing.toArray(new BundleContextImpl[size]);
- }
- }
-
- /* must not hold the registrationLock while releasing services */
- for (int i = 0; i < size; i++) {
- releaseService(users[i]);
- }
-
- synchronized (registrationLock) {
- contextsUsing.clear();
-
- reference = null; /* mark registration dead */
- }
-
- /* The properties field must remain valid after unregister completes. */
- }
-
- /**
- * 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.
- * @return A {@link ServiceReferenceImpl} object.
- */
- public ServiceReference<S> getReference() {
- return getReferenceImpl();
- }
-
- ServiceReferenceImpl<S> 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.
- */
- synchronized (registrationLock) {
- if (reference == null) {
- throw new IllegalStateException(Msg.SERVICE_ALREADY_UNREGISTERED_EXCEPTION);
- }
-
- return reference;
- }
- }
-
- /**
- * Construct a properties object from the dictionary for this
- * ServiceRegistration.
- *
- * @param p The properties for this service.
- * @return A Properties object for this ServiceRegistration.
- */
- /* @GuardedBy("registrationLock") */
- private ServiceProperties createProperties(Dictionary<String, ?> p) {
- assert Thread.holdsLock(registrationLock);
- ServiceProperties props = new ServiceProperties(p);
-
- props.set(Constants.OBJECTCLASS, clazzes, true);
- props.set(Constants.SERVICE_ID, new Long(serviceid), true);
- props.setReadOnly();
- Object ranking = props.getProperty(Constants.SERVICE_RANKING);
-
- serviceranking = (ranking instanceof Integer) ? ((Integer) ranking).intValue() : 0;
-
- return props;
- }
-
- /**
- * Return the properties object. This is for framework internal use only.
- * @return The service registration's properties.
- */
- public ServiceProperties getProperties() {
- synchronized (registrationLock) {
- return properties;
- }
- }
-
- /**
- * Get the value of a service's property.
- *
- * <p>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 <code>null</code> if there is
- * no property by that name.
- */
- Object getProperty(String key) {
- synchronized (registrationLock) {
- return properties.getProperty(key);
- }
- }
-
- /**
- * Get the list of key names for the service's properties.
- *
- * <p>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.
- */
- String[] getPropertyKeys() {
- synchronized (registrationLock) {
- return properties.getPropertyKeys();
- }
- }
-
- /**
- * Return the service id for this service.
- * @return The service id for this service.
- */
- long getId() {
- return serviceid;
- }
-
- /**
- * Return the service ranking for this service.
- * @return The service ranking for this service.
- */
- int getRanking() {
- synchronized (registrationLock) {
- return serviceranking;
- }
- }
-
- String[] getClasses() {
- return clazzes;
- }
-
- S getServiceObject() {
- return service;
- }
-
- /**
- * Return the bundle which registered the service.
- *
- * <p>This method will always return <code>null</code> 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.
- */
- Bundle getBundle() {
- synchronized (registrationLock) {
- if (reference == null) {
- return null;
- }
-
- return bundle;
- }
- }
-
- /**
- * 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() {
- return bundle;
- }
-
- Object getSafeService(BundleContextImpl user) {
- try {
- return getService(user);
- } catch (IllegalStateException e) {
- // can happen if the user is stopped on another thread
- return null;
- }
- }
-
- /**
- * Get a service object for the using BundleContext.
- *
- * @param user BundleContext using service.
- * @return Service object
- */
- Object getService(BundleContextImpl user) {
- synchronized (registrationLock) {
- if (state == UNREGISTERED) { /* service unregistered */
- return null;
- }
- }
- if (Debug.DEBUG_SERVICES) {
- Debug.println("getService[" + user.getBundleImpl() + "](" + this + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- Map<ServiceRegistrationImpl<?>, ServiceUse<?>> servicesInUse = user.getServicesInUseMap();
- if (servicesInUse == null) { /* user is closed */
- user.checkValid(); /* throw exception */
- }
- /* Use a while loop to support retry if a call to a ServiceFactory fails */
- while (true) {
- ServiceUse<?> use;
- boolean added = false;
- /* Obtain the ServiceUse object for this service by bundle user */
- synchronized (servicesInUse) {
- user.checkValid();
- use = servicesInUse.get(this);
- if (use == null) {
- /* if this is the first use of the service
- * optimistically record this service is being used. */
- use = new ServiceUse<S>(user, this);
- added = true;
- synchronized (registrationLock) {
- if (state == UNREGISTERED) { /* service unregistered */
- return null;
- }
- servicesInUse.put(this, use);
- contextsUsing.add(user);
- }
- }
- }
-
- /* Obtain and return the service object */
- synchronized (use) {
- /* if another thread removed the ServiceUse, then
- * go back to the top and start again */
- synchronized (servicesInUse) {
- user.checkValid();
- if (servicesInUse.get(this) != use) {
- continue;
- }
- }
- Object serviceObject = use.getService();
- /* if the service factory failed to return an object and
- * we created the service use, then remove the
- * optimistically added ServiceUse. */
- if ((serviceObject == null) && added) {
- synchronized (servicesInUse) {
- synchronized (registrationLock) {
- servicesInUse.remove(this);
- contextsUsing.remove(user);
- }
- }
- }
- return serviceObject;
- }
- }
- }
-
- /**
- * Unget a service for the using BundleContext.
- *
- * @param user BundleContext using service.
- * @return <code>false</code> if the context bundle's use count for the service
- * is zero or if the service has been unregistered,
- * otherwise <code>true</code>.
- */
- boolean ungetService(BundleContextImpl user) {
- synchronized (registrationLock) {
- if (state == UNREGISTERED) {
- return false;
- }
- }
-
- if (Debug.DEBUG_SERVICES) {
- Debug.println("ungetService[" + user.getBundleImpl() + "](" + this + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- Map<ServiceRegistrationImpl<?>, ServiceUse<?>> servicesInUse = user.getServicesInUseMap();
- if (servicesInUse == null) {
- return false;
- }
-
- ServiceUse<?> use;
- synchronized (servicesInUse) {
- use = servicesInUse.get(this);
- if (use == null) {
- return false;
- }
- }
-
- synchronized (use) {
- if (use.ungetService()) {
- /* use count is now zero */
- synchronized (servicesInUse) {
- synchronized (registrationLock) {
- servicesInUse.remove(this);
- contextsUsing.remove(user);
- }
- }
- }
- }
- return true;
- }
-
- /**
- * Release the service for the using BundleContext.
- *
- * @param user BundleContext using service.
- */
- void releaseService(BundleContextImpl user) {
- synchronized (registrationLock) {
- if (reference == null) { /* registration dead */
- return;
- }
- }
-
- if (Debug.DEBUG_SERVICES) {
- Debug.println("releaseService[" + user.getBundleImpl() + "](" + this + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- Map<ServiceRegistrationImpl<?>, ServiceUse<?>> servicesInUse = user.getServicesInUseMap();
- if (servicesInUse == null) {
- return;
- }
- ServiceUse<?> use;
- synchronized (servicesInUse) {
- synchronized (registrationLock) {
- use = servicesInUse.remove(this);
- if (use == null) {
- return;
- }
- contextsUsing.remove(user);
- }
- }
- synchronized (use) {
- use.releaseService();
- }
- }
-
- /**
- * Return the list of bundle which are using this service.
- *
- * @return Array of Bundles using this service.
- */
- Bundle[] getUsingBundles() {
- synchronized (registrationLock) {
- if (state == UNREGISTERED) /* service unregistered */
- return null;
-
- int size = contextsUsing.size();
- if (size == 0)
- return null;
-
- /* Copy list of BundleContext into an array of Bundle. */
- Bundle[] bundles = new Bundle[size];
- for (int i = 0; i < size; i++)
- bundles[i] = contextsUsing.get(i).getBundleImpl();
-
- return bundles;
- }
- }
-
- boolean isAssignableTo(Bundle client, String className) {
- return framework.isServiceAssignableTo(bundle, client, className, service.getClass());
- }
-
- /**
- * Return a String representation of this object.
- *
- * @return String representation of this object.
- */
- public String toString() {
- int size = clazzes.length;
- StringBuffer sb = new StringBuffer(50 * size);
-
- sb.append('{');
-
- for (int i = 0; i < size; i++) {
- if (i > 0) {
- sb.append(", "); //$NON-NLS-1$
- }
- sb.append(clazzes[i]);
- }
-
- sb.append("}="); //$NON-NLS-1$
- sb.append(getProperties().toString());
-
- return sb.toString();
- }
-
- /**
- * Compares this <code>ServiceRegistrationImpl</code> with the specified
- * <code>ServiceRegistrationImpl</code> for order.
- *
- * <p>
- * 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 <code>ServiceRegistrationImpl</code> to be compared.
- * @return Returns a negative integer, zero, or a positive integer if this
- * <code>ServiceRegistrationImpl</code> is greater than, equal to, or
- * less than the specified <code>ServiceRegistrationImpl</code>.
- */
- public int compareTo(ServiceRegistrationImpl<?> other) {
- final int thisRanking = this.getRanking();
- final int otherRanking = other.getRanking();
- if (thisRanking != otherRanking) {
- if (thisRanking < otherRanking) {
- return 1;
- }
- return -1;
- }
- final long thisId = this.getId();
- final long otherId = other.getId();
- if (thisId == otherId) {
- return 0;
- }
- if (thisId < otherId) {
- return -1;
- }
- return 1;
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ServiceRegistry.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ServiceRegistry.java
deleted file mode 100644
index a80b00b2e..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ServiceRegistry.java
+++ /dev/null
@@ -1,1362 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2004, 2012 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.internal.serviceregistry;
-
-import java.security.*;
-import java.util.*;
-import org.eclipse.osgi.framework.debug.Debug;
-import org.eclipse.osgi.framework.eventmgr.*;
-import org.eclipse.osgi.framework.internal.core.*;
-import org.eclipse.osgi.util.NLS;
-import org.osgi.framework.*;
-import org.osgi.framework.Constants;
-import org.osgi.framework.hooks.service.*;
-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.
- *
- * @ThreadSafe
- */
-public class ServiceRegistry {
- public static final int SERVICEEVENT = 3;
-
- static final String findHookName = FindHook.class.getName();
- static final String eventHookName = EventHook.class.getName();
- static final String eventListenerHookName = EventListenerHook.class.getName();
- static final String listenerHookName = ListenerHook.class.getName();
-
- /** Published services by class name.
- * The {@literal List<ServiceRegistrationImpl<?>>}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<String, List<ServiceRegistrationImpl<?>>> 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.
- */
- /* @GuardedBy("this") */
- private final List<ServiceRegistrationImpl<?>> allPublishedServices;
-
- /** Published services by BundleContextImpl.
- * The {@literal List<ServiceRegistrationImpl<?>>}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<BundleContextImpl, List<ServiceRegistrationImpl<?>>> publishedServicesByContext;
-
- /** next free service id. */
- /* @GuardedBy("this") */
- private long serviceid;
-
- /** Active Service Listeners.
- * {@literal Map<BundleContextImpl,CopyOnWriteIdentityMap<ServiceListener,FilteredServiceListener>>}.
- */
- /* @GuardedBy("serviceEventListeners") */
- private final Map<BundleContextImpl, CopyOnWriteIdentityMap<ServiceListener, FilteredServiceListener>> serviceEventListeners;
-
- /** initial capacity of the main data structure */
- private static final int initialCapacity = 50;
- /** initial capacity of the nested data structure */
- private static final int initialSubCapacity = 10;
- /** framework which created this service registry */
- private final Framework framework;
-
- /**
- * Initializes the internal data structures of this ServiceRegistry.
- *
- */
- public ServiceRegistry(Framework framework) {
- this.framework = framework;
- serviceid = 1;
- publishedServicesByClass = new HashMap<String, List<ServiceRegistrationImpl<?>>>(initialCapacity);
- publishedServicesByContext = new HashMap<BundleContextImpl, List<ServiceRegistrationImpl<?>>>(initialCapacity);
- allPublishedServices = new ArrayList<ServiceRegistrationImpl<?>>(initialCapacity);
- serviceEventListeners = new HashMap<BundleContextImpl, CopyOnWriteIdentityMap<ServiceListener, FilteredServiceListener>>(initialCapacity);
- }
-
- /**
- * Registers the specified service object with the specified properties
- * under the specified class names into the Framework. A
- * <code>ServiceRegistrationImpl</code> object is returned. The
- * <code>ServiceRegistrationImpl</code> 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.
- *
- * <p>
- * A bundle can register a service object that implements the
- * {@link ServiceFactory} interface to have more flexibility in providing
- * service objects to other bundles.
- *
- * <p>
- * The following steps are required to register a service:
- * <ol>
- * <li>If <code>service</code> is not a <code>ServiceFactory</code>,
- * an <code>IllegalArgumentException</code> is thrown if
- * <code>service</code> is not an <code>instanceof</code> all the
- * classes named.
- * <li>The Framework adds these service properties to the specified
- * <code>Dictionary</code> (which may be <code>null</code>): 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.
- * <li>The service is added to the Framework service registry and may now
- * be used by other bundles.
- * <li>A service event of type {@link ServiceEvent#REGISTERED} is fired.
- * <li>A <code>ServiceRegistration</code> object for this registration is
- * returned.
- * </ol>
- *
- * @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 <code>ServiceFactory</code>
- * object.
- * @param properties The properties for this service. The keys in the
- * properties object must all be <code>String</code> 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 <code>null</code> if the service
- * has no properties.
- *
- * @return A <code>ServiceRegistrationImpl</code> 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:
- * <ul>
- * <li><code>service</code> is <code>null</code>.
- * <li><code>service</code> is not a <code>ServiceFactory</code>
- * object and is not an instance of all the named classes in
- * <code>clazzes</code>.
- * <li><code>properties</code> contains case variants of the same
- * key name.
- * </ul>
- *
- * @throws java.lang.SecurityException If the caller does not have the
- * <code>ServicePermission</code> 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.
- *
- * @see ServiceRegistration
- * @see ServiceFactory
- */
- public ServiceRegistrationImpl<?> registerService(BundleContextImpl context, String[] clazzes, Object service, Dictionary<String, ?> properties) {
- if (service == null) {
- if (Debug.DEBUG_SERVICES) {
- Debug.println("Service object is null"); //$NON-NLS-1$
- }
-
- throw new IllegalArgumentException(Msg.SERVICE_ARGUMENT_NULL_EXCEPTION);
- }
-
- int size = clazzes.length;
-
- if (size == 0) {
- if (Debug.DEBUG_SERVICES) {
- Debug.println("Classes array is empty"); //$NON-NLS-1$
- }
-
- throw new IllegalArgumentException(Msg.SERVICE_EMPTY_CLASS_LIST_EXCEPTION);
- }
-
- /* copy the array so that changes to the original will not affect us. */
- List<String> copy = new ArrayList<String>(size);
- // intern the strings and remove duplicates
- for (int i = 0; i < size; i++) {
- String clazz = clazzes[i].intern();
- if (!copy.contains(clazz)) {
- copy.add(clazz);
- }
- }
- size = copy.size();
- clazzes = copy.toArray(new String[size]);
-
- /* check for ServicePermissions. */
- checkRegisterServicePermission(clazzes);
-
- if (!(service instanceof ServiceFactory<?>)) {
- String invalidService = checkServiceClass(clazzes, service);
- if (invalidService != null) {
- 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));
- }
- }
-
- ServiceRegistrationImpl<?> registration = new ServiceRegistrationImpl<Object>(this, context, clazzes, service);
- registration.register(properties);
- if (copy.contains(listenerHookName)) {
- notifyNewListenerHook(registration);
- }
- return registration;
- }
-
- /**
- * Returns an array of <code>ServiceReferenceImpl</code> objects. The returned
- * array of <code>ServiceReferenceImpl</code> 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
- * {@link ServiceReference#isAssignableTo(Bundle, String)}.
- *
- * <p>
- * 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.
- *
- * <p>
- * <code>filter</code> 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.
- *
- * <p>
- * If <code>filter</code> is <code>null</code>, all registered services
- * are considered to match the filter. If <code>filter</code> cannot be
- * parsed, an {@link InvalidSyntaxException} will be thrown with a human
- * readable message where the filter became unparsable.
- *
- * <p>
- * The following steps are required to select a set of
- * <code>ServiceReferenceImpl</code> objects:
- * <ol>
- * <li>If the filter string is not <code>null</code>, the filter string
- * is parsed and the set <code>ServiceReferenceImpl</code> objects of
- * registered services that satisfy the filter is produced. If the filter
- * string is <code>null</code>, then all registered services are
- * considered to satisfy the filter.
- * <li>If the Java Runtime Environment supports permissions, the set of
- * <code>ServiceReferenceImpl</code> objects produced by the previous step is
- * reduced by checking that the caller has the
- * <code>ServicePermission</code> 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 <code>ServiceReferenceImpl</code>
- * object, then it is removed from the set.
- * <li>If <code>clazz</code> is not <code>null</code>, the set is
- * further reduced to those services that are an <code>instanceof</code>
- * 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.
- * <li>The set is reduced one final time by cycling through each
- * <code>ServiceReference</code> object and calling
- * {@link ServiceReference#isAssignableTo(Bundle, String)} with the context
- * bundle and each class name under which the <code>ServiceReference</code>
- * object was registered. For any given <code>ServiceReferenceImpl</code>
- * object, if any call to
- * {@link ServiceReference#isAssignableTo(Bundle, String)} returns
- * <code>false</code>, then it is removed from the set of
- * <code>ServiceReferenceImpl</code> objects.
- * <li>An array of the remaining <code>ServiceReferenceImpl</code> objects is
- * returned.
- * </ol>
- *
- * @param context The BundleContext of the requesting bundle.
- * @param clazz The class name with which the service was registered or
- * <code>null</code> for all services.
- * @param filterstring The filter criteria.
- * @param allservices True if the bundle called getAllServiceReferences.
- * @param callHooks True if the references should be filtered using service find hooks.
- * @return An array of <code>ServiceReferenceImpl</code> objects or
- * <code>null</code> if no services are registered which satisfy
- * the search.
- * @throws InvalidSyntaxException If <code>filter</code> 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, boolean callHooks) 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$
- }
- Filter filter = (filterstring == null) ? null : context.createFilter(filterstring);
- List<ServiceRegistrationImpl<?>> registrations = lookupServiceRegistrations(clazz, filter);
- List<ServiceReferenceImpl<?>> references = new ArrayList<ServiceReferenceImpl<?>>(registrations.size());
- for (ServiceRegistrationImpl<?> registration : registrations) {
- ServiceReferenceImpl<?> reference;
- try {
- reference = registration.getReferenceImpl();
- } catch (IllegalStateException e) {
- continue; // got unregistered, don't return reference
- }
- if (allservices || isAssignableTo(context, reference)) {
- try { /* test for permission to get the service */
- checkGetServicePermission(reference);
- } catch (SecurityException se) {
- continue; // don't return reference
- }
- } else {
- continue; // don't return reference
- }
- references.add(reference);
- }
-
- if (callHooks) {
- Collection<ServiceReference<?>> shrinkable = new ShrinkableCollection<ServiceReference<?>>(references);
- notifyFindHooks(context, clazz, filterstring, allservices, shrinkable);
- }
- int size = references.size();
- if (size == 0) {
- return null;
- }
- return references.toArray(new ServiceReferenceImpl[size]);
- }
-
- /**
- * This method performs the same function as calling
- * {@link #getServiceReferences(BundleContextImpl, String, String, boolean, boolean)} with a
- * {@code true} callHooks value.
- * @param context The BundleContext of the requesting bundle.
- * @param clazz The class name with which the service was registered or
- * <code>null</code> for all services.
- * @param filterstring The filter criteria.
- * @param allservices True if the bundle called getAllServiceReferences.
- * @return An array of <code>ServiceReferenceImpl</code> objects or
- * <code>null</code> if no services are registered which satisfy
- * the search.
- * @throws InvalidSyntaxException If <code>filter</code> 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 {
- return getServiceReferences(context, clazz, filterstring, allservices, true);
- }
-
- /**
- * Returns a <code>ServiceReference</code> object for a service that
- * implements and was registered under the specified class.
- *
- * <p>
- * This <code>ServiceReference</code> 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.
- *
- * <p>
- * This method is the same as calling
- * {@link BundleContext#getServiceReferences(String, String)} with a
- * <code>null</code> filter string. It is provided as a convenience for
- * when the caller is interested in any service that implements the
- * specified class.
- * <p>
- * If multiple such services exist, the service with the highest ranking (as
- * specified in its {@link Constants#SERVICE_RANKING} property) is returned.
- * <p>
- * 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.
- *
- * @param context The BundleContext of the requesting bundle.
- * @param clazz The class name with which the service was registered.
- * @return A <code>ServiceReference</code> object, or <code>null</code>
- * 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) {
- Debug.println("getServiceReference(" + clazz + ")"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- try {
- 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
- // correct one to return.
- return references[0];
- }
- } catch (InvalidSyntaxException e) {
- if (Debug.DEBUG_GENERAL) {
- Debug.println("InvalidSyntaxException w/ null filter" + e.getMessage()); //$NON-NLS-1$
- Debug.printStackTrace(e);
- }
- }
-
- return null;
- }
-
- /**
- * Returns the specified service object for a service.
- * <p>
- * 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.
- * <p>
- * When a bundle's use count for a service drops to zero, the bundle should
- * no longer use that service.
- *
- * <p>
- * This method will always return <code>null</code> when the service
- * associated with this <code>reference</code> has been unregistered.
- *
- * <p>
- * The following steps are required to get the service object:
- * <ol>
- * <li>If the service has been unregistered, <code>null</code> is
- * returned.
- * <li>The context bundle's use count for this service is incremented by
- * one.
- * <li>If the context bundle's use count for the service is currently one
- * and the service was registered with an object implementing the
- * <code>ServiceFactory</code> 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. <br>
- * If the service object returned by the <code>ServiceFactory</code>
- * object is not an <code>instanceof</code> all the classes named when the
- * service was registered or the <code>ServiceFactory</code> object throws
- * an exception, <code>null</code> is returned and a Framework event of
- * type {@link FrameworkEvent#ERROR} containing a {@link ServiceException}
- * describing the error is fired.
- * <li>The service object for the service is returned.
- * </ol>
- *
- * @param context The BundleContext of the requesting bundle.
- * @param reference A reference to the service.
- * @return A service object for the service associated with
- * <code>reference</code> or <code>null</code> if the service is
- * not registered, the service object returned by a
- * <code>ServiceFactory</code> does not implement the classes
- * under which it was registered or the <code>ServiceFactory</code>
- * threw an exception.
- * @throws java.lang.SecurityException If the caller does not have the
- * <code>ServicePermission</code> 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
- */
- public Object getService(BundleContextImpl context, ServiceReferenceImpl<?> reference) {
- /* test for permission to get the service */
- checkGetServicePermission(reference);
- return reference.getRegistration().getService(context);
- }
-
- /**
- * Releases the service object referenced by the specified
- * <code>ServiceReference</code> object. If the context bundle's use count
- * for the service is zero, this method returns <code>false</code>.
- * Otherwise, the context bundle's use count for the service is decremented
- * by one.
- *
- * <p>
- * 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.
- *
- * <p>
- * The following steps are required to unget the service object:
- * <ol>
- * <li>If the context bundle's use count for the service is zero or the
- * service has been unregistered, <code>false</code> is returned.
- * <li>The context bundle's use count for this service is decremented by
- * one.
- * <li>If the context bundle's use count for the service is currently zero
- * and the service was registered with a <code>ServiceFactory</code>
- * object, the
- * {@link ServiceFactory#ungetService(Bundle, ServiceRegistration, Object)}
- * method is called to release the service object for the context bundle.
- * <li><code>true</code> is returned.
- * </ol>
- *
- * @param context The BundleContext of the requesting bundle.
- * @param reference A reference to the service to be released.
- * @return <code>false</code> if the context bundle's use count for the
- * service is zero or if the service has been unregistered;
- * <code>true</code> otherwise.
- * @throws java.lang.IllegalStateException If this BundleContext is no
- * longer valid.
- * @see #getService
- * @see ServiceFactory
- */
- public boolean ungetService(BundleContextImpl context, ServiceReferenceImpl<?> reference) {
- ServiceRegistrationImpl<?> registration = reference.getRegistration();
-
- return registration.ungetService(context);
- }
-
- /**
- * Returns this bundle's <code>ServiceReference</code> list for all
- * services it has registered or <code>null</code> if this bundle has no
- * registered services.
- *
- * <p>
- * If the Java runtime supports permissions, a <code>ServiceReference</code>
- * object to a service is included in the returned list only if the caller
- * has the <code>ServicePermission</code> to get the service using at
- * least one of the named classes the service was registered under.
- *
- * <p>
- * 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.
- *
- * @param context The BundleContext of the requesting bundle.
- * @return An array of <code>ServiceReference</code> objects or
- * <code>null</code>.
- * @throws java.lang.IllegalStateException If this bundle has been
- * uninstalled.
- * @see ServiceRegistration
- * @see ServiceReference
- * @see ServicePermission
- */
- public ServiceReferenceImpl<?>[] getRegisteredServices(BundleContextImpl context) {
- List<ServiceRegistrationImpl<?>> registrations = lookupServiceRegistrations(context);
- List<ServiceReferenceImpl<?>> references = new ArrayList<ServiceReferenceImpl<?>>(registrations.size());
- for (ServiceRegistrationImpl<?> registration : registrations) {
- ServiceReferenceImpl<?> reference;
- try {
- reference = registration.getReferenceImpl();
- } catch (IllegalStateException e) {
- continue; // got unregistered, don't return reference
- }
- try {
- /* test for permission to get the service */
- checkGetServicePermission(reference);
- } catch (SecurityException se) {
- continue; // don't return reference
- }
- references.add(reference);
- }
-
- int size = references.size();
- if (size == 0) {
- return null;
- }
- return references.toArray(new ServiceReferenceImpl[size]);
- }
-
- /**
- * Returns this bundle's <code>ServiceReference</code> list for all
- * services it is using or returns <code>null</code> 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.
- *
- * <p>
- * If the Java Runtime Environment supports permissions, a
- * <code>ServiceReference</code> object to a service is included in the
- * returned list only if the caller has the <code>ServicePermission</code>
- * to get the service using at least one of the named classes the service
- * was registered under.
- * <p>
- * 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.
- *
- * @param context The BundleContext of the requesting bundle.
- * @return An array of <code>ServiceReference</code> objects or
- * <code>null</code>.
- * @throws java.lang.IllegalStateException If this bundle has been
- * uninstalled.
- * @see ServiceReference
- * @see ServicePermission
- */
- public ServiceReferenceImpl<?>[] getServicesInUse(BundleContextImpl context) {
- Map<ServiceRegistrationImpl<?>, ServiceUse<?>> servicesInUse = context.getServicesInUseMap();
- if (servicesInUse == null) {
- return null;
- }
-
- List<ServiceRegistrationImpl<?>> registrations;
- synchronized (servicesInUse) {
- if (servicesInUse.isEmpty()) {
- return null;
- }
- registrations = new ArrayList<ServiceRegistrationImpl<?>>(servicesInUse.keySet());
- }
- List<ServiceReferenceImpl<?>> references = new ArrayList<ServiceReferenceImpl<?>>(registrations.size());
- for (ServiceRegistrationImpl<?> registration : registrations) {
- ServiceReferenceImpl<?> reference;
- try {
- reference = registration.getReferenceImpl();
- } catch (IllegalStateException e) {
- continue; // got unregistered, don't return reference
- }
- try {
- /* test for permission to get the service */
- checkGetServicePermission(reference);
- } catch (SecurityException se) {
- continue; // don't return reference
- }
- references.add(reference);
- }
-
- int size = references.size();
- if (size == 0) {
- return null;
- }
- return references.toArray(new ServiceReferenceImpl[size]);
- }
-
- /**
- * Called when the BundleContext is closing to unregister all services
- * currently registered by the bundle.
- *
- * @param context The BundleContext of the closing bundle.
- */
- public void unregisterServices(BundleContextImpl context) {
- for (ServiceRegistrationImpl<?> registration : lookupServiceRegistrations(context)) {
- try {
- registration.unregister();
- } catch (IllegalStateException e) {
- /* already unregistered */
- }
- }
- removeServiceRegistrations(context); // remove empty list
- }
-
- /**
- * Called when the BundleContext is closing to unget all services
- * currently used by the bundle.
- *
- * @param context The BundleContext of the closing bundle.
- */
- public void releaseServicesInUse(BundleContextImpl context) {
- Map<ServiceRegistrationImpl<?>, ServiceUse<?>> servicesInUse = context.getServicesInUseMap();
- if (servicesInUse == null) {
- return;
- }
- List<ServiceRegistrationImpl<?>> registrations;
- synchronized (servicesInUse) {
- if (servicesInUse.isEmpty()) {
- return;
- }
- registrations = new ArrayList<ServiceRegistrationImpl<?>>(servicesInUse.keySet());
- }
- if (Debug.DEBUG_SERVICES) {
- Debug.println("Releasing services"); //$NON-NLS-1$
- }
- for (ServiceRegistrationImpl<?> registration : registrations) {
- registration.releaseService(context);
- }
- }
-
- /**
- * Add a new Service Listener for a bundle.
- *
- * @param context Context of bundle adding listener.
- * @param listener Service Listener to be added.
- * @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 {
- 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$
- }
-
- FilteredServiceListener filteredListener = new FilteredServiceListener(context, listener, filter);
- FilteredServiceListener oldFilteredListener;
- synchronized (serviceEventListeners) {
- CopyOnWriteIdentityMap<ServiceListener, FilteredServiceListener> listeners = serviceEventListeners.get(context);
- if (listeners == null) {
- listeners = new CopyOnWriteIdentityMap<ServiceListener, FilteredServiceListener>();
- serviceEventListeners.put(context, listeners);
- }
- oldFilteredListener = listeners.put(listener, filteredListener);
- }
-
- if (oldFilteredListener != null) {
- oldFilteredListener.markRemoved();
- Collection<ListenerInfo> removedListeners = Collections.<ListenerInfo> singletonList(oldFilteredListener);
- notifyListenerHooks(removedListeners, false);
- }
-
- Collection<ListenerInfo> addedListeners = Collections.<ListenerInfo> singletonList(filteredListener);
- notifyListenerHooks(addedListeners, true);
- }
-
- /**
- * Remove a Service Listener for a bundle.
- *
- * @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$
- Debug.println("removeServiceListener[" + context.getBundleImpl() + "](" + listenerName + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- FilteredServiceListener oldFilteredListener;
- synchronized (serviceEventListeners) {
- Map<ServiceListener, FilteredServiceListener> listeners = serviceEventListeners.get(context);
- if (listeners == null) {
- return; // this context has no listeners to begin with
- }
- oldFilteredListener = listeners.remove(listener);
- }
-
- if (oldFilteredListener == null) {
- return;
- }
- oldFilteredListener.markRemoved();
- Collection<ListenerInfo> removedListeners = Collections.<ListenerInfo> singletonList(oldFilteredListener);
- notifyListenerHooks(removedListeners, false);
- }
-
- /**
- * Remove all Service Listener for a bundle.
- *
- * @param context Context of bundle removing all listeners.
- */
- public void removeAllServiceListeners(BundleContextImpl context) {
- Map<ServiceListener, FilteredServiceListener> removedListenersMap;
- synchronized (serviceEventListeners) {
- removedListenersMap = serviceEventListeners.remove(context);
- }
- if ((removedListenersMap == null) || removedListenersMap.isEmpty()) {
- return;
- }
- Collection<FilteredServiceListener> removedListeners = removedListenersMap.values();
- for (FilteredServiceListener oldFilteredListener : removedListeners) {
- oldFilteredListener.markRemoved();
- }
- notifyListenerHooks(asListenerInfos(removedListeners), false);
- }
-
- /**
- * Coerce the generic type of a collection from Collection<FilteredServiceListener>
- * to Collection<ListenerInfo>
- * @param c Collection to be coerced.
- * @return c coerced to Collection<ListenerInfo>
- */
- @SuppressWarnings("unchecked")
- private static Collection<ListenerInfo> asListenerInfos(Collection<? extends ListenerInfo> c) {
- return (Collection<ListenerInfo>) c;
- }
-
- /**
- * Deliver a ServiceEvent.
- *
- * @param event The ServiceEvent to deliver.
- */
- public void publishServiceEvent(final ServiceEvent event) {
- if (System.getSecurityManager() == null) {
- publishServiceEventPrivileged(event);
- } else {
- AccessController.doPrivileged(new PrivilegedAction<Object>() {
- public Object run() {
- publishServiceEventPrivileged(event);
- return null;
- }
- });
- }
- }
-
- void publishServiceEventPrivileged(final ServiceEvent event) {
- /* Build the listener snapshot */
- Map<BundleContextImpl, Set<Map.Entry<ServiceListener, FilteredServiceListener>>> listenerSnapshot;
- synchronized (serviceEventListeners) {
- listenerSnapshot = new HashMap<BundleContextImpl, Set<Map.Entry<ServiceListener, FilteredServiceListener>>>(serviceEventListeners.size());
- for (Map.Entry<BundleContextImpl, CopyOnWriteIdentityMap<ServiceListener, FilteredServiceListener>> entry : serviceEventListeners.entrySet()) {
- CopyOnWriteIdentityMap<ServiceListener, FilteredServiceListener> listeners = entry.getValue();
- if (!listeners.isEmpty()) {
- listenerSnapshot.put(entry.getKey(), listeners.entrySet());
- }
- }
- }
-
- /* 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<BundleContext> contexts = asBundleContexts(listenerSnapshot.keySet());
- notifyEventHooksPrivileged(event, contexts);
- if (listenerSnapshot.isEmpty()) {
- return;
- }
- Map<BundleContext, Collection<ListenerInfo>> listeners = new ShrinkableValueCollectionMap<BundleContext, ListenerInfo>(listenerSnapshot);
- notifyEventListenerHooksPrivileged(event, listeners);
- if (listenerSnapshot.isEmpty()) {
- return;
- }
-
- /* deliver the event to the snapshot */
- ListenerQueue<ServiceListener, FilteredServiceListener, ServiceEvent> queue = framework.newListenerQueue();
- for (Map.Entry<BundleContextImpl, Set<Map.Entry<ServiceListener, FilteredServiceListener>>> entry : listenerSnapshot.entrySet()) {
- @SuppressWarnings({"unchecked", "rawtypes"})
- EventDispatcher<ServiceListener, FilteredServiceListener, ServiceEvent> dispatcher = (EventDispatcher) entry.getKey();
- Set<Map.Entry<ServiceListener, FilteredServiceListener>> listenerSet = entry.getValue();
- queue.queueListeners(listenerSet, dispatcher);
- }
- queue.dispatchEventSynchronous(SERVICEEVENT, event);
- }
-
- /**
- * Coerce the generic type of a collection from Collection<BundleContextImpl>
- * to Collection<BundleContext>
- * @param c Collection to be coerced.
- * @return c coerced to Collection<BundleContext>
- */
- @SuppressWarnings("unchecked")
- private static Collection<BundleContext> asBundleContexts(Collection<? extends BundleContext> c) {
- return (Collection<BundleContext>) c;
- }
-
- /**
- * Return the next available service id.
- *
- * @return next service id.
- */
- synchronized long getNextServiceId() {
- long id = serviceid;
- serviceid = id + 1;
- return id;
- }
-
- /**
- * Add the ServiceRegistrationImpl to the data structure.
- *
- * @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.
- List<ServiceRegistrationImpl<?>> contextServices = publishedServicesByContext.get(context);
- if (contextServices == null) {
- contextServices = new ArrayList<ServiceRegistrationImpl<?>>(initialSubCapacity);
- publishedServicesByContext.put(context, contextServices);
- }
- // The list is NOT sorted, so we just add
- contextServices.add(registration);
-
- // Add the ServiceRegistrationImpl to the list of Services published by Class Name.
- int insertIndex;
- for (String clazz : registration.getClasses()) {
- List<ServiceRegistrationImpl<?>> services = publishedServicesByClass.get(clazz);
-
- if (services == null) {
- services = new ArrayList<ServiceRegistrationImpl<?>>(initialSubCapacity);
- publishedServicesByClass.put(clazz, services);
- }
-
- // The list is sorted, so we must find the proper location to insert
- insertIndex = -Collections.binarySearch(services, registration) - 1;
- services.add(insertIndex, registration);
- }
-
- // Add the ServiceRegistrationImpl to the list of all published Services.
- // The list is sorted, so we must find the proper location to insert
- insertIndex = -Collections.binarySearch(allPublishedServices, registration) - 1;
- allPublishedServices.add(insertIndex, registration);
- }
-
- /**
- * Modify the ServiceRegistrationImpl in the data structure.
- *
- * @param context The BundleContext of the bundle registering the service.
- * @param registration The modified ServiceRegistration.
- */
- /* @GuardedBy("this") */
- void modifyServiceRegistration(BundleContextImpl context, ServiceRegistrationImpl<?> registration) {
- assert Thread.holdsLock(this);
- // The list of Services published by BundleContextImpl is not sorted, so
- // we do not need to modify it.
-
- // Remove the ServiceRegistrationImpl from the list of Services published by Class Name
- // and then add at the correct index.
- int insertIndex;
- for (String clazz : registration.getClasses()) {
- List<ServiceRegistrationImpl<?>> services = publishedServicesByClass.get(clazz);
- services.remove(registration);
- // The list is sorted, so we must find the proper location to insert
- insertIndex = -Collections.binarySearch(services, registration) - 1;
- services.add(insertIndex, registration);
- }
-
- // Remove the ServiceRegistrationImpl from the list of all published Services
- // and then add at the correct index.
- allPublishedServices.remove(registration);
- // The list is sorted, so we must find the proper location to insert
- insertIndex = -Collections.binarySearch(allPublishedServices, registration) - 1;
- allPublishedServices.add(insertIndex, registration);
- }
-
- /**
- * Remove the ServiceRegistrationImpl from the data structure.
- *
- * @param context The BundleContext of the bundle registering the service.
- * @param registration The ServiceRegistration to remove.
- */
- /* @GuardedBy("this") */
- void removeServiceRegistration(BundleContextImpl context, ServiceRegistrationImpl<?> registration) {
- assert Thread.holdsLock(this);
- // Remove the ServiceRegistrationImpl from the list of Services published by BundleContextImpl.
- List<ServiceRegistrationImpl<?>> contextServices = publishedServicesByContext.get(context);
- if (contextServices != null) {
- contextServices.remove(registration);
- }
-
- // Remove the ServiceRegistrationImpl from the list of Services published by Class Name.
- for (String clazz : registration.getClasses()) {
- List<ServiceRegistrationImpl<?>> services = publishedServicesByClass.get(clazz);
- services.remove(registration);
- if (services.isEmpty()) { // remove empty list
- publishedServicesByClass.remove(clazz);
- }
- }
-
- // Remove the ServiceRegistrationImpl from the list of all published Services.
- allPublishedServices.remove(registration);
- }
-
- /**
- * Lookup Service Registrations in the data structure by class name and filter.
- *
- * @param clazz The class name with which the service was registered or
- * <code>null</code> for all services.
- * @param filter The filter criteria.
- * @return List<ServiceRegistrationImpl>
- */
- private List<ServiceRegistrationImpl<?>> lookupServiceRegistrations(String clazz, Filter filter) {
- List<ServiceRegistrationImpl<?>> result;
- synchronized (this) {
- if (clazz == null) { /* all services */
- result = allPublishedServices;
- } else {
- /* services registered under the class name */
- result = publishedServicesByClass.get(clazz);
- }
-
- if ((result == null) || result.isEmpty()) {
- @SuppressWarnings("unchecked")
- List<ServiceRegistrationImpl<?>> empty = Collections.EMPTY_LIST;
- return empty;
- }
-
- result = new LinkedList<ServiceRegistrationImpl<?>>(result); /* make a new list since we don't want to change the real list */
- }
-
- if (filter == null) {
- return result;
- }
-
- for (Iterator<ServiceRegistrationImpl<?>> iter = result.iterator(); iter.hasNext();) {
- ServiceRegistrationImpl<?> registration = iter.next();
- ServiceReferenceImpl<?> reference;
- try {
- reference = registration.getReferenceImpl();
- } catch (IllegalStateException e) {
- iter.remove(); /* service was unregistered after we left the synchronized block above */
- continue;
- }
- if (!filter.match(reference)) {
- iter.remove();
- }
- }
- return result;
- }
-
- /**
- * Lookup Service Registrations in the data structure by BundleContext.
- *
- * @param context The BundleContext for which to return Service Registrations.
- * @return List<ServiceRegistrationImpl>
- */
- private synchronized List<ServiceRegistrationImpl<?>> lookupServiceRegistrations(BundleContextImpl context) {
- List<ServiceRegistrationImpl<?>> result = publishedServicesByContext.get(context);
-
- if ((result == null) || result.isEmpty()) {
- @SuppressWarnings("unchecked")
- List<ServiceRegistrationImpl<?>> empty = Collections.EMPTY_LIST;
- return empty;
- }
-
- return new ArrayList<ServiceRegistrationImpl<?>>(result); /* make a new list since we don't want to change the real list */
- }
-
- /**
- * Remove Service Registrations in the data structure by BundleContext.
- *
- * @param context The BundleContext for which to remove Service Registrations.
- */
- private synchronized void removeServiceRegistrations(BundleContextImpl context) {
- publishedServicesByContext.remove(context);
- }
-
- /**
- * Check for permission to register a service.
- *
- * The caller must have permission for ALL names.
- */
- private static void checkRegisterServicePermission(String[] names) {
- SecurityManager sm = System.getSecurityManager();
- if (sm == null) {
- return;
- }
- for (int i = 0, len = names.length; i < len; i++) {
- sm.checkPermission(new ServicePermission(names[i], ServicePermission.REGISTER));
- }
- }
-
- /**
- * Check for permission to get a service.
- */
- private static void checkGetServicePermission(ServiceReference<?> reference) {
- SecurityManager sm = System.getSecurityManager();
- if (sm == null) {
- return;
- }
- sm.checkPermission(new ServicePermission(reference, ServicePermission.GET));
- }
-
- /**
- * Check for permission to listen to a service.
- */
- static boolean hasListenServicePermission(ServiceEvent event, BundleContextImpl context) {
- ProtectionDomain domain = context.getBundleImpl().getProtectionDomain();
- if (domain == null) {
- return true;
- }
-
- return domain.implies(new ServicePermission(event.getServiceReference(), ServicePermission.GET));
- }
-
- /**
- * Return the name of the class that is not satisfied by the service object.
- * @param clazzes Array of class names.
- * @param serviceObject Service object.
- * @return The name of the class that is not satisfied by the service object.
- */
- static String checkServiceClass(final String[] clazzes, final Object serviceObject) {
- ClassLoader cl = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
- public ClassLoader run() {
- return serviceObject.getClass().getClassLoader();
- }
- });
- for (int i = 0, len = clazzes.length; i < len; i++) {
- try {
- Class<?> serviceClazz = cl == null ? Class.forName(clazzes[i]) : cl.loadClass(clazzes[i]);
- if (!serviceClazz.isInstance(serviceObject))
- return clazzes[i];
- } catch (ClassNotFoundException e) {
- //This check is rarely done
- if (extensiveCheckServiceClass(clazzes[i], serviceObject.getClass()))
- return clazzes[i];
- }
- }
- return null;
- }
-
- private static boolean extensiveCheckServiceClass(String clazz, Class<?> serviceClazz) {
- if (clazz.equals(serviceClazz.getName()))
- return false;
- Class<?>[] interfaces = serviceClazz.getInterfaces();
- for (int i = 0, len = interfaces.length; i < len; i++)
- if (!extensiveCheckServiceClass(clazz, interfaces[i]))
- return false;
- Class<?> superClazz = serviceClazz.getSuperclass();
- if (superClazz != null)
- if (!extensiveCheckServiceClass(clazz, superClazz))
- return false;
- return true;
- }
-
- static boolean isAssignableTo(BundleContextImpl context, ServiceReferenceImpl<?> reference) {
- Bundle bundle = context.getBundleImpl();
- String[] clazzes = reference.getClasses();
- for (int i = 0, len = clazzes.length; i < len; i++)
- if (!reference.isAssignableTo(bundle, clazzes[i]))
- return false;
- return true;
- }
-
- /**
- * 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 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.
- */
- private void notifyFindHooks(final BundleContextImpl context, final String clazz, final String filterstring, final boolean allservices, final Collection<ServiceReference<?>> result) {
- if (System.getSecurityManager() == null) {
- notifyFindHooksPrivileged(context, clazz, filterstring, allservices, result);
- } else {
- AccessController.doPrivileged(new PrivilegedAction<Object>() {
- public Object run() {
- notifyFindHooksPrivileged(context, clazz, filterstring, allservices, result);
- return null;
- }
- });
- }
- }
-
- void notifyFindHooksPrivileged(final BundleContextImpl context, final String clazz, final String filterstring, final boolean allservices, final Collection<ServiceReference<?>> 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$
- }
- notifyHooksPrivileged(new HookContext() {
- public void call(Object hook, ServiceRegistration<?> hookRegistration) throws Exception {
- if (hook instanceof FindHook) {
- ((FindHook) hook).find(context, clazz, filterstring, allservices, result);
- }
- }
-
- public String getHookClassName() {
- return findHookName;
- }
-
- public String getHookMethodName() {
- return "find"; //$NON-NLS-1$
- }
- });
- }
-
- /**
- * 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.
- */
- private void notifyEventHooksPrivileged(final ServiceEvent event, final Collection<BundleContext> 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$
- }
- notifyHooksPrivileged(new HookContext() {
- public void call(Object hook, ServiceRegistration<?> hookRegistration) throws Exception {
- if (hook instanceof EventHook) {
- ((EventHook) hook).event(event, result);
- }
- }
-
- public String getHookClassName() {
- return eventHookName;
- }
-
- public String getHookMethodName() {
- return "event"; //$NON-NLS-1$
- }
- });
- }
-
- /**
- * 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.
- */
- private void notifyEventListenerHooksPrivileged(final ServiceEvent event, final Map<BundleContext, Collection<ListenerInfo>> 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$
- }
- notifyHooksPrivileged(new HookContext() {
- public void call(Object hook, ServiceRegistration<?> hookRegistration) throws Exception {
- if (hook instanceof EventListenerHook) {
- ((EventListenerHook) hook).event(event, result);
- }
- }
-
- public String getHookClassName() {
- return eventListenerHookName;
- }
-
- public String getHookMethodName() {
- return "event"; //$NON-NLS-1$
- }
- });
- }
-
- /**
- * Calls all hook services of the type specified by the hook context.
- *
- * @param hookContext Context to use when calling the hook services.
- */
- public void notifyHooksPrivileged(HookContext hookContext) {
- BundleContextImpl systemBundleContext = framework.getSystemBundleContext();
- if (systemBundleContext == null) { // if no system bundle context, we are done!
- return;
- }
-
- List<ServiceRegistrationImpl<?>> hooks = lookupServiceRegistrations(hookContext.getHookClassName(), null);
- // 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) {
- notifyHookPrivileged(systemBundleContext, registration, hookContext);
- }
- }
-
- /**
- * Call a hook service via a hook context.
- *
- * @param context Context of the bundle to get the hook service.
- * @param registration Hook service to call.
- * @param hookContext Context to use when calling the hook service.
- */
- private void notifyHookPrivileged(BundleContextImpl context, ServiceRegistrationImpl<?> registration, HookContext hookContext) {
- Object hook = registration.getSafeService(context);
- if (hook == null) { // if the hook is null
- return;
- }
- try {
- hookContext.call(hook, registration);
- } catch (Throwable t) {
- if (Debug.DEBUG_HOOKS) {
- Debug.println(hook.getClass().getName() + "." + hookContext.getHookMethodName() + "() exception: " + t.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
- Debug.printStackTrace(t);
- }
- // allow the adaptor to handle this unexpected error
- framework.getAdaptor().handleRuntimeError(t);
- ServiceException se = new ServiceException(NLS.bind(Msg.SERVICE_FACTORY_EXCEPTION, hook.getClass().getName(), hookContext.getHookMethodName()), t);
- framework.publishFrameworkEvent(FrameworkEvent.ERROR, registration.getBundle(), se);
- } finally {
- registration.ungetService(context);
- }
- }
-
- /**
- * Call a newly registered ListenerHook service to provide the current collection of
- * service listeners.
- *
- * @param registration The newly registered ListenerHook service.
- */
- private void notifyNewListenerHook(final ServiceRegistrationImpl<?> registration) {
- if (System.getSecurityManager() == null) {
- notifyNewListenerHookPrivileged(registration);
- } else {
- AccessController.doPrivileged(new PrivilegedAction<Object>() {
- public Object run() {
- notifyNewListenerHookPrivileged(registration);
- return null;
- }
- });
- }
-
- }
-
- void notifyNewListenerHookPrivileged(ServiceRegistrationImpl<?> registration) {
- BundleContextImpl systemBundleContext = framework.getSystemBundleContext();
- if (systemBundleContext == null) { // if no system bundle context, we are done!
- return;
- }
-
- if (Debug.DEBUG_HOOKS) {
- Debug.println("notifyServiceNewListenerHook(" + registration + ")"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- // snapshot the listeners
- Collection<ListenerInfo> addedListeners = new ArrayList<ListenerInfo>(initialCapacity);
- synchronized (serviceEventListeners) {
- for (CopyOnWriteIdentityMap<ServiceListener, FilteredServiceListener> listeners : serviceEventListeners.values()) {
- if (!listeners.isEmpty()) {
- addedListeners.addAll(listeners.values());
- }
- }
- }
-
- final Collection<ListenerInfo> listeners = Collections.unmodifiableCollection(addedListeners);
- notifyHookPrivileged(systemBundleContext, registration, new HookContext() {
- public void call(Object hook, ServiceRegistration<?> hookRegistration) throws Exception {
- if (hook instanceof ListenerHook) {
- ((ListenerHook) hook).added(listeners);
- }
- }
-
- public String getHookClassName() {
- return listenerHookName;
- }
-
- public String getHookMethodName() {
- return "added"; //$NON-NLS-1$
- }
- });
- }
-
- /**
- * 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 <code>true</code> if the specified listeners are being added. <code>false</code>
- * if they are being removed.
- */
- private void notifyListenerHooks(final Collection<ListenerInfo> listeners, final boolean added) {
- if (System.getSecurityManager() == null) {
- notifyListenerHooksPrivileged(listeners, added);
- } else {
- AccessController.doPrivileged(new PrivilegedAction<Object>() {
- public Object run() {
- notifyListenerHooksPrivileged(listeners, added);
- return null;
- }
- });
- }
-
- }
-
- void notifyListenerHooksPrivileged(final Collection<ListenerInfo> listeners, final boolean added) {
- assert !listeners.isEmpty();
- if (Debug.DEBUG_HOOKS) {
- Debug.println("notifyServiceListenerHooks(" + listeners + "," + (added ? "added" : "removed") + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- }
-
- notifyHooksPrivileged(new HookContext() {
- public void call(Object hook, ServiceRegistration<?> hookRegistration) throws Exception {
- if (hook instanceof ListenerHook) {
- if (added) {
- ((ListenerHook) hook).added(listeners);
- } else {
- ((ListenerHook) hook).removed(listeners);
- }
- }
- }
-
- public String getHookClassName() {
- return listenerHookName;
- }
-
- public String getHookMethodName() {
- return added ? "added" : "removed"; //$NON-NLS-1$ //$NON-NLS-2$
- }
- });
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ServiceUse.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ServiceUse.java
deleted file mode 100644
index 2f0bab55c..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ServiceUse.java
+++ /dev/null
@@ -1,294 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2003, 2011 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.internal.serviceregistry;
-
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import org.eclipse.osgi.framework.debug.Debug;
-import org.eclipse.osgi.framework.internal.core.BundleContextImpl;
-import org.eclipse.osgi.framework.internal.core.Msg;
-import org.eclipse.osgi.util.NLS;
-import org.osgi.framework.*;
-
-/**
- * This class represents the use of a service by a bundle. One is created for each
- * service acquired by a bundle. This class manages the calls to ServiceFactory
- * and the bundle's use count.
- *
- * @ThreadSafe
- */
-
-public class ServiceUse<S> {
- /** ServiceFactory object if the service instance represents a factory,
- null otherwise */
- final ServiceFactory<S> factory;
- /** BundleContext associated with this service use */
- final BundleContextImpl context;
- /** ServiceDescription of the registered service */
- final ServiceRegistrationImpl<S> registration;
-
- /** Service object either registered or that returned by
- ServiceFactory.getService() */
- /* @GuardedBy("this") */
- private S cachedService;
- /** bundle's use count for this service */
- /* @GuardedBy("this") */
- private int useCount;
- /** true if we are calling the factory getService method. Used to detect recursion. */
- /* @GuardedBy("this") */
- private boolean factoryInUse;
-
- /** Internal framework object. */
-
- /**
- * Constructs a service use encapsulating the service object.
- * Objects of this class should be constructed while holding the
- * registrations lock.
- *
- * @param context bundle getting the service
- * @param registration ServiceRegistration of the service
- */
- ServiceUse(BundleContextImpl context, ServiceRegistrationImpl<S> registration) {
- this.useCount = 0;
- this.factoryInUse = false;
- S service = registration.getServiceObject();
- if (service instanceof ServiceFactory<?>) {
- @SuppressWarnings("unchecked")
- ServiceFactory<S> f = (ServiceFactory<S>) service;
- this.factory = f;
- this.cachedService = null;
- } else {
- this.factory = null;
- this.cachedService = service;
- }
- this.context = context;
- this.registration = registration;
- }
-
- /**
- * 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.
- *
- * <p>The following steps are followed to get the service object:
- * <ol>
- * <li>The context bundle's use count for this service is incremented by one.
- * <li>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.
- * <br>If the service object returned by the {@link ServiceFactory}
- * is not an <code>instanceof</code>
- * all the classes named when the service was registered or
- * the {@link ServiceFactory} throws an exception,
- * <code>null</code> is returned and a
- * {@link FrameworkEvent} of type {@link FrameworkEvent#ERROR} is broadcast.
- * <li>The service object for the service is returned.
- * </ol>
- *
- * @return A service object for the service associated with this
- * reference.
- */
- /* @GuardedBy("this") */
- S getService() {
- assert Thread.holdsLock(this);
- if ((useCount > 0) || (factory == null)) {
- if (useCount == Integer.MAX_VALUE) {
- throw new ServiceException(Msg.SERVICE_USE_OVERFLOW);
- }
- useCount++;
- return cachedService;
- }
-
- if (Debug.DEBUG_SERVICES) {
- Debug.println("getService[factory=" + registration.getBundle() + "](" + context.getBundleImpl() + "," + registration + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
- // check for recursive call
- if (factoryInUse == true) {
- if (Debug.DEBUG_SERVICES) {
- 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.getFramework().publishFrameworkEvent(FrameworkEvent.WARNING, registration.getBundle(), se);
- return null;
- }
- factoryInUse = true;
- final S service;
- try {
- service = AccessController.doPrivileged(new PrivilegedAction<S>() {
- public S run() {
- return factory.getService(context.getBundleImpl(), registration);
- }
- });
- } catch (Throwable t) {
- if (Debug.DEBUG_SERVICES) {
- Debug.println(factory + ".getService() exception: " + t.getMessage()); //$NON-NLS-1$
- Debug.printStackTrace(t);
- }
- // allow the adaptor to handle this unexpected error
- context.getFramework().getAdaptor().handleRuntimeError(t);
- ServiceException se = new ServiceException(NLS.bind(Msg.SERVICE_FACTORY_EXCEPTION, factory.getClass().getName(), "getService"), ServiceException.FACTORY_EXCEPTION, t); //$NON-NLS-1$
- context.getFramework().publishFrameworkEvent(FrameworkEvent.ERROR, registration.getBundle(), se);
- return null;
- } finally {
- factoryInUse = false;
- }
-
- if (service == null) {
- if (Debug.DEBUG_SERVICES) {
- 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.getFramework().publishFrameworkEvent(FrameworkEvent.WARNING, registration.getBundle(), se);
- return null;
- }
-
- String[] clazzes = registration.getClasses();
- String invalidService = ServiceRegistry.checkServiceClass(clazzes, service);
- if (invalidService != null) {
- 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, factory.getClass().getName(), invalidService), ServiceException.FACTORY_ERROR);
- context.getFramework().publishFrameworkEvent(FrameworkEvent.ERROR, registration.getBundle(), se);
- return null;
- }
-
- this.cachedService = service;
- useCount++;
-
- return 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 <code>false</code>. Otherwise, the context bundle's use count for the
- * service is decremented by one.
- *
- * <p>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.
- *
- * <p>The following steps are followed to unget the service object:
- * <ol>
- * <li>If the context bundle's use count for the service is zero or
- * the service has been unregistered,
- * <code>false</code> is returned.
- * <li>The context bundle's use count for this service is decremented by one.
- * <li>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.
- * <li><code>true</code> is returned.
- * </ol>
- *
- * @return <code>true</code> if the context bundle's use count for the service
- * is zero otherwise <code>false</code>.
- */
- /* @GuardedBy("this") */
- boolean ungetService() {
- assert Thread.holdsLock(this);
- if (useCount == 0) {
- return true;
- }
-
- useCount--;
- if (useCount > 0) {
- return false;
- }
-
- if (factory == null) {
- return true;
- }
-
- final S service = cachedService;
- cachedService = null;
-
- if (Debug.DEBUG_SERVICES) {
- Debug.println("ungetService[factory=" + registration.getBundle() + "](" + context.getBundleImpl() + "," + registration + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
- try {
- AccessController.doPrivileged(new PrivilegedAction<S>() {
- public S run() {
- factory.ungetService(context.getBundleImpl(), registration, service);
- return null;
- }
- });
- } catch (Throwable t) {
- if (Debug.DEBUG_GENERAL) {
- Debug.println(factory + ".ungetService() exception"); //$NON-NLS-1$
- 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.getFramework().publishFrameworkEvent(FrameworkEvent.ERROR, registration.getBundle(), se);
- }
-
- return true;
- }
-
- /**
- * Release a service's service object.
- * <ol>
- * <li>The bundle's use count for this service is set to zero.
- * <li>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.
- * </ol>
- */
- /* @GuardedBy("this") */
- void releaseService() {
- assert Thread.holdsLock(this);
- if ((useCount == 0) || (factory == null)) {
- return;
- }
- final S service = cachedService;
- cachedService = null;
- useCount = 0;
-
- if (Debug.DEBUG_SERVICES) {
- Debug.println("releaseService[factory=" + registration.getBundle() + "](" + context.getBundleImpl() + "," + registration + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
- try {
- AccessController.doPrivileged(new PrivilegedAction<S>() {
- public S run() {
- factory.ungetService(context.getBundleImpl(), registration, service);
- return null;
- }
- });
- } catch (Throwable t) {
- if (Debug.DEBUG_SERVICES) {
- Debug.println(factory + ".ungetService() exception"); //$NON-NLS-1$
- 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.getFramework().publishFrameworkEvent(FrameworkEvent.ERROR, registration.getBundle(), se);
- }
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ShrinkableCollection.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ShrinkableCollection.java
deleted file mode 100644
index 2c2e6002f..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ShrinkableCollection.java
+++ /dev/null
@@ -1,196 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.internal.serviceregistry;
-
-import java.util.*;
-
-/**
- * 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.
- *
- * <p>
- * The collections must act as sets in that each collection in the list
- * must not have two entries which are equal.
- *
- * <p>
- * All the optional <code>Collection</code> operations except
- * <code>add</code> and <code>addAll</code> are supported. Attempting to add to the
- * collection will result in an <code>UnsupportedOperationException</code>.
- *
- */
-
-public class ShrinkableCollection<E> implements Collection<E> {
- private final Collection<? extends E> collection;
- private final List<Collection<? extends E>> list;
-
- public ShrinkableCollection(Collection<? extends E> c) {
- if (c == null) {
- throw new NullPointerException();
- }
- @SuppressWarnings("unchecked")
- List<Collection<? extends E>> empty = Collections.EMPTY_LIST;
- list = empty;
- collection = c;
- }
-
- public ShrinkableCollection(Collection<? extends E> c1, Collection<? extends E> c2) {
- list = new ArrayList<Collection<? extends E>>(2);
- list.add(c1);
- list.add(c2);
- collection = initComposite(list);
- }
-
- public ShrinkableCollection(List<Collection<? extends E>> l) {
- list = new ArrayList<Collection<? extends E>>(l);
- collection = initComposite(list);
- }
-
- private static <E> Collection<? extends E> initComposite(List<Collection<? extends E>> collections) {
- int size = 0;
- for (Collection<? extends E> c : collections) {
- assert verifyNoDuplicates(c);
- size += c.size();
- }
- Collection<E> result = new ArrayList<E>(size);
- for (Collection<? extends E> c : collections) {
- for (E e : c) {
- if (!result.contains(e)) {
- result.add(e);
- }
- }
- }
- return result;
- }
-
- private static <E> boolean verifyNoDuplicates(Collection<? extends E> c) {
- for (E e : c) {
- int count = 0;
- for (E f : c) {
- if (e == null) {
- if (f == null) {
- count++;
- }
- } else {
- if (e.equals(f)) {
- count++;
- }
- }
- }
- if (count != 1) {
- return false;
- }
- }
- return true;
- }
-
- public boolean add(E e) {
- throw new UnsupportedOperationException();
- }
-
- public boolean addAll(Collection<? extends E> c) {
- throw new UnsupportedOperationException();
- }
-
- public void clear() {
- collection.clear();
- for (Collection<? extends E> c : list) {
- c.clear();
- }
- }
-
- public boolean contains(Object o) {
- return collection.contains(o);
- }
-
- public boolean containsAll(Collection<?> c) {
- return collection.containsAll(c);
- }
-
- public boolean isEmpty() {
- return collection.isEmpty();
- }
-
- public Iterator<E> iterator() {
- @SuppressWarnings("unchecked")
- final Iterator<E> iter = (Iterator<E>) collection.iterator();
- final List<Collection<? extends E>> collections = list;
- if (collections.isEmpty()) {
- return iter;
- }
- return new Iterator<E>() {
- private E last;
-
- public boolean hasNext() {
- return iter.hasNext();
- }
-
- public E next() {
- last = iter.next();
- return last;
- }
-
- public void remove() {
- iter.remove();
- for (Collection<? extends E> c : collections) {
- c.remove(last);
- }
- }
- };
- }
-
- public boolean remove(Object o) {
- final boolean result = collection.remove(o);
- if (result) {
- for (Collection<? extends E> c : list) {
- c.remove(o);
- }
- }
- return result;
- }
-
- public boolean removeAll(Collection<?> c) {
- final boolean result = collection.removeAll(c);
- if (result) {
- for (Collection<? extends E> cc : list) {
- cc.removeAll(c);
- }
- }
- return result;
- }
-
- public boolean retainAll(Collection<?> c) {
- final boolean result = collection.retainAll(c);
- if (result) {
- for (Collection<? extends E> cc : list) {
- cc.retainAll(c);
- }
- }
- return result;
- }
-
- public int size() {
- return collection.size();
- }
-
- public Object[] toArray() {
- return collection.toArray();
- }
-
- public <T> T[] toArray(T[] var0) {
- return collection.toArray(var0);
- }
-
- public String toString() {
- return collection.toString();
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ShrinkableEntrySetValueCollection.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ShrinkableEntrySetValueCollection.java
deleted file mode 100644
index a98fdce71..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ShrinkableEntrySetValueCollection.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.internal.serviceregistry;
-
-import java.util.*;
-
-public class ShrinkableEntrySetValueCollection<E> extends AbstractCollection<E> implements Collection<E> {
- private final Set<? extends Map.Entry<?, ? extends E>> entrySet;
-
- public ShrinkableEntrySetValueCollection(Set<? extends Map.Entry<?, ? extends E>> e) {
- if (e == null) {
- throw new NullPointerException();
- }
- entrySet = e;
- }
-
- public void clear() {
- entrySet.clear();
- }
-
- public boolean isEmpty() {
- return entrySet.isEmpty();
- }
-
- public Iterator<E> iterator() {
- return new ValueIterator<E>(entrySet.iterator());
- }
-
- public int size() {
- return entrySet.size();
- }
-
- /**
- * Iterator over the values of the entry set.
- */
- static private final class ValueIterator<E> implements Iterator<E> {
- private final Iterator<? extends Map.Entry<?, ? extends E>> iter;
-
- ValueIterator(Iterator<? extends Map.Entry<?, ? extends E>> i) {
- iter = i;
- }
-
- public boolean hasNext() {
- return iter.hasNext();
- }
-
- public E next() {
- final Map.Entry<?, ? extends E> entry = iter.next();
- return entry.getValue();
- }
-
- public void remove() {
- iter.remove();
- }
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ShrinkableValueCollectionMap.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ShrinkableValueCollectionMap.java
deleted file mode 100644
index d9992605d..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/serviceregistry/ShrinkableValueCollectionMap.java
+++ /dev/null
@@ -1,191 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.osgi.internal.serviceregistry;
-
-import java.util.*;
-
-public class ShrinkableValueCollectionMap<K, V> extends AbstractMap<K, Collection<V>> implements Map<K, Collection<V>> {
- final Map<? extends K, ? extends Set<? extends Map.Entry<?, ? extends V>>> map;
- Map<Object, Collection<V>> values;
-
- public ShrinkableValueCollectionMap(Map<? extends K, ? extends Set<? extends Map.Entry<?, ? extends V>>> m) {
- if (m == null) {
- throw new NullPointerException();
- }
- map = m;
- values = null;
- }
-
- public void clear() {
- map.clear();
- if (values != null) {
- values.clear();
- }
- }
-
- public boolean containsKey(Object key) {
- return map.containsKey(key);
- }
-
- 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.
- */
- if (values == null) {
- return false;
- }
- return values.containsValue(value);
- }
-
- public Set<Map.Entry<K, Collection<V>>> entrySet() {
- return new EntrySet();
- }
-
- public Collection<V> get(Object key) {
- Collection<V> value = null;
- if (values != null) {
- value = values.get(key);
- }
- if (value == null) {
- Set<? extends Map.Entry<?, ? extends V>> entrySet = map.get(key);
- if (entrySet == null) {
- return null;
- }
- value = new ShrinkableEntrySetValueCollection<V>(entrySet);
- if (values == null) {
- values = new HashMap<Object, Collection<V>>(map.size());
- }
- values.put(key, value);
- }
- return value;
- }
-
- public boolean isEmpty() {
- return map.isEmpty();
- }
-
- public Collection<V> remove(Object key) {
- Set<? extends Map.Entry<?, ? extends V>> entrySet = map.remove(key);
- Collection<V> value = null;
- if (values != null) {
- value = values.remove(key);
- }
- if ((value == null) && (entrySet != null)) {
- value = new ShrinkableEntrySetValueCollection<V>(entrySet);
- }
- return value;
- }
-
- public int size() {
- return map.size();
- }
-
- /**
- * Set class used for entry sets.
- */
- private final class EntrySet extends AbstractSet<Map.Entry<K, Collection<V>>> {
- EntrySet() {
- super();
- }
-
- public Iterator<Map.Entry<K, Collection<V>>> iterator() {
- return new EntryIterator();
- }
-
- public int size() {
- return ShrinkableValueCollectionMap.this.size();
- }
- }
-
- /**
- * Iterator class used for entry sets.
- */
- private final class EntryIterator implements Iterator<Map.Entry<K, Collection<V>>> {
- private final Iterator<? extends K> iter;
- private K last;
-
- EntryIterator() {
- iter = map.keySet().iterator();
- }
-
- public boolean hasNext() {
- return iter.hasNext();
- }
-
- public Map.Entry<K, Collection<V>> next() {
- last = iter.next();
- return new Entry(last);
- }
-
- public void remove() {
- iter.remove();
- if (values != null) {
- values.remove(last);
- }
- }
- }
-
- /**
- * This class represents the entry in this map.
- */
- private final class Entry implements Map.Entry<K, Collection<V>> {
- private final K key;
- private Collection<V> value;
-
- Entry(final K k) {
- key = k;
- }
-
- public K getKey() {
- return key;
- }
-
- public Collection<V> getValue() {
- if (value == null) {
- value = ShrinkableValueCollectionMap.this.get(key);
- }
- return value;
- }
-
- public Collection<V> setValue(Collection<V> value) {
- throw new UnsupportedOperationException(); // entries cannot be modified.
- }
-
- public String toString() {
- return getKey() + "=" + getValue(); //$NON-NLS-1$
- }
-
- public int hashCode() {
- return hash(getKey()) ^ hash(getValue());
- }
-
- public boolean equals(Object obj) {
- if (obj == this) {
- return true;
- }
- if (!(obj instanceof Map.Entry)) {
- return false;
- }
- Map.Entry<?, ?> other = (Map.Entry<?, ?>) obj;
- return equality(getKey(), other.getKey()) && equality(getValue(), other.getValue());
- }
- }
-
- static int hash(Object one) {
- return (one == null) ? 0 : one.hashCode();
- }
-
- static boolean equality(Object one, Object two) {
- return (one == null) ? (two == null) : one.equals(two);
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/launch/Equinox.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/launch/Equinox.java
deleted file mode 100644
index d24ff52a2..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/launch/Equinox.java
+++ /dev/null
@@ -1,301 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.osgi.launch;
-
-import java.io.*;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.net.*;
-import java.security.*;
-import java.security.cert.X509Certificate;
-import java.util.*;
-import org.eclipse.osgi.framework.internal.core.FrameworkProperties;
-import org.eclipse.osgi.framework.util.Headers;
-import org.eclipse.osgi.internal.baseadaptor.DevClassPathHelper;
-import org.eclipse.osgi.util.ManifestElement;
-import org.osgi.framework.*;
-import org.osgi.framework.launch.Framework;
-
-/**
- * The System Bundle implementation for the Equinox Framework.
- *
- * @since 3.5
- */
-public class Equinox implements Framework {
- private static final String implName = "org.eclipse.osgi.framework.internal.core.EquinoxLauncher"; //$NON-NLS-1$
- /**@GuardedBy this*/
- private Framework impl;
- private final boolean useSeparateCL;
- private final Map<String, Object> configuration;
-
- public Equinox(Map<String, ?> configuration) {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null)
- sm.checkPermission(new AllPermission());
- useSeparateCL = FrameworkProperties.inUse();
- @SuppressWarnings("unchecked")
- final Map<String, Object> empty = Collections.EMPTY_MAP;
- this.configuration = configuration == null ? empty : new HashMap<String, Object>(configuration);
- }
-
- private Framework createImpl() {
- if (System.getSecurityManager() == null)
- return createImpl0();
- return AccessController.doPrivileged(new PrivilegedAction<Framework>() {
- public Framework run() {
- return createImpl0();
- }
- });
- }
-
- Framework createImpl0() {
- try {
- Class<?> implClazz = getImplClass();
- Constructor<?> constructor = implClazz.getConstructor(new Class[] {Map.class});
- return (Framework) constructor.newInstance(new Object[] {configuration});
- } catch (ClassNotFoundException e) {
- throw new NoClassDefFoundError(implName);
- } catch (IllegalAccessException e) {
- throw new RuntimeException(e.getMessage(), e);
- } catch (NoSuchMethodException e) {
- throw new NoSuchMethodError(e.getMessage());
- } catch (InstantiationException e) {
- throw new RuntimeException(e.getMessage(), e);
- } catch (InvocationTargetException e) {
- throw new RuntimeException(e.getMessage(), e);
- }
- }
-
- private Class<?> getImplClass() throws ClassNotFoundException {
- ClassLoader thisCL = this.getClass().getClassLoader();
- if (!(useSeparateCL && (thisCL instanceof URLClassLoader)))
- return Class.forName(implName);
- URL[] cp = getFrameworkURLs((URLClassLoader) thisCL);
- EquinoxFWClassLoader fwCL = new EquinoxFWClassLoader(cp, thisCL);
- return fwCL.loadClass(implName);
- }
-
- private URL[] getFrameworkURLs(URLClassLoader frameworkLoader) {
- // use the classpath of the framework class loader
- URL[] cp = frameworkLoader.getURLs();
- List<URL> result = new ArrayList<URL>(cp.length);
- for (int i = 0; i < cp.length; i++) {
- // need to add only the urls for the framework and any framework fragments
- InputStream manifest = null;
- try {
- if (cp[i].getFile().endsWith("/")) { //$NON-NLS-1$
- manifest = new URL(cp[i], org.eclipse.osgi.framework.internal.core.Constants.OSGI_BUNDLE_MANIFEST).openStream();
- } else {
- manifest = new URL("jar:" + cp[i].toExternalForm() + "!/" + org.eclipse.osgi.framework.internal.core.Constants.OSGI_BUNDLE_MANIFEST).openStream(); //$NON-NLS-1$ //$NON-NLS-2$
- }
- Map<String, String> headers = ManifestElement.parseBundleManifest(manifest, new Headers<String, String>(10));
- String bsnSpec = getValue(headers, Constants.BUNDLE_SYMBOLICNAME);
- if (bsnSpec == null)
- continue;
- String internalBSN = org.eclipse.osgi.framework.internal.core.Constants.getInternalSymbolicName();
- if (internalBSN.equals(bsnSpec)) {
- // this is the framework
- addDevClassPaths(cp[i], bsnSpec, result);
- result.add(cp[i]);
- } else {
- if (!isFrameworkFragment(headers, internalBSN))
- continue;
- // this is for a framework extension
- addDevClassPaths(cp[i], bsnSpec, result);
- result.add(cp[i]);
- }
- } catch (IOException e) {
- continue; // no manifest;
- } catch (BundleException e) {
- continue; // bad manifest;
- } finally {
- if (manifest != null)
- try {
- manifest.close();
- } catch (IOException e) {
- // ignore
- }
- }
- }
- return result.toArray(new URL[result.size()]);
- }
-
- private void addDevClassPaths(URL cp, String bsn, List<URL> result) {
- if (!cp.getPath().endsWith("/")) //$NON-NLS-1$
- return;
- String[] devPaths = DevClassPathHelper.getDevClassPath(bsn);
- if (devPaths == null)
- return;
- for (int i = 0; i < devPaths.length; i++)
- try {
- char lastChar = devPaths[i].charAt(devPaths[i].length() - 1);
- URL url;
- if ((devPaths[i].endsWith(".jar") || (lastChar == '/' || lastChar == '\\'))) //$NON-NLS-1$
- url = new URL(cp, devPaths[i]);
- else
- url = new URL(cp, devPaths[i] + "/"); //$NON-NLS-1$
- result.add(url);
- } catch (MalformedURLException e) {
- continue;
- }
- }
-
- private boolean isFrameworkFragment(Map<String, String> headers, String internalBSN) {
- String hostBSN = getValue(headers, Constants.FRAGMENT_HOST);
- return internalBSN.equals(hostBSN) || Constants.SYSTEM_BUNDLE_SYMBOLICNAME.equals(hostBSN);
- }
-
- private String getValue(Map<String, String> headers, String key) {
- String headerSpec = headers.get(key);
- if (headerSpec == null)
- return null;
- ManifestElement[] elements;
- try {
- elements = ManifestElement.parseHeader(key, headerSpec);
- } catch (BundleException e) {
- return null;
- }
- if (elements == null)
- return null;
- return elements[0].getValue();
- }
-
- private synchronized Framework getImpl() {
- if (impl == null)
- impl = createImpl();
- return impl;
- }
-
- public void init() throws BundleException {
- getImpl().init();
- }
-
- public FrameworkEvent waitForStop(long timeout) throws InterruptedException {
- return getImpl().waitForStop(timeout);
- }
-
- public Enumeration<URL> findEntries(String path, String filePattern, boolean recurse) {
- return getImpl().findEntries(path, filePattern, recurse);
- }
-
- public BundleContext getBundleContext() {
- return getImpl().getBundleContext();
- }
-
- public long getBundleId() {
- return getImpl().getBundleId();
- }
-
- public URL getEntry(String path) {
- return getImpl().getEntry(path);
- }
-
- public Enumeration<String> getEntryPaths(String path) {
- return getImpl().getEntryPaths(path);
- }
-
- public Dictionary<String, String> getHeaders() {
- return getImpl().getHeaders();
- }
-
- public Dictionary<String, String> getHeaders(String locale) {
- return getImpl().getHeaders(locale);
- }
-
- public long getLastModified() {
- return getImpl().getLastModified();
- }
-
- public String getLocation() {
- return getImpl().getLocation();
- }
-
- public ServiceReference<?>[] getRegisteredServices() {
- return getImpl().getRegisteredServices();
- }
-
- public URL getResource(String name) {
- return getImpl().getResource(name);
- }
-
- public Enumeration<URL> getResources(String name) throws IOException {
- return getImpl().getResources(name);
- }
-
- public ServiceReference<?>[] getServicesInUse() {
- return getImpl().getServicesInUse();
- }
-
- public int getState() {
- return getImpl().getState();
- }
-
- public String getSymbolicName() {
- return getImpl().getSymbolicName();
- }
-
- public boolean hasPermission(Object permission) {
- return getImpl().hasPermission(permission);
- }
-
- public Class<?> loadClass(String name) throws ClassNotFoundException {
- return getImpl().loadClass(name);
- }
-
- public void start(int options) throws BundleException {
- getImpl().start(options);
- }
-
- public void start() throws BundleException {
- getImpl().start();
- }
-
- public void stop(int options) throws BundleException {
- getImpl().stop(options);
- }
-
- public void stop() throws BundleException {
- getImpl().stop();
- }
-
- public void uninstall() throws BundleException {
- getImpl().uninstall();
- }
-
- public void update() throws BundleException {
- getImpl().update();
- }
-
- public void update(InputStream in) throws BundleException {
- getImpl().update(in);
- }
-
- public Map<X509Certificate, List<X509Certificate>> getSignerCertificates(int signersType) {
- return getImpl().getSignerCertificates(signersType);
- }
-
- public Version getVersion() {
- return getImpl().getVersion();
- }
-
- public <A> A adapt(Class<A> adapterType) {
- return getImpl().adapt(adapterType);
- }
-
- public int compareTo(Bundle o) {
- return getImpl().compareTo(o);
- }
-
- public File getDataFile(String filename) {
- return getImpl().getDataFile(filename);
- }
-
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/launch/EquinoxFWClassLoader.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/launch/EquinoxFWClassLoader.java
deleted file mode 100644
index 7011b5b13..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/launch/EquinoxFWClassLoader.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.osgi.launch;
-
-import java.net.URL;
-import java.net.URLClassLoader;
-
-class EquinoxFWClassLoader extends URLClassLoader {
-
- private static final String[] DELEGATE_PARENT_FIRST = {"java.", "org.osgi.", "org.eclipse.osgi.launch.", "org.eclipse.osgi.service.", "org.eclipse.osgi.framework.log", "org.eclipse.osgi.framework.adaptor", "org.eclipse.osgi.framework.internal.core.ReferenceInputStream"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
- private static final String[] DELEGATE_CHILD_FIRST = new String[0]; // nothing right now is skipped
-
- private final ClassLoader parent;
-
- public EquinoxFWClassLoader(URL[] urls, ClassLoader parent) {
- super(urls, parent);
- this.parent = parent;
- }
-
- protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
- Class<?> clazz = findLoadedClass(name);
- if (clazz != null)
- return clazz;
-
- boolean childFirst = childFirst(name);
- ClassNotFoundException cnfe = null;
-
- if (childFirst)
- try {
- clazz = findClass(name);
- } catch (ClassNotFoundException e) {
- // continue
- cnfe = e;
- }
-
- if (clazz == null)
- try {
- clazz = parent.loadClass(name);
- } catch (ClassNotFoundException e) {
- // continue
- }
-
- if (clazz == null && cnfe != null)
- throw cnfe;
- if (clazz == null && !childFirst)
- clazz = findClass(name);
-
- if (resolve)
- resolveClass(clazz);
- return clazz;
- }
-
- private boolean childFirst(String name) {
- for (int i = DELEGATE_CHILD_FIRST.length - 1; i >= 0; i--)
- if (name.startsWith(DELEGATE_CHILD_FIRST[i]))
- return true;
- for (int i = DELEGATE_PARENT_FIRST.length - 1; i >= 0; i--)
- if (name.startsWith(DELEGATE_PARENT_FIRST[i]))
- return false;
- return true;
-
- }
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/launch/EquinoxFactory.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/launch/EquinoxFactory.java
deleted file mode 100644
index 389f07a7a..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/launch/EquinoxFactory.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2009, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.osgi.launch;
-
-import java.util.Map;
-import org.osgi.framework.launch.Framework;
-import org.osgi.framework.launch.FrameworkFactory;
-
-/**
- * The framework factory implementation for the Equinox framework.
- * @since 3.5
- */
-public class EquinoxFactory implements FrameworkFactory {
-
- public Framework newFramework(Map<String, String> configuration) {
- return new Equinox(configuration);
- }
-
-}
diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/launch/package.html b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/launch/package.html
deleted file mode 100644
index b2d671be0..000000000
--- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/launch/package.html
+++ /dev/null
@@ -1,17 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
-<html>
-<head>
- <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
- <title>Package-level Javadoc</title>
-</head>
-<body>
-Provides the Equinox framework launch API.
-<h2>
-Package Specification</h2>
-This package specifies the Equinox framework launch API.
-<p>
-Clients that want to launch an embedded instance of Equinox
-will likely be interested in the types provided by this package.
-</p>
-</body>
-</html>

Back to the top