diff options
author | BJ Hargrave | 2010-09-08 13:56:33 -0400 |
---|---|---|
committer | BJ Hargrave | 2010-09-08 13:56:33 -0400 |
commit | a3cec579d3e0dcc8b14fafce44e9a4f0e517f5b6 (patch) | |
tree | 79392a762c31d51f8dae0c3d876fcd8ba702a5e3 | |
parent | 7c63118bc299208b1222df56454700a91c2e7a75 (diff) | |
download | rt.equinox.framework-a3cec579d3e0dcc8b14fafce44e9a4f0e517f5b6.tar.gz rt.equinox.framework-a3cec579d3e0dcc8b14fafce44e9a4f0e517f5b6.tar.xz rt.equinox.framework-a3cec579d3e0dcc8b14fafce44e9a4f0e517f5b6.zip |
bug 324774: Update the framework source code for generics
161 files changed, 1735 insertions, 1651 deletions
diff --git a/bundles/org.eclipse.osgi/.settings/org.eclipse.jdt.core.prefs b/bundles/org.eclipse.osgi/.settings/org.eclipse.jdt.core.prefs index a93f9a214..b393fa058 100644 --- a/bundles/org.eclipse.osgi/.settings/org.eclipse.jdt.core.prefs +++ b/bundles/org.eclipse.osgi/.settings/org.eclipse.jdt.core.prefs @@ -1,4 +1,4 @@ -#Fri Jul 16 15:45:06 CDT 2010 +#Fri Aug 06 17:50:19 EDT 2010 eclipse.preferences.version=1 org.eclipse.jdt.core.builder.cleanOutputFolder=clean org.eclipse.jdt.core.builder.duplicateResourceTask=warning @@ -30,7 +30,7 @@ org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled org.eclipse.jdt.core.compiler.problem.fieldHiding=warning -org.eclipse.jdt.core.compiler.problem.finalParameterBound=ignore +org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning org.eclipse.jdt.core.compiler.problem.forbiddenReference=error org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning @@ -61,7 +61,7 @@ org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=warning org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore -org.eclipse.jdt.core.compiler.problem.rawTypeReference=ignore +org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled @@ -70,7 +70,7 @@ org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=warning org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning -org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=ignore +org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=warning org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning org.eclipse.jdt.core.compiler.problem.unnecessaryElse=warning diff --git a/bundles/org.eclipse.osgi/console/src/org/eclipse/osgi/framework/internal/core/ConsoleManager.java b/bundles/org.eclipse.osgi/console/src/org/eclipse/osgi/framework/internal/core/ConsoleManager.java index a40f24e56..28bdc31c1 100644 --- a/bundles/org.eclipse.osgi/console/src/org/eclipse/osgi/framework/internal/core/ConsoleManager.java +++ b/bundles/org.eclipse.osgi/console/src/org/eclipse/osgi/framework/internal/core/ConsoleManager.java @@ -14,6 +14,7 @@ import java.io.*; import java.lang.reflect.Method; import java.net.ServerSocket; import java.net.Socket; +import java.util.Dictionary; import java.util.Hashtable; import org.eclipse.osgi.framework.console.CommandProvider; import org.eclipse.osgi.framework.console.ConsoleSession; @@ -23,7 +24,7 @@ import org.osgi.framework.ServiceRegistration; import org.osgi.util.tracker.ServiceTracker; import org.osgi.util.tracker.ServiceTrackerCustomizer; -public class ConsoleManager implements ServiceTrackerCustomizer { +public class ConsoleManager implements ServiceTrackerCustomizer<ConsoleSession, FrameworkConsole> { /** * ConsoleSocketGetter - provides a Thread that listens on the port * for FrameworkConsole. @@ -87,18 +88,18 @@ public class ConsoleManager implements ServiceTrackerCustomizer { private static final String PROP_SYSTEM_IN_OUT = "console.systemInOut"; //$NON-NLS-1$ private static final String CONSOLE_NAME = "OSGi Console"; //$NON-NLS-1$ final Framework framework; - private final ServiceTracker cpTracker; - private final ServiceTracker sessions; + private final ServiceTracker<CommandProvider, CommandProvider> cpTracker; + private final ServiceTracker<ConsoleSession, FrameworkConsole> sessions; private final String consolePort; private FrameworkCommandProvider fwkCommands; - private ServiceRegistration builtinSession; + private ServiceRegistration<?> builtinSession; private ConsoleSocketGetter scsg; public ConsoleManager(Framework framework, String consolePort) { this.framework = framework; this.consolePort = consolePort != null ? consolePort.trim() : consolePort; - this.cpTracker = new ServiceTracker(framework.getSystemBundleContext(), CommandProvider.class.getName(), null); - this.sessions = new ServiceTracker(framework.getSystemBundleContext(), ConsoleSession.class.getName(), this); + this.cpTracker = new ServiceTracker<CommandProvider, CommandProvider>(framework.getSystemBundleContext(), CommandProvider.class.getName(), null); + this.sessions = new ServiceTracker<ConsoleSession, FrameworkConsole>(framework.getSystemBundleContext(), ConsoleSession.class.getName(), this); } public static ConsoleManager startConsole(Framework framework) { @@ -146,8 +147,8 @@ public class ConsoleManager implements ServiceTrackerCustomizer { }; FrameworkConsoleSession session = new FrameworkConsoleSession(in, out, null); - Hashtable props = null; - props = new Hashtable(1); + Dictionary<String, Object> props = null; + props = new Hashtable<String, Object>(1); props.put(PROP_SYSTEM_IN_OUT, Boolean.TRUE); builtinSession = framework.getSystemBundleContext().registerService(ConsoleSession.class.getName(), session, props); } else { @@ -178,14 +179,14 @@ public class ConsoleManager implements ServiceTrackerCustomizer { fwkCommands.stop(); } - public Object addingService(ServiceReference reference) { + public FrameworkConsole addingService(ServiceReference<ConsoleSession> reference) { FrameworkConsole console = null; Boolean isSystemInOut = (Boolean) reference.getProperty(PROP_SYSTEM_IN_OUT); if (isSystemInOut == null) isSystemInOut = Boolean.FALSE; - ConsoleSession session = (ConsoleSession) framework.getSystemBundleContext().getService(reference); + ConsoleSession session = framework.getSystemBundleContext().getService(reference); console = new FrameworkConsole(framework.getSystemBundleContext(), session, isSystemInOut.booleanValue(), cpTracker); Thread t = new Thread(console, CONSOLE_NAME); @@ -194,11 +195,11 @@ public class ConsoleManager implements ServiceTrackerCustomizer { return console; } - public void modifiedService(ServiceReference reference, Object service) { + public void modifiedService(ServiceReference<ConsoleSession> reference, FrameworkConsole service) { // nothing } - public void removedService(ServiceReference reference, Object service) { - ((FrameworkConsole) service).shutdown(); + public void removedService(ServiceReference<ConsoleSession> reference, FrameworkConsole service) { + service.shutdown(); } } diff --git a/bundles/org.eclipse.osgi/console/src/org/eclipse/osgi/framework/internal/core/FrameworkCommandInterpreter.java b/bundles/org.eclipse.osgi/console/src/org/eclipse/osgi/framework/internal/core/FrameworkCommandInterpreter.java index 76a808f64..dc2a7c993 100644 --- a/bundles/org.eclipse.osgi/console/src/org/eclipse/osgi/framework/internal/core/FrameworkCommandInterpreter.java +++ b/bundles/org.eclipse.osgi/console/src/org/eclipse/osgi/framework/internal/core/FrameworkCommandInterpreter.java @@ -36,7 +36,7 @@ public class FrameworkCommandInterpreter implements CommandInterpreter { /** The command line in StringTokenizer form */ private StringTokenizer tok; /** The active CommandProviders */ - private Object[] commandProviders; + private CommandProvider[] commandProviders; /** The FrameworkConsole */ private FrameworkConsole con; /** The stream to send output to */ @@ -60,7 +60,7 @@ public class FrameworkCommandInterpreter implements CommandInterpreter { * The constructor. It turns the cmdline string into a StringTokenizer and remembers * the input parms. */ - public FrameworkCommandInterpreter(String cmdline, Object[] commandProviders, FrameworkConsole con) { + public FrameworkCommandInterpreter(String cmdline, CommandProvider[] commandProviders, FrameworkConsole con) { tok = new StringTokenizer(cmdline); this.commandProviders = commandProviders; this.con = con; @@ -144,7 +144,7 @@ public class FrameworkCommandInterpreter implements CommandInterpreter { } return retval; } - Class[] parameterTypes = new Class[] {CommandInterpreter.class}; + Class<?>[] parameterTypes = new Class[] {CommandInterpreter.class}; Object[] parameters = new Object[] {this}; boolean executed = false; int size = commandProviders.length; @@ -168,7 +168,7 @@ public class FrameworkCommandInterpreter implements CommandInterpreter { if (!executed) { for (int i = 0; i < size; i++) { try { - CommandProvider commandProvider = (CommandProvider) commandProviders[i]; + CommandProvider commandProvider = commandProviders[i]; out.print(commandProvider.getHelp()); out.flush(); } catch (Exception ee) { @@ -270,7 +270,7 @@ public class FrameworkCommandInterpreter implements CommandInterpreter { Method[] methods = t.getClass().getMethods(); int size = methods.length; - Class throwable = Throwable.class; + Class<Throwable> throwable = Throwable.class; for (int i = 0; i < size; i++) { Method method = methods[i]; @@ -321,13 +321,13 @@ public class FrameworkCommandInterpreter implements CommandInterpreter { * @param dic the dictionary to print * @param title the header to print above the key/value pairs */ - public void printDictionary(Dictionary dic, String title) { + public void printDictionary(Dictionary<?, ?> dic, String title) { if (dic == null) return; int count = dic.size(); String[] keys = new String[count]; - Enumeration keysEnum = dic.keys(); + Enumeration<?> keysEnum = dic.keys(); int i = 0; while (keysEnum.hasMoreElements()) { keys[i++] = (String) keysEnum.nextElement(); diff --git a/bundles/org.eclipse.osgi/console/src/org/eclipse/osgi/framework/internal/core/FrameworkCommandProvider.java b/bundles/org.eclipse.osgi/console/src/org/eclipse/osgi/framework/internal/core/FrameworkCommandProvider.java index a1e39e93d..0470779d7 100644 --- a/bundles/org.eclipse.osgi/console/src/org/eclipse/osgi/framework/internal/core/FrameworkCommandProvider.java +++ b/bundles/org.eclipse.osgi/console/src/org/eclipse/osgi/framework/internal/core/FrameworkCommandProvider.java @@ -27,6 +27,7 @@ import org.osgi.service.condpermadmin.ConditionalPermissionInfo; import org.osgi.service.condpermadmin.ConditionalPermissionUpdate; import org.osgi.service.packageadmin.PackageAdmin; import org.osgi.service.packageadmin.RequiredBundle; +import org.osgi.service.startlevel.StartLevel; /** * This class provides methods to execute commands from the command line. It registers @@ -83,14 +84,14 @@ public class FrameworkCommandProvider implements CommandProvider, SynchronousBun /** The start level implementation */ private final StartLevelManager slImpl; private final SecurityAdmin securityAdmin; - private ServiceRegistration providerReg; + private ServiceRegistration<?> providerReg; /** Strings used to format other strings */ private final static String tab = "\t"; //$NON-NLS-1$ private final static String newline = "\r\n"; //$NON-NLS-1$ /** this list contains the bundles known to be lazily awaiting activation */ - private final List lazyActivation = new ArrayList(); + private final List<Bundle> lazyActivation = new ArrayList<Bundle>(); /** * Constructor. @@ -113,7 +114,7 @@ public class FrameworkCommandProvider implements CommandProvider, SynchronousBun * Adds this object as a SynchronousBundleListener. */ void start() { - Dictionary props = new Hashtable(); + Dictionary<String, Object> props = new Hashtable<String, Object>(); props.put(Constants.SERVICE_RANKING, new Integer(Integer.MAX_VALUE)); providerReg = context.registerService(CommandProvider.class.getName(), this, props); context.addBundleListener(this); @@ -498,7 +499,7 @@ public class FrameworkCommandProvider implements CommandProvider, SynchronousBun intp.println(bundle.bundledata); } - ServiceReference[] services = context.getServiceReferences((String) null, (String) null); + ServiceReference<?>[] services = context.getServiceReferences((String) null, (String) null); if (services != null) { intp.println(ConsoleMsg.CONSOLE_REGISTERED_SERVICES_MESSAGE); size = services.length; @@ -536,12 +537,12 @@ public class FrameworkCommandProvider implements CommandProvider, SynchronousBun filter = buf.toString(); } - ServiceReference[] services = context.getServiceReferences((String) null, filter); + ServiceReference<?>[] services = context.getServiceReferences((String) null, filter); if (services != null) { int size = services.length; if (size > 0) { for (int j = 0; j < size; j++) { - ServiceReference service = services[j]; + ServiceReference<?> service = services[j]; intp.println(service); intp.print(" "); //$NON-NLS-1$ intp.print(ConsoleMsg.CONSOLE_REGISTERED_BY_BUNDLE_MESSAGE); @@ -588,9 +589,9 @@ public class FrameworkCommandProvider implements CommandProvider, SynchronousBun bundle = getBundleFromToken(intp, token, false); } - org.osgi.framework.ServiceReference packageAdminRef = context.getServiceReference("org.osgi.service.packageadmin.PackageAdmin"); //$NON-NLS-1$ + ServiceReference<?> packageAdminRef = context.getServiceReference("org.osgi.service.packageadmin.PackageAdmin"); //$NON-NLS-1$ if (packageAdminRef != null) { - org.osgi.service.packageadmin.PackageAdmin packageAdmin = (org.osgi.service.packageadmin.PackageAdmin) context.getService(packageAdminRef); + PackageAdmin packageAdmin = (PackageAdmin) context.getService(packageAdminRef); if (packageAdmin != null) { try { org.osgi.service.packageadmin.ExportedPackage[] packages = null; @@ -682,7 +683,7 @@ public class FrameworkCommandProvider implements CommandProvider, SynchronousBun intp.println(); } - ServiceReference[] services = bundle.getRegisteredServices(); + ServiceReference<?>[] services = bundle.getRegisteredServices(); if (services != null) { intp.print(" "); //$NON-NLS-1$ intp.println(ConsoleMsg.CONSOLE_REGISTERED_SERVICES_MESSAGE); @@ -749,7 +750,7 @@ public class FrameworkCommandProvider implements CommandProvider, SynchronousBun intp.println(); } - ServiceReference[] services = bundle.getRegisteredServices(); + ServiceReference<?>[] services = bundle.getRegisteredServices(); if (services != null) { intp.print(" "); //$NON-NLS-1$ intp.println(ConsoleMsg.CONSOLE_REGISTERED_SERVICES_MESSAGE); @@ -775,7 +776,7 @@ public class FrameworkCommandProvider implements CommandProvider, SynchronousBun intp.println(ConsoleMsg.CONSOLE_NO_SERVICES_IN_USE_MESSAGE); } - org.osgi.framework.ServiceReference packageAdminRef = context.getServiceReference("org.osgi.service.packageadmin.PackageAdmin"); //$NON-NLS-1$ + ServiceReference<?> packageAdminRef = context.getServiceReference("org.osgi.service.packageadmin.PackageAdmin"); //$NON-NLS-1$ if (packageAdminRef != null) { BundleDescription desc = bundle.getBundleDescription(); if (desc != null) { @@ -813,7 +814,7 @@ public class FrameworkCommandProvider implements CommandProvider, SynchronousBun } title = true; if (desc != null) { - ArrayList fragmentsImportPackages = new ArrayList(); + List<ImportPackageSpecification> fragmentsImportPackages = new ArrayList<ImportPackageSpecification>(); // Get bundle' fragments imports BundleDescription[] fragments = desc.getFragments(); @@ -836,7 +837,7 @@ public class FrameworkCommandProvider implements CommandProvider, SynchronousBun int offset = directImportPackages.length; for (int i = 0; i < fragmentsImportPackages.size(); i++) { - importPackages[offset + i] = (ImportPackageSpecification) fragmentsImportPackages.get(i); + importPackages[offset + i] = fragmentsImportPackages.get(i); } } else { importPackages = desc.getImportPackages(); @@ -847,7 +848,7 @@ public class FrameworkCommandProvider implements CommandProvider, SynchronousBun imports = desc.getContainingState().getStateHelper().getVisiblePackages(desc, StateHelper.VISIBLE_INCLUDE_EE_PACKAGES | StateHelper.VISIBLE_INCLUDE_ALL_HOST_WIRES); // Get the unresolved optional and dynamic imports - ArrayList unresolvedImports = new ArrayList(); + List<ImportPackageSpecification> unresolvedImports = new ArrayList<ImportPackageSpecification>(); for (int i = 0; i < importPackages.length; i++) { if (importPackages[i].getDirective(Constants.RESOLUTION_DIRECTIVE).equals(ImportPackageSpecification.RESOLUTION_OPTIONAL)) { @@ -1014,9 +1015,9 @@ public class FrameworkCommandProvider implements CommandProvider, SynchronousBun return title; } - private void printUnwiredDynamicImports(ArrayList dynamicImports, CommandInterpreter intp) { + private void printUnwiredDynamicImports(List<ImportPackageSpecification> dynamicImports, CommandInterpreter intp) { for (int i = 0; i < dynamicImports.size(); i++) { - ImportPackageSpecification importPackage = (ImportPackageSpecification) dynamicImports.get(i); + ImportPackageSpecification importPackage = dynamicImports.get(i); intp.print(" "); //$NON-NLS-1$ intp.print(importPackage.getName()); intp.print("; version=\""); //$NON-NLS-1$ @@ -1065,6 +1066,7 @@ public class FrameworkCommandProvider implements CommandProvider, SynchronousBun * * @param intp A CommandInterpreter object containing the command and it's arguments. */ + @SuppressWarnings("deprecation") public void _init(CommandInterpreter intp) throws Exception { if (framework.isActive()) { intp.print(newline); @@ -1104,8 +1106,8 @@ public class FrameworkCommandProvider implements CommandProvider, SynchronousBun } // clear the permissions from conditional permission admin if (securityAdmin != null) - for (Enumeration infos = securityAdmin.getConditionalPermissionInfos(); infos.hasMoreElements();) - ((ConditionalPermissionInfo) infos.nextElement()).delete(); + for (Enumeration<ConditionalPermissionInfo> infos = securityAdmin.getConditionalPermissionInfos(); infos.hasMoreElements();) + infos.nextElement().delete(); } /** @@ -1134,22 +1136,22 @@ public class FrameworkCommandProvider implements CommandProvider, SynchronousBun * @param intp A CommandInterpreter object containing the command and it's arguments. */ public void _refresh(CommandInterpreter intp) throws Exception { - org.osgi.framework.ServiceReference packageAdminRef = context.getServiceReference("org.osgi.service.packageadmin.PackageAdmin"); //$NON-NLS-1$ + ServiceReference<?> packageAdminRef = context.getServiceReference("org.osgi.service.packageadmin.PackageAdmin"); //$NON-NLS-1$ if (packageAdminRef != null) { org.osgi.service.packageadmin.PackageAdmin packageAdmin = (org.osgi.service.packageadmin.PackageAdmin) context.getService(packageAdminRef); if (packageAdmin != null) { try { - AbstractBundle[] refresh = null; + Bundle[] refresh = null; String token = intp.nextArgument(); if (token != null) { - Vector bundles = new Vector(); + List<Bundle> bundles = new ArrayList<Bundle>(); while (token != null) { AbstractBundle bundle = getBundleFromToken(intp, token, true); if (bundle != null) { - bundles.addElement(bundle); + bundles.add(bundle); } token = intp.nextArgument(); } @@ -1161,8 +1163,8 @@ public class FrameworkCommandProvider implements CommandProvider, SynchronousBun return; } - refresh = new AbstractBundle[size]; - bundles.copyInto(refresh); + refresh = new Bundle[size]; + bundles.toArray(refresh); } packageAdmin.refreshPackages(refresh); @@ -1285,7 +1287,7 @@ public class FrameworkCommandProvider implements CommandProvider, SynchronousBun Properties newprops = new Properties(); newprops.load(in); intp.println(ConsoleMsg.CONSOLE_SETTING_PROPERTIES_TITLE); - Enumeration keys = newprops.propertyNames(); + Enumeration<?> keys = newprops.propertyNames(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); String value = (String) newprops.get(key); @@ -1549,9 +1551,9 @@ public class FrameworkCommandProvider implements CommandProvider, SynchronousBun String token = intp.nextArgument(); - org.osgi.framework.ServiceReference packageAdminRef = context.getServiceReference("org.osgi.service.packageadmin.PackageAdmin"); //$NON-NLS-1$ + ServiceReference<?> packageAdminRef = context.getServiceReference("org.osgi.service.packageadmin.PackageAdmin"); //$NON-NLS-1$ if (packageAdminRef != null) { - org.osgi.service.packageadmin.PackageAdmin packageAdmin = (org.osgi.service.packageadmin.PackageAdmin) context.getService(packageAdminRef); + PackageAdmin packageAdmin = (PackageAdmin) context.getService(packageAdminRef); if (packageAdmin != null) { try { org.osgi.service.packageadmin.RequiredBundle[] symBundles = null; @@ -1618,7 +1620,7 @@ public class FrameworkCommandProvider implements CommandProvider, SynchronousBun if (nextArg == null) return; AbstractBundle bundle = getBundleFromToken(intp, nextArg, true); - ServiceReference ref = context.getServiceReference("org.eclipse.osgi.service.resolver.PlatformAdmin"); //$NON-NLS-1$ + ServiceReference<?> ref = context.getServiceReference("org.eclipse.osgi.service.resolver.PlatformAdmin"); //$NON-NLS-1$ if (ref == null) return; PlatformAdmin platformAdmin = (PlatformAdmin) context.getService(ref); @@ -1639,9 +1641,9 @@ public class FrameworkCommandProvider implements CommandProvider, SynchronousBun */ protected boolean isStartLevelSvcPresent(CommandInterpreter intp) { boolean retval = false; - org.osgi.framework.ServiceReference slSvcRef = context.getServiceReference("org.osgi.service.startlevel.StartLevel"); //$NON-NLS-1$ + ServiceReference<?> slSvcRef = context.getServiceReference("org.osgi.service.startlevel.StartLevel"); //$NON-NLS-1$ if (slSvcRef != null) { - org.osgi.service.startlevel.StartLevel slSvc = (org.osgi.service.startlevel.StartLevel) context.getService(slSvcRef); + StartLevel slSvc = (StartLevel) context.getService(slSvcRef); if (slSvc != null) { retval = true; } @@ -1768,7 +1770,7 @@ public class FrameworkCommandProvider implements CommandProvider, SynchronousBun private boolean isDisabled(Bundle bundle) { boolean disabled = false; - ServiceReference platformAdminRef = null; + ServiceReference<?> platformAdminRef = null; try { platformAdminRef = context.getServiceReference(PlatformAdmin.class.getName()); if (platformAdminRef != null) { @@ -1843,7 +1845,7 @@ public class FrameworkCommandProvider implements CommandProvider, SynchronousBun public void _getprop(CommandInterpreter ci) throws Exception { Properties allProperties = FrameworkProperties.getProperties(); String filter = ci.nextArgument(); - Iterator propertyNames = new TreeSet(allProperties.keySet()).iterator(); + Iterator<?> propertyNames = new TreeSet<Object>(allProperties.keySet()).iterator(); while (propertyNames.hasNext()) { String prop = (String) propertyNames.next(); if (filter == null || prop.startsWith(filter)) { diff --git a/bundles/org.eclipse.osgi/console/src/org/eclipse/osgi/framework/internal/core/FrameworkConsole.java b/bundles/org.eclipse.osgi/console/src/org/eclipse/osgi/framework/internal/core/FrameworkConsole.java index 317e2bb2d..8ecbcf968 100644 --- a/bundles/org.eclipse.osgi/console/src/org/eclipse/osgi/framework/internal/core/FrameworkConsole.java +++ b/bundles/org.eclipse.osgi/console/src/org/eclipse/osgi/framework/internal/core/FrameworkConsole.java @@ -12,8 +12,7 @@ package org.eclipse.osgi.framework.internal.core; import java.io.*; -import org.eclipse.osgi.framework.console.CommandInterpreter; -import org.eclipse.osgi.framework.console.ConsoleSession; +import org.eclipse.osgi.framework.console.*; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.util.tracker.ServiceTracker; @@ -32,7 +31,7 @@ public class FrameworkConsole implements Runnable { /** The current bundle context */ private final BundleContext context; /** A tracker containing the service object of all registered command providers */ - private final ServiceTracker cptracker; + private final ServiceTracker<CommandProvider, CommandProvider> cptracker; private final ConsoleSession consoleSession; private final boolean isSystemInOut; /** Default code page which must be supported by all JVMs */ @@ -42,7 +41,7 @@ public class FrameworkConsole implements Runnable { private static final boolean blockOnready = FrameworkProperties.getProperty("osgi.dev") != null || FrameworkProperties.getProperty("osgi.console.blockOnReady") != null; //$NON-NLS-1$ //$NON-NLS-2$ volatile boolean shutdown = false; - public FrameworkConsole(BundleContext context, ConsoleSession consoleSession, boolean isSystemInOut, ServiceTracker cptracker) { + public FrameworkConsole(BundleContext context, ConsoleSession consoleSession, boolean isSystemInOut, ServiceTracker<CommandProvider, CommandProvider> cptracker) { this.context = context; this.cptracker = cptracker; this.isSystemInOut = isSystemInOut; @@ -185,13 +184,13 @@ public class FrameworkConsole implements Runnable { * @return Array of service objects; if no service * are being tracked then an empty array is returned */ - public Object[] getServices() { - ServiceReference[] serviceRefs = cptracker.getServiceReferences(); + public CommandProvider[] getServices() { + ServiceReference<CommandProvider>[] serviceRefs = cptracker.getServiceReferences(); if (serviceRefs == null) - return new Object[0]; + return new CommandProvider[0]; Util.dsort(serviceRefs, 0, serviceRefs.length); - Object[] serviceObjects = new Object[serviceRefs.length]; + CommandProvider[] serviceObjects = new CommandProvider[serviceRefs.length]; for (int i = 0; i < serviceRefs.length; i++) serviceObjects[i] = FrameworkConsole.this.context.getService(serviceRefs[i]); return serviceObjects; diff --git a/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/framework/adaptor/BundleClassLoader.java b/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/framework/adaptor/BundleClassLoader.java index 34c9602be..36ef39d7e 100644 --- a/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/framework/adaptor/BundleClassLoader.java +++ b/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/framework/adaptor/BundleClassLoader.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2004, 2009 IBM Corporation and others. + * 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 @@ -55,7 +55,7 @@ public interface BundleClassLoader /*extends ClassLoader*/extends BundleReferenc * @return An Enumeration of all resources found or null if the resource. * does not exist. */ - public Enumeration findLocalResources(String resource); + public Enumeration<URL> findLocalResources(String resource); /** * Finds a local class in the BundleClassLoader without @@ -64,7 +64,7 @@ public interface BundleClassLoader /*extends ClassLoader*/extends BundleReferenc * @return The class object found. * @throws ClassNotFoundException if the classname does not exist locally. */ - public Class findLocalClass(String classname) throws ClassNotFoundException; + public Class<?> findLocalClass(String classname) throws ClassNotFoundException; /** * This method will first search the parent class loader for the resource; @@ -82,7 +82,7 @@ public interface BundleClassLoader /*extends ClassLoader*/extends BundleReferenc * @param name the resource path to get. * @return an Enumeration of URL objects for the resource or <code>null</code> if the resource is not found. */ - public Enumeration getResources(String name) throws IOException; + public Enumeration<URL> getResources(String name) throws IOException; /** * This method will first search the parent class loader for the class; @@ -92,7 +92,7 @@ public interface BundleClassLoader /*extends ClassLoader*/extends BundleReferenc * @return the Class. * @throws ClassNotFoundException */ - public Class loadClass(String name) throws ClassNotFoundException; + public Class<?> loadClass(String name) throws ClassNotFoundException; /** * Closes this class loader. After this method is called diff --git a/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/framework/adaptor/BundleData.java b/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/framework/adaptor/BundleData.java index ff33a0232..e556a44cc 100644 --- a/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/framework/adaptor/BundleData.java +++ b/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/framework/adaptor/BundleData.java @@ -84,7 +84,7 @@ public interface BundleData { * @return An Enumeration of the entry paths or null if the specified path * does not exist. */ - public Enumeration getEntryPaths(String path); + public Enumeration<String> getEntryPaths(String path); /** * Returns the absolute path name of a native library. The BundleData @@ -123,7 +123,7 @@ public interface BundleData { * @throws BundleException if an error occurred while reading the * bundle manifest data. */ - public Dictionary getManifest() throws BundleException; + public Dictionary<String, String> getManifest() throws BundleException; /** * Get the BundleData bundle ID. This will be used as the bundle diff --git a/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/framework/adaptor/ClassLoaderDelegate.java b/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/framework/adaptor/ClassLoaderDelegate.java index 997cadc72..0e8c57bd0 100644 --- a/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/framework/adaptor/ClassLoaderDelegate.java +++ b/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/framework/adaptor/ClassLoaderDelegate.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2004, 2009 IBM Corporation and others. + * 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 @@ -43,7 +43,7 @@ public interface ClassLoaderDelegate { * @return the Class. * @throws ClassNotFoundException if the class is not found. */ - public Class findClass(String classname) throws ClassNotFoundException; + public Class<?> findClass(String classname) throws ClassNotFoundException; /** * Finds a resource for a bundle that may be outside of the actual bundle @@ -72,7 +72,7 @@ public interface ClassLoaderDelegate { * @return the enumeration of resources found or null if the resource * does not exist. */ - public Enumeration findResources(String resource) throws IOException; + public Enumeration<URL> findResources(String resource) throws IOException; /** * Returns the absolute path name of a native library. The following is diff --git a/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/framework/adaptor/ClassLoaderDelegateHook.java b/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/framework/adaptor/ClassLoaderDelegateHook.java index e77e76d82..424feb98a 100644 --- a/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/framework/adaptor/ClassLoaderDelegateHook.java +++ b/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/framework/adaptor/ClassLoaderDelegateHook.java @@ -36,7 +36,7 @@ public interface ClassLoaderDelegateHook { * @return the class found by this hook or null if normal delegation should continue * @throws ClassNotFoundException to terminate the delegation and throw an exception */ - public Class preFindClass(String name, BundleClassLoader classLoader, BundleData data) throws ClassNotFoundException; + public Class<?> preFindClass(String name, BundleClassLoader classLoader, BundleData data) throws ClassNotFoundException; /** * Called by a {@link ClassLoaderDelegate#findClass(String)} method after delegating to the resolved constraints and @@ -48,7 +48,7 @@ public interface ClassLoaderDelegateHook { * @return the class found by this hook or null if normal delegation should continue * @throws ClassNotFoundException to terminate the delegation and throw an exception */ - public Class postFindClass(String name, BundleClassLoader classLoader, BundleData data) throws ClassNotFoundException; + public Class<?> postFindClass(String name, BundleClassLoader classLoader, BundleData data) throws ClassNotFoundException; /** * Called by a {@link ClassLoaderDelegate #findResource(String)} before delegating to the resolved constraints and @@ -86,7 +86,7 @@ public interface ClassLoaderDelegateHook { * @return the resources found by this hook or null if normal delegation should continue * @throws FileNotFoundException to terminate the delegation */ - public Enumeration preFindResources(String name, BundleClassLoader classLoader, BundleData data) throws FileNotFoundException; + public Enumeration<URL> preFindResources(String name, BundleClassLoader classLoader, BundleData data) throws FileNotFoundException; /** * Called by a {@link ClassLoaderDelegate} after delegating to the resolved constraints and @@ -98,7 +98,7 @@ public interface ClassLoaderDelegateHook { * @return the resources found by this hook or null if normal delegation should continue * @throws FileNotFoundException to terminate the delegation */ - public Enumeration postFindResources(String name, BundleClassLoader classLoader, BundleData data) throws FileNotFoundException; + public Enumeration<URL> postFindResources(String name, BundleClassLoader classLoader, BundleData data) throws FileNotFoundException; /** * Called by a {@link ClassLoaderDelegate} before normal delegation. If this method returns diff --git a/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/framework/adaptor/FilePath.java b/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/framework/adaptor/FilePath.java index fbb69c103..55dd1d39c 100644 --- a/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/framework/adaptor/FilePath.java +++ b/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/framework/adaptor/FilePath.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2009 IBM Corporation and others. + * 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 @@ -137,7 +137,7 @@ public class FilePath { * @return an array containing all segments for this path */ public String[] getSegments() { - return (String[]) segments.clone(); + return segments.clone(); } /** diff --git a/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/framework/util/KeyedHashSet.java b/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/framework/util/KeyedHashSet.java index 17bd38bb0..0fc3f415f 100644 --- a/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/framework/util/KeyedHashSet.java +++ b/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/framework/util/KeyedHashSet.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2006 IBM Corporation and others. + * Copyright (c) 2000, 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 @@ -450,11 +450,11 @@ public class KeyedHashSet { * Returns an iterator of elements in this set * @return an iterator of elements in this set */ - public Iterator iterator() { + public Iterator<KeyedElement> iterator() { return new EquinoxSetIterator(); } - class EquinoxSetIterator implements Iterator { + class EquinoxSetIterator implements Iterator<KeyedElement> { private int currentIndex = -1; private int found; @@ -462,7 +462,7 @@ public class KeyedHashSet { return found < elementCount; } - public Object next() { + public KeyedElement next() { if (!hasNext()) throw new NoSuchElementException(); while (++currentIndex < elements.length) diff --git a/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/framework/util/ObjectPool.java b/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/framework/util/ObjectPool.java index e80bd1ac6..45cb44c10 100644 --- a/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/framework/util/ObjectPool.java +++ b/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/framework/util/ObjectPool.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. + * Copyright (c) 2009, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -21,7 +21,7 @@ public class ObjectPool { private static String OPTION_DEBUG_OBJECTPOOL_DUPS = Debug.ECLIPSE_OSGI + "/debug/objectPool/dups"; //$NON-NLS-1$ private static final boolean DEBUG_OBJECTPOOL_ADDS; private static final boolean DEBUG_OBJECTPOOL_DUPS; - private static Map objectCache = new WeakHashMap(); + private static Map<Object, WeakReference<Object>> objectCache = new WeakHashMap<Object, WeakReference<Object>>(); static { FrameworkDebugOptions dbgOptions = FrameworkDebugOptions.getDefault(); if (dbgOptions != null) { @@ -35,7 +35,7 @@ public class ObjectPool { public static Object intern(Object obj) { synchronized (objectCache) { - WeakReference ref = (WeakReference) objectCache.get(obj); + WeakReference<Object> ref = objectCache.get(obj); if (ref != null) { Object refValue = ref.get(); if (refValue != null) { @@ -44,7 +44,7 @@ public class ObjectPool { Debug.println("[ObjectPool] Found duplicate object: " + getObjectString(obj)); //$NON-NLS-1$ } } else { - objectCache.put(obj, new WeakReference(obj)); + objectCache.put(obj, new WeakReference<Object>(obj)); if (DEBUG_OBJECTPOOL_ADDS) Debug.println("[ObjectPool] Added unique object to pool: " + getObjectString(obj) + " Pool size: " + objectCache.size()); //$NON-NLS-1$ //$NON-NLS-2$ } diff --git a/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/service/resolver/BundleDelta.java b/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/service/resolver/BundleDelta.java index 74e7931b2..f8b575eae 100644 --- a/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/service/resolver/BundleDelta.java +++ b/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/service/resolver/BundleDelta.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2003, 2008 IBM Corporation and others. + * 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 @@ -20,7 +20,7 @@ package org.eclipse.osgi.service.resolver; * @since 3.1 * @noimplement This interface is not intended to be implemented by clients. */ -public interface BundleDelta extends Comparable { +public interface BundleDelta extends Comparable<BundleDelta> { /** * Delta type constant (bit mask) indicating that the bundle has been added @@ -121,5 +121,5 @@ public interface BundleDelta extends Comparable { * if the argument can not be converted into something * comparable with the receiver. */ - public int compareTo(Object obj); + public int compareTo(BundleDelta obj); } diff --git a/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/service/resolver/ExportPackageDescription.java b/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/service/resolver/ExportPackageDescription.java index cb9a8397a..9aff1241b 100644 --- a/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/service/resolver/ExportPackageDescription.java +++ b/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/service/resolver/ExportPackageDescription.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2003, 2008 IBM Corporation and others. + * 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 @@ -37,13 +37,13 @@ public interface ExportPackageDescription extends BaseDescription { * Returns the arbitrary attributes for this package. * @return the arbitrary attributes for this package */ - public Map getAttributes(); + public Map<String, String> getAttributes(); /** * Returns the directives for this package. * @return the directives for this package */ - public Map getDirectives(); + public Map<String, String> getDirectives(); /** * Returns the specified directive for this package. diff --git a/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/service/resolver/GenericDescription.java b/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/service/resolver/GenericDescription.java index eb255d32b..ea736060c 100644 --- a/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/service/resolver/GenericDescription.java +++ b/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/service/resolver/GenericDescription.java @@ -28,7 +28,7 @@ public interface GenericDescription extends BaseDescription { * Returns the arbitrary attributes for this description * @return the arbitrary attributes for this description */ - public Dictionary getAttributes(); + public Dictionary<String, String> getAttributes(); /** * Returns the type of generic description capability diff --git a/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/service/resolver/ImportPackageSpecification.java b/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/service/resolver/ImportPackageSpecification.java index 8e128464f..658944009 100644 --- a/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/service/resolver/ImportPackageSpecification.java +++ b/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/service/resolver/ImportPackageSpecification.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2003, 2008 IBM Corporation and others. + * 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 @@ -53,13 +53,13 @@ public interface ImportPackageSpecification extends VersionConstraint { * Returns the arbitrary attributes which this import package may be resolved to. * @return the arbitrary attributes which this import package may be resolved to. */ - public Map getAttributes(); + public Map<String, String> getAttributes(); /** * Returns the directives that control this import package. * @return the directives that control this import package. */ - public Map getDirectives(); + public Map<String, String> getDirectives(); /** * Returns the specified directive that control this import package. diff --git a/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/service/resolver/NativeCodeDescription.java b/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/service/resolver/NativeCodeDescription.java index c788a99d0..1cd159655 100644 --- a/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/service/resolver/NativeCodeDescription.java +++ b/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/service/resolver/NativeCodeDescription.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. + * Copyright (c) 2007, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -21,7 +21,7 @@ import org.osgi.framework.Filter; * @since 3.4 * @noimplement This interface is not intended to be implemented by clients. */ -public interface NativeCodeDescription extends BaseDescription, Comparable { +public interface NativeCodeDescription extends BaseDescription, Comparable<NativeCodeDescription> { /** * Returns the paths to the native code libraries. * @return the paths to the native code libraries. @@ -72,7 +72,7 @@ public interface NativeCodeDescription extends BaseDescription, Comparable { * @return a negative integer, zero, or a positive integer as this natve * code description is less than, equal to, or greater than the specified object. */ - public int compareTo(Object other); + public int compareTo(NativeCodeDescription other); /** * Indicates if this native code description has invalid native code paths. Native diff --git a/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/service/resolver/Resolver.java b/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/service/resolver/Resolver.java index e24e85550..842a8ec1f 100644 --- a/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/service/resolver/Resolver.java +++ b/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/service/resolver/Resolver.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2003, 2008 IBM Corporation and others. + * 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 @@ -46,7 +46,7 @@ public interface Resolver { * against. A <tt>null</tt> value indicates that the system properties should * be used to match against */ - public void resolve(BundleDescription[] discard, Dictionary[] platformProperties); + public void resolve(BundleDescription[] discard, Dictionary<String, String>[] platformProperties); /** * Flushes this resolver of any stored/cached data it may be keeping to @@ -135,12 +135,12 @@ public interface Resolver { * @param selectionPolicy the selection policy for this resolver * @since 3.2 */ - public void setSelectionPolicy(Comparator selectionPolicy); + public void setSelectionPolicy(Comparator<BaseDescription> selectionPolicy); /** * Returns the selection policy for this resolver or null if it is not set * @return the selection policy for this resolver or null if it is not set * @since 3.2 */ - public Comparator getSelectionPolicy(); + public Comparator<BaseDescription> getSelectionPolicy(); } diff --git a/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/service/resolver/State.java b/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/service/resolver/State.java index ff7d0bf25..2602b886a 100644 --- a/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/service/resolver/State.java +++ b/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/service/resolver/State.java @@ -459,7 +459,7 @@ public interface State { * supported properties already set. If any of the supported property values * are changed as a result of calling this method then true is returned. */ - public boolean setPlatformProperties(Dictionary platformProperties); + public boolean setPlatformProperties(Dictionary<String, String> platformProperties); /** * Sets the platform properties of the state to a list of platform properties. @@ -470,13 +470,13 @@ public interface State { * supported properties already set. If any of the supported property values * are changed as a result of calling this method then true is returned. */ - public boolean setPlatformProperties(Dictionary[] platformProperties); + public boolean setPlatformProperties(Dictionary<String, String>[] platformProperties); /** * Returns the list of platform properties currently set for this state. * @return the list of platform properties currently set for this state. */ - public Dictionary[] getPlatformProperties(); + public Dictionary<String, String>[] getPlatformProperties(); /** * Returns the list of system packages which are exported by the system bundle. diff --git a/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/service/resolver/StateObjectFactory.java b/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/service/resolver/StateObjectFactory.java index f3f6ba964..b87f571f7 100644 --- a/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/service/resolver/StateObjectFactory.java +++ b/bundles/org.eclipse.osgi/core/adaptor/org/eclipse/osgi/service/resolver/StateObjectFactory.java @@ -172,7 +172,7 @@ public interface StateObjectFactory { * @return a bundle description derived from the given information * @throws BundleException if an error occurs while reading the manifest */ - public BundleDescription createBundleDescription(State state, Dictionary manifest, String location, long id) throws BundleException; + public BundleDescription createBundleDescription(State state, Dictionary<String, String> manifest, String location, long id) throws BundleException; /** * Returns a bundle description based on the information in the supplied manifest dictionary. @@ -186,7 +186,7 @@ public interface StateObjectFactory { * @throws BundleException if an error occurs while reading the manifest * @deprecated use {@link #createBundleDescription(State, Dictionary, String, long)} */ - public BundleDescription createBundleDescription(Dictionary manifest, String location, long id) throws BundleException; + public BundleDescription createBundleDescription(Dictionary<String, String> manifest, String location, long id) throws BundleException; /** * Creates a bundle description that is a copy of the given description. @@ -246,7 +246,7 @@ public interface StateObjectFactory { * @param importer the importing bundle (may be <code>null</code>) * @return the created package specification */ - public ImportPackageSpecification createImportPackageSpecification(String packageName, VersionRange versionRange, String bundleSymbolicName, VersionRange bundleVersionRange, Map directives, Map attributes, BundleDescription importer); + public ImportPackageSpecification createImportPackageSpecification(String packageName, VersionRange versionRange, String bundleSymbolicName, VersionRange bundleVersionRange, Map<String, String> directives, Map<String, String> attributes, BundleDescription importer); /** * Creates an import package specification that is a copy of the given import package @@ -268,7 +268,7 @@ public interface StateObjectFactory { * @param exporter the exporter of the package (may be <code>null</code>) * @return the created package */ - public ExportPackageDescription createExportPackageDescription(String packageName, Version version, Map directives, Map attributes, boolean root, BundleDescription exporter); + public ExportPackageDescription createExportPackageDescription(String packageName, Version version, Map<String, String> directives, Map<String, String> attributes, boolean root, BundleDescription exporter); /** * Creates a generic description from the given parameters @@ -279,7 +279,7 @@ public interface StateObjectFactory { * @return the created generic description * @deprecated use {@link #createGenericDescription(String, String, Version, Map)} */ - public GenericDescription createGenericDescription(String name, String type, Version version, Map attributes); + public GenericDescription createGenericDescription(String name, String type, Version version, Map<String, String> attributes); /** * Creates a generic description from the given parameters @@ -290,7 +290,7 @@ public interface StateObjectFactory { * @return the created generic description * @since 3.7 */ - public GenericDescription createGenericDescription(String type, Map attributes, Map directives, BundleDescription supplier); + public GenericDescription createGenericDescription(String type, Map<String, String> attributes, Map<String, String> directives, BundleDescription supplier); /** * Creates a generic specification from the given parameters diff --git a/bundles/org.eclipse.osgi/core/composite/org/eclipse/osgi/internal/composite/CompositeImpl.java b/bundles/org.eclipse.osgi/core/composite/org/eclipse/osgi/internal/composite/CompositeImpl.java index f900dc6fa..61e7a9dac 100644 --- a/bundles/org.eclipse.osgi/core/composite/org/eclipse/osgi/internal/composite/CompositeImpl.java +++ b/bundles/org.eclipse.osgi/core/composite/org/eclipse/osgi/internal/composite/CompositeImpl.java @@ -57,7 +57,7 @@ public class CompositeImpl extends CompositeBase implements CompositeBundle { props.put(PROP_PARENTFRAMEWORK, thisFramework.getSystemBundleContext().getBundle()); // TODO leaks "this" out of the constructor props.put(PROP_COMPOSITE, this); - Equinox equinox = new Equinox(props); + Equinox equinox = new Equinox((Map) props); if (!firstTime) // if not the first time then we are done return equinox; 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 index 4289feae1..627d98180 100644 --- 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 @@ -79,7 +79,7 @@ public interface CommandInterpreter { * @param dic the dictionary to print * @param title the header to print above the key/value pairs */ - public void printDictionary(Dictionary dic, String title); + public void printDictionary(Dictionary<?, ?> dic, String title); /** * Prints the given bundle resource if it exists 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 index bb43b14ec..f6ec4c51f 100644 --- 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 @@ -28,8 +28,8 @@ import org.osgi.framework.*; * </p> * @since 3.6 */ -public abstract class ConsoleSession implements ServiceFactory { - private volatile ServiceRegistration sessionRegistration; +public abstract class ConsoleSession implements ServiceFactory<ConsoleSession> { + private volatile ServiceRegistration<ConsoleSession> sessionRegistration; /** * Called by the console implementation to free resources associated @@ -39,7 +39,7 @@ public abstract class ConsoleSession implements ServiceFactory { */ public final void close() { doClose(); - ServiceRegistration current = sessionRegistration; + ServiceRegistration<ConsoleSession> current = sessionRegistration; if (current != null) { sessionRegistration = null; try { @@ -79,7 +79,7 @@ public abstract class ConsoleSession implements ServiceFactory { /** * @noreference This method is not intended to be referenced by clients. */ - public final Object getService(Bundle bundle, ServiceRegistration registration) { + public final ConsoleSession getService(Bundle bundle, ServiceRegistration<ConsoleSession> registration) { if (sessionRegistration == null) sessionRegistration = registration; return this; @@ -88,7 +88,7 @@ public abstract class ConsoleSession implements ServiceFactory { /** * @noreference This method is not intended to be referenced by clients. */ - public final void ungetService(Bundle bundle, ServiceRegistration registration, Object service) { + public final void ungetService(Bundle bundle, ServiceRegistration<ConsoleSession> registration, ConsoleSession service) { // do nothing } diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/eventmgr/CopyOnWriteIdentityMap.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/eventmgr/CopyOnWriteIdentityMap.java index cc9fa78ba..71b83cebf 100644 --- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/eventmgr/CopyOnWriteIdentityMap.java +++ b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/eventmgr/CopyOnWriteIdentityMap.java @@ -27,7 +27,7 @@ public class CopyOnWriteIdentityMap<K, V> implements Map<K, V> { /** * The empty array singleton instance. */ - @SuppressWarnings("unchecked") + @SuppressWarnings("rawtypes") private static final Entry[] emptyArray = new Entry[0]; /** diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/eventmgr/EventDispatcher.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/eventmgr/EventDispatcher.java index 3e6f3cb18..18327d402 100644 --- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/eventmgr/EventDispatcher.java +++ b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/eventmgr/EventDispatcher.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2003, 2008 IBM Corporation and others. + * 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 @@ -19,7 +19,7 @@ package org.eclipse.osgi.framework.eventmgr; * </p> * @since 3.1 */ -public interface EventDispatcher { +public interface EventDispatcher<K, V, E> { /** * This method is called once for each listener. * This method must cast the event listener object to the appropriate listener @@ -45,5 +45,5 @@ public interface EventDispatcher { * can complete the delivery of the event to the listener. * This is typically the actual event object. */ - public void dispatchEvent(Object eventListener, Object listenerObject, int eventAction, Object eventObject); + public void dispatchEvent(K eventListener, V listenerObject, int eventAction, E eventObject); } diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/eventmgr/EventListeners.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/eventmgr/EventListeners.java index fee66aeb5..431e4be94 100644 --- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/eventmgr/EventListeners.java +++ b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/eventmgr/EventListeners.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2003, 2008 IBM Corporation and others. + * 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 @@ -11,6 +11,7 @@ package org.eclipse.osgi.framework.eventmgr; +import java.util.Map; import java.util.Set; /** @@ -24,8 +25,8 @@ import java.util.Set; * @deprecated As of 3.5. Replaced by CopyOnWriteIdentityMap. * @noextend This class is not intended to be subclassed by clients. */ -public class EventListeners { - private final CopyOnWriteIdentityMap list = new CopyOnWriteIdentityMap(); +public class EventListeners<K, V> { + private final CopyOnWriteIdentityMap<K, V> list = new CopyOnWriteIdentityMap<K, V>(); /** * Creates an empty listener list. @@ -55,7 +56,7 @@ public class EventListeners { * when the listener is to be called. This may be null * @throws IllegalArgumentException If listener is null. */ - public void addListener(Object listener, Object listenerObject) { + public void addListener(K listener, V listenerObject) { list.put(listener, listenerObject); } @@ -66,7 +67,7 @@ public class EventListeners { * @param listener This is the listener object to be removed from the list. * @throws IllegalArgumentException If listener is null. */ - public void removeListener(Object listener) { + public void removeListener(V listener) { list.remove(listener); } @@ -83,7 +84,7 @@ public class EventListeners { * Get the entry Set from the internal CopyOnWriteIdentityMap. * @return The entry Set. */ - Set entrySet() { + Set<Map.Entry<K, V>> entrySet() { return list.entrySet(); } } diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/eventmgr/EventManager.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/eventmgr/EventManager.java index 2dc7188c7..9e371ee34 100644 --- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/eventmgr/EventManager.java +++ b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/eventmgr/EventManager.java @@ -13,7 +13,8 @@ package org.eclipse.osgi.framework.eventmgr; import java.security.AccessController; import java.security.PrivilegedAction; -import java.util.*; +import java.util.Map; +import java.util.Set; /** * This class is the central class for the Event Manager. Each @@ -104,7 +105,7 @@ public class EventManager { * EventThread for asynchronous dispatch of events. * Access to this field must be protected by a synchronized region. */ - private EventThread thread; + private EventThread<?, ?, ?> thread; /** * Once closed, an attempt to create a new EventThread will result in an @@ -185,22 +186,25 @@ public class EventManager { * @return EventThread to use for dispatching events asynchronously for * this EventManager. */ - synchronized EventThread getEventThread() { + synchronized <K, V, E> EventThread<K, V, E> getEventThread() { if (closed) { throw new IllegalStateException(); } if (thread == null) { /* if there is no thread, then create a new one */ - thread = (EventThread) AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { - EventThread t = new EventThread(threadGroup, threadName); + thread = AccessController.doPrivileged(new PrivilegedAction<EventThread<K, V, E>>() { + public EventThread<K, V, E> run() { + EventThread<K, V, E> t = new EventThread<K, V, E>(threadGroup, threadName); return t; } }); /* start the new thread */ thread.start(); } - return thread; + + @SuppressWarnings("unchecked") + EventThread<K, V, E> result = (EventThread<K, V, E>) thread; + return result; } /** @@ -217,18 +221,17 @@ public class EventManager { * @param eventObject This object was created by the event source and * is passed to this method. This is passed on to the call back object. */ - static void dispatchEvent(Set/*<Map.Entry<Object,Object>>*/listeners, EventDispatcher dispatcher, int eventAction, Object eventObject) { - for (Iterator iter = listeners.iterator(); iter.hasNext();) { /* iterate over the list of listeners */ - Map.Entry listener = (Map.Entry) iter.next(); - Object eventListener = listener.getKey(); - Object listenerObject = listener.getValue(); + static <K, V, E> void dispatchEvent(Set<Map.Entry<K, V>> listeners, EventDispatcher<K, V, E> dispatcher, int eventAction, E eventObject) { + for (Map.Entry<K, V> listener : listeners) { /* iterate over the list of listeners */ + final K eventListener = listener.getKey(); + final V listenerObject = listener.getValue(); try { /* Call the EventDispatcher to complete the delivery of the event. */ dispatcher.dispatchEvent(eventListener, listenerObject, eventAction, eventObject); } catch (Throwable t) { /* Consume and ignore any exceptions thrown by the listener */ if (DEBUG) { - System.out.println("Exception in " + listener.getKey()); //$NON-NLS-1$ + System.out.println("Exception in " + eventListener); //$NON-NLS-1$ t.printStackTrace(); } } @@ -239,7 +242,7 @@ public class EventManager { * This package private class is used for asynchronously dispatching events. */ - static class EventThread extends Thread { + static class EventThread<K, V, E> extends Thread { private static int nextThreadNumber; /** @@ -247,17 +250,17 @@ public class EventManager { * represents the items which are placed on the asynch dispatch queue. * This class is private. */ - private static class Queued { + private static class Queued<K, V, E> { /** listener list for this event */ - final Set/*<Map.Entry<Object,Object>>*/listeners; + final Set<Map.Entry<K, V>> listeners; /** dispatcher of this event */ - final EventDispatcher dispatcher; + final EventDispatcher<K, V, E> dispatcher; /** action for this event */ final int action; /** object for this event */ - final Object object; + final E object; /** next item in event queue */ - Queued next; + Queued<K, V, E> next; /** * Constructor for event queue item @@ -267,7 +270,7 @@ public class EventManager { * @param a Action for this event * @param o Object for this event */ - Queued(Set/*<Map.Entry<Object,Object>>*/l, EventDispatcher d, int a, Object o) { + Queued(Set<Map.Entry<K, V>> l, EventDispatcher<K, V, E> d, int a, E o) { listeners = l; dispatcher = d; action = a; @@ -277,9 +280,9 @@ public class EventManager { } /** item at the head of the event queue */ - private Queued head; + private Queued<K, V, E> head; /** item at the tail of the event queue */ - private Queued tail; + private Queued<K, V, E> tail; /** if false the thread must terminate */ private volatile boolean running; @@ -330,7 +333,7 @@ public class EventManager { public void run() { try { while (true) { - Queued item = getNextEvent(); + Queued<K, V, E> item = getNextEvent(); if (item == null) { return; } @@ -363,12 +366,12 @@ public class EventManager { * @param a Action for this event * @param o Object for this event */ - synchronized void postEvent(Set/*<Map.Entry<Object,Object>>*/l, EventDispatcher d, int a, Object o) { + synchronized void postEvent(Set<Map.Entry<K, V>> l, EventDispatcher<K, V, E> d, int a, E o) { if (!isAlive()) { /* If the thread is not alive, throw an exception */ throw new IllegalStateException(); } - Queued item = new Queued(l, d, a, o); + Queued<K, V, E> item = new Queued<K, V, E>(l, d, a, o); if (head == null) /* if the queue was empty */ { @@ -391,7 +394,7 @@ public class EventManager { * @return The Queued removed from the top of the queue or null * if the thread has been requested to stop. */ - private synchronized Queued getNextEvent() { + private synchronized Queued<K, V, E> getNextEvent() { while (running && (head == null)) { try { wait(); @@ -404,7 +407,7 @@ public class EventManager { return null; } - Queued item = head; + Queued<K, V, E> item = head; head = item.next; if (head == null) { tail = null; diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/eventmgr/ListenerQueue.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/eventmgr/ListenerQueue.java index 0f63ecc18..6f1d7319d 100644 --- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/eventmgr/ListenerQueue.java +++ b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/eventmgr/ListenerQueue.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2003, 2009 IBM Corporation and others. + * 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 @@ -11,7 +11,8 @@ package org.eclipse.osgi.framework.eventmgr; -import java.util.*; +import java.util.Map; +import java.util.Set; import org.eclipse.osgi.framework.eventmgr.EventManager.EventThread; /** @@ -33,7 +34,7 @@ import org.eclipse.osgi.framework.eventmgr.EventManager.EventThread; * added to the list. * @since 3.1 */ -public class ListenerQueue { +public class ListenerQueue<K, V, E> { /** * EventManager with which this queue is associated. */ @@ -41,7 +42,7 @@ public class ListenerQueue { /** * A list of listener lists. */ - private final Map /*<Set<Map.Entry<Object,Object>>,EventDispatcher>*/queue; + private final Map<Set<Map.Entry<K, V>>, EventDispatcher<K, V, E>> queue; /** * Once the listener queue has been used to dispatch an event, @@ -62,7 +63,7 @@ public class ListenerQueue { } this.manager = manager; - queue = new CopyOnWriteIdentityMap(); + queue = new CopyOnWriteIdentityMap<Set<Map.Entry<K, V>>, EventDispatcher<K, V, E>>(); readOnly = false; } @@ -79,7 +80,7 @@ public class ListenerQueue { * @throws IllegalStateException If called after one of the dispatch methods has been called. * @deprecated As of 3.5. Replaced by {@link #queueListeners(Set, EventDispatcher)}. */ - public void queueListeners(EventListeners listeners, EventDispatcher dispatcher) { + public void queueListeners(EventListeners<K, V> listeners, EventDispatcher<K, V, E> dispatcher) { queueListeners(listeners.entrySet(), dispatcher); } @@ -97,7 +98,7 @@ public class ListenerQueue { * @throws IllegalStateException If called after one of the dispatch methods has been called. * @since 3.5 */ - public synchronized void queueListeners(Set/*<Map.Entry<Object,Object>>*/listeners, EventDispatcher dispatcher) { + public synchronized void queueListeners(Set<Map.Entry<K, V>> listeners, EventDispatcher<K, V, E> dispatcher) { if (readOnly) { throw new IllegalStateException(); } @@ -115,15 +116,14 @@ public class ListenerQueue { * @param eventAction This value is passed to the EventDispatcher. * @param eventObject This object is passed to the EventDispatcher. */ - public void dispatchEventAsynchronous(int eventAction, Object eventObject) { + public void dispatchEventAsynchronous(int eventAction, E eventObject) { synchronized (this) { readOnly = true; } - EventThread eventThread = manager.getEventThread(); + EventThread<K, V, E> eventThread = manager.getEventThread(); synchronized (eventThread) { /* synchronize on the EventThread to ensure no interleaving of posting to the event thread */ - for (Iterator iter = queue.entrySet().iterator(); iter.hasNext();) { /* iterate over the list of listener lists */ - Map.Entry entry = (Map.Entry) iter.next(); - eventThread.postEvent((Set) entry.getKey(), (EventDispatcher) entry.getValue(), eventAction, eventObject); + for (Map.Entry<Set<Map.Entry<K, V>>, EventDispatcher<K, V, E>> entry : queue.entrySet()) { /* iterate over the list of listener lists */ + eventThread.postEvent(entry.getKey(), entry.getValue(), eventAction, eventObject); } } } @@ -138,15 +138,14 @@ public class ListenerQueue { * @param eventAction This value is passed to the EventDispatcher. * @param eventObject This object is passed to the EventDispatcher. */ - public void dispatchEventSynchronous(int eventAction, Object eventObject) { + public void dispatchEventSynchronous(int eventAction, E eventObject) { synchronized (this) { readOnly = true; } // We can't guarantee any delivery order for synchronous events. // Attempts to do so result in deadly embraces. - for (Iterator iter = queue.entrySet().iterator(); iter.hasNext();) { /* iterate over the list of listener lists */ - Map.Entry entry = (Map.Entry) iter.next(); - EventManager.dispatchEvent((Set) entry.getKey(), (EventDispatcher) entry.getValue(), eventAction, eventObject); + for (Map.Entry<Set<Map.Entry<K, V>>, EventDispatcher<K, V, E>> entry : queue.entrySet()) { /* iterate over the list of listener lists */ + EventManager.dispatchEvent(entry.getKey(), entry.getValue(), eventAction, eventObject); } } } 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 index 01863b1a9..49231378e 100644 --- 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 @@ -15,6 +15,7 @@ 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; @@ -148,7 +149,7 @@ public abstract class AbstractBundle implements Bundle, Comparable<Bundle>, Keye String activatorClassName = bundledata.getActivator(); if (activatorClassName != null) { try { - Class activatorClass = loadClass(activatorClassName, false); + Class<?> activatorClass = loadClass(activatorClassName, false); /* Create the activator for the bundle */ return (BundleActivator) (activatorClass.newInstance()); } catch (Throwable t) { @@ -172,7 +173,7 @@ public abstract class AbstractBundle implements Bundle, Comparable<Bundle>, Keye * @exception java.lang.ClassNotFoundException * if the class definition was not found. */ - protected abstract Class loadClass(String name, boolean checkPermission) throws ClassNotFoundException; + protected abstract Class<?> loadClass(String name, boolean checkPermission) throws ClassNotFoundException; /** * Returns the current state of the bundle. @@ -471,7 +472,7 @@ public abstract class AbstractBundle implements Bundle, Comparable<Bundle>, Keye */ protected void setStatus(final int mask, final boolean state) { try { - AccessController.doPrivileged(new PrivilegedExceptionAction() { + AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { public Object run() throws IOException { int status = bundledata.getStatus(); boolean test = ((status & mask) != 0); @@ -575,12 +576,12 @@ public abstract class AbstractBundle implements Bundle, Comparable<Bundle>, Keye try { final AccessControlContext callerContext = AccessController.getContext(); //note AdminPermission is checked again after updated bundle is loaded - updateWorker(new PrivilegedExceptionAction() { + updateWorker(new PrivilegedExceptionAction<Object>() { public Object run() throws BundleException { /* compute the update location */ URLConnection source = null; if (in == null) { - String updateLocation = (String) bundledata.getManifest().get(Constants.BUNDLE_UPDATELOCATION); + String updateLocation = bundledata.getManifest().get(Constants.BUNDLE_UPDATELOCATION); if (updateLocation == null) updateLocation = bundledata.getLocation(); if (Debug.DEBUG_GENERAL) @@ -604,7 +605,7 @@ public abstract class AbstractBundle implements Bundle, Comparable<Bundle>, Keye /** * Update worker. Assumes the caller has the state change lock. */ - protected void updateWorker(PrivilegedExceptionAction action) throws BundleException { + protected void updateWorker(PrivilegedExceptionAction<Object> action) throws BundleException { int previousState = 0; if (!isFragment()) previousState = state; @@ -665,7 +666,7 @@ public abstract class AbstractBundle implements Bundle, Comparable<Bundle>, Keye 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() { + AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { public Object run() throws Exception { framework.checkAdminPermission(newBundle, AdminPermission.LIFECYCLE); if (extension) // need special permission to update extension bundles @@ -767,7 +768,7 @@ public abstract class AbstractBundle implements Bundle, Comparable<Bundle>, Keye checkValid(); beginStateChange(); try { - uninstallWorker(new PrivilegedExceptionAction() { + uninstallWorker(new PrivilegedExceptionAction<Object>() { public Object run() throws BundleException { uninstallWorkerPrivileged(); return null; @@ -781,7 +782,7 @@ public abstract class AbstractBundle implements Bundle, Comparable<Bundle>, Keye /** * Uninstall worker. Assumes the caller has the state change lock. */ - protected void uninstallWorker(PrivilegedExceptionAction action) throws BundleException { + protected void uninstallWorker(PrivilegedExceptionAction<Object> action) throws BundleException { boolean bundleActive = false; if (!isFragment()) bundleActive = (state & (ACTIVE | STARTING)) != 0; @@ -894,7 +895,7 @@ public abstract class AbstractBundle implements Bundle, Comparable<Bundle>, Keye * permission and the Java runtime environment supports * permissions. */ - public Dictionary getHeaders() { + public Dictionary<String, String> getHeaders() { return getHeaders(null); } @@ -936,7 +937,7 @@ public abstract class AbstractBundle implements Bundle, Comparable<Bundle>, Keye * If the caller does not have the <tt>AdminPermission</tt>, * and the Java Runtime Environment supports permissions. */ - public Dictionary getHeaders(String localeString) { + public Dictionary<String, String> getHeaders(String localeString) { framework.checkAdminPermission(this, AdminPermission.METADATA); ManifestLocalization localization; try { @@ -944,7 +945,7 @@ public abstract class AbstractBundle implements Bundle, Comparable<Bundle>, Keye } catch (BundleException e) { framework.publishFrameworkEvent(FrameworkEvent.ERROR, this, e); // return an empty dictinary. - return new Hashtable(); + return new Hashtable<String, String>(); } if (localeString == null) localeString = Locale.getDefault().toString(); @@ -1190,7 +1191,7 @@ public abstract class AbstractBundle implements Bundle, Comparable<Bundle>, Keye * * @see org.osgi.framework.Bundle#findClass(java.lang.String) */ - public Class loadClass(String classname) throws ClassNotFoundException { + public Class<?> loadClass(String classname) throws ClassNotFoundException { return loadClass(classname, true); } @@ -1199,7 +1200,7 @@ public abstract class AbstractBundle implements Bundle, Comparable<Bundle>, Keye * * @see org.osgi.framework.Bundle#getResourcePaths(java.lang.String) */ - public Enumeration getEntryPaths(final String path) { + public Enumeration<String> getEntryPaths(final String path) { try { framework.checkAdminPermission(this, AdminPermission.RESOURCE); } catch (SecurityException e) { @@ -1207,8 +1208,8 @@ public abstract class AbstractBundle implements Bundle, Comparable<Bundle>, Keye } checkValid(); // TODO this doPrivileged is probably not needed. The adaptor isolates callers from disk access - return (Enumeration) AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { + return AccessController.doPrivileged(new PrivilegedAction<Enumeration<String>>() { + public Enumeration<String> run() { return bundledata.getEntryPaths(path); } }); @@ -1348,7 +1349,7 @@ public abstract class AbstractBundle implements Bundle, Comparable<Bundle>, Keye private synchronized ManifestLocalization getManifestLocalization() throws BundleException { ManifestLocalization currentLocalization = manifestLocalization; if (currentLocalization == null) { - Dictionary rawHeaders = bundledata.getManifest(); + Dictionary<String, String> rawHeaders = bundledata.getManifest(); manifestLocalization = currentLocalization = new ManifestLocalization(this, rawHeaders); } return currentLocalization; @@ -1362,7 +1363,7 @@ public abstract class AbstractBundle implements Bundle, Comparable<Bundle>, Keye return stateChanging; } - public Enumeration findEntries(String path, String filePattern, boolean recurse) { + public Enumeration<URL> findEntries(String path, String filePattern, boolean recurse) { try { framework.checkAdminPermission(this, AdminPermission.RESOURCE); } catch (SecurityException e) { @@ -1374,15 +1375,15 @@ public abstract class AbstractBundle implements Bundle, Comparable<Bundle>, Keye framework.packageAdmin.resolveBundles(new Bundle[] {this}); // a list used to store the results of the search - List pathList = new ArrayList(); + List<String> pathList = new ArrayList<String>(); Filter patternFilter = null; - Hashtable patternProps = null; + Hashtable<String, String> patternProps = null; if (filePattern != null) try { // create a file pattern filter with 'filename' as the key patternFilter = FilterImpl.newInstance("(filename=" + filePattern + ")"); //$NON-NLS-1$ //$NON-NLS-2$ // create a single hashtable to be shared during the recursive search - patternProps = new Hashtable(2); + patternProps = new Hashtable<String, String>(2); } catch (InvalidSyntaxException e) { // cannot happen } @@ -1397,8 +1398,8 @@ public abstract class AbstractBundle implements Bundle, Comparable<Bundle>, Keye if (pathList.size() == 0) return null; // create an enumeration to enumerate the pathList - final String[] pathArray = (String[]) pathList.toArray(new String[pathList.size()]); - return new Enumeration() { + final String[] pathArray = pathList.toArray(new String[pathList.size()]); + return new Enumeration<URL>() { int curIndex = 0; int curFragment = -1; URL nextElement = null; @@ -1410,7 +1411,7 @@ public abstract class AbstractBundle implements Bundle, Comparable<Bundle>, Keye return nextElement != null; } - public Object nextElement() { + public URL nextElement() { if (!hasMoreElements()) throw new NoSuchElementException(); URL result; @@ -1447,12 +1448,12 @@ public abstract class AbstractBundle implements Bundle, Comparable<Bundle>, Keye }; } - protected void findLocalEntryPaths(String path, Filter patternFilter, Hashtable patternProps, boolean recurse, List pathList) { - Enumeration entryPaths = bundledata.getEntryPaths(path); + protected void findLocalEntryPaths(String path, Filter patternFilter, Hashtable<String, String> patternProps, boolean recurse, List<String> pathList) { + Enumeration<String> entryPaths = bundledata.getEntryPaths(path); if (entryPaths == null) return; while (entryPaths.hasMoreElements()) { - String entry = (String) entryPaths.nextElement(); + String entry = entryPaths.nextElement(); int lastSlash = entry.lastIndexOf('/'); if (patternProps != null) { int secondToLastSlash = entry.lastIndexOf('/', lastSlash - 1); @@ -1504,37 +1505,40 @@ public abstract class AbstractBundle implements Bundle, Comparable<Bundle>, Keye } - public Map/* <X509Certificate, List<X509Certificate>> */getSignerCertificates(int signersType) { + 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 Collections.EMPTY_MAP; + return empty; SignedContentFactory factory = framework.getSignedContentFactory(); if (factory == null) - return Collections.EMPTY_MAP; + return empty; try { SignedContent signedContent = factory.getSignedContent(this); SignerInfo[] infos = signedContent.getSignerInfos(); if (infos.length == 0) - return Collections.EMPTY_MAP; - Map/* <X509Certificate, List<X509Certificate>> */results = new HashMap(infos.length); + 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(); + List<X509Certificate> certChain = new ArrayList<X509Certificate>(); for (int j = 0; j < certs.length; j++) - certChain.add(certs[j]); - results.put(certs[0], certChain); + certChain.add((X509Certificate) certs[j]); + results.put((X509Certificate) certs[0], certChain); } return results; } catch (Exception e) { - return Collections.EMPTY_MAP; + return empty; } } + @SuppressWarnings("unchecked") public <A> A adapt(Class<A> adapterType) { if (adapterType.isInstance(this)) return (A) this; 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 index a623969ec..728745362 100644 --- 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 @@ -11,27 +11,20 @@ package org.eclipse.osgi.framework.internal.core; import java.io.*; -import java.util.Hashtable; -import java.util.Vector; +import java.util.*; import org.eclipse.osgi.framework.debug.Debug; /** * This class maps aliases. */ public class AliasMapper { - private static Hashtable processorAliasTable; - private static Hashtable osnameAliasTable; + private static Map<String, Object> processorAliasTable; + private static Map<String, Object> 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(); + // Safe lazy initialization + private static synchronized Map<String, Object> getProcessorAliasTable() { if (processorAliasTable == null) { - InputStream in = getClass().getResourceAsStream(Constants.OSGI_PROCESSOR_ALIASES); + InputStream in = AliasMapper.class.getResourceAsStream(Constants.OSGI_PROCESSOR_ALIASES); if (in != null) { try { processorAliasTable = initAliases(in); @@ -44,25 +37,13 @@ public class AliasMapper { } } } - if (processorAliasTable != null) { - String alias = (String) processorAliasTable.get(processor); - if (alias != null) { - processor = alias; - } - } - return (processor); + return processorAliasTable; } - /** - * Return the master alias for the osname. - * - * @param osname Input name - * @return aliased name (if any) - */ - public Object aliasOSName(String osname) { - osname = osname.toLowerCase(); + // Safe lazy initialization + private static synchronized Map<String, Object> getOSNameAliasTable() { if (osnameAliasTable == null) { - InputStream in = getClass().getResourceAsStream(Constants.OSGI_OSNAME_ALIASES); + InputStream in = AliasMapper.class.getResourceAsStream(Constants.OSGI_OSNAME_ALIASES); if (in != null) { try { osnameAliasTable = initAliases(in); @@ -75,8 +56,38 @@ public class AliasMapper { } } } - if (osnameAliasTable != null) { - Object aliasObject = osnameAliasTable.get(osname); + 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) { @@ -85,17 +96,17 @@ public class AliasMapper { return aliasObject; } } - return (osname); + return osname; } /** - * Read alias data and populate a Hashtable. + * Read alias data and populate a Map. * * @param in InputStream from which to read alias data. - * @return Hashtable of aliases. + * @return Map of aliases. */ - protected static Hashtable initAliases(InputStream in) { - Hashtable aliases = new Hashtable(37); + protected static Map<String, Object> initAliases(InputStream in) { + Map<String, Object> aliases = new HashMap<String, Object>(37); try { BufferedReader br; try { @@ -122,13 +133,14 @@ public class AliasMapper { if (storedMaster == null) { aliases.put(lowerCaseAlias, master); } else if (storedMaster instanceof String) { - Vector newMaster = new Vector(); - newMaster.add(storedMaster); + List<String> newMaster = new ArrayList<String>(); + newMaster.add((String) storedMaster); newMaster.add(master); aliases.put(lowerCaseAlias, newMaster); } else { - ((Vector) storedMaster).add(master); - aliases.put(lowerCaseAlias, storedMaster); + @SuppressWarnings("unchecked") + List<String> newMaster = ((List<String>) storedMaster); + newMaster.add(master); } } } @@ -138,6 +150,6 @@ public class AliasMapper { Debug.printStackTrace(e); } } - return (aliases); + 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 index 1db5798f6..8dca83523 100644 --- 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 @@ -31,7 +31,7 @@ import org.osgi.framework.*; * It is destroyed when a bundle is stopped. */ -public class BundleContextImpl implements BundleContext, EventDispatcher { +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; @@ -957,7 +957,9 @@ public class BundleContextImpl implements BundleContext, EventDispatcher { @SuppressWarnings("unchecked") ServiceReference<S>[] refs = (ServiceReference<S>[]) getServiceReferences(clazz.getName(), filter); if (refs == null) { - return Collections.EMPTY_LIST; + @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) { 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 index 468a0c85b..3b02ac2b4 100644 --- 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 @@ -177,7 +177,7 @@ public class BundleFragment extends AbstractBundle { * @return the resulting Class * @exception java.lang.ClassNotFoundException if the class definition was not found. */ - protected Class loadClass(String name, boolean checkPermission) throws ClassNotFoundException { + protected Class<?> loadClass(String name, boolean checkPermission) throws ClassNotFoundException { if (checkPermission) { try { framework.checkAdminPermission(this, AdminPermission.CLASS); @@ -216,7 +216,7 @@ public class BundleFragment extends AbstractBundle { } - public Enumeration getResources(String name) { + public Enumeration<URL> getResources(String name) { checkValid(); // cannot get a resource for a fragment because there is no classloader // associated with fragments. @@ -257,7 +257,7 @@ public class BundleFragment extends AbstractBundle { * @see ServiceRegistration * @see ServiceReference */ - public ServiceReference[] getRegisteredServices() { + public ServiceReference<?>[] getRegisteredServices() { checkValid(); // Fragments cannot have a BundleContext and therefore // cannot have any services registered. @@ -280,7 +280,7 @@ public class BundleFragment extends AbstractBundle { * bundle has been uninstalled. * @see ServiceReference */ - public ServiceReference[] getServicesInUse() { + public ServiceReference<?>[] getServicesInUse() { checkValid(); // Fragments cannot have a BundleContext and therefore // cannot have any services in use. @@ -340,6 +340,7 @@ public class BundleFragment extends AbstractBundle { return null; } + @SuppressWarnings("unchecked") public <A> A adapt(Class<A> adapterType) { if (BundleWirings.class.equals(adapterType)) { return (A) new BundleWirings() { 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 index 7c5611673..6544152c5 100644 --- 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 @@ -219,7 +219,7 @@ public class BundleHost extends AbstractBundle { * @return the resulting Class * @exception java.lang.ClassNotFoundException if the class definition was not found. */ - protected Class loadClass(String name, boolean checkPermission) throws ClassNotFoundException { + protected Class<?> loadClass(String name, boolean checkPermission) throws ClassNotFoundException { if (checkPermission) { try { framework.checkAdminPermission(this, AdminPermission.CLASS); @@ -276,7 +276,7 @@ public class BundleHost extends AbstractBundle { return (loader.findResource(name)); } - public Enumeration getResources(String name) throws IOException { + public Enumeration<URL> getResources(String name) throws IOException { BundleLoader loader = null; try { framework.checkAdminPermission(this, AdminPermission.RESOURCE); @@ -286,7 +286,7 @@ public class BundleHost extends AbstractBundle { loader = checkLoader(); if (loader == null) return null; - Enumeration result = loader.getResources(name); + Enumeration<URL> result = loader.getResources(name); if (result != null && result.hasMoreElements()) return result; return null; @@ -551,7 +551,7 @@ public class BundleHost extends AbstractBundle { * @see ServiceRegistration * @see ServiceReference */ - public ServiceReference[] getRegisteredServices() { + public ServiceReference<?>[] getRegisteredServices() { checkValid(); if (context == null) { @@ -577,7 +577,7 @@ public class BundleHost extends AbstractBundle { * bundle has been uninstalled. * @see ServiceReference */ - public ServiceReference[] getServicesInUse() { + public ServiceReference<?>[] getServicesInUse() { checkValid(); if (context == null) { @@ -677,6 +677,7 @@ public class BundleHost extends AbstractBundle { return (bcl instanceof ClassLoader) ? (ClassLoader) bcl : null; } + @SuppressWarnings("unchecked") public <A> A adapt(Class<A> adapterType) { if (BundleWirings.class.equals(adapterType)) { return (A) new BundleWirings() { 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 index 22819def4..b5dae7fd1 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2003, 2009 IBM Corporation and others. + * 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 @@ -28,19 +28,19 @@ import org.osgi.framework.Version; */ public final class BundleRepository { /** bundles by install order */ - private ArrayList bundlesByInstallOrder; + private List<AbstractBundle> bundlesByInstallOrder; /** bundles keyed by bundle Id */ private KeyedHashSet bundlesById; /** bundles keyed by SymbolicName */ - private HashMap bundlesBySymbolicName; + private Map<String, AbstractBundle[]> bundlesBySymbolicName; public BundleRepository(int initialCapacity) { synchronized (this) { - bundlesByInstallOrder = new ArrayList(initialCapacity); + bundlesByInstallOrder = new ArrayList<AbstractBundle>(initialCapacity); bundlesById = new KeyedHashSet(initialCapacity, true); - bundlesBySymbolicName = new HashMap(initialCapacity); + bundlesBySymbolicName = new HashMap<String, AbstractBundle[]>(initialCapacity); } } @@ -48,7 +48,7 @@ public final class BundleRepository { * Gets a list of bundles ordered by install order. * @return List of bundles by install order. */ - public synchronized List getBundles() { + public synchronized List<AbstractBundle> getBundles() { return bundlesByInstallOrder; } @@ -65,7 +65,7 @@ public final class BundleRepository { public synchronized AbstractBundle[] getBundles(String symbolicName) { if (Constants.SYSTEM_BUNDLE_SYMBOLICNAME.equals(symbolicName)) symbolicName = Constants.getInternalSymbolicName(); - return (AbstractBundle[]) bundlesBySymbolicName.get(symbolicName); + return bundlesBySymbolicName.get(symbolicName); } public synchronized AbstractBundle getBundle(String symbolicName, Version version) { @@ -92,7 +92,7 @@ public final class BundleRepository { String symbolicName = bundle.getSymbolicName(); if (symbolicName == null) return; - AbstractBundle[] bundles = (AbstractBundle[]) bundlesBySymbolicName.get(symbolicName); + AbstractBundle[] bundles = bundlesBySymbolicName.get(symbolicName); if (bundles == null) { // making the initial capacity on this 1 since it // should be rare that multiple version exist @@ -102,7 +102,7 @@ public final class BundleRepository { return; } - ArrayList list = new ArrayList(bundles.length + 1); + List<AbstractBundle> list = new ArrayList<AbstractBundle>(bundles.length + 1); // find place to insert the bundle Version newVersion = bundle.getVersion(); boolean added = false; @@ -141,7 +141,7 @@ public final class BundleRepository { } private void removeSymbolicName(String symbolicName, AbstractBundle bundle) { - AbstractBundle[] bundles = (AbstractBundle[]) bundlesBySymbolicName.get(symbolicName); + AbstractBundle[] bundles = bundlesBySymbolicName.get(symbolicName); if (bundles == null) return; diff --git a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/CoreResolverHook.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/CoreResolverHook.java index a94ae6b0e..c71ea35f7 100644 --- a/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/CoreResolverHook.java +++ b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/core/CoreResolverHook.java @@ -62,7 +62,9 @@ public class CoreResolverHook implements ResolverHook { private ServiceReferenceImpl<ResolverHook>[] getHookReferences() { try { - return (ServiceReferenceImpl<ResolverHook>[]) registry.getServiceReferences(context, ResolverHook.class.getName(), null, false, false); + @SuppressWarnings("unchecked") + ServiceReferenceImpl<ResolverHook>[] result = (ServiceReferenceImpl<ResolverHook>[]) registry.getServiceReferences(context, ResolverHook.class.getName(), null, false, false); + return result; } catch (InvalidSyntaxException e) { // cannot happen; no filter return null; 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 index 0a856fb30..615d889cb 100644 --- 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 @@ -13,6 +13,7 @@ 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.core.runtime.adaptor.LocationManager; @@ -24,10 +25,10 @@ public class EquinoxLauncher implements org.osgi.framework.launch.Framework { private volatile Framework framework; private volatile Bundle systemBundle; - private final Map configuration; + private final Map<String, String> configuration; private volatile ConsoleManager consoleMgr = null; - public EquinoxLauncher(Map configuration) { + public EquinoxLauncher(Map<String, String> configuration) { this.configuration = configuration; } @@ -36,7 +37,7 @@ public class EquinoxLauncher implements org.osgi.framework.launch.Framework { if (System.getSecurityManager() == null) internalInit(); else { - AccessController.doPrivileged(new PrivilegedAction() { + AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { internalInit(); return null; @@ -77,7 +78,7 @@ public class EquinoxLauncher implements org.osgi.framework.launch.Framework { return current; } - private void setEquinoxProperties(Map configuration) { + 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) @@ -127,7 +128,7 @@ public class EquinoxLauncher implements org.osgi.framework.launch.Framework { return current.waitForStop(timeout); } - public Enumeration findEntries(String path, String filePattern, boolean recurse) { + public Enumeration<URL> findEntries(String path, String filePattern, boolean recurse) { Bundle current = systemBundle; if (current == null) return null; @@ -152,21 +153,21 @@ public class EquinoxLauncher implements org.osgi.framework.launch.Framework { return current.getEntry(path); } - public Enumeration getEntryPaths(String path) { + public Enumeration<String> getEntryPaths(String path) { Bundle current = systemBundle; if (current == null) return null; return current.getEntryPaths(path); } - public Dictionary getHeaders() { + public Dictionary<String, String> getHeaders() { Bundle current = systemBundle; if (current == null) return null; return current.getHeaders(); } - public Dictionary getHeaders(String locale) { + public Dictionary<String, String> getHeaders(String locale) { Bundle current = systemBundle; if (current == null) return null; @@ -184,7 +185,7 @@ public class EquinoxLauncher implements org.osgi.framework.launch.Framework { return Constants.SYSTEM_BUNDLE_LOCATION; } - public ServiceReference[] getRegisteredServices() { + public ServiceReference<?>[] getRegisteredServices() { Bundle current = systemBundle; if (current == null) return null; @@ -198,14 +199,14 @@ public class EquinoxLauncher implements org.osgi.framework.launch.Framework { return current.getResource(name); } - public Enumeration getResources(String name) throws IOException { + public Enumeration<URL> getResources(String name) throws IOException { Bundle current = systemBundle; if (current == null) return null; return current.getResources(name); } - public ServiceReference[] getServicesInUse() { + public ServiceReference<?>[] getServicesInUse() { Bundle current = systemBundle; if (current == null) return null; @@ -230,7 +231,7 @@ public class EquinoxLauncher implements org.osgi.framework.launch.Framework { return current.hasPermission(permission); } - public Class loadClass(String name) throws ClassNotFoundException { + public Class<?> loadClass(String name) throws ClassNotFoundException { Bundle current = systemBundle; if (current == null) return null; @@ -250,7 +251,7 @@ public class EquinoxLauncher implements org.osgi.framework.launch.Framework { internalStart(); else try { - AccessController.doPrivileged(new PrivilegedExceptionAction() { + AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { public Object run() { internalStart(); return null; @@ -273,7 +274,7 @@ public class EquinoxLauncher implements org.osgi.framework.launch.Framework { Framework current = internalInit(); int level = 1; try { - level = Integer.parseInt((String) configuration.get(Constants.FRAMEWORK_BEGINNING_STARTLEVEL)); + level = Integer.parseInt(configuration.get(Constants.FRAMEWORK_BEGINNING_STARTLEVEL)); } catch (Throwable t) { // do nothing } @@ -316,11 +317,13 @@ public class EquinoxLauncher implements org.osgi.framework.launch.Framework { update(); } - public Map getSignerCertificates(int signersType) { + public Map<X509Certificate, List<X509Certificate>> getSignerCertificates(int signersType) { Bundle current = systemBundle; if (current != null) return current.getSignerCertificates(signersType); - return Collections.EMPTY_MAP; + @SuppressWarnings("unchecked") + final Map<X509Certificate, List<X509Certificate>> empty = Collections.EMPTY_MAP; + return empty; } public Version getVersion() { 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 index 177689adc..f4482e0b1 100644 --- 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 @@ -11,6 +11,7 @@ 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; @@ -58,7 +59,7 @@ public class ExportedPackageImpl implements ExportedPackage { if (bundle == null) return null; AbstractBundle[] bundles = bundle.framework.getAllBundles(); - ArrayList importers = new ArrayList(10); + 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)) @@ -70,7 +71,7 @@ public class ExportedPackageImpl implements ExportedPackage { if (supplierSource != null && supplierSource.hasCommonSource(importerSource)) importers.add(bundles[i]); } - return (Bundle[]) importers.toArray(new Bundle[importers.size()]); + return importers.toArray(new Bundle[importers.size()]); } /** 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 index ec9900b5b..d4ccda31f 100644 --- 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 @@ -585,6 +585,7 @@ public class FilterImpl implements Filter /* since Framework 1.1 */{ 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); } 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 index 0bbcc9c2d..68964bb8f 100644 --- 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 @@ -87,14 +87,14 @@ public class Framework implements EventPublisher, Runnable { * installed in the Framework. */ // Map of BundleContexts for bundle's BundleListeners. - private final Map<BundleContextImpl, CopyOnWriteIdentityMap<BundleListener, BundleListener>> allBundleListeners = new HashMap(); + 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(); + 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(); + 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; @@ -103,7 +103,7 @@ public class Framework implements EventPublisher, Runnable { /** EventManager for event delivery. */ protected EventManager eventManager; /* Reservation object for install synchronization */ - protected Hashtable installLock; + private Map<String, Thread> installLock; /** System Bundle object */ protected InternalSystemBundle systemBundle; private String[] bootDelegation; @@ -117,15 +117,15 @@ public class Framework implements EventPublisher, Runnable { * The AliasMapper used to alias OS Names. */ protected static AliasMapper aliasMapper = new AliasMapper(); - SecureAction secureAction = (SecureAction) AccessController.doPrivileged(SecureAction.createSecureAction()); + SecureAction secureAction = AccessController.doPrivileged(SecureAction.createSecureAction()); // cache of AdminPermissions keyed by Bundle ID - private HashMap adminPermissions = new HashMap(); + 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; + private volatile ServiceTracker<SignedContentFactory, SignedContentFactory> signedContentFactory; private volatile ContextFinder contextFinder; /* @@ -133,12 +133,12 @@ public class Framework implements EventPublisher, Runnable { * see bug 161561 */ static { - Class c; + Class<?> c; c = GetDataFileAction.class; c.getName(); // to prevent compiler warnings } - static class GetDataFileAction implements PrivilegedAction { + static class GetDataFileAction implements PrivilegedAction<File> { private AbstractBundle bundle; private String filename; @@ -147,7 +147,7 @@ public class Framework implements EventPublisher, Runnable { this.filename = filename; } - public Object run() { + public File run() { return bundle.getBundleData().getDataFile(filename); } } @@ -218,7 +218,7 @@ public class Framework implements EventPublisher, Runnable { // 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 Hashtable(10); + installLock = new HashMap<String, Thread>(10); /* create the system bundle */ createSystemBundle(); loadVMProfile(); // load VM profile after the system bundle has been created @@ -292,7 +292,7 @@ public class Framework implements EventPublisher, Runnable { */ protected void initializeProperties(Properties adaptorProperties) { properties = FrameworkProperties.getProperties(); - Enumeration enumKeys = adaptorProperties.propertyNames(); + Enumeration<?> enumKeys = adaptorProperties.propertyNames(); while (enumKeys.hasMoreElements()) { String key = (String) enumKeys.nextElement(); if (properties.getProperty(key) == null) { @@ -402,8 +402,8 @@ public class Framework implements EventPublisher, Runnable { if (bootDelegationProp.trim().length() == 0) return; String[] bootPackages = ManifestElement.getArrayFromList(bootDelegationProp); - ArrayList exactMatch = new ArrayList(bootPackages.length); - ArrayList stemMatch = new ArrayList(bootPackages.length); + 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; @@ -416,11 +416,12 @@ public class Framework implements EventPublisher, Runnable { } } if (!exactMatch.isEmpty()) - bootDelegation = (String[]) exactMatch.toArray(new String[exactMatch.size()]); + bootDelegation = exactMatch.toArray(new String[exactMatch.size()]); if (!stemMatch.isEmpty()) - bootDelegationStems = (String[]) stemMatch.toArray(new String[stemMatch.size()]); + bootDelegationStems = stemMatch.toArray(new String[stemMatch.size()]); } + @SuppressWarnings("deprecation") private void loadVMProfile() { Properties profileProps = findVMProfile(); String systemExports = properties.getProperty(Constants.FRAMEWORK_SYSTEMPACKAGES); @@ -595,10 +596,10 @@ public class Framework implements EventPublisher, Runnable { shutdown(FrameworkEvent.STOPPED); synchronized (bundles) { - List allBundles = bundles.getBundles(); + List<AbstractBundle> allBundles = bundles.getBundles(); int size = allBundles.size(); for (int i = 0; i < size; i++) { - AbstractBundle bundle = (AbstractBundle) allBundles.get(i); + AbstractBundle bundle = allBundles.get(i); bundle.close(); } bundles.removeAllBundles(); @@ -650,7 +651,7 @@ public class Framework implements EventPublisher, Runnable { Debug.println("Trying to launch framework"); //$NON-NLS-1$ } systemBundle.resume(); - signedContentFactory = new ServiceTracker(systemBundle.getBundleContext(), SignedContentFactory.class.getName(), null); + signedContentFactory = new ServiceTracker<SignedContentFactory, SignedContentFactory>(systemBundle.getBundleContext(), SignedContentFactory.class.getName(), null); signedContentFactory.open(); } @@ -827,8 +828,8 @@ public class Framework implements EventPublisher, Runnable { Debug.println("install from inputstream: " + location + ", " + in); //$NON-NLS-1$ //$NON-NLS-2$ } final AccessControlContext callerContext = AccessController.getContext(); - return installWorker(location, new PrivilegedExceptionAction() { - public Object run() throws BundleException { + 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 */ @@ -849,7 +850,7 @@ public class Framework implements EventPublisher, Runnable { * @exception BundleException * If the action throws an error. */ - protected AbstractBundle installWorker(String location, PrivilegedExceptionAction action) throws BundleException { + protected AbstractBundle installWorker(String location, PrivilegedExceptionAction<AbstractBundle> action) throws BundleException { synchronized (installLock) { while (true) { /* Check that the bundle is not already installed. */ @@ -860,7 +861,7 @@ public class Framework implements EventPublisher, Runnable { } Thread current = Thread.currentThread(); /* Check for and make reservation */ - Thread reservation = (Thread) installLock.put(location, current); + Thread reservation = installLock.put(location, current); /* if the location is not already reserved */ if (reservation == null) { /* we have made the reservation and can continue */ @@ -885,7 +886,7 @@ public class Framework implements EventPublisher, Runnable { } /* Don't call adaptor while holding the install lock */ try { - AbstractBundle bundle = (AbstractBundle) AccessController.doPrivileged(action); + AbstractBundle bundle = AccessController.doPrivileged(action); publishBundleEvent(BundleEvent.INSTALLED, bundle); return bundle; } catch (PrivilegedActionException e) { @@ -933,7 +934,7 @@ public class Framework implements EventPublisher, Runnable { 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() { + AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { public Object run() throws Exception { checkAdminPermission(bundle, AdminPermission.LIFECYCLE); if (extension) // need special permission to install extension bundles @@ -1035,7 +1036,7 @@ public class Framework implements EventPublisher, Runnable { */ protected AbstractBundle[] getAllBundles() { synchronized (bundles) { - List allBundles = bundles.getBundles(); + List<AbstractBundle> allBundles = bundles.getBundles(); int size = allBundles.size(); if (size == 0) { return (null); @@ -1162,17 +1163,17 @@ public class Framework implements EventPublisher, Runnable { final String finalLocation = location; //Bundle.getLocation requires AdminPermission (metadata) - return (AbstractBundle) AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { - List allBundles = bundles.getBundles(); + 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 = (AbstractBundle) allBundles.get(i); + AbstractBundle bundle = allBundles.get(i); if (finalLocation.equals(bundle.getLocation())) { - return (bundle); + return bundle; } } - return (null); + return null; } }); } @@ -1204,7 +1205,7 @@ public class Framework implements EventPublisher, Runnable { * parameter. */ protected File getDataFile(final AbstractBundle bundle, final String filename) { - return (File) AccessController.doPrivileged(new GetDataFileAction(bundle, filename)); + return AccessController.doPrivileged(new GetDataFileAction(bundle, filename)); } /** @@ -1221,12 +1222,12 @@ public class Framework implements EventPublisher, Runnable { private AdminPermission getAdminPermission(Bundle bundle, String action) { synchronized (adminPermissions) { Long ID = new Long(bundle.getBundleId()); - HashMap bundlePermissions = (HashMap) adminPermissions.get(ID); + Map<String, AdminPermission> bundlePermissions = adminPermissions.get(ID); if (bundlePermissions == null) { - bundlePermissions = new HashMap(); + bundlePermissions = new HashMap<String, AdminPermission>(); adminPermissions.put(ID, bundlePermissions); } - AdminPermission result = (AdminPermission) bundlePermissions.get(action); + AdminPermission result = bundlePermissions.get(action); if (result == null) { result = new AdminPermission(bundle, action); bundlePermissions.put(action, result); @@ -1251,7 +1252,7 @@ public class Framework implements EventPublisher, Runnable { else { // try to use a specific classloader by classname try { - Class clazz = Class.forName(securityManager); + Class<?> clazz = Class.forName(securityManager); sm = (SecurityManager) clazz.newInstance(); } catch (ClassNotFoundException e) { // do nothing @@ -1277,7 +1278,7 @@ public class Framework implements EventPublisher, Runnable { synchronized (allFrameworkListeners) { CopyOnWriteIdentityMap<FrameworkListener, FrameworkListener> listeners = allFrameworkListeners.get(context); if (listeners == null) { - listeners = new CopyOnWriteIdentityMap(); + listeners = new CopyOnWriteIdentityMap<FrameworkListener, FrameworkListener>(); allFrameworkListeners.put(context, listeners); } listeners.put(listener, listener); @@ -1318,14 +1319,14 @@ public class Framework implements EventPublisher, Runnable { publishFrameworkEvent(type, bundle, throwable, (FrameworkListener[]) null); } - public void publishFrameworkEvent(int type, org.osgi.framework.Bundle bundle, Throwable throwable, final FrameworkListener... listeners) { + 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() { + AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { publishFrameworkEventPrivileged(event, listeners); return null; @@ -1355,22 +1356,26 @@ public class Framework implements EventPublisher, Runnable { // If framework event hook were defined they would be called here // deliver the event to the snapshot - ListenerQueue queue = newListenerQueue(); + 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(); + 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) - queue.queueListeners(listeners.entrySet(), getSystemBundleContext()); + 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()) { - EventDispatcher dispatcher = entry.getKey(); + @SuppressWarnings({"rawtypes", "unchecked"}) + EventDispatcher<FrameworkListener, FrameworkListener, FrameworkEvent> dispatcher = (EventDispatcher) entry.getKey(); Set<Map.Entry<FrameworkListener, FrameworkListener>> listeners = entry.getValue(); queue.queueListeners(listeners, dispatcher); } @@ -1384,7 +1389,7 @@ public class Framework implements EventPublisher, Runnable { synchronized (allSyncBundleListeners) { CopyOnWriteIdentityMap<SynchronousBundleListener, SynchronousBundleListener> listeners = allSyncBundleListeners.get(context); if (listeners == null) { - listeners = new CopyOnWriteIdentityMap(); + listeners = new CopyOnWriteIdentityMap<SynchronousBundleListener, SynchronousBundleListener>(); allSyncBundleListeners.put(context, listeners); } listeners.put((SynchronousBundleListener) listener, (SynchronousBundleListener) listener); @@ -1393,7 +1398,7 @@ public class Framework implements EventPublisher, Runnable { synchronized (allBundleListeners) { CopyOnWriteIdentityMap<BundleListener, BundleListener> listeners = allBundleListeners.get(context); if (listeners == null) { - listeners = new CopyOnWriteIdentityMap(); + listeners = new CopyOnWriteIdentityMap<BundleListener, BundleListener>(); allBundleListeners.put(context, listeners); } listeners.put(listener, listener); @@ -1432,7 +1437,7 @@ public class Framework implements EventPublisher, Runnable { if (System.getSecurityManager() == null) { publishBundleEventPrivileged(event); } else { - AccessController.doPrivileged(new PrivilegedAction() { + AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { publishBundleEventPrivileged(event); return null; @@ -1487,9 +1492,10 @@ public class Framework implements EventPublisher, Runnable { /* Dispatch the event to the snapshot for sync listeners */ if (!listenersSync.isEmpty()) { - ListenerQueue queue = newListenerQueue(); + ListenerQueue<SynchronousBundleListener, SynchronousBundleListener, BundleEvent> queue = newListenerQueue(); for (Map.Entry<BundleContextImpl, Set<Map.Entry<SynchronousBundleListener, SynchronousBundleListener>>> entry : listenersSync.entrySet()) { - EventDispatcher dispatcher = entry.getKey(); + @SuppressWarnings({"rawtypes", "unchecked"}) + EventDispatcher<SynchronousBundleListener, SynchronousBundleListener, BundleEvent> dispatcher = (EventDispatcher) entry.getKey(); Set<Map.Entry<SynchronousBundleListener, SynchronousBundleListener>> listeners = entry.getValue(); queue.queueListeners(listeners, dispatcher); } @@ -1498,9 +1504,10 @@ public class Framework implements EventPublisher, Runnable { /* Dispatch the event to the snapshot for async listeners */ if ((listenersAsync != null) && !listenersAsync.isEmpty()) { - ListenerQueue queue = newListenerQueue(); + ListenerQueue<BundleListener, BundleListener, BundleEvent> queue = newListenerQueue(); for (Map.Entry<BundleContextImpl, Set<Map.Entry<BundleListener, BundleListener>>> entry : listenersAsync.entrySet()) { - EventDispatcher dispatcher = entry.getKey(); + @SuppressWarnings({"rawtypes", "unchecked"}) + EventDispatcher<BundleListener, BundleListener, BundleEvent> dispatcher = (EventDispatcher) entry.getKey(); Set<Map.Entry<BundleListener, BundleListener>> listeners = entry.getValue(); queue.queueListeners(listeners, dispatcher); } @@ -1543,8 +1550,8 @@ public class Framework implements EventPublisher, Runnable { }); } - public ListenerQueue newListenerQueue() { - return new ListenerQueue(eventManager); + public <K, V, E> ListenerQueue<K, V, E> newListenerQueue() { + return new ListenerQueue<K, V, E>(eventManager); } private void initializeContextFinder() { @@ -1576,7 +1583,7 @@ public class Framework implements EventPublisher, Runnable { } - public static Field getField(Class clazz, Class type, boolean instance) { + 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()); @@ -1670,7 +1677,8 @@ public class Framework implements EventPublisher, Runnable { private static void resetContentHandlers() throws IllegalAccessException { Field handlersField = getField(URLConnection.class, Hashtable.class, false); if (handlersField != null) { - Hashtable handlers = (Hashtable) handlersField.get(null); + @SuppressWarnings("rawtypes") + Hashtable<?, ?> handlers = (Hashtable) handlersField.get(null); if (handlers != null) handlers.clear(); } @@ -1767,7 +1775,8 @@ public class Framework implements EventPublisher, Runnable { private static void resetURLStreamHandlers() throws IllegalAccessException { Field handlersField = getField(URL.class, Hashtable.class, false); if (handlersField != null) { - Hashtable handlers = (Hashtable) handlersField.get(null); + @SuppressWarnings("rawtypes") + Hashtable<?, ?> handlers = (Hashtable) handlersField.get(null); if (handlers != null) handlers.clear(); } @@ -1828,7 +1837,7 @@ public class Framework implements EventPublisher, Runnable { * @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) { + public boolean isServiceAssignableTo(Bundle registrant, Bundle client, String className, Class<?> serviceClass) { // always return false for fragments AbstractBundle consumer = (AbstractBundle) client; if (consumer.isFragment()) @@ -1869,7 +1878,7 @@ public class Framework implements EventPublisher, Runnable { return producerSource.hasCommonSource(consumerSource); } - private PackageSource getPackageSource(Class serviceClass, String pkgName) { + private PackageSource getPackageSource(Class<?> serviceClass, String pkgName) { if (serviceClass == null) return null; AbstractBundle serviceBundle = (AbstractBundle) packageAdmin.getBundle(serviceClass); @@ -1882,7 +1891,7 @@ public class Framework implements EventPublisher, Runnable { if (producerSource != null) return producerSource; // try the interfaces - Class[] interfaces = serviceClass.getInterfaces(); + Class<?>[] interfaces = serviceClass.getInterfaces(); // note that getInterfaces never returns null for (int i = 0; i < interfaces.length; i++) { producerSource = getPackageSource(interfaces[i], pkgName); @@ -1908,8 +1917,8 @@ public class Framework implements EventPublisher, Runnable { } SignedContentFactory getSignedContentFactory() { - ServiceTracker currentTracker = signedContentFactory; - return (SignedContentFactory) (currentTracker == null ? null : currentTracker.getService()); + ServiceTracker<SignedContentFactory, SignedContentFactory> currentTracker = signedContentFactory; + return (currentTracker == null ? null : currentTracker.getService()); } ContextFinder getContextFinder() { 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 index 992411800..ad4da2ac6 100644 --- 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 @@ -30,18 +30,18 @@ import org.osgi.framework.wiring.FrameworkWiring; */ public class InternalSystemBundle extends BundleHost implements org.osgi.framework.launch.Framework { - class SystemBundleHeaders extends Dictionary { - private final Dictionary headers; + class SystemBundleHeaders extends Dictionary<String, String> { + private final Dictionary<String, String> headers; - public SystemBundleHeaders(Dictionary headers) { + public SystemBundleHeaders(Dictionary<String, String> headers) { this.headers = headers; } - public Enumeration elements() { + public Enumeration<String> elements() { return headers.elements(); } - public Object get(Object key) { + public String get(Object key) { if (!(key instanceof String)) return null; if (org.osgi.framework.Constants.EXPORT_PACKAGE.equalsIgnoreCase((String) key)) { @@ -59,7 +59,7 @@ public class InternalSystemBundle extends BundleHost implements org.osgi.framewo systemValue = systemExtraValue; else if (systemExtraValue != null) systemValue += ", " + systemExtraValue; //$NON-NLS-1$ - String result = (String) headers.get(header); + String result = headers.get(header); if (systemValue != null) { if (result != null) result += ", " + systemValue; //$NON-NLS-1$ @@ -73,15 +73,15 @@ public class InternalSystemBundle extends BundleHost implements org.osgi.framewo return headers.isEmpty(); } - public Enumeration keys() { + public Enumeration<String> keys() { return headers.keys(); } - public Object put(Object key, Object value) { + public String put(String key, String value) { return headers.put(key, value); } - public Object remove(Object key) { + public String remove(Object key) { return headers.remove(key); } @@ -171,7 +171,7 @@ public class InternalSystemBundle extends BundleHost implements org.osgi.framewo * @return the resulting Class * @exception java.lang.ClassNotFoundException if the class definition was not found. */ - protected Class loadClass(String name, boolean checkPermission) throws ClassNotFoundException { + protected Class<?> loadClass(String name, boolean checkPermission) throws ClassNotFoundException { if (checkPermission) { framework.checkAdminPermission(this, AdminPermission.CLASS); checkValid(); @@ -383,7 +383,7 @@ public class InternalSystemBundle extends BundleHost implements org.osgi.framewo // Do nothing } - public Dictionary getHeaders(String localeString) { + public Dictionary<String, String> getHeaders(String localeString) { return new SystemBundleHeaders(super.getHeaders(localeString)); } @@ -399,6 +399,7 @@ public class InternalSystemBundle extends BundleHost implements org.osgi.framewo return getClass().getClassLoader(); } + @SuppressWarnings("unchecked") @Override public <A> A adapt(Class<A> adapterType) { if (FrameworkStartLevel.class.equals(adapterType)) 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 index f0130d3f9..62fb27c85 100644 --- 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 @@ -23,16 +23,16 @@ import org.osgi.framework.Constants; */ public class ManifestLocalization { private AbstractBundle bundle = null; - private Dictionary rawHeaders = null; - private Dictionary defaultLocaleHeaders = null; - private Hashtable cache = new Hashtable(5); + private Dictionary<String, String> rawHeaders = null; + private Dictionary<String, String> defaultLocaleHeaders = null; + private Hashtable<String, BundleResourceBundle> cache = new Hashtable<String, BundleResourceBundle>(5); - public ManifestLocalization(AbstractBundle bundle, Dictionary rawHeaders) { + public ManifestLocalization(AbstractBundle bundle, Dictionary<String, String> rawHeaders) { this.bundle = bundle; this.rawHeaders = rawHeaders; } - protected Dictionary getHeaders(String localeString) { + protected Dictionary<String, String> getHeaders(String localeString) { if (localeString.length() == 0) return (rawHeaders); boolean isDefaultLocale = false; @@ -54,11 +54,11 @@ public class ManifestLocalization { if (localeProperties == null && !isDefaultLocale) // could not find the requested locale use the default locale localeProperties = getResourceBundle(defaultLocale); - Enumeration e = this.rawHeaders.keys(); - Headers localeHeaders = new Headers(this.rawHeaders.size()); + Enumeration<String> e = this.rawHeaders.keys(); + Headers<String, String> localeHeaders = new Headers<String, String>(this.rawHeaders.size()); while (e.hasMoreElements()) { - String key = (String) e.nextElement(); - String value = (String) this.rawHeaders.get(key); + 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 { @@ -77,14 +77,14 @@ public class ManifestLocalization { } private String[] buildNLVariants(String nl) { - ArrayList result = new ArrayList(); + 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 (String[]) result.toArray(new String[result.size()]); + return result.toArray(new String[result.size()]); } /* @@ -92,12 +92,12 @@ public class ManifestLocalization { * bundle. If not found, return null. */ protected ResourceBundle getResourceBundle(String localeString) { - String propertiesLocation = (String) rawHeaders.get(Constants.BUNDLE_LOCALIZATION); + String propertiesLocation = rawHeaders.get(Constants.BUNDLE_LOCALIZATION); if (propertiesLocation == null) { propertiesLocation = Constants.BUNDLE_LOCALIZATION_DEFAULT_BASENAME; } - BundleResourceBundle result = (BundleResourceBundle) cache.get(localeString); + BundleResourceBundle result = cache.get(localeString); if (result != null) return (ResourceBundle) (result.isEmpty() ? null : result); String[] nlVarients = buildNLVariants(localeString); @@ -106,7 +106,7 @@ public class ManifestLocalization { BundleResourceBundle varientBundle = null; URL varientURL = findResource(propertiesLocation + (nlVarients[i].equals("") ? nlVarients[i] : '_' + nlVarients[i]) + ".properties"); //$NON-NLS-1$ //$NON-NLS-2$ if (varientURL == null) { - varientBundle = (BundleResourceBundle) cache.get(nlVarients[i]); + varientBundle = cache.get(nlVarients[i]); } else { InputStream resourceStream = null; try { @@ -133,7 +133,7 @@ public class ManifestLocalization { cache.put(nlVarients[i], varientBundle); parent = varientBundle; } - result = (BundleResourceBundle) cache.get(localeString); + result = cache.get(localeString); return (ResourceBundle) (result.isEmpty() ? null : result); } @@ -189,7 +189,7 @@ public class ManifestLocalization { } class EmptyResouceBundle extends ResourceBundle implements BundleResourceBundle { - public Enumeration getKeys() { + public Enumeration<String> getKeys() { return null; } 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 index 691531066..b50d60ede 100644 --- 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 @@ -52,28 +52,28 @@ import org.osgi.service.packageadmin.*; public class PackageAdminImpl implements PackageAdmin, FrameworkWiring { /** framework object */ protected Framework framework; - private Map<Long, List<BundleData>> removalPendings = new HashMap(); + private Map<Long, List<BundleData>> removalPendings = new HashMap<Long, List<BundleData>>(); /* * We need to make sure that the GetBundleAction class loads early to prevent a ClassCircularityError when checking permissions. * See bug 161561 */ static { - Class c; + Class<?> c; c = GetBundleAction.class; c.getName(); // to prevent compiler warnings } - static class GetBundleAction implements PrivilegedAction { - private Class clazz; + static class GetBundleAction implements PrivilegedAction<Bundle> { + private Class<?> clazz; private PackageAdminImpl impl; - public GetBundleAction(PackageAdminImpl impl, Class clazz) { + public GetBundleAction(PackageAdminImpl impl, Class<?> clazz) { this.impl = impl; this.clazz = clazz; } - public Object run() { + public Bundle run() { return impl.getBundlePriv(clazz); } } @@ -88,7 +88,7 @@ public class PackageAdminImpl implements PackageAdmin, FrameworkWiring { } public ExportedPackage[] getExportedPackages(Bundle bundle) { - ArrayList allExports = new ArrayList(); + List<ExportedPackage> allExports = new ArrayList<ExportedPackage>(); FrameworkAdaptor adaptor = framework.adaptor; if (adaptor == null) return null; @@ -100,7 +100,7 @@ public class PackageAdminImpl implements PackageAdmin, FrameworkWiring { if (bundle == null || exportedPackage.getBundle() == bundle) allExports.add(exportedPackage); } - return (ExportedPackage[]) (allExports.size() == 0 ? null : allExports.toArray(new ExportedPackage[allExports.size()])); + return (allExports.size() == 0 ? null : allExports.toArray(new ExportedPackage[allExports.size()])); } private ExportedPackageImpl createExportedPackage(ExportPackageDescription description) { @@ -141,11 +141,11 @@ public class PackageAdminImpl implements PackageAdmin, FrameworkWiring { ExportedPackage[] allExports = getExportedPackages((Bundle) null); if (allExports == null) return null; - ArrayList result = new ArrayList(1); // rare to have more than one + 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 (ExportedPackage[]) (result.size() == 0 ? null : result.toArray(new ExportedPackage[result.size()])); + return (result.size() == 0 ? null : result.toArray(new ExportedPackage[result.size()])); } public void refreshPackages(Bundle[] input) { @@ -211,7 +211,7 @@ public class PackageAdminImpl implements PackageAdmin, FrameworkWiring { populateLoaders(framework.getAllBundles()); synchronized (framework.bundles) { // now collect the descriptions to refresh - ArrayList results = new ArrayList(numBundles); + List<BundleDescription> results = new ArrayList<BundleDescription>(numBundles); BundleDelta[] addDeltas = null; for (int i = 0; i < numBundles; i++) { BundleDescription description = bundles[i].getBundleDescription(); @@ -232,7 +232,7 @@ public class PackageAdminImpl implements PackageAdmin, FrameworkWiring { } } } - descriptions = (BundleDescription[]) (results.size() == 0 ? null : results.toArray(new BundleDescription[results.size()])); + descriptions = (results.size() == 0 ? null : results.toArray(new BundleDescription[results.size()])); } } BundleDelta[] delta = systemState.resolve(descriptions).getChanges(); @@ -384,9 +384,9 @@ public class PackageAdminImpl implements PackageAdmin, FrameworkWiring { } private void applyDeltas(BundleDelta[] bundleDeltas) throws BundleException { - Arrays.sort(bundleDeltas, new Comparator() { - public int compare(Object delta0, Object delta1) { - return (int) (((BundleDelta) delta0).getBundle().getBundleId() - ((BundleDelta) delta1).getBundle().getBundleId()); + 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++) { @@ -410,7 +410,7 @@ public class PackageAdminImpl implements PackageAdmin, FrameworkWiring { } private AbstractBundle[] processDelta(BundleDelta[] bundleDeltas, boolean refreshPackages, State systemState) { - ArrayList bundlesList = new ArrayList(bundleDeltas.length); + 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) @@ -420,7 +420,7 @@ public class PackageAdminImpl implements PackageAdmin, FrameworkWiring { if (changedBundle != null && !bundlesList.contains(changedBundle)) bundlesList.add(changedBundle); } - AbstractBundle[] refresh = (AbstractBundle[]) bundlesList.toArray(new AbstractBundle[bundlesList.size()]); + 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 @@ -557,14 +557,14 @@ public class PackageAdminImpl implements PackageAdmin, FrameworkWiring { if (bundles == null || bundles.length == 0) return null; - ArrayList result = new ArrayList(bundles.length); + 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 : (RequiredBundle[]) result.toArray(new RequiredBundle[result.size()]); + return result.size() == 0 ? null : result.toArray(new RequiredBundle[result.size()]); } public Bundle[] getBundles(String symbolicName, String versionRange) { @@ -583,7 +583,7 @@ public class PackageAdminImpl implements PackageAdmin, FrameworkWiring { // This code depends on the array of bundles being in descending // version order. - ArrayList result = new ArrayList(bundles.length); + 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())) { @@ -593,7 +593,7 @@ public class PackageAdminImpl implements PackageAdmin, FrameworkWiring { if (result.size() == 0) return null; - return (AbstractBundle[]) result.toArray(new AbstractBundle[result.size()]); + return result.toArray(new AbstractBundle[result.size()]); } public Bundle[] getFragments(Bundle bundle) { @@ -611,7 +611,7 @@ public class PackageAdminImpl implements PackageAdmin, FrameworkWiring { return result; } - Bundle getBundlePriv(Class clazz) { + Bundle getBundlePriv(Class<?> clazz) { ClassLoader cl = clazz.getClassLoader(); if (cl instanceof BundleClassLoader) { ClassLoaderDelegate delegate = ((BundleClassLoader) cl).getDelegate(); @@ -623,10 +623,10 @@ public class PackageAdminImpl implements PackageAdmin, FrameworkWiring { return null; } - public Bundle getBundle(final Class clazz) { + public Bundle getBundle(@SuppressWarnings("rawtypes") final Class clazz) { if (System.getSecurityManager() == null) return getBundlePriv(clazz); - return (Bundle) AccessController.doPrivileged(new GetBundleAction(this, clazz)); + return AccessController.doPrivileged(new GetBundleAction(this, clazz)); } public int getBundleType(Bundle bundle) { @@ -636,11 +636,10 @@ public class PackageAdminImpl implements PackageAdmin, FrameworkWiring { protected void cleanup() { //This is only called when the framework is shutting down synchronized (removalPendings) { - for (Iterator pendings = removalPendings.values().iterator(); pendings.hasNext();) { - List removals = (List) pendings.next(); - for (Iterator iRemovals = removals.iterator(); iRemovals.hasNext();) + for (List<BundleData> removals : removalPendings.values()) { + for (BundleData data : removals) try { - ((BundleData) iRemovals.next()).close(); + data.close(); } catch (IOException e) { // ignore } @@ -720,7 +719,7 @@ public class PackageAdminImpl implements PackageAdmin, FrameworkWiring { Long id = new Long(bundledata.getBundleID()); List<BundleData> removals = removalPendings.get(id); if (removals == null) { - removals = new ArrayList(1); + removals = new ArrayList<BundleData>(1); removalPendings.put(id, removals); } removals.add(bundledata); 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 index 2b5d620dd..e9396cf7f 100644 --- 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 @@ -32,9 +32,9 @@ import org.osgi.service.startlevel.StartLevel; * If present, there will only be a single instance of this service * registered in the framework. */ -public class StartLevelManager implements EventDispatcher, EventListener, StartLevel { +public class StartLevelManager implements EventDispatcher<Object, Object, StartLevelEvent>, StartLevel { protected static EventManager eventManager; - protected static Map startLevelListeners; + protected static Map<Object, Object> startLevelListeners; /** The initial bundle start level for newly installed bundles */ protected int initialBundleStartLevel = 1; @@ -58,7 +58,7 @@ public class StartLevelManager implements EventDispatcher, EventListener, StartL // 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(); + startLevelListeners = new CopyOnWriteIdentityMap<Object, Object>(); startLevelListeners.put(this, this); } @@ -370,7 +370,7 @@ public class StartLevelManager implements EventDispatcher, EventListener, StartL final AbstractBundle b = (AbstractBundle) bundle; b.getBundleData().setStartLevel(newSL); try { - AccessController.doPrivileged(new PrivilegedExceptionAction() { + AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { public Object run() throws Exception { b.getBundleData().save(); return null; @@ -399,7 +399,7 @@ public class StartLevelManager implements EventDispatcher, EventListener, StartL private void issueEvent(StartLevelEvent sle) { /* queue to hold set of listeners */ - ListenerQueue queue = new ListenerQueue(eventManager); + ListenerQueue<Object, Object, StartLevelEvent> queue = new ListenerQueue<Object, Object, StartLevelEvent>(eventManager); /* add set of StartLevelListeners to queue */ queue.queueListeners(startLevelListeners.entrySet(), this); @@ -428,9 +428,8 @@ public class StartLevelManager implements EventDispatcher, EventListener, StartL * 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, Object eventObject) { + public void dispatchEvent(Object listener, Object listenerObject, int eventAction, StartLevelEvent event) { try { - StartLevelEvent event = (StartLevelEvent) eventObject; switch (eventAction) { case StartLevelEvent.CHANGE_BUNDLE_SL : setBundleSL(event); @@ -470,7 +469,7 @@ public class StartLevelManager implements EventDispatcher, EventListener, StartL AbstractBundle[] installedBundles; synchronized (bundles) { - List allBundles = bundles.getBundles(); + List<AbstractBundle> allBundles = bundles.getBundles(); installedBundles = new AbstractBundle[allBundles.size()]; allBundles.toArray(installedBundles); @@ -510,8 +509,8 @@ public class StartLevelManager implements EventDispatcher, EventListener, StartL private void sortByDependencies(AbstractBundle[] bundles, int start, int end) { if (end - start <= 1) return; - List descList = new ArrayList(end - start); - List missingDescs = new ArrayList(0); + 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) @@ -521,14 +520,14 @@ public class StartLevelManager implements EventDispatcher, EventListener, StartL } if (descList.size() <= 1) return; - BundleDescription[] descriptions = (BundleDescription[]) descList.toArray(new BundleDescription[descList.size()]); + 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 missing = missingDescs.iterator(); + Iterator<AbstractBundle> missing = missingDescs.iterator(); for (int i = start + descriptions.length; i < end && missing.hasNext(); i++) - bundles[i] = (AbstractBundle) missing.next(); + bundles[i] = missing.next(); } } @@ -644,11 +643,11 @@ public class StartLevelManager implements EventDispatcher, EventListener, StartL private void unloadAllBundles(BundleRepository bundles) { synchronized (bundles) { /* unload all installed bundles */ - List allBundles = bundles.getBundles(); + List<AbstractBundle> allBundles = bundles.getBundles(); int size = allBundles.size(); for (int i = 0; i < size; i++) { - AbstractBundle bundle = (AbstractBundle) allBundles.get(i); + AbstractBundle bundle = allBundles.get(i); if (Debug.DEBUG_STARTLEVEL) { Debug.println("SLL: Trying to unload bundle " + bundle); //$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 index 468ad2d88..b3b71a674 100644 --- 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 @@ -27,11 +27,11 @@ 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; + 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; @@ -51,7 +51,7 @@ public class SystemBundleActivator implements BundleActivator { } ClassLoader tccl = framework.getContextFinder(); if (tccl != null) { - Hashtable props = new Hashtable(7); + 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); } @@ -97,10 +97,10 @@ public class SystemBundleActivator implements BundleActivator { * Register a service object. * */ - private ServiceRegistration register(String[] names, Object service, Hashtable properties) { + private ServiceRegistration<?> register(String[] names, Object service, Dictionary<String, Object> properties) { if (properties == null) - properties = new Hashtable(7); - Dictionary headers = bundle.getHeaders(); + 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$ 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 index de5683cc1..63ccfd2d7 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2003, 2009 IBM Corporation and others. + * 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 @@ -92,6 +92,7 @@ public class Util { * @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) @@ -100,7 +101,7 @@ public class Util { sort(array, middle, end); if (start + 1 >= end) return; // this case can only happen when this method is called by the user - if (((Comparable) array[middle - 1]).compareTo(array[middle]) <= 0) + if (((Comparable<Object>) array[middle - 1]).compareTo(array[middle]) <= 0) return; if (start + 2 == end) { Object temp = array[start]; @@ -111,7 +112,7 @@ public class Util { int i1 = start, i2 = middle, i3 = 0; Object[] merge = new Object[end - start]; while (i1 < middle && i2 < end) { - merge[i3++] = ((Comparable) array[i1]).compareTo(array[i2]) <= 0 ? array[i1++] : array[i2++]; + 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); 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 index 5e296dd82..552eb3276 100644 --- 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 @@ -20,6 +20,7 @@ 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; @@ -32,24 +33,24 @@ import org.osgi.util.tracker.ServiceTracker; */ // 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 contentHandlerTracker; + 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 ignoredClasses = Arrays.asList(new Class[] {MultiplexingContentHandler.class, ContentHandlerFactory.class, URLConnection.class}); + private static final List<Class<?>> ignoredClasses = Arrays.asList(new Class<?>[] {MultiplexingContentHandler.class, ContentHandlerFactory.class, URLConnection.class}); - private Hashtable proxies; + private Map<String, ContentHandlerProxy> proxies; private java.net.ContentHandlerFactory parentFactory; public ContentHandlerFactory(BundleContext context, FrameworkAdaptor adaptor) { super(context, adaptor); - proxies = new Hashtable(5); + proxies = new Hashtable<String, ContentHandlerProxy>(5); //We need to track content handler registrations - contentHandlerTracker = new ServiceTracker(context, contentHandlerClazz, null); + contentHandlerTracker = new ServiceTracker<ContentHandler, ContentHandler>(context, contentHandlerClazz, null); contentHandlerTracker.open(); } @@ -62,7 +63,7 @@ public class ContentHandlerFactory extends MultiplexingFactory implements java.n //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; + Class<?> clazz = null; if (builtInHandlers != null) { //replace '/' with a '.' and all characters not allowed in a java class name //with a '_'. @@ -96,11 +97,11 @@ public class ContentHandlerFactory extends MultiplexingFactory implements java.n public ContentHandler createInternalContentHandler(String contentType) { //first check to see if the handler is in the cache - ContentHandlerProxy proxy = (ContentHandlerProxy) proxies.get(contentType); + ContentHandlerProxy proxy = proxies.get(contentType); if (proxy != null) { return (proxy); } - org.osgi.framework.ServiceReference[] serviceReferences = contentHandlerTracker.getServiceReferences(); + 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); 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 index 54021ccea..b60b7940c 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2003, 2008 IBM Corporation and others. + * 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 @@ -27,20 +27,20 @@ import org.osgi.util.tracker.ServiceTrackerCustomizer; * because the JVM caches ContentHandlers and therefore would not support a dynamic environment of * ContentHandlers being registered and unregistered. */ -public class ContentHandlerProxy extends ContentHandler implements ServiceTrackerCustomizer { +public class ContentHandlerProxy extends ContentHandler implements ServiceTrackerCustomizer<ContentHandler, ServiceReference<ContentHandler>> { protected ContentHandler realHandler; //TODO avoid type-based names - protected ServiceTracker contentHandlerServiceTracker; + protected ServiceTracker<ContentHandler, ServiceReference<ContentHandler>> contentHandlerServiceTracker; protected BundleContext context; - protected ServiceReference contentHandlerServiceReference; + protected ServiceReference<ContentHandler> contentHandlerServiceReference; protected String contentType; protected int ranking = Integer.MIN_VALUE; - public ContentHandlerProxy(String contentType, ServiceReference reference, BundleContext context) { + public ContentHandlerProxy(String contentType, ServiceReference<ContentHandler> reference, BundleContext context) { this.context = context; this.contentType = contentType; @@ -48,11 +48,11 @@ public class ContentHandlerProxy extends ContentHandler implements ServiceTracke // until a real ContentHandler for this mime-type is registered setNewHandler(reference, getRank(reference)); - contentHandlerServiceTracker = new ServiceTracker(context, ContentHandler.class.getName(), this); + contentHandlerServiceTracker = new ServiceTracker<ContentHandler, ServiceReference<ContentHandler>>(context, ContentHandler.class.getName(), this); StreamHandlerFactory.secureAction.open(contentHandlerServiceTracker); } - private void setNewHandler(ServiceReference reference, int rank) { + private void setNewHandler(ServiceReference<ContentHandler> reference, int rank) { if (contentHandlerServiceReference != null) context.ungetService(contentHandlerServiceReference); @@ -62,13 +62,13 @@ public class ContentHandlerProxy extends ContentHandler implements ServiceTracke if (reference == null) realHandler = new DefaultContentHandler(); else - realHandler = (ContentHandler) StreamHandlerFactory.secureAction.getService(reference, context); + realHandler = StreamHandlerFactory.secureAction.getService(reference, context); } /** * @see org.osgi.util.tracker.ServiceTrackerCustomizer#addingService(ServiceReference) */ - public Object addingService(ServiceReference reference) { + 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[])) @@ -92,14 +92,14 @@ public class ContentHandlerProxy extends ContentHandler implements ServiceTracke * @see org.osgi.util.tracker.ServiceTrackerCustomizer#modifiedService(ServiceReference, Object) */ - public void modifiedService(ServiceReference reference, Object service) { + 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 newReference = contentHandlerServiceTracker.getServiceReference(); + ServiceReference<ContentHandler> newReference = contentHandlerServiceTracker.getServiceReference(); if (newReference != contentHandlerServiceReference && newReference != null) { setNewHandler(newReference, ((Integer) newReference.getProperty(Constants.SERVICE_RANKING)).intValue()); } @@ -114,13 +114,13 @@ public class ContentHandlerProxy extends ContentHandler implements ServiceTracke /** * @see org.osgi.util.tracker.ServiceTrackerCustomizer#removedService(ServiceReference, Object) */ - public void removedService(ServiceReference reference, Object service) { + 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 newReference = contentHandlerServiceTracker.getServiceReference(); + ServiceReference<ContentHandler> newReference = contentHandlerServiceTracker.getServiceReference(); // if newReference == null then we will use the DefaultContentHandler here setNewHandler(newReference, getRank(newReference)); } @@ -133,7 +133,7 @@ public class ContentHandlerProxy extends ContentHandler implements ServiceTracke return realHandler.getContent(uConn); } - private int getRank(ServiceReference reference) { + private int getRank(ServiceReference<?> reference) { if (reference == null) return Integer.MIN_VALUE; Object property = reference.getProperty(Constants.SERVICE_RANKING); 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 index 33685262a..648292324 100644 --- 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 @@ -9,10 +9,12 @@ package org.eclipse.osgi.framework.internal.protocol; import java.lang.reflect.Method; -import java.util.*; +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; @@ -25,12 +27,12 @@ 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 factories; // list of multiplexed factories - private ServiceTracker packageAdminTracker; + 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() { + public Class<?>[] getClassContext() { return super.getClassContext(); } } @@ -40,7 +42,7 @@ public abstract class MultiplexingFactory { MultiplexingFactory(BundleContext context, FrameworkAdaptor adaptor) { this.context = context; this.adaptor = adaptor; - packageAdminTracker = new ServiceTracker(context, PACKAGEADMINCLASS, null); + packageAdminTracker = new ServiceTracker<ServiceReference<?>, PackageAdmin>(context, PACKAGEADMINCLASS, null); packageAdminTracker.open(); } @@ -55,7 +57,7 @@ public abstract class MultiplexingFactory { public void register(Object factory) { // set parent for each factory so they can do proper delegation try { - Class clazz = factory.getClass(); + 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) { @@ -80,7 +82,7 @@ public abstract class MultiplexingFactory { } public Object designateSuccessor() { - List released = releaseFactories(); + 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 @@ -93,10 +95,10 @@ public abstract class MultiplexingFactory { return getParentFactory(); Object successor = released.remove(0); try { - Class clazz = successor.getClass(); + Class<?> clazz = successor.getClass(); Method register = clazz.getMethod("register", new Class[] {Object.class}); //$NON-NLS-1$ - for (Iterator it = released.iterator(); it.hasNext();) { - register.invoke(successor, new Object[] {it.next()}); + 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$ @@ -110,19 +112,18 @@ public abstract class MultiplexingFactory { packageAdminTracker.close(); } - public Object findAuthorizedFactory(List ignoredClasses) { - List current = getFactories(); - Class[] classStack = internalSecurityManager.getClassContext(); + 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]; + 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 (Iterator it = current.iterator(); it.hasNext();) { - Object factory = it.next(); + 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()) { @@ -137,35 +138,35 @@ public abstract class MultiplexingFactory { return null; } - public boolean hasAuthority(Class clazz) { - PackageAdmin packageAdminService = (PackageAdmin) packageAdminTracker.getService(); + public boolean hasAuthority(Class<?> clazz) { + PackageAdmin packageAdminService = packageAdminTracker.getService(); if (packageAdminService != null) { return packageAdminService.getBundle(clazz) != null; } return false; } - private synchronized List getFactories() { + private synchronized List<Object> getFactories() { return factories; } - private synchronized List releaseFactories() { + private synchronized List<Object> releaseFactories() { if (factories == null) return null; - List released = new LinkedList(factories); + List<Object> released = new LinkedList<Object>(factories); factories = null; return released; } private synchronized void addFactory(Object factory) { - List updated = (factories == null) ? new LinkedList() : new LinkedList(factories); + List<Object> updated = (factories == null) ? new LinkedList<Object>() : new LinkedList<Object>(factories); updated.add(factory); factories = updated; } private synchronized void removeFactory(Object factory) { - List updated = new LinkedList(factories); + 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/StreamHandlerFactory.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/framework/internal/protocol/StreamHandlerFactory.java index 10c5d0372..df1a0fc25 100644 --- 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 @@ -22,25 +22,27 @@ 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 = (SecureAction) AccessController.doPrivileged(SecureAction.createSecureAction()); + static final SecureAction secureAction = AccessController.doPrivileged(SecureAction.createSecureAction()); - private ServiceTracker handlerTracker; + 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 ignoredClasses = Arrays.asList(new Class[] {MultiplexingURLStreamHandler.class, StreamHandlerFactory.class, URL.class}); + 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; + Class<?> clazz = null; try { clazz = Class.forName("java.net.Proxy"); //$NON-NLS-1$ } catch (ClassNotFoundException e) { @@ -48,9 +50,9 @@ public class StreamHandlerFactory extends MultiplexingFactory implements URLStre } useNetProxy = clazz != null; } - private Hashtable proxies; + private Map<String, URLStreamHandler> proxies; private URLStreamHandlerFactory parentFactory; - private ThreadLocal creatingProtocols = new ThreadLocal(); + private ThreadLocal<List<String>> creatingProtocols = new ThreadLocal<List<String>>(); /** * Create the factory. @@ -60,15 +62,15 @@ public class StreamHandlerFactory extends MultiplexingFactory implements URLStre public StreamHandlerFactory(BundleContext context, FrameworkAdaptor adaptor) { super(context, adaptor); - proxies = new Hashtable(15); - handlerTracker = new ServiceTracker(context, URLSTREAMHANDLERCLASS, null); + 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) { + private Class<?> getBuiltIn(String protocol, String builtInHandlers, boolean fromFramework) { if (builtInHandlers == null) return null; - Class clazz; + Class<?> clazz; StringTokenizer tok = new StringTokenizer(builtInHandlers, "|"); //$NON-NLS-1$ while (tok.hasMoreElements()) { StringBuffer name = new StringBuffer(); @@ -104,7 +106,7 @@ public class StreamHandlerFactory extends MultiplexingFactory implements URLStre try { //first check for built in handlers String builtInHandlers = secureAction.getProperty(PROTOCOL_HANDLER_PKGS); - Class clazz = getBuiltIn(protocol, builtInHandlers, false); + Class<?> clazz = getBuiltIn(protocol, builtInHandlers, false); if (clazz != null) return null; // let the VM handle it URLStreamHandler result = null; @@ -124,9 +126,9 @@ public class StreamHandlerFactory extends MultiplexingFactory implements URLStre } private boolean isRecursive(String protocol) { - List protocols = (List) creatingProtocols.get(); + List<String> protocols = creatingProtocols.get(); if (protocols == null) { - protocols = new ArrayList(1); + protocols = new ArrayList<String>(1); creatingProtocols.set(protocols); } if (protocols.contains(protocol)) @@ -136,7 +138,7 @@ public class StreamHandlerFactory extends MultiplexingFactory implements URLStre } private void releaseRecursive(String protocol) { - List protocols = (List) creatingProtocols.get(); + List<String> protocols = creatingProtocols.get(); protocols.remove(protocol); } @@ -144,7 +146,7 @@ public class StreamHandlerFactory extends MultiplexingFactory implements URLStre //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); + Class<?> clazz = getBuiltIn(protocol, internalHandlerPkgs, true); if (clazz == null) { //Now we check the service registry @@ -153,7 +155,7 @@ public class StreamHandlerFactory extends MultiplexingFactory implements URLStre if (handler != null) return (handler); //look through the service registry for a URLStramHandler registered for this protocol - org.osgi.framework.ServiceReference[] serviceReferences = handlerTracker.getServiceReferences(); + ServiceReference<URLStreamHandlerService>[] serviceReferences = handlerTracker.getServiceReferences(); if (serviceReferences == null) return null; for (int i = 0; i < serviceReferences.length; i++) { 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 index 48b9f7325..ddfaf80f3 100644 --- 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 @@ -17,10 +17,11 @@ 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 reference, BundleContext context) { + public URLStreamHandlerFactoryProxyFor15(String protocol, ServiceReference<URLStreamHandlerService> reference, BundleContext context) { super(protocol, reference, context); } 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 index ec441d627..cb0dc57ae 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2003, 2008 IBM Corporation and others. + * 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 @@ -29,22 +29,22 @@ import org.osgi.util.tracker.ServiceTrackerCustomizer; * and unregistered. */ -public class URLStreamHandlerProxy extends URLStreamHandler implements ServiceTrackerCustomizer { +public class URLStreamHandlerProxy extends URLStreamHandler implements ServiceTrackerCustomizer<URLStreamHandlerService, ServiceReference<URLStreamHandlerService>> { // TODO lots of type-based names protected URLStreamHandlerService realHandlerService; protected URLStreamHandlerSetter urlSetter; - protected ServiceTracker urlStreamHandlerServiceTracker; + protected ServiceTracker<URLStreamHandlerService, ServiceReference<URLStreamHandlerService>> urlStreamHandlerServiceTracker; protected BundleContext context; - protected ServiceReference urlStreamServiceReference; + protected ServiceReference<URLStreamHandlerService> urlStreamServiceReference; protected String protocol; protected int ranking = Integer.MIN_VALUE; - public URLStreamHandlerProxy(String protocol, ServiceReference reference, BundleContext context) { + public URLStreamHandlerProxy(String protocol, ServiceReference<URLStreamHandlerService> reference, BundleContext context) { this.context = context; this.protocol = protocol; @@ -53,11 +53,11 @@ public class URLStreamHandlerProxy extends URLStreamHandler implements ServiceTr //set the handler and ranking setNewHandler(reference, getRank(reference)); - urlStreamHandlerServiceTracker = new ServiceTracker(context, StreamHandlerFactory.URLSTREAMHANDLERCLASS, this); + urlStreamHandlerServiceTracker = new ServiceTracker<URLStreamHandlerService, ServiceReference<URLStreamHandlerService>>(context, StreamHandlerFactory.URLSTREAMHANDLERCLASS, this); StreamHandlerFactory.secureAction.open(urlStreamHandlerServiceTracker); } - private void setNewHandler(ServiceReference reference, int rank) { + private void setNewHandler(ServiceReference<URLStreamHandlerService> reference, int rank) { if (urlStreamServiceReference != null) context.ungetService(urlStreamServiceReference); @@ -67,7 +67,7 @@ public class URLStreamHandlerProxy extends URLStreamHandler implements ServiceTr if (reference == null) realHandlerService = new NullURLStreamHandlerService(); else - realHandlerService = (URLStreamHandlerService) StreamHandlerFactory.secureAction.getService(reference, context); + realHandlerService = StreamHandlerFactory.secureAction.getService(reference, context); } /** @@ -140,6 +140,7 @@ public class URLStreamHandlerProxy extends URLStreamHandler implements ServiceTr 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. @@ -150,7 +151,7 @@ public class URLStreamHandlerProxy extends URLStreamHandler implements ServiceTr /** * @see org.osgi.util.tracker.ServiceTrackerCustomizer#addingService(ServiceReference) */ - public Object addingService(ServiceReference reference) { + 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[])) @@ -162,26 +163,26 @@ public class URLStreamHandlerProxy extends URLStreamHandler implements ServiceTr int newServiceRanking = getRank(reference); if (newServiceRanking > ranking || urlStreamServiceReference == null) setNewHandler(reference, newServiceRanking); - return (reference); + return reference; } } //we don't want to continue hearing events about a URLStreamHandlerService not registered under our protocol - return (null); + 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 reference, Object service) { + 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 newReference = urlStreamHandlerServiceTracker.getServiceReference(); + ServiceReference<URLStreamHandlerService> newReference = urlStreamHandlerServiceTracker.getServiceReference(); if (newReference != urlStreamServiceReference && newReference != null) { setNewHandler(newReference, ((Integer) newReference.getProperty(Constants.SERVICE_RANKING)).intValue()); } @@ -196,18 +197,18 @@ public class URLStreamHandlerProxy extends URLStreamHandler implements ServiceTr /** * @see org.osgi.util.tracker.ServiceTrackerCustomizer#removedService(ServiceReference, Object) */ - public void removedService(ServiceReference reference, Object service) { + 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 newReference = urlStreamHandlerServiceTracker.getServiceReference(); + ServiceReference<URLStreamHandlerService> newReference = urlStreamHandlerServiceTracker.getServiceReference(); // if newReference == null then we will use the NullURLStreamHandlerService here setNewHandler(newReference, getRank(newReference)); } - private int getRank(ServiceReference reference) { + private int getRank(ServiceReference<?> reference) { if (reference == null) return Integer.MIN_VALUE; Object property = reference.getProperty(Constants.SERVICE_RANKING); 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 index 1bf4e1e58..a8577e465 100644 --- 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 @@ -43,8 +43,8 @@ public class BundleLoader implements ClassLoaderDelegate { public final static byte FLAG_CLOSED = 0x08; public final static byte FLAG_LAZYTRIGGER = 0x10; - public final static ClassContext CLASS_CONTEXT = (ClassContext) AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { + public final static ClassContext CLASS_CONTEXT = AccessController.doPrivileged(new PrivilegedAction<ClassContext>() { + public ClassContext run() { return new ClassContext(); } }); @@ -60,7 +60,7 @@ public class BundleLoader implements ClassLoaderDelegate { private static final int POST_LIBRARY = 8; private static final boolean USE_GLOBAL_DEADLOCK_AVOIDANCE_LOCK = "true".equals(BundleLoaderProxy.secureAction.getProperty("osgi.classloader.singleThreadLoads")); //$NON-NLS-1$//$NON-NLS-2$ - private static final List waitingList = USE_GLOBAL_DEADLOCK_AVOIDANCE_LOCK ? new ArrayList(0) : null; + private static final List<Object[]> waitingList = USE_GLOBAL_DEADLOCK_AVOIDANCE_LOCK ? new ArrayList<Object[]>(0) : null; private static Object lockThread; private static int lockCount = 0; @@ -70,8 +70,8 @@ public class BundleLoader implements ClassLoaderDelegate { final BundleHost bundle; final private PolicyHandler policy; /* List of package names that are exported by this BundleLoader */ - final private Collection exportedPackages; - final private Collection substitutedPackages; + 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 */ @@ -149,7 +149,7 @@ public class BundleLoader implements ClassLoaderDelegate { BundleDescription[] required = description.getResolvedRequires(); if (required.length > 0) { // get a list of re-exported symbolic names - HashSet reExportSet = new HashSet(required.length); + 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++) @@ -180,15 +180,15 @@ public class BundleLoader implements ClassLoaderDelegate { // init the provided packages set ExportPackageDescription[] exports = description.getSelectedExports(); if (exports != null && exports.length > 0) { - exportedPackages = Collections.synchronizedCollection(exports.length > 10 ? (Collection) new HashSet(exports.length) : new ArrayList(exports.length)); + 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(0)); + exportedPackages = Collections.synchronizedCollection(new ArrayList<String>(0)); } ExportPackageDescription substituted[] = description.getSubstitutedExports(); if (substituted.length > 0) { - substitutedPackages = substituted.length > 10 ? (Collection) new HashSet(substituted.length) : new ArrayList(substituted.length); + 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 { @@ -211,7 +211,7 @@ public class BundleLoader implements ClassLoaderDelegate { //Initialize the policy handler String buddyList = null; try { - buddyList = (String) bundle.getBundleData().getManifest().get(Constants.BUDDY_LOADER); + buddyList = bundle.getBundleData().getManifest().get(Constants.BUDDY_LOADER); } catch (BundleException e) { // do nothing; buddyList == null } @@ -220,7 +220,7 @@ public class BundleLoader implements ClassLoaderDelegate { policy.open(bundle.getFramework().getSystemBundleContext()); } - private void initializeExports(ExportPackageDescription[] exports, Collection exportNames) { + 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())) { @@ -280,14 +280,14 @@ public class BundleLoader implements ClassLoaderDelegate { private static PackageSource createMultiSource(String packageName, PackageSource[] sources) { if (sources.length == 1) return sources[0]; - ArrayList sourceList = new ArrayList(sources.length); + 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, (SingleSourcePackage[]) sourceList.toArray(new SingleSourcePackage[sourceList.size()])); + return new MultiSourcePackage(packageName, sourceList.toArray(new SingleSourcePackage[sourceList.size()])); } /* @@ -329,7 +329,7 @@ public class BundleLoader implements ClassLoaderDelegate { * @return the resulting Class * @exception java.lang.ClassNotFoundException if the class definition was not found. */ - final public Class loadClass(String name) throws ClassNotFoundException { + 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. @@ -386,11 +386,11 @@ public class BundleLoader implements ClassLoaderDelegate { * @return The loaded Class or null if the class is not found. * @throws ClassNotFoundException */ - Class findLocalClass(String name) 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); + 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; @@ -406,11 +406,11 @@ public class BundleLoader implements ClassLoaderDelegate { /** * Finds the class for a bundle. This method is used for delegation by the bundle's classloader. */ - public Class findClass(String name) throws ClassNotFoundException { + public Class<?> findClass(String name) throws ClassNotFoundException { return findClass(name, true); } - Class findClass(String name, boolean checkParent) throws ClassNotFoundException { + 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 @@ -426,7 +426,7 @@ public class BundleLoader implements ClassLoaderDelegate { } } - private Class findClassInternal(String name, boolean checkParent, ClassLoader parentCL) throws ClassNotFoundException { + 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); @@ -440,9 +440,9 @@ public class BundleLoader implements ClassLoaderDelegate { // we want to continue bootDelegation = true; } - Class result = null; + Class<?> result = null; try { - result = (Class) searchHooks(name, PRE_CLASS); + result = (Class<?>) searchHooks(name, PRE_CLASS); } catch (ClassNotFoundException e) { throw e; } catch (FileNotFoundException e) { @@ -483,7 +483,7 @@ public class BundleLoader implements ClassLoaderDelegate { if (result == null) try { - result = (Class) searchHooks(name, POST_CLASS); + result = (Class<?>) searchHooks(name, POST_CLASS); } catch (ClassNotFoundException e) { throw e; } catch (FileNotFoundException e) { @@ -506,36 +506,37 @@ public class BundleLoader implements ClassLoaderDelegate { throw new ClassNotFoundException(name); } - private Object searchHooks(String name, int type) throws ClassNotFoundException, FileNotFoundException { + @SuppressWarnings("unchecked") + private <E> E searchHooks(String name, int type) throws ClassNotFoundException, FileNotFoundException { ClassLoaderDelegateHook[] delegateHooks = bundle.getFramework().getDelegateHooks(); if (delegateHooks == null) return null; - Object result = null; + E result = null; for (int i = 0; i < delegateHooks.length && result == null; i++) { switch (type) { case PRE_CLASS : - result = delegateHooks[i].preFindClass(name, createClassLoader(), bundle.getBundleData()); + result = (E) delegateHooks[i].preFindClass(name, createClassLoader(), bundle.getBundleData()); break; case POST_CLASS : - result = delegateHooks[i].postFindClass(name, createClassLoader(), bundle.getBundleData()); + result = (E) delegateHooks[i].postFindClass(name, createClassLoader(), bundle.getBundleData()); break; case PRE_RESOURCE : - result = delegateHooks[i].preFindResource(name, createClassLoader(), bundle.getBundleData()); + result = (E) delegateHooks[i].preFindResource(name, createClassLoader(), bundle.getBundleData()); break; case POST_RESOURCE : - result = delegateHooks[i].postFindResource(name, createClassLoader(), bundle.getBundleData()); + result = (E) delegateHooks[i].postFindResource(name, createClassLoader(), bundle.getBundleData()); break; case PRE_RESOURCES : - result = delegateHooks[i].preFindResources(name, createClassLoader(), bundle.getBundleData()); + result = (E) delegateHooks[i].preFindResources(name, createClassLoader(), bundle.getBundleData()); break; case POST_RESOURCES : - result = delegateHooks[i].postFindResources(name, createClassLoader(), bundle.getBundleData()); + result = (E) delegateHooks[i].postFindResources(name, createClassLoader(), bundle.getBundleData()); break; case PRE_LIBRARY : - result = delegateHooks[i].preFindLibrary(name, createClassLoader(), bundle.getBundleData()); + result = (E) delegateHooks[i].preFindLibrary(name, createClassLoader(), bundle.getBundleData()); break; case POST_LIBRARY : - result = delegateHooks[i].postFindLibrary(name, createClassLoader(), bundle.getBundleData()); + result = (E) delegateHooks[i].postFindLibrary(name, createClassLoader(), bundle.getBundleData()); break; } } @@ -546,7 +547,7 @@ public class BundleLoader implements ClassLoaderDelegate { 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(); + Class<?>[] context = CLASS_CONTEXT.getClassContext(); if (context == null || context.length < 2) return false; // skip the first class; it is the ClassContext class @@ -564,11 +565,11 @@ public class BundleLoader implements ClassLoaderDelegate { return false; } - private static ClassLoader getClassLoader(final Class clazz) { + private static ClassLoader getClassLoader(final Class<?> clazz) { if (System.getSecurityManager() == null) return clazz.getClassLoader(); - return (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { + return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { + public ClassLoader run() { return clazz.getClassLoader(); } }); @@ -660,14 +661,14 @@ public class BundleLoader implements ClassLoaderDelegate { /** * Finds the resources for a bundle. This method is used for delegation by the bundle's classloader. */ - public Enumeration findResources(String name) throws IOException { + 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 result = null; + Enumeration<URL> result = null; try { - result = (Enumeration) searchHooks(name, PRE_RESOURCES); + result = searchHooks(name, PRE_RESOURCES); } catch (ClassNotFoundException e) { // will not happen } catch (FileNotFoundException e) { @@ -689,7 +690,7 @@ public class BundleLoader implements ClassLoaderDelegate { // 5) search the local bundle // compound the required source results with the local ones - Enumeration localResults = findLocalResources(name); + 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) { @@ -699,14 +700,14 @@ public class BundleLoader implements ClassLoaderDelegate { } if (result == null) try { - result = (Enumeration) searchHooks(name, POST_RESOURCES); + result = searchHooks(name, POST_RESOURCES); } catch (ClassNotFoundException e) { // will not happen } catch (FileNotFoundException e) { return null; } if (policy != null) { - Enumeration buddyResult = policy.doBuddyResourcesLoading(name); + Enumeration<URL> buddyResult = policy.doBuddyResourcesLoading(name); result = compoundEnumerations(result, buddyResult); } return result; @@ -715,13 +716,13 @@ public class BundleLoader implements ClassLoaderDelegate { /* * This method is used by Bundle.getResources to do proper parent delegation. */ - public Enumeration getResources(String name) throws IOException { + 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 result = null; + 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 @@ -733,20 +734,20 @@ public class BundleLoader implements ClassLoaderDelegate { return compoundEnumerations(result, findResources(name)); } - public static Enumeration compoundEnumerations(Enumeration list1, Enumeration list2) { + 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; - Vector compoundResults = new Vector(); + List<E> compoundResults = new ArrayList<E>(); while (list1.hasMoreElements()) compoundResults.add(list1.nextElement()); while (list2.hasMoreElements()) { - Object item = list2.nextElement(); + E item = list2.nextElement(); if (!compoundResults.contains(item)) //don't add duplicates compoundResults.add(item); } - return compoundResults.elements(); + return Collections.enumeration(compoundResults); } /** @@ -765,7 +766,7 @@ public class BundleLoader implements ClassLoaderDelegate { * @param name the resource name * @return an Enumeration of URLs for the resources */ - Enumeration findLocalResources(String name) { + Enumeration<URL> findLocalResources(String name) { return createClassLoader().findLocalResources(name); } @@ -778,8 +779,8 @@ public class BundleLoader implements ClassLoaderDelegate { public String findLibrary(final String name) { if (System.getSecurityManager() == null) return findLocalLibrary(name); - return (String) AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { + return AccessController.doPrivileged(new PrivilegedAction<String>() { + public String run() { return findLocalLibrary(name); } }); @@ -830,8 +831,8 @@ public class BundleLoader implements ClassLoaderDelegate { if (System.getSecurityManager() == null) return createBCL(pd, cp); - return (BundleClassLoader) AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { + return AccessController.doPrivileged(new PrivilegedAction<BundleClassLoader>() { + public BundleClassLoader run() { return createBCL(pd, cp); } }); @@ -902,7 +903,7 @@ public class BundleLoader implements ClassLoaderDelegate { return false; } - final void addExportedProvidersFor(String symbolicName, String packageName, ArrayList result, KeyedHashSet visited) { + final void addExportedProvidersFor(String symbolicName, String packageName, List<PackageSource> result, KeyedHashSet visited) { if (!visited.add(bundle)) return; @@ -947,12 +948,12 @@ public class BundleLoader implements ClassLoaderDelegate { private void addDynamicImportPackage(ImportPackageSpecification[] packages) { if (packages == null) return; - ArrayList dynamicImports = new ArrayList(packages.length); + 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((String[]) dynamicImports.toArray(new String[dynamicImports.size()])); + addDynamicImportPackage(dynamicImports.toArray(new String[dynamicImports.size()])); } /** @@ -968,21 +969,21 @@ public class BundleLoader implements ClassLoaderDelegate { loaderFlags |= FLAG_HASDYNAMICIMPORTS; int size = packages.length; - ArrayList stems; + List<String> stems; if (dynamicImportPackageStems == null) { - stems = new ArrayList(size); + stems = new ArrayList<String>(size); } else { - stems = new ArrayList(size + dynamicImportPackageStems.length); + stems = new ArrayList<String>(size + dynamicImportPackageStems.length); for (int i = 0; i < dynamicImportPackageStems.length; i++) { stems.add(dynamicImportPackageStems[i]); } } - ArrayList names; + List<String> names; if (dynamicImportPackages == null) { - names = new ArrayList(size); + names = new ArrayList<String>(size); } else { - names = new ArrayList(size + dynamicImportPackages.length); + names = new ArrayList<String>(size + dynamicImportPackages.length); for (int i = 0; i < dynamicImportPackages.length; i++) { names.add(dynamicImportPackages[i]); } @@ -1005,11 +1006,11 @@ public class BundleLoader implements ClassLoaderDelegate { size = stems.size(); if (size > 0) - dynamicImportPackageStems = (String[]) stems.toArray(new String[size]); + dynamicImportPackageStems = stems.toArray(new String[size]); size = names.size(); if (size > 0) - dynamicImportPackages = (String[]) names.toArray(new String[size]); + dynamicImportPackages = names.toArray(new String[size]); } /** @@ -1021,11 +1022,11 @@ public class BundleLoader implements ClassLoaderDelegate { public final synchronized void addDynamicImportPackage(ManifestElement[] packages) { if (packages == null) return; - ArrayList dynamicImports = new ArrayList(packages.length); + List<String> dynamicImports = new ArrayList<String>(packages.length); for (int i = 0; i < packages.length; i++) dynamicImports.add(packages[i].getValue()); if (dynamicImports.size() > 0) - addDynamicImportPackage((String[]) dynamicImports.toArray(new String[dynamicImports.size()])); + addDynamicImportPackage(dynamicImports.toArray(new String[dynamicImports.size()])); } synchronized public void attachFragment(BundleFragment fragment) throws BundleException { @@ -1092,7 +1093,7 @@ public class BundleLoader implements ClassLoaderDelegate { if (visited == null) visited = new KeyedHashSet(false); visited.add(bundle); // always add ourselves so we do not recurse back to ourselves - ArrayList result = new ArrayList(3); + 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); @@ -1105,10 +1106,10 @@ public class BundleLoader implements ClassLoaderDelegate { source = NullPackageSource.getNullPackageSource(pkgName); } else if (result.size() == 1) { // if there is just one source, remember just the single source - source = (PackageSource) result.get(0); + source = result.get(0); } else { // if there was more than one source, build a multisource and cache that. - PackageSource[] srcs = (PackageSource[]) result.toArray(new PackageSource[result.size()]); + PackageSource[] srcs = result.toArray(new PackageSource[result.size()]); source = createMultiSource(pkgName, srcs); } synchronized (requiredSources) { @@ -1139,8 +1140,8 @@ public class BundleLoader implements ClassLoaderDelegate { if (System.getSecurityManager() == null) return bcl.getParent(); - return (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { + return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { + public ClassLoader run() { return bcl.getParent(); } }); @@ -1148,7 +1149,7 @@ public class BundleLoader implements ClassLoaderDelegate { static final class ClassContext extends SecurityManager { // need to make this method public - public Class[] getClassContext() { + public Class<?>[] getClassContext() { return super.getClassContext(); } } @@ -1227,7 +1228,7 @@ public class BundleLoader implements ClassLoaderDelegate { return; } - Object[] waiting = (Object[]) waitingList.get(0); + Object[] waiting = waitingList.get(0); waitingThread = (Thread) waiting[0]; loader = waiting[1]; } 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 index 73cc622d2..80fe8a72c 100644 --- 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 @@ -13,6 +13,7 @@ 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.internal.core.*; import org.eclipse.osgi.framework.internal.core.Constants; import org.eclipse.osgi.framework.util.KeyedHashSet; @@ -31,7 +32,7 @@ import org.osgi.service.packageadmin.RequiredBundle; * Framework. */ public class BundleLoaderProxy implements RequiredBundle, BundleReference { - static SecureAction secureAction = (SecureAction) AccessController.doPrivileged(SecureAction.createSecureAction()); + static SecureAction secureAction = AccessController.doPrivileged(SecureAction.createSecureAction()); // The BundleLoader that this BundleLoaderProxy is managing private BundleLoader loader; // The Bundle that this BundleLoaderProxy is for @@ -53,8 +54,8 @@ public class BundleLoaderProxy implements RequiredBundle, BundleReference { public BundleLoader getBundleLoader() { if (System.getSecurityManager() == null) return getBundleLoader0(); - return (BundleLoader) AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { + return AccessController.doPrivileged(new PrivilegedAction<BundleLoader>() { + public BundleLoader run() { return getBundleLoader0(); } }); @@ -108,20 +109,20 @@ public class BundleLoaderProxy implements RequiredBundle, BundleReference { return bundle; } - public org.osgi.framework.Bundle[] getRequiringBundles() { + 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]; - ArrayList result = new ArrayList(dependents.length); + List<Bundle> result = new ArrayList<Bundle>(dependents.length); for (int i = 0; i < dependents.length; i++) addRequirers(dependents[i], result); - return (Bundle[]) result.toArray(new org.osgi.framework.Bundle[result.size()]); + return result.toArray(new org.osgi.framework.Bundle[result.size()]); } - void addRequirers(BundleDescription dependent, ArrayList result) { + void addRequirers(BundleDescription dependent, List<Bundle> result) { if (dependent.getHost() != null) // don't look in fragments. return; BundleLoaderProxy dependentProxy = getBundleLoader().getLoaderProxy(dependent); 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 index f14829397..b2d4afe9a 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2004, 2008 IBM Corporation and others. + * 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 @@ -44,13 +44,13 @@ public class FilteredSourcePackage extends SingleSourcePackage { return super.getResource(name); } - public Enumeration getResources(String name) { + public Enumeration<URL> getResources(String name) { if (isFiltered(name, getId())) return null; return super.getResources(name); } - public Class loadClass(String name) throws ClassNotFoundException { + public Class<?> loadClass(String name) throws ClassNotFoundException { if (isFiltered(name, getId())) return null; return super.loadClass(name); 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 index 3155fa52f..0abe17ead 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2003, 2008 IBM Corporation and others. + * 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 @@ -25,8 +25,8 @@ public class MultiSourcePackage extends PackageSource { return suppliers; } - public Class loadClass(String name) throws ClassNotFoundException { - Class result = null; + 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) @@ -45,8 +45,8 @@ public class MultiSourcePackage extends PackageSource { return result; } - public Enumeration getResources(String name) { - Enumeration results = null; + 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; 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 index b70b4837a..9ded793e1 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2003, 2008 IBM Corporation and others. + * 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 @@ -39,7 +39,7 @@ public class NullPackageSource extends PackageSource { return id + " -> null"; //$NON-NLS-1$ } - public Class loadClass(String name) { + public Class<?> loadClass(String name) { return null; } @@ -47,7 +47,7 @@ public class NullPackageSource extends PackageSource { return null; } - public Enumeration getResources(String name) { + public Enumeration<URL> getResources(String name) { return null; } 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 index 6b4eaeb66..f662eaefd 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2003, 2008 IBM Corporation and others. + * 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 @@ -49,11 +49,11 @@ public abstract class PackageSource implements KeyedElement { return true; } - public abstract Class loadClass(String name) throws ClassNotFoundException; + public abstract Class<?> loadClass(String name) throws ClassNotFoundException; public abstract URL getResource(String name); - public abstract Enumeration getResources(String name) throws IOException; + 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) 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 index 7079bb2f0..52b4c85ff 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2003, 2008 IBM Corporation and others. + * 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 @@ -29,7 +29,7 @@ public class SingleSourcePackage extends PackageSource { return id + " -> " + supplier; //$NON-NLS-1$ } - public Class loadClass(String name) throws ClassNotFoundException { + public Class<?> loadClass(String name) throws ClassNotFoundException { return supplier.getBundleLoader().findLocalClass(name); } @@ -37,7 +37,7 @@ public class SingleSourcePackage extends PackageSource { return supplier.getBundleLoader().findLocalResource(name); } - public Enumeration getResources(String name) { + public Enumeration<URL> getResources(String name) { return supplier.getBundleLoader().findLocalResources(name); } 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 index bfefa8ae1..2de03e8d3 100644 --- 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 @@ -14,8 +14,7 @@ package org.eclipse.osgi.internal.loader; import java.io.IOException; import java.net.URL; import java.security.ProtectionDomain; -import java.util.Enumeration; -import java.util.HashSet; +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; @@ -30,8 +29,8 @@ import org.osgi.framework.BundleException; public class SystemBundleLoader extends BundleLoader { public static final String EQUINOX_EE = "x-equinox-ee"; //$NON-NLS-1$ final ClassLoader classLoader; - private final HashSet eePackages; - private final HashSet extPackages; + private final Set<String> eePackages; + private final Set<String> extPackages; private final ClassLoader extClassLoader; /** @@ -45,13 +44,13 @@ public class SystemBundleLoader extends BundleLoader { if (exports == null || exports.length == 0) eePackages = null; else { - eePackages = new HashSet(exports.length); + 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(0); // not common; start with 0 + 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++) @@ -94,8 +93,8 @@ public class SystemBundleLoader extends BundleLoader { * 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); + public Class<?> findClass(String name) throws ClassNotFoundException { + Class<?> result = findLocalClass(name); if (result == null) throw new ClassNotFoundException(name); return result; @@ -112,7 +111,7 @@ public class SystemBundleLoader extends BundleLoader { /** * The ClassLoader that loads OSGi framework classes is used to find the class. */ - Class findLocalClass(String name) { + Class<?> findLocalClass(String name) { try { return classLoader.loadClass(name); } catch (ClassNotFoundException e) { @@ -145,8 +144,8 @@ public class SystemBundleLoader extends BundleLoader { /** * The ClassLoader that loads OSGi framework classes is used to find the resource. */ - Enumeration findLocalResources(String name) { - Enumeration result = null; + Enumeration<URL> findLocalResources(String name) { + Enumeration<URL> result = null; try { result = classLoader.getResources(name); } catch (IOException e) { @@ -177,7 +176,7 @@ public class SystemBundleLoader extends BundleLoader { * This method never gets called because there is no BundleClassLoader for the framework. * @throws IOException */ - public Enumeration findResources(String name) throws IOException { + public Enumeration<URL> findResources(String name) throws IOException { return findLocalResources(name); } @@ -199,7 +198,7 @@ public class SystemBundleLoader extends BundleLoader { return SystemBundleLoader.this.getBundle(); } - public Class loadClass(String name) throws ClassNotFoundException { + public Class<?> loadClass(String name) throws ClassNotFoundException { return SystemBundleLoader.this.loadClass(name); } @@ -210,7 +209,7 @@ public class SystemBundleLoader extends BundleLoader { /** * @throws IOException */ - public Enumeration getResources(String name) throws IOException { + public Enumeration<URL> getResources(String name) throws IOException { return findLocalResources(name); } @@ -226,7 +225,7 @@ public class SystemBundleLoader extends BundleLoader { return SystemBundleLoader.this; } - public Enumeration findLocalResources(String resource) { + public Enumeration<URL> findLocalResources(String resource) { return SystemBundleLoader.this.findLocalResources(resource); } @@ -237,7 +236,7 @@ public class SystemBundleLoader extends BundleLoader { /** * @throws ClassNotFoundException */ - public Class findLocalClass(String classname) throws ClassNotFoundException { + public Class<?> findLocalClass(String classname) throws ClassNotFoundException { return SystemBundleLoader.this.findLocalClass(classname); } 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 index 85240f288..74121aeaa 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2008 IBM Corporation and others. + * 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 @@ -26,27 +26,27 @@ import org.eclipse.osgi.service.resolver.BundleDescription; public class DependentPolicy implements IBuddyPolicy { BundleLoader buddyRequester; int lastDependentOfAdded = -1; //remember the index of the bundle for which we last added the dependent - List allDependents = null; //the list of all dependents known so far + 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(); + 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) { + public Class<?> loadClass(String name) { if (allDependents == null) return null; - Class result = 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 = (BundleDescription) allDependents.get(i); + BundleDescription searchedBundle = allDependents.get(i); try { BundleLoaderProxy proxy = buddyRequester.getLoaderProxy(searchedBundle); if (proxy == null) @@ -74,7 +74,7 @@ public class DependentPolicy implements IBuddyPolicy { 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 = (BundleDescription) allDependents.get(i); + BundleDescription searchedBundle = allDependents.get(i); BundleLoaderProxy proxy = buddyRequester.getLoaderProxy(searchedBundle); if (proxy == null) continue; @@ -86,14 +86,14 @@ public class DependentPolicy implements IBuddyPolicy { return result; } - public Enumeration loadResources(String name) { + public Enumeration<URL> loadResources(String name) { if (allDependents == null) return null; - Enumeration results = 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 = (BundleDescription) allDependents.get(i); + BundleDescription searchedBundle = allDependents.get(i); try { BundleLoaderProxy proxy = buddyRequester.getLoaderProxy(searchedBundle); if (proxy == null) 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 index e1dc69b3a..1985ff87a 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2008 IBM Corporation and others. + * 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 @@ -30,7 +30,7 @@ public class GlobalPolicy implements IBuddyPolicy { this.admin = admin; } - public Class loadClass(String name) { + public Class<?> loadClass(String name) { ExportedPackage pkg = admin.getExportedPackage(BundleLoader.getPackageName(name)); if (pkg == null) return null; @@ -49,14 +49,14 @@ public class GlobalPolicy implements IBuddyPolicy { return pkg.getExportingBundle().getResource(name); } - public Enumeration loadResources(String 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 results = null; + Enumeration<URL> results = null; for (int i = 0; i < pkgs.length; i++) { try { results = BundleLoader.compoundEnumerations(results, pkgs[i].getExportingBundle().getResources(name)); 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 index 3e513f67d..a4066eeea 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2008 IBM Corporation and others. + * 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 @@ -14,9 +14,9 @@ import java.net.URL; import java.util.Enumeration; public interface IBuddyPolicy { - public Class loadClass(String name); + public Class<?> loadClass(String name); public URL loadResource(String name); - public Enumeration loadResources(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 index 6ade20ea3..0795902e1 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2008 IBM Corporation and others. + * 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 @@ -33,27 +33,27 @@ public class PolicyHandler implements SynchronousBundleListener { 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 beingLoaded; + 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(); + beingLoaded = new ThreadLocal<Set<String>>(); this.packageAdmin = packageAdmin; } static Object[] getArrayFromList(String stringList) { if (stringList == null || stringList.trim().equals("")) //$NON-NLS-1$ return null; - Vector list = new Vector(); + 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.addElement(token); + list.add(token); } - return list.isEmpty() ? new Object[0] : (Object[]) list.toArray(new Object[list.size()]); + return list.isEmpty() ? new Object[0] : list.toArray(new Object[list.size()]); } private IBuddyPolicy getPolicyImplementation(Object[] policiesSnapshot, int policyOrder) { @@ -122,11 +122,11 @@ public class PolicyHandler implements SynchronousBundleListener { } } - public Class doBuddyClassLoading(String name) { + public Class<?> doBuddyClassLoading(String name) { if (startLoading(name) == false) return null; - Class result = null; + Class<?> result = null; Object[] policiesSnapshot = policies; int policyCount = (policiesSnapshot == null) ? 0 : policiesSnapshot.length; for (int i = 0; i < policyCount && result == null; i++) { @@ -154,39 +154,39 @@ public class PolicyHandler implements SynchronousBundleListener { return result; } - public Enumeration doBuddyResourcesLoading(String name) { + public Enumeration<URL> doBuddyResourcesLoading(String name) { if (startLoading(name) == false) return null; - Vector results = 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 result = policy.loadResources(name); + Enumeration<URL> result = policy.loadResources(name); if (result != null) { if (results == null) - results = new Vector(policyCount); + results = new ArrayList<URL>(policyCount); while (result.hasMoreElements()) { - Object url = result.nextElement(); + 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 : results.elements(); + return results == null || results.isEmpty() ? null : Collections.enumeration(results); } private boolean startLoading(String name) { - Set classesAndResources = (Set) beingLoaded.get(); + Set<String> classesAndResources = beingLoaded.get(); if (classesAndResources != null && classesAndResources.contains(name)) return false; if (classesAndResources == null) { - classesAndResources = new HashSet(3); + classesAndResources = new HashSet<String>(3); beingLoaded.set(classesAndResources); } classesAndResources.add(name); @@ -194,7 +194,7 @@ public class PolicyHandler implements SynchronousBundleListener { } private void stopLoading(String name) { - ((Set) beingLoaded.get()).remove(name); + beingLoaded.get().remove(name); } public void open(BundleContext context) { @@ -210,7 +210,7 @@ public class PolicyHandler implements SynchronousBundleListener { return; // reinitialize the policies try { - String list = (String) policedLoader.getBundle().getBundleData().getManifest().get(Constants.BUDDY_LOADER); + 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 index 9623081d2..86c43fdd9 100644 --- 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 @@ -36,13 +36,13 @@ public class RegisteredPolicy extends DependentPolicy { if (allDependents == null) return; - for (Iterator iter = allDependents.iterator(); iter.hasNext();) { - BundleLoaderProxy proxy = buddyRequester.getLoaderProxy((BundleDescription) iter.next()); + for (Iterator<BundleDescription> iter = allDependents.iterator(); iter.hasNext();) { + BundleLoaderProxy proxy = buddyRequester.getLoaderProxy(iter.next()); if (proxy == null) iter.remove(); try { - String[] allContributions = ManifestElement.getArrayFromList((String) ((AbstractBundle) proxy.getBundle()).getBundleData().getManifest().get(Constants.REGISTERED_POLICY)); + String[] allContributions = ManifestElement.getArrayFromList(((AbstractBundle) proxy.getBundle()).getBundleData().getManifest().get(Constants.REGISTERED_POLICY)); if (allContributions == null) { iter.remove(); continue; @@ -65,15 +65,15 @@ public class RegisteredPolicy extends DependentPolicy { allDependents = null; } - public Class loadClass(String name) { + public Class<?> loadClass(String name) { if (allDependents == null) return null; - Class result = null; + Class<?> result = null; int size = allDependents.size(); for (int i = 0; i < size && result == null; i++) { try { - BundleLoaderProxy proxy = buddyRequester.getLoaderProxy((BundleDescription) allDependents.get(i)); + BundleLoaderProxy proxy = buddyRequester.getLoaderProxy(allDependents.get(i)); if (proxy == null) continue; result = proxy.getBundleLoader().findClass(name); @@ -92,7 +92,7 @@ public class RegisteredPolicy extends DependentPolicy { URL result = null; int size = allDependents.size(); for (int i = 0; i < size && result == null; i++) { - BundleLoaderProxy proxy = buddyRequester.getLoaderProxy((BundleDescription) allDependents.get(i)); + BundleLoaderProxy proxy = buddyRequester.getLoaderProxy(allDependents.get(i)); if (proxy == null) continue; result = proxy.getBundleLoader().findResource(name); @@ -100,15 +100,15 @@ public class RegisteredPolicy extends DependentPolicy { return result; } - public Enumeration loadResources(String name) { + public Enumeration<URL> loadResources(String name) { if (allDependents == null) return null; - Enumeration results = null; + Enumeration<URL> results = null; int size = allDependents.size(); for (int i = 0; i < size; i++) { try { - BundleLoaderProxy proxy = buddyRequester.getLoaderProxy((BundleDescription) allDependents.get(i)); + BundleLoaderProxy proxy = buddyRequester.getLoaderProxy(allDependents.get(i)); if (proxy == null) continue; results = BundleLoader.compoundEnumerations(results, proxy.getBundleLoader().findResources(name)); 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 index 04d12f153..a72e6ac15 100644 --- 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 @@ -35,8 +35,8 @@ public class SystemPolicy implements IBuddyPolicy { public static SystemPolicy getInstance(final byte type) { if (instances[type] == null) { instances[type] = new SystemPolicy(); - instances[type].classLoader = (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { + instances[type].classLoader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { + public ClassLoader run() { return createClassLoader(type); } }); @@ -70,7 +70,7 @@ public class SystemPolicy implements IBuddyPolicy { return null; } - public Class loadClass(String name) { + public Class<?> loadClass(String name) { try { return classLoader.loadClass(name); } catch (ClassNotFoundException e) { @@ -82,7 +82,7 @@ public class SystemPolicy implements IBuddyPolicy { return classLoader.getResource(name); } - public Enumeration loadResources(String name) { + public Enumeration<URL> loadResources(String name) { try { return classLoader.getResources(name); } catch (IOException e) { 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 index 659410a1e..5ade23ff0 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. + * Copyright (c) 2008, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -20,12 +20,12 @@ 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 EMPTY_ENUMERATION = new Enumeration() { + static final Enumeration<Permission> EMPTY_ENUMERATION = new Enumeration<Permission>() { public boolean hasMoreElements() { return false; } - public Object nextElement() { + public Permission nextElement() { throw new NoSuchElementException(); } }; @@ -47,7 +47,7 @@ public final class BundlePermissions extends PermissionCollection { throw new SecurityException(); } - public Enumeration elements() { + 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) 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 index dd94b59cd..10d5ce78e 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. + * Copyright (c) 2008, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -28,7 +28,7 @@ public class EquinoxSecurityManager extends SecurityManager { * CheckPermissionAction classes load early. Otherwise, we run into problems later. */ static { - Class c; + Class<?> c; c = CheckPermissionAction.class; c = CheckContext.class; c.getName(); // to prevent compiler warnings @@ -36,16 +36,16 @@ public class EquinoxSecurityManager extends SecurityManager { static class CheckContext { // A non zero depth indicates that we are doing a recursive permission check. - ArrayList depthCondSets = new ArrayList(2); - ArrayList accs = new ArrayList(2); - ArrayList CondClassSet; + 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 { + static class CheckPermissionAction implements PrivilegedAction<Object> { Permission perm; Object context; EquinoxSecurityManager fsm; @@ -62,18 +62,18 @@ public class EquinoxSecurityManager extends SecurityManager { } } - private final ThreadLocal localCheckContext = new ThreadLocal(); + private final ThreadLocal<CheckContext> localCheckContext = new ThreadLocal<CheckContext>(); - boolean addConditionsForDomain(Decision results[]) { - CheckContext cc = (CheckContext) localCheckContext.get(); + 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; } - ArrayList condSets = (ArrayList) cc.depthCondSets.get(cc.getDepth()); + List<Decision[]> condSets = cc.depthCondSets.get(cc.getDepth()); if (condSets == null) { - condSets = new ArrayList(1); + condSets = new ArrayList<Decision[]>(1); cc.depthCondSets.set(cc.getDepth(), condSets); } condSets.add(results); @@ -98,15 +98,15 @@ public class EquinoxSecurityManager extends SecurityManager { * rather than the SecurityManager. */ public AccessControlContext getContextToBeChecked() { - CheckContext cc = (CheckContext) localCheckContext.get(); + CheckContext cc = localCheckContext.get(); if (cc != null && cc.accs != null && !cc.accs.isEmpty()) - return (AccessControlContext) cc.accs.get(cc.accs.size() - 1); + return cc.accs.get(cc.accs.size() - 1); return null; } void internalCheckPermission(Permission perm, Object context) { AccessControlContext acc = (AccessControlContext) context; - CheckContext cc = (CheckContext) localCheckContext.get(); + CheckContext cc = localCheckContext.get(); if (cc == null) { cc = new CheckContext(); localCheckContext.set(cc); @@ -116,13 +116,12 @@ public class EquinoxSecurityManager extends SecurityManager { try { acc.checkPermission(perm); // We want to pop the first set of postponed conditions and process them - ArrayList conditionSets = (ArrayList) cc.depthCondSets.get(cc.getDepth()); + 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 - HashMap conditionDictionaries = new HashMap(); - for (Iterator iConditionSets = conditionSets.iterator(); iConditionSets.hasNext();) { - Decision[] domainDecisions = (Decision[]) iConditionSets.next(); + 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) @@ -154,17 +153,17 @@ public class EquinoxSecurityManager extends SecurityManager { } } - private int getPostponedDecision(Decision decision, HashMap conditionDictionaries, CheckContext cc) { + 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 condContext = (Dictionary) conditionDictionaries.get(postponed[i].getClass()); + Dictionary<Object, Object> condContext = conditionDictionaries.get(postponed[i].getClass()); if (condContext == null) { - condContext = new Hashtable(); + condContext = new Hashtable<Object, Object>(); conditionDictionaries.put(postponed[i].getClass(), condContext); } // prevent recursion into Condition if (cc.CondClassSet == null) - cc.CondClassSet = new ArrayList(2); + cc.CondClassSet = new ArrayList<Class<?>>(2); if (cc.CondClassSet.contains(postponed[i].getClass())) return SecurityTable.ABSTAIN; cc.CondClassSet.add(postponed[i].getClass()); 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 index c9333234e..472c35009 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008 IBM Corporation and others. + * Copyright (c) 2008, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -11,17 +11,18 @@ 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 HashMap locations = new HashMap(); + private final Map<String, PermissionInfoCollection> locations = new HashMap<String, PermissionInfoCollection>(); String[] getLocations() { - return (String[]) locations.keySet().toArray(new String[locations.size()]); + return locations.keySet().toArray(new String[locations.size()]); } PermissionInfo[] getPermissions(String location) { - PermissionInfoCollection collection = (PermissionInfoCollection) locations.get(location); + PermissionInfoCollection collection = locations.get(location); if (collection != null) return collection.getPermissionInfos(); return null; @@ -36,7 +37,7 @@ public class PermissionAdminTable { } PermissionInfoCollection getCollection(String location) { - return (PermissionInfoCollection) locations.get(location); + return locations.get(location); } PermissionInfoCollection[] getCollections() { 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 index f15e6b525..8d72ff1cd 100644 --- 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 @@ -14,20 +14,19 @@ import java.io.File; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.security.*; -import java.util.Enumeration; -import java.util.HashMap; +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}; + 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 HashMap cachedPermissionCollections = new HashMap(); + private final Map<Class<? extends Permission>, PermissionCollection> cachedPermissionCollections = new HashMap<Class<? extends Permission>, PermissionCollection>(); private final boolean hasAllPermission; private final PermissionInfo[] permInfos; @@ -45,7 +44,7 @@ public final class PermissionInfoCollection extends PermissionCollection { throw new SecurityException(); } - public Enumeration elements() { + public Enumeration<Permission> elements() { // TODO return an empty enumeration for now; return BundlePermissions.EMPTY_ENUMERATION; } @@ -53,10 +52,10 @@ public final class PermissionInfoCollection extends PermissionCollection { public boolean implies(Permission perm) { if (hasAllPermission) return true; - Class permClass = perm.getClass(); + Class<? extends Permission> permClass = perm.getClass(); PermissionCollection collection; synchronized (cachedPermissionCollections) { - collection = (PermissionCollection) cachedPermissionCollections.get(permClass); + collection = cachedPermissionCollections.get(permClass); } // must populate the collection outside of the lock to prevent class loader deadlock if (collection == null) { @@ -70,7 +69,7 @@ public final class PermissionInfoCollection extends PermissionCollection { } synchronized (cachedPermissionCollections) { // check to see if another thread beat this thread at adding the collection - PermissionCollection exists = (PermissionCollection) cachedPermissionCollections.get(permClass); + PermissionCollection exists = cachedPermissionCollections.get(permClass); if (exists != null) collection = exists; else @@ -84,9 +83,9 @@ public final class PermissionInfoCollection extends PermissionCollection { return permInfos; } - private void addPermissions(PermissionCollection collection, Class permClass) throws NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException { + private void addPermissions(PermissionCollection collection, Class<? extends Permission> permClass) throws NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException { String permClassName = permClass.getName(); - Constructor constructor = null; + Constructor<? extends Permission> constructor = null; int numArgs = -1; for (int i = permClassArrayArgs.length - 1; i >= 0; i--) { try { @@ -120,7 +119,7 @@ public final class PermissionInfoCollection extends PermissionCollection { } } } - collection.add((Permission) constructor.newInstance((Object[]) args)); + collection.add(constructor.newInstance((Object[]) args)); } } } 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 index b2dc8a861..667f23e01 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008 IBM Corporation and others. + * Copyright (c) 2008, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -35,7 +35,7 @@ class PermissionsHash extends PermissionCollection { /** * A hashtable to store the elements of the collection. */ - Hashtable perms = new Hashtable(8); + Hashtable<Permission, Permission> perms = new Hashtable<Permission, Permission>(8); /** * Constructs a new instance of this class. @@ -68,7 +68,7 @@ class PermissionsHash extends PermissionCollection { * @return Enumeration * the permissions in the receiver. */ - public Enumeration elements() { + public Enumeration<Permission> elements() { return perms.keys(); } @@ -84,16 +84,16 @@ class PermissionsHash extends PermissionCollection { * the permission to check */ public boolean implies(Permission perm) { - Permission p = (Permission) perms.get(perm); + Permission p = perms.get(perm); if ((p != null) && p.implies(perm)) { return true; } - Enumeration permsEnum = elements(); + Enumeration<Permission> permsEnum = elements(); while (permsEnum.hasMoreElements()) { - if (((Permission) permsEnum.nextElement()).implies(perm)) { + if (permsEnum.nextElement().implies(perm)) { return true; } } 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 index 1ebea1a92..270212b85 100644 --- 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 @@ -19,7 +19,7 @@ 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 { +public class SecurePermissionStorage implements PermissionStorage, PrivilegedExceptionAction<String[]> { private final PermissionStorage storage; private String location; private String[] data; @@ -35,7 +35,7 @@ public class SecurePermissionStorage implements PermissionStorage, PrivilegedExc this.storage = storage; } - public Object run() throws IOException { + public String[] run() throws IOException { switch (action) { case GET : return storage.getPermissionData(location); @@ -59,7 +59,7 @@ public class SecurePermissionStorage implements PermissionStorage, PrivilegedExc this.action = GET; try { - return (String[]) AccessController.doPrivileged(this); + return AccessController.doPrivileged(this); } catch (PrivilegedActionException e) { throw (IOException) e.getException(); } @@ -69,7 +69,7 @@ public class SecurePermissionStorage implements PermissionStorage, PrivilegedExc this.action = LOCATION; try { - return (String[]) AccessController.doPrivileged(this); + return AccessController.doPrivileged(this); } catch (PrivilegedActionException e) { throw (IOException) e.getException(); } @@ -101,7 +101,7 @@ public class SecurePermissionStorage implements PermissionStorage, PrivilegedExc public String[] getConditionalPermissionInfos() throws IOException { this.action = GET_INFOS; try { - return (String[]) AccessController.doPrivileged(this); + 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 index 764324db8..356c4cee2 100644 --- 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 @@ -202,9 +202,10 @@ public final class SecurityAdmin implements PermissionAdmin, ConditionalPermissi void delete(SecurityRow securityRow, boolean firstTry) { ConditionalPermissionUpdate update = newConditionalPermissionUpdate(); - List rows = update.getConditionalPermissionInfos(); - for (Iterator iRows = rows.iterator(); iRows.hasNext();) { - ConditionalPermissionInfo info = (ConditionalPermissionInfo) iRows.next(); + @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) { @@ -257,14 +258,14 @@ public final class SecurityAdmin implements PermissionAdmin, ConditionalPermissi /** * @deprecated */ - public Enumeration getConditionalPermissionInfos() { + 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(); - Vector vRows = new Vector(rows.length); + List<ConditionalPermissionInfo> vRows = new ArrayList<ConditionalPermissionInfo>(rows.length); for (int i = 0; i < rows.length; i++) vRows.add(rows[i]); - return vRows.elements(); + return Collections.enumeration(vRows); } } @@ -290,12 +291,13 @@ public final class SecurityAdmin implements PermissionAdmin, ConditionalPermissi private ConditionalPermissionInfo setConditionalPermissionInfo(String name, ConditionInfo[] conds, PermissionInfo[] perms, boolean firstTry) { ConditionalPermissionUpdate update = newConditionalPermissionUpdate(); - List rows = update.getConditionalPermissionInfos(); + @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 = (ConditionalPermissionInfo) rows.get(i); + ConditionalPermissionInfo info = rows.get(i); if (name.equals(info.getName())) { index = i; } @@ -318,13 +320,13 @@ public final class SecurityAdmin implements PermissionAdmin, ConditionalPermissi } } - boolean commit(List rows, long updateStamp) { + boolean commit(List<ConditionalPermissionInfo> rows, long updateStamp) { checkAllPermission(); synchronized (lock) { if (updateStamp != timeStamp) return false; SecurityRow[] newRows = new SecurityRow[rows.size()]; - Collection names = new ArrayList(); + Collection<String> names = new ArrayList<String>(); for (int i = 0; i < newRows.length; i++) { Object rowObj = rows.get(i); if (!(rowObj instanceof ConditionalPermissionInfo)) @@ -430,7 +432,7 @@ public final class SecurityAdmin implements PermissionAdmin, ConditionalPermissi DataInputStream in = null; try { in = new DataInputStream(resource.openStream()); - ArrayList permissions = new ArrayList(); + List<PermissionInfo> permissions = new ArrayList<PermissionInfo>(); BufferedReader reader; try { reader = new BufferedReader(new InputStreamReader(in, "UTF8")); //$NON-NLS-1$ @@ -456,7 +458,7 @@ public final class SecurityAdmin implements PermissionAdmin, ConditionalPermissi } int size = permissions.size(); if (size > 0) - info = (PermissionInfo[]) permissions.toArray(new PermissionInfo[size]); + info = permissions.toArray(new PermissionInfo[size]); } catch (IOException e) { // do nothing } finally { @@ -471,15 +473,15 @@ public final class SecurityAdmin implements PermissionAdmin, ConditionalPermissi } private static Bundle createMockBundle(String[] signers) { - Map /* <X509Certificate, List<X509Certificate>> */signersMap = new HashMap(); + Map<X509Certificate, List<X509Certificate>> signersMap = new HashMap<X509Certificate, List<X509Certificate>>(); for (int i = 0; i < signers.length; i++) { - List chain = parseDNchain(signers[i]); - List /* <X509Certificate> */signersList = new ArrayList(); + List<String> chain = parseDNchain(signers[i]); + List<X509Certificate> signersList = new ArrayList<X509Certificate>(); Principal subject = null, issuer = null; X509Certificate first = null; - for (Iterator iChain = chain.iterator(); iChain.hasNext();) { - subject = issuer == null ? new MockPrincipal((String) iChain.next()) : issuer; - issuer = iChain.hasNext() ? new MockPrincipal((String) iChain.next()) : subject; + 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; @@ -493,13 +495,13 @@ public final class SecurityAdmin implements PermissionAdmin, ConditionalPermissi } static class MockBundle implements Bundle { - private final Map signers; + private final Map<X509Certificate, List<X509Certificate>> signers; - MockBundle(Map signers) { + MockBundle(Map<X509Certificate, List<X509Certificate>> signers) { this.signers = signers; } - public Enumeration findEntries(String path, String filePattern, boolean recurse) { + public Enumeration<URL> findEntries(String path, String filePattern, boolean recurse) { return null; } @@ -515,15 +517,15 @@ public final class SecurityAdmin implements PermissionAdmin, ConditionalPermissi return null; } - public Enumeration getEntryPaths(String path) { + public Enumeration<String> getEntryPaths(String path) { return null; } - public Dictionary getHeaders() { - return new Hashtable(); + public Dictionary<String, String> getHeaders() { + return new Hashtable<String, String>(); } - public Dictionary getHeaders(String locale) { + public Dictionary<String, String> getHeaders(String locale) { return getHeaders(); } @@ -535,7 +537,7 @@ public final class SecurityAdmin implements PermissionAdmin, ConditionalPermissi return ""; //$NON-NLS-1$ } - public ServiceReference[] getRegisteredServices() { + public ServiceReference<?>[] getRegisteredServices() { return null; } @@ -546,16 +548,16 @@ public final class SecurityAdmin implements PermissionAdmin, ConditionalPermissi /** * @throws IOException */ - public Enumeration getResources(String name) throws IOException { + public Enumeration<URL> getResources(String name) throws IOException { return null; } - public ServiceReference[] getServicesInUse() { + public ServiceReference<?>[] getServicesInUse() { return null; } - public Map getSignerCertificates(int signersType) { - return new HashMap(signers); + public Map<X509Certificate, List<X509Certificate>> getSignerCertificates(int signersType) { + return new HashMap<X509Certificate, List<X509Certificate>>(signers); } public int getState() { @@ -577,7 +579,7 @@ public final class SecurityAdmin implements PermissionAdmin, ConditionalPermissi /** * @throws ClassNotFoundException */ - public Class loadClass(String name) throws ClassNotFoundException { + public Class<?> loadClass(String name) throws ClassNotFoundException { throw new IllegalStateException(); } @@ -780,7 +782,7 @@ public final class SecurityAdmin implements PermissionAdmin, ConditionalPermissi throw new UnsupportedOperationException(); } - public Set getCriticalExtensionOIDs() { + public Set<String> getCriticalExtensionOIDs() { throw new UnsupportedOperationException(); } @@ -788,7 +790,7 @@ public final class SecurityAdmin implements PermissionAdmin, ConditionalPermissi throw new UnsupportedOperationException(); } - public Set getNonCriticalExtensionOIDs() { + public Set<String> getNonCriticalExtensionOIDs() { throw new UnsupportedOperationException(); } @@ -827,11 +829,11 @@ public final class SecurityAdmin implements PermissionAdmin, ConditionalPermissi } } - private static ArrayList parseDNchain(String dnChain) { + private static List<String> parseDNchain(String dnChain) { if (dnChain == null) { throw new IllegalArgumentException("The DN chain must not be null."); //$NON-NLS-1$ } - ArrayList parsed = new ArrayList(); + List<String> parsed = new ArrayList<String>(); int startIndex = 0; startIndex = skipSpaces(dnChain, startIndex); while (startIndex < dnChain.length()) { 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 index fb3d9b324..25d269449 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. + * Copyright (c) 2008, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -19,7 +19,7 @@ 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 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); @@ -32,7 +32,7 @@ public final class SecurityRow implements ConditionalPermissionInfo { private final PermissionInfoCollection permissionInfoCollection; private final boolean deny; /* GuardedBy(bundleConditions) */ - final HashMap bundleConditions; + final Map<BundlePermissions, Condition[]> bundleConditions; public SecurityRow(SecurityAdmin securityAdmin, String name, ConditionInfo[] conditionInfos, PermissionInfo[] permissionInfos, String decision) { if (permissionInfos == null || permissionInfos.length == 0) @@ -50,7 +50,7 @@ public final class SecurityRow implements ConditionalPermissionInfo { if (conditionInfos == null || conditionInfos.length == 0) bundleConditions = null; else - bundleConditions = new HashMap(); + bundleConditions = new HashMap<BundlePermissions, Condition[]>(); } static SecurityRowSnapShot createSecurityRowSnapShot(String encoded) { @@ -103,8 +103,8 @@ public final class SecurityRow implements ConditionalPermissionInfo { if (decision.length() == 0 || (!ConditionalPermissionInfo.DENY.equalsIgnoreCase(decision) && !ConditionalPermissionInfo.ALLOW.equalsIgnoreCase(decision))) throw new IllegalArgumentException(encoded); - ArrayList condList = new ArrayList(); - ArrayList permList = new ArrayList(); + 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] != '(') @@ -134,8 +134,8 @@ public final class SecurityRow implements ConditionalPermissionInfo { } if (permList.size() == 0) throw new IllegalArgumentException("No Permission infos: " + encoded); //$NON-NLS-1$ - ConditionInfo[] conds = (ConditionInfo[]) condList.toArray(new ConditionInfo[condList.size()]); - PermissionInfo[] perms = (PermissionInfo[]) permList.toArray(new PermissionInfo[permList.size()]); + 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); @@ -243,14 +243,14 @@ public final class SecurityRow implements ConditionalPermissionInfo { /* * TODO: Can we pre-get the Constructors in our own constructor */ - Class clazz; + 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; + Constructor<?> constructor = null; Method method = null; try { method = clazz.getMethod("getCondition", conditionMethodArgs); //$NON-NLS-1$ @@ -287,7 +287,7 @@ public final class SecurityRow implements ConditionalPermissionInfo { return evaluatePermission(permission); Condition[] conditions; synchronized (bundleConditions) { - conditions = (Condition[]) bundleConditions.get(bundlePermissions); + conditions = bundleConditions.get(bundlePermissions); if (conditions == null) { conditions = getConditions(bundlePermissions.getBundle()); bundleConditions.put(bundlePermissions, conditions); @@ -299,7 +299,7 @@ public final class SecurityRow implements ConditionalPermissionInfo { return evaluatePermission(permission); boolean empty = true; - List postponedConditions = null; + List<Condition> postponedConditions = null; Decision postponedPermCheck = null; for (int i = 0; i < conditions.length; i++) { Condition condition = conditions[i]; @@ -327,7 +327,7 @@ public final class SecurityRow implements ConditionalPermissionInfo { 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(1); + postponedConditions = new ArrayList<Condition>(1); postponedConditions.add(condition); } empty &= conditions[i] == null; @@ -338,7 +338,7 @@ public final class SecurityRow implements ConditionalPermissionInfo { } } if (postponedPermCheck != null) - return new Decision(postponedPermCheck.decision | SecurityTable.POSTPONED, (Condition[]) postponedConditions.toArray(new Condition[postponedConditions.size()]), this, bundlePermissions); + return new Decision(postponedPermCheck.decision | SecurityTable.POSTPONED, postponedConditions.toArray(new Condition[postponedConditions.size()]), this, bundlePermissions); return evaluatePermission(permission); } @@ -436,7 +436,7 @@ public final class SecurityRow implements ConditionalPermissionInfo { return; // do nothing if (isSatisfied) { synchronized (row.bundleConditions) { - Condition[] rowConditions = (Condition[]) row.bundleConditions.get(bundlePermissions); + Condition[] rowConditions = row.bundleConditions.get(bundlePermissions); boolean isEmpty = true; for (int i = 0; i < rowConditions.length; i++) { if (rowConditions[i] == condition) 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 index 62d412674..72d587d48 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. + * Copyright (c) 2008, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -123,7 +123,7 @@ public class SecurityTable extends PermissionCollection { throw new SecurityException(); } - public Enumeration elements() { + public Enumeration<Permission> elements() { return BundlePermissions.EMPTY_ENUMERATION; } 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 index 421492407..286e328cc 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. + * Copyright (c) 2008, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -12,19 +12,20 @@ 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 rows; + 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(rows.length); + 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 @@ -35,7 +36,7 @@ public class SecurityTableUpdate implements ConditionalPermissionUpdate { return securityAdmin.commit(rows, timeStamp); } - public List getConditionalPermissionInfos() { + 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/profile/DefaultProfileLogger.java b/bundles/org.eclipse.osgi/core/framework/org/eclipse/osgi/internal/profile/DefaultProfileLogger.java index b3b27e1c8..00d60d93d 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2006 IBM Corporation and others. + * 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 @@ -43,8 +43,8 @@ public class DefaultProfileLogger implements ProfileLogger { private StringBuffer padsb = new StringBuffer(16); // to prevent creating this over and over protected int indent; protected int timePaddingLength; - protected Stack scopeStack; - protected Map scopeToAccumPerfDataMap; + protected Stack<AccumPerfScope> scopeStack; + protected Map<String, AccumPerfData> scopeToAccumPerfDataMap; public DefaultProfileLogger() { initProps(); @@ -168,9 +168,9 @@ public class DefaultProfileLogger implements ProfileLogger { public synchronized void accumLogEnter(String scope) { // Initialize our data structures if (scopeStack == null) - scopeStack = new Stack(); + scopeStack = new Stack<AccumPerfScope>(); if (scopeToAccumPerfDataMap == null) - scopeToAccumPerfDataMap = new TreeMap(); + scopeToAccumPerfDataMap = new TreeMap<String, AccumPerfData>(); // We want getTime() to evaluate as late as possible scopeStack.push(new AccumPerfScope(scope, getTime())); @@ -182,19 +182,19 @@ public class DefaultProfileLogger implements ProfileLogger { // Initialize our data structures if (scopeStack == null) - scopeStack = new Stack(); + scopeStack = new Stack<AccumPerfScope>(); if (scopeToAccumPerfDataMap == null) - scopeToAccumPerfDataMap = new TreeMap(); + scopeToAccumPerfDataMap = new TreeMap<String, AccumPerfData>(); // Do our calculations - AccumPerfScope then = (AccumPerfScope) scopeStack.pop(); + 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 = (AccumPerfData) scopeToAccumPerfDataMap.get(scope); + AccumPerfData now = scopeToAccumPerfDataMap.get(scope); if (now == null) { now = new AccumPerfData(scope); scopeToAccumPerfDataMap.put(scope, now); @@ -291,9 +291,7 @@ public class DefaultProfileLogger implements ProfileLogger { return; // No data; nothing to do timelog.append("\r\n"); //$NON-NLS-1$ timelog.append("Cumulative Log:\r\n"); //$NON-NLS-1$ - Iterator iter = scopeToAccumPerfDataMap.values().iterator(); - while (iter.hasNext()) { - AccumPerfData d = (AccumPerfData) iter.next(); + for (AccumPerfData d : scopeToAccumPerfDataMap.values()) { timelog.append(accumEntryReport(d)); } scopeToAccumPerfDataMap.clear(); 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 index b8c49cadf..aed3e7eca 100644 --- 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 @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2006 IBM Corporation and others. + * 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 @@ -249,7 +249,7 @@ public class Profile { // Try to create it by class name if (profileLoggerClassName != null) { - Class profileImplClass = null; + Class<?> profileImplClass = null; try { profileImplClass = Class.forName(profileLoggerClassName); result = (ProfileLogger) profileImplClass.newInstance(); 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 index a060139ad..dc2559109 100755 --- 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 @@ -803,9 +803,10 @@ public class ServiceRegistry { } /* deliver the event to the snapshot */ - ListenerQueue queue = framework.newListenerQueue(); + ListenerQueue<ServiceListener, FilteredServiceListener, ServiceEvent> queue = framework.newListenerQueue(); for (Map.Entry<BundleContextImpl, Set<Map.Entry<ServiceListener, FilteredServiceListener>>> entry : listenerSnapshot.entrySet()) { - EventDispatcher dispatcher = entry.getKey(); + @SuppressWarnings({"unchecked", "rawtypes"}) + EventDispatcher<ServiceListener, FilteredServiceListener, ServiceEvent> dispatcher = (EventDispatcher) entry.getKey(); Set<Map.Entry<ServiceListener, FilteredServiceListener>> listeners = entry.getValue(); queue.queueListeners(listeners, dispatcher); } 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 index 2dfc94294..2c2e6002f 100644 --- 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 @@ -37,7 +37,9 @@ public class ShrinkableCollection<E> implements Collection<E> { if (c == null) { throw new NullPointerException(); } - list = Collections.EMPTY_LIST; + @SuppressWarnings("unchecked") + List<Collection<? extends E>> empty = Collections.EMPTY_LIST; + list = empty; collection = c; } 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 index 1b194737f..d24ff52a2 100644 --- 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 @@ -15,6 +15,7 @@ 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; @@ -33,21 +34,23 @@ public class Equinox implements Framework { /**@GuardedBy this*/ private Framework impl; private final boolean useSeparateCL; - private final Map configuration; + private final Map<String, Object> configuration; - public Equinox(Map configuration) { + public Equinox(Map<String, ?> configuration) { SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkPermission(new AllPermission()); useSeparateCL = FrameworkProperties.inUse(); - this.configuration = configuration == null ? Collections.EMPTY_MAP : new HashMap(configuration); + @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 (Framework) AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { + return AccessController.doPrivileged(new PrivilegedAction<Framework>() { + public Framework run() { return createImpl0(); } }); @@ -55,8 +58,8 @@ public class Equinox implements Framework { Framework createImpl0() { try { - Class implClazz = getImplClass(); - Constructor constructor = implClazz.getConstructor(new Class[] {Map.class}); + 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); @@ -71,7 +74,7 @@ public class Equinox implements Framework { } } - private Class getImplClass() throws ClassNotFoundException { + private Class<?> getImplClass() throws ClassNotFoundException { ClassLoader thisCL = this.getClass().getClassLoader(); if (!(useSeparateCL && (thisCL instanceof URLClassLoader))) return Class.forName(implName); @@ -83,7 +86,7 @@ public class Equinox implements Framework { private URL[] getFrameworkURLs(URLClassLoader frameworkLoader) { // use the classpath of the framework class loader URL[] cp = frameworkLoader.getURLs(); - ArrayList result = new ArrayList(cp.length); + 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; @@ -93,7 +96,7 @@ public class Equinox implements Framework { } 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 headers = ManifestElement.parseBundleManifest(manifest, new Headers(10)); + Map<String, String> headers = ManifestElement.parseBundleManifest(manifest, new Headers<String, String>(10)); String bsnSpec = getValue(headers, Constants.BUNDLE_SYMBOLICNAME); if (bsnSpec == null) continue; @@ -122,10 +125,10 @@ public class Equinox implements Framework { } } } - return (URL[]) result.toArray(new URL[result.size()]); + return result.toArray(new URL[result.size()]); } - private void addDevClassPaths(URL cp, String bsn, ArrayList result) { + private void addDevClassPaths(URL cp, String bsn, List<URL> result) { if (!cp.getPath().endsWith("/")) //$NON-NLS-1$ return; String[] devPaths = DevClassPathHelper.getDevClassPath(bsn); @@ -145,13 +148,13 @@ public class Equinox implements Framework { } } - private boolean isFrameworkFragment(Map headers, String internalBSN) { + 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 headers, String key) { - String headerSpec = (String) headers.get(key); + private String getValue(Map<String, String> headers, String key) { + String headerSpec = headers.get(key); if (headerSpec == null) return null; ManifestElement[] elements; @@ -179,7 +182,7 @@ public class Equinox implements Framework { return getImpl().waitForStop(timeout); } - public Enumeration findEntries(String path, String filePattern, boolean recurse) { + public Enumeration<URL> findEntries(String path, String filePattern, boolean recurse) { return getImpl().findEntries(path, filePattern, recurse); } @@ -195,15 +198,15 @@ public class Equinox implements Framework { return getImpl().getEntry(path); } - public Enumeration getEntryPaths(String path) { + public Enumeration<String> getEntryPaths(String path) { return getImpl().getEntryPaths(path); } - public Dictionary getHeaders() { + public Dictionary<String, String> getHeaders() { return getImpl().getHeaders(); } - public Dictionary getHeaders(String locale) { + public Dictionary<String, String> getHeaders(String locale) { return getImpl().getHeaders(locale); } @@ -215,7 +218,7 @@ public class Equinox implements Framework { return getImpl().getLocation(); } - public ServiceReference[] getRegisteredServices() { + public ServiceReference<?>[] getRegisteredServices() { return getImpl().getRegisteredServices(); } @@ -223,11 +226,11 @@ public class Equinox implements Framework { return getImpl().getResource(name); } - public Enumeration getResources(String name) throws IOException { + public Enumeration<URL> getResources(String name) throws IOException { return getImpl().getResources(name); } - public ServiceReference[] getServicesInUse() { + public ServiceReference<?>[] getServicesInUse() { return getImpl().getServicesInUse(); } @@ -243,7 +246,7 @@ public class Equinox implements Framework { return getImpl().hasPermission(permission); } - public Class loadClass(String name) throws ClassNotFoundException { + public Class<?> loadClass(String name) throws ClassNotFoundException { return getImpl().loadClass(name); } @@ -275,7 +278,7 @@ public class Equinox implements Framework { getImpl().update(in); } - public Map getSignerCertificates(int signersType) { + public Map<X509Certificate, List<X509Certificate>> getSignerCertificates(int signersType) { return getImpl().getSignerCertificates(signersType); } 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 index 01fd48b94..97c274b4e 100644 --- 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 @@ -25,8 +25,8 @@ class EquinoxFWClassLoader extends URLClassLoader { this.parent = parent; } - protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { - Class clazz = findLoadedClass(name); + protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { + Class<?> clazz = findLoadedClass(name); if (clazz != null) return clazz; 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 index 5c0c9e879..eac9fcb6c 100644 --- 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 @@ -20,7 +20,7 @@ import org.osgi.framework.launch.FrameworkFactory; */ public class EquinoxFactory implements FrameworkFactory { - public Framework newFramework(Map configuration) { + public Framework newFramework(Map<String, String> configuration) { return new Equinox(configuration); } diff --git a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/BaseData.java b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/BaseData.java index 65a6bd25e..1f71470e6 100644 --- a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/BaseData.java +++ b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/BaseData.java @@ -53,11 +53,11 @@ public class BaseData implements BundleData { private long lastModified; protected BundleFile bundleFile; private boolean dirty = false; - protected Dictionary manifest; + protected Dictionary<String, String> manifest; // This field is only used by PDE source lookup, and is set by a hook (bug 126517). It serves no purpose at runtime. protected String fileName; // This is only used to keep track of when the same native library is loaded more than once - protected Collection loadedNativeCode; + protected Collection<String> loadedNativeCode; ///////////////////// Begin values from Manifest ///////////////////// private String symbolicName; @@ -100,8 +100,8 @@ public class BaseData implements BundleData { public final URL getEntry(final String path) { if (System.getSecurityManager() == null) return getEntry0(path); - return (URL) AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { + return AccessController.doPrivileged(new PrivilegedAction<URL>() { + public URL run() { return getEntry0(path); } }); @@ -120,7 +120,7 @@ public class BaseData implements BundleData { } } - public final Enumeration getEntryPaths(String path) { + public final Enumeration<String> getEntryPaths(String path) { return getBundleFile().getEntryPaths(path); } @@ -141,7 +141,7 @@ public class BaseData implements BundleData { if (result != null) synchronized (this) { if (loadedNativeCode == null) - loadedNativeCode = new ArrayList(1); + loadedNativeCode = new ArrayList<String>(1); if (loadedNativeCode.contains(result) || COPY_NATIVES) { // we must copy the library to a temp space to allow another class loader to load the library String temp = copyToTempLibrary(result); @@ -171,7 +171,7 @@ public class BaseData implements BundleData { return adaptor.getStorage().getDataFile(this, path); } - public Dictionary getManifest() throws BundleException { + public Dictionary<String, String> getManifest() throws BundleException { if (manifest == null) manifest = adaptor.getStorage().loadManifest(this); return manifest; @@ -409,7 +409,7 @@ public class BaseData implements BundleData { return new String[] {"."}; //$NON-NLS-1$ } - ArrayList result = new ArrayList(classpath.length); + List<String> result = new ArrayList<String>(classpath.length); for (int i = 0; i < classpath.length; i++) { if (Debug.DEBUG_LOADER) Debug.println(" found classpath entry " + classpath[i].getValueComponents()); //$NON-NLS-1$ @@ -419,7 +419,7 @@ public class BaseData implements BundleData { } } - return (String[]) result.toArray(new String[result.size()]); + return result.toArray(new String[result.size()]); } /** diff --git a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/HookRegistry.java b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/HookRegistry.java index de883f841..e0c91e0c8 100644 --- a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/HookRegistry.java +++ b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/HookRegistry.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2009 IBM Corporation and others. + * 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 @@ -93,20 +93,20 @@ public final class HookRegistry { * @return an array of error log entries that occurred while initializing the hooks */ public FrameworkLogEntry[] initialize() { - ArrayList configurators = new ArrayList(5); - ArrayList errors = new ArrayList(0); // optimistic that no errors will occur + List<String> configurators = new ArrayList<String>(5); + List<FrameworkLogEntry> errors = new ArrayList<FrameworkLogEntry>(0); // optimistic that no errors will occur mergeFileHookConfigurators(configurators, errors); mergePropertyHookConfigurators(configurators); loadConfigurators(configurators, errors); // set to read-only readonly = true; - return (FrameworkLogEntry[]) errors.toArray(new FrameworkLogEntry[errors.size()]); + return errors.toArray(new FrameworkLogEntry[errors.size()]); } - private void mergeFileHookConfigurators(ArrayList configuratorList, ArrayList errors) { + private void mergeFileHookConfigurators(List<String> configuratorList, List<FrameworkLogEntry> errors) { ClassLoader cl = getClass().getClassLoader(); // get all hook configurators files in your classloader delegation - Enumeration hookConfigurators; + Enumeration<URL> hookConfigurators; try { hookConfigurators = cl != null ? cl.getResources(HookRegistry.HOOK_CONFIGURATORS_FILE) : ClassLoader.getSystemResources(HookRegistry.HOOK_CONFIGURATORS_FILE); } catch (IOException e) { @@ -115,7 +115,7 @@ public final class HookRegistry { } int curBuiltin = 0; while (hookConfigurators.hasMoreElements()) { - URL url = (URL) hookConfigurators.nextElement(); + URL url = hookConfigurators.nextElement(); InputStream input = null; try { // check each file for a hook.configurators property @@ -148,7 +148,7 @@ public final class HookRegistry { } } - private void mergePropertyHookConfigurators(ArrayList configuratorList) { + private void mergePropertyHookConfigurators(List<String> configuratorList) { // see if there is a configurators list String[] configurators = ManifestElement.getArrayFromList(FrameworkProperties.getProperty(HookRegistry.PROP_HOOK_CONFIGURATORS), ","); //$NON-NLS-1$ if (configurators.length > 0) { @@ -169,11 +169,11 @@ public final class HookRegistry { configuratorList.remove(excludeHooks[i]); } - private void loadConfigurators(ArrayList configurators, ArrayList errors) { - for (Iterator iHooks = configurators.iterator(); iHooks.hasNext();) { - String hookName = (String) iHooks.next(); + private void loadConfigurators(List<String> configurators, List<FrameworkLogEntry> errors) { + for (Iterator<String> iHooks = configurators.iterator(); iHooks.hasNext();) { + String hookName = iHooks.next(); try { - Class clazz = Class.forName(hookName); + Class<?> clazz = Class.forName(hookName); HookConfigurator configurator = (HookConfigurator) clazz.newInstance(); configurator.addHooks(this); } catch (Throwable t) { diff --git a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/BundleFile.java b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/BundleFile.java index 35d4cc5fe..011359dab 100644 --- a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/BundleFile.java +++ b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/BundleFile.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2004, 2009 IBM Corporation and others. + * 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 @@ -16,8 +16,7 @@ import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.security.AccessController; -import java.util.ArrayList; -import java.util.Enumeration; +import java.util.*; import org.eclipse.osgi.baseadaptor.BaseData; import org.eclipse.osgi.framework.internal.core.*; import org.eclipse.osgi.framework.internal.protocol.bundleresource.Handler; @@ -34,7 +33,7 @@ import org.eclipse.osgi.util.ManifestElement; */ abstract public class BundleFile { protected static final String PROP_SETPERMS_CMD = "osgi.filepermissions.command"; //$NON-NLS-1$ - static final SecureAction secureAction = (SecureAction) AccessController.doPrivileged(SecureAction.createSecureAction()); + static final SecureAction secureAction = AccessController.doPrivileged(SecureAction.createSecureAction()); /** * The File object for this BundleFile. */ @@ -91,7 +90,7 @@ abstract public class BundleFile { * @return an Enumeration of Strings that indicate the paths found or * null if the path does not exist. */ - abstract public Enumeration getEntryPaths(String path); + abstract public Enumeration<String> getEntryPaths(String path); /** * Closes the BundleFile. @@ -189,7 +188,7 @@ abstract public class BundleFile { if (commandProp == null) return; String[] temp = ManifestElement.getArrayFromList(commandProp, " "); //$NON-NLS-1$ - ArrayList command = new ArrayList(temp.length + 1); + List<String> command = new ArrayList<String>(temp.length + 1); boolean foundFullPath = false; for (int i = 0; i < temp.length; i++) { if ("[fullpath]".equals(temp[i]) || "${abspath}".equals(temp[i])) { //$NON-NLS-1$ //$NON-NLS-2$ @@ -201,7 +200,7 @@ abstract public class BundleFile { if (!foundFullPath) command.add(file.getAbsolutePath()); try { - Runtime.getRuntime().exec((String[]) command.toArray(new String[command.size()])).waitFor(); + Runtime.getRuntime().exec(command.toArray(new String[command.size()])).waitFor(); } catch (Exception e) { e.printStackTrace(); } diff --git a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/BundleFileWrapperChain.java b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/BundleFileWrapperChain.java index 29f2fd2dc..24e4730d5 100644 --- a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/BundleFileWrapperChain.java +++ b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/BundleFileWrapperChain.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008 IBM Corporation and others. + * Copyright (c) 2008, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -11,13 +11,12 @@ package org.eclipse.osgi.baseadaptor.bundlefile; -import org.eclipse.osgi.baseadaptor.hooks.BundleFileWrapperFactoryHook; - import java.io.File; import java.io.IOException; import java.net.URL; import java.util.Enumeration; import org.eclipse.osgi.baseadaptor.BaseData; +import org.eclipse.osgi.baseadaptor.hooks.BundleFileWrapperFactoryHook; /** * Used to chain the BundleFile objects returned from {@link BundleFileWrapperFactoryHook}. @@ -44,7 +43,7 @@ public class BundleFileWrapperChain extends BundleFile { return wrapped.getEntry(path); } - public Enumeration getEntryPaths(String path) { + public Enumeration<String> getEntryPaths(String path) { return wrapped.getEntryPaths(path); } diff --git a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/DirBundleFile.java b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/DirBundleFile.java index 1bf864335..64c3f7191 100644 --- a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/DirBundleFile.java +++ b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/DirBundleFile.java @@ -66,7 +66,7 @@ public class DirBundleFile extends BundleFile { return dirPath != null && BundleFile.secureAction.isDirectory(dirPath); } - public Enumeration getEntryPaths(String path) { + public Enumeration<String> getEntryPaths(String path) { if (path.length() > 0 && path.charAt(0) == '/') path = path.substring(1); final File pathFile = getFile(path, false); @@ -76,14 +76,14 @@ public class DirBundleFile extends BundleFile { if (fileList == null || fileList.length == 0) return null; final String dirPath = path.length() == 0 || path.charAt(path.length() - 1) == '/' ? path : path + '/'; - return new Enumeration() { + return new Enumeration<String>() { int cur = 0; public boolean hasMoreElements() { return fileList != null && cur < fileList.length; } - public Object nextElement() { + public String nextElement() { if (!hasMoreElements()) { throw new NoSuchElementException(); } diff --git a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/DirZipBundleEntry.java b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/DirZipBundleEntry.java index bd216798b..de3209a4b 100644 --- a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/DirZipBundleEntry.java +++ b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/DirZipBundleEntry.java @@ -57,6 +57,7 @@ public class DirZipBundleEntry extends BundleEntry { return 0; } + @SuppressWarnings("deprecation") public URL getLocalURL() { try { return new URL("jar:" + bundleFile.basefile.toURL() + "!/" + name); //$NON-NLS-1$ //$NON-NLS-2$ @@ -66,6 +67,7 @@ public class DirZipBundleEntry extends BundleEntry { } } + @SuppressWarnings("deprecation") public URL getFileURL() { try { return bundleFile.extractDirectory(name).toURL(); diff --git a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/FileBundleEntry.java b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/FileBundleEntry.java index 5c143adc5..686aef5d6 100644 --- a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/FileBundleEntry.java +++ b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/FileBundleEntry.java @@ -89,6 +89,7 @@ public class FileBundleEntry extends BundleEntry { return getFileURL(); } + @SuppressWarnings("deprecation") public URL getFileURL() { try { return file.toURL(); diff --git a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/MRUBundleFileList.java b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/MRUBundleFileList.java index 1ac4e5821..40f75afef 100644 --- a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/MRUBundleFileList.java +++ b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/MRUBundleFileList.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2009 IBM Corporation and others. + * 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 @@ -22,11 +22,11 @@ import org.eclipse.osgi.framework.eventmgr.*; * file limit. * @since 3.2 */ -public class MRUBundleFileList implements EventDispatcher { +public class MRUBundleFileList implements EventDispatcher<Object, Object, BundleFile> { private static final String PROP_FILE_LIMIT = "osgi.bundlefile.limit"; //$NON-NLS-1$ private static final int MIN = 10; private static final int PROP_FILE_LIMIT_VALUE; - private static final ThreadLocal closingBundleFile = new ThreadLocal(); + private static final ThreadLocal<BundleFile> closingBundleFile = new ThreadLocal<BundleFile>(); static { int propValue = 100; // enable to 100 open files by default try { @@ -45,7 +45,7 @@ public class MRUBundleFileList implements EventDispatcher { // the limit of open files to allow before least used bundle file is closed final private int fileLimit; // value < MIN will disable MRU final private EventManager bundleFileCloserManager; - final private Map bundleFileCloser; + final private Map<Object, Object> bundleFileCloser; // the current number of open bundle files private int numOpen = 0; // the current use stamp @@ -64,7 +64,7 @@ public class MRUBundleFileList implements EventDispatcher { this.bundleFileList = new BundleFile[fileLimit]; this.useStampList = new long[fileLimit]; this.bundleFileCloserManager = new EventManager("Bundle File Closer"); //$NON-NLS-1$ - this.bundleFileCloser = new CopyOnWriteIdentityMap(); + this.bundleFileCloser = new CopyOnWriteIdentityMap<Object, Object>(); this.bundleFileCloser.put(this, this); } else { this.bundleFileList = null; @@ -172,7 +172,7 @@ public class MRUBundleFileList implements EventDispatcher { useStampList[index] = ++curUseStamp; } - public final void dispatchEvent(Object eventListener, Object listenerObject, int eventAction, Object eventObject) { + public final void dispatchEvent(Object eventListener, Object listenerObject, int eventAction, BundleFile eventObject) { if (firstDispatch) { // used to work around bug 275166; we don't want to leak the TCCL in this thread. Thread.currentThread().setContextClassLoader(null); @@ -180,7 +180,7 @@ public class MRUBundleFileList implements EventDispatcher { } try { closingBundleFile.set(eventObject); - ((BundleFile) eventObject).close(); + eventObject.close(); } catch (IOException e) { // TODO should log ?? } finally { @@ -193,7 +193,7 @@ public class MRUBundleFileList implements EventDispatcher { return; try { /* queue to hold set of listeners */ - ListenerQueue queue = new ListenerQueue(bundleFileCloserManager); + ListenerQueue<Object, Object, BundleFile> queue = new ListenerQueue<Object, Object, BundleFile>(bundleFileCloserManager); /* add bundle file closer to the queue */ queue.queueListeners(bundleFileCloser.entrySet(), this); /* dispatch event to set of listeners */ diff --git a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/NestedDirBundleFile.java b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/NestedDirBundleFile.java index e3b5d13fd..fbace46ca 100644 --- a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/NestedDirBundleFile.java +++ b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/NestedDirBundleFile.java @@ -66,7 +66,7 @@ public class NestedDirBundleFile extends BundleFile { return baseBundleFile.containsDir(newdir); } - public Enumeration getEntryPaths(String path) { + public Enumeration<String> getEntryPaths(String path) { // getEntryPaths is only valid if this is a root bundle file. return null; } diff --git a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/ZipBundleEntry.java b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/ZipBundleEntry.java index 37495b465..06a46aa9b 100644 --- a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/ZipBundleEntry.java +++ b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/ZipBundleEntry.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2009 IBM Corporation and others. + * 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 @@ -94,6 +94,7 @@ public class ZipBundleEntry extends BundleEntry { return zipEntry.getTime(); } + @SuppressWarnings("deprecation") public URL getLocalURL() { try { return new URL("jar:" + bundleFile.basefile.toURL() + "!/" + zipEntry.getName()); //$NON-NLS-1$//$NON-NLS-2$ @@ -103,6 +104,7 @@ public class ZipBundleEntry extends BundleEntry { } } + @SuppressWarnings("deprecation") public URL getFileURL() { try { File file = bundleFile.getFile(zipEntry.getName(), false); diff --git a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/ZipBundleFile.java b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/ZipBundleFile.java index 74f1a89b0..9ce5c789d 100644 --- a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/ZipBundleFile.java +++ b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/bundlefile/ZipBundleFile.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2008 IBM Corporation and others. + * 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 @@ -13,8 +13,7 @@ package org.eclipse.osgi.baseadaptor.bundlefile; import java.io.*; -import java.util.Enumeration; -import java.util.Vector; +import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.eclipse.osgi.baseadaptor.BaseData; @@ -135,9 +134,9 @@ public class ZipBundleFile extends BundleFile { protected synchronized File extractDirectory(String dirName) { if (!checkedOpen()) return null; - Enumeration entries = zipFile.entries(); + Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { - String entryPath = ((ZipEntry) entries.nextElement()).getName(); + String entryPath = entries.nextElement().getName(); if (entryPath.startsWith(dirName) && !entryPath.endsWith("/")) //$NON-NLS-1$ getFile(entryPath, false); } @@ -229,11 +228,11 @@ public class ZipBundleFile extends BundleFile { if (dir.length() > 0 && dir.charAt(dir.length() - 1) != '/') dir = dir + '/'; - Enumeration entries = zipFile.entries(); + Enumeration<? extends ZipEntry> entries = zipFile.entries(); ZipEntry zipEntry; String entryPath; while (entries.hasMoreElements()) { - zipEntry = (ZipEntry) entries.nextElement(); + zipEntry = entries.nextElement(); entryPath = zipEntry.getName(); if (entryPath.startsWith(dir)) { return true; @@ -259,7 +258,7 @@ public class ZipBundleFile extends BundleFile { } - public synchronized Enumeration getEntryPaths(String path) { + public synchronized Enumeration<String> getEntryPaths(String path) { if (!checkedOpen()) return null; if (path == null) @@ -270,10 +269,10 @@ public class ZipBundleFile extends BundleFile { if (path.length() > 0 && path.charAt(path.length() - 1) != '/') path = new StringBuffer(path).append("/").toString(); //$NON-NLS-1$ - Vector vEntries = new Vector(); - Enumeration entries = zipFile.entries(); + List<String> vEntries = new ArrayList<String>(); + Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { - ZipEntry zipEntry = (ZipEntry) entries.nextElement(); + ZipEntry zipEntry = entries.nextElement(); String entryPath = zipEntry.getName(); if (entryPath.startsWith(path)) { if (path.length() < entryPath.length()) { @@ -289,7 +288,7 @@ public class ZipBundleFile extends BundleFile { } } } - return vEntries.size() == 0 ? null : vEntries.elements(); + return vEntries.size() == 0 ? null : Collections.enumeration(vEntries); } public synchronized void close() throws IOException { diff --git a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/hooks/ClassLoadingHook.java b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/hooks/ClassLoadingHook.java index 896b6d639..59e36eac4 100644 --- a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/hooks/ClassLoadingHook.java +++ b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/hooks/ClassLoadingHook.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2006 IBM Corporation and others. + * 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 @@ -49,7 +49,7 @@ public interface ClassLoadingHook { * @param sourcedomain the source domain of the requested ClasspathEntry * @return true if a ClasspathEntry has been added to cpEntries */ - boolean addClassPathEntry(ArrayList cpEntries, String cp, ClasspathManager hostmanager, BaseData sourcedata, ProtectionDomain sourcedomain); + boolean addClassPathEntry(ArrayList<ClasspathEntry> cpEntries, String cp, ClasspathManager hostmanager, BaseData sourcedata, ProtectionDomain sourcedomain); /** * Gets called by a base data during {@link BundleData#findLibrary(String)}. diff --git a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/hooks/ClassLoadingStatsHook.java b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/hooks/ClassLoadingStatsHook.java index 41a320c61..26a84a160 100644 --- a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/hooks/ClassLoadingStatsHook.java +++ b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/hooks/ClassLoadingStatsHook.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006 IBM Corporation and others. + * Copyright (c) 2006, 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 @@ -44,7 +44,7 @@ public interface ClassLoadingStatsHook { * @param clazz the loaded class or null if not found * @param manager the classpath manager used to find and load the requested class */ - void postFindLocalClass(String name, Class clazz, ClasspathManager manager) throws ClassNotFoundException; + void postFindLocalClass(String name, Class<?> clazz, ClasspathManager manager) throws ClassNotFoundException; /** * Gets called by a classpath manager during {@link ClasspathManager#findLocalResource(String)} before @@ -75,6 +75,6 @@ public interface ClassLoadingStatsHook { * @param entry the BundleEntyr source of the class bytes * @param manager the classpath manager used to define the class */ - void recordClassDefine(String name, Class clazz, byte[] classbytes, ClasspathEntry classpathEntry, BundleEntry entry, ClasspathManager manager); + void recordClassDefine(String name, Class<?> clazz, byte[] classbytes, ClasspathEntry classpathEntry, BundleEntry entry, ClasspathManager manager); } diff --git a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/hooks/StorageHook.java b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/hooks/StorageHook.java index 28a7b8c3f..160f2c128 100644 --- a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/hooks/StorageHook.java +++ b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/hooks/StorageHook.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2008 IBM Corporation and others. + * 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 @@ -55,7 +55,7 @@ public interface StorageHook extends KeyedElement { * @param manifest the bundle manifest to load into this storage hook * @throws BundleException if any error occurs */ - void initialize(Dictionary manifest) throws BundleException; + void initialize(Dictionary<String, String> manifest) throws BundleException; /** * Creates a new storage hook and loads the data from the specified @@ -112,7 +112,7 @@ public interface StorageHook extends KeyedElement { * not provide the manifest * @throws BundleException */ - Dictionary getManifest(boolean firstLoad) throws BundleException; + Dictionary<String, String> getManifest(boolean firstLoad) throws BundleException; /** * Gets called by a base data during {@link BundleData#setStatus(int)}. diff --git a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/loader/BaseClassLoader.java b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/loader/BaseClassLoader.java index c10632a3e..5f727076a 100644 --- a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/loader/BaseClassLoader.java +++ b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/loader/BaseClassLoader.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * 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 @@ -46,14 +46,14 @@ public interface BaseClassLoader extends BundleClassLoader { * @param entry the bundle entry used to load the class bytes * @return a defined Class */ - Class defineClass(String name, byte[] classbytes, ClasspathEntry classpathEntry, BundleEntry entry); + Class<?> defineClass(String name, byte[] classbytes, ClasspathEntry classpathEntry, BundleEntry entry); /** * A public version of the ClassLoader.findLoadedClass(java.lang.String) method. * @param classname the class name to find. * @return a loaded class */ - Class publicFindLoaded(String classname); + Class<?> publicFindLoaded(String classname); /** * A public version of the ClassLoader#getPackage(java.lang.String) method. diff --git a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/loader/ClasspathManager.java b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/loader/ClasspathManager.java index e338dba9b..0b1823666 100644 --- a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/loader/ClasspathManager.java +++ b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/baseadaptor/loader/ClasspathManager.java @@ -55,8 +55,8 @@ public class ClasspathManager { // Note that PDE has internal dependency on this field type/name (bug 267238) private FragmentClasspath[] fragments = emptyFragments; // a collection of String[2], each element is {"libname", "libpath"} - private Collection loadedLibraries = null; - private HashMap classNameLocks = new HashMap(5); + private Collection<String[]> loadedLibraries = null; + private Map<String, Thread> classNameLocks = new HashMap<String, Thread>(5); private final boolean isParallelClassLoader; /** @@ -144,11 +144,11 @@ public class ClasspathManager { } private static ClasspathEntry[] buildClasspath(String[] cp, ClasspathManager hostloader, BaseData sourcedata, ProtectionDomain sourcedomain) { - ArrayList result = new ArrayList(cp.length); + ArrayList<ClasspathEntry> result = new ArrayList<ClasspathEntry>(cp.length); // add the regular classpath entries. for (int i = 0; i < cp.length; i++) findClassPathEntry(result, cp[i], hostloader, sourcedata, sourcedomain); - return (ClasspathEntry[]) result.toArray(new ClasspathEntry[result.size()]); + return result.toArray(new ClasspathEntry[result.size()]); } /** @@ -163,7 +163,7 @@ public class ClasspathManager { * @param sourcedata the source EquionoxData to search for the classpath * @param sourcedomain the source domain to used by the new ClasspathEntry */ - public static void findClassPathEntry(ArrayList result, String cp, ClasspathManager hostloader, BaseData sourcedata, ProtectionDomain sourcedomain) { + public static void findClassPathEntry(ArrayList<ClasspathEntry> result, String cp, ClasspathManager hostloader, BaseData sourcedata, ProtectionDomain sourcedomain) { // look in classpath manager hooks first ClassLoadingHook[] loaderHooks = sourcedata.getAdaptor().getHookRegistry().getClassLoadingHooks(); boolean hookAdded = false; @@ -186,7 +186,7 @@ public class ClasspathManager { * @param sourcedomain the source domain to used by the new ClasspathEntry * @return true if a ClasspathEntry was added to the result */ - public static boolean addClassPathEntry(ArrayList result, String cp, ClasspathManager hostloader, BaseData sourcedata, ProtectionDomain sourcedomain) { + public static boolean addClassPathEntry(ArrayList<ClasspathEntry> result, String cp, ClasspathManager hostloader, BaseData sourcedata, ProtectionDomain sourcedomain) { if (cp.equals(".")) { //$NON-NLS-1$ result.add(hostloader.createClassPathEntry(sourcedata.getBundleFile(), sourcedomain, sourcedata)); return true; @@ -321,14 +321,14 @@ public class ClasspathManager { * @param resource the requested resource name. * @return an enumeration of the the requested resources or null if the resources do not exist */ - public Enumeration findLocalResources(String resource) { - Vector resources = new Vector(6); // use a Vector instead of ArrayList because we need an enumeration + public Enumeration<URL> findLocalResources(String resource) { + List<URL> resources = new ArrayList<URL>(6); int classPathIndex = 0; for (int i = 0; i < entries.length; i++) { if (entries[i] != null) { URL url = findResourceImpl(resource, entries[i].getBundleFile(), classPathIndex); if (url != null) - resources.addElement(url); + resources.add(url); } classPathIndex++; } @@ -338,12 +338,12 @@ public class ClasspathManager { for (int j = 0; j < fragEntries.length; j++) { URL url = findResourceImpl(resource, fragEntries[j].getBundleFile(), classPathIndex); if (url != null) - resources.addElement(url); + resources.add(url); classPathIndex++; } } if (resources.size() > 0) - return resources.elements(); + return Collections.enumeration(resources); return null; } @@ -396,13 +396,13 @@ public class ClasspathManager { * @param path the requested entry path. * @return an enumeration of the the requested entries or null if the entries do not exist */ - public Enumeration findLocalEntries(String path) { - Vector objects = new Vector(6); // use a Vector instead of ArrayList because we need an enumeration + public Enumeration<BundleEntry> findLocalEntries(String path) { + List<BundleEntry> objects = new ArrayList<BundleEntry>(6); for (int i = 0; i < entries.length; i++) { if (entries[i] != null) { BundleEntry result = findEntryImpl(path, entries[i].getBundleFile()); if (result != null) - objects.addElement(result); + objects.add(result); } } // look in fragments @@ -411,11 +411,11 @@ public class ClasspathManager { for (int j = 0; j < fragEntries.length; j++) { BundleEntry result = findEntryImpl(path, fragEntries[j].getBundleFile()); if (result != null) - objects.addElement(result); + objects.add(result); } } if (objects.size() > 0) - return objects.elements(); + return Collections.enumeration(objects); return null; } @@ -437,8 +437,8 @@ public class ClasspathManager { * @return the requested class * @throws ClassNotFoundException if the class does not exist */ - public Class findLocalClass(String classname) throws ClassNotFoundException { - Class result = null; + public Class<?> findLocalClass(String classname) throws ClassNotFoundException { + Class<?> result = null; ClassLoadingStatsHook[] hooks = data.getAdaptor().getHookRegistry().getClassLoadingStatsHooks(); try { for (int i = 0; i < hooks.length; i++) @@ -454,7 +454,7 @@ public class ClasspathManager { } } - private Class findLocalClass_LockClassName(String classname, ClassLoadingStatsHook[] hooks) throws ClassNotFoundException { + private Class<?> findLocalClass_LockClassName(String classname, ClassLoadingStatsHook[] hooks) throws ClassNotFoundException { boolean initialLock = lockClassName(classname); try { return findLocalClassImpl(classname, hooks); @@ -464,16 +464,16 @@ public class ClasspathManager { } } - private Class findLocalClass_LockClassLoader(String classname, ClassLoadingStatsHook[] hooks) throws ClassNotFoundException { + private Class<?> findLocalClass_LockClassLoader(String classname, ClassLoadingStatsHook[] hooks) throws ClassNotFoundException { synchronized (classloader) { return findLocalClassImpl(classname, hooks); } } - private Class findLocalClassImpl(String classname, ClassLoadingStatsHook[] hooks) throws ClassNotFoundException { + private Class<?> findLocalClassImpl(String classname, ClassLoadingStatsHook[] hooks) throws ClassNotFoundException { // must call findLoadedClass here even if it was called earlier, // the findLoadedClass and defineClass calls must be atomic - Class result = classloader.publicFindLoaded(classname); + Class<?> result = classloader.publicFindLoaded(classname); if (result != null) return result; for (int i = 0; i < entries.length; i++) { @@ -524,7 +524,7 @@ public class ClasspathManager { } } - private Class findClassImpl(String name, ClasspathEntry classpathEntry, ClassLoadingStatsHook[] hooks) { + private Class<?> findClassImpl(String name, ClasspathEntry classpathEntry, ClassLoadingStatsHook[] hooks) { if (Debug.DEBUG_LOADER) Debug.println("BundleClassLoader[" + classpathEntry.getBundleFile() + "].findClass(" + name + ")"); //$NON-NLS-1$ //$NON-NLS-2$//$NON-NLS-3$ String filename = name.replace('.', '/').concat(".class"); //$NON-NLS-1$ @@ -568,7 +568,7 @@ public class ClasspathManager { * @param statsHooks the class loading stat hooks * @return the defined class */ - private Class defineClass(String name, byte[] classbytes, ClasspathEntry classpathEntry, BundleEntry entry, ClassLoadingStatsHook[] statsHooks) { + private Class<?> defineClass(String name, byte[] classbytes, ClasspathEntry classpathEntry, BundleEntry entry, ClassLoadingStatsHook[] statsHooks) { ClassLoadingHook[] hooks = data.getAdaptor().getHookRegistry().getClassLoadingHooks(); byte[] modifiedBytes = classbytes; for (int i = 0; i < hooks.length; i++) { @@ -577,7 +577,7 @@ public class ClasspathManager { classbytes = modifiedBytes; } - Class result = classloader.defineClass(name, classbytes, classpathEntry, entry); + Class<?> result = classloader.defineClass(name, classbytes, classpathEntry, entry); for (int i = 0; i < statsHooks.length; i++) statsHooks[i].recordClassDefine(name, result, classbytes, classpathEntry, entry, this); @@ -619,14 +619,14 @@ public class ClasspathManager { public String findLibrary(String libname) { synchronized (this) { if (loadedLibraries == null) - loadedLibraries = new ArrayList(1); + loadedLibraries = new ArrayList<String[]>(1); } synchronized (loadedLibraries) { // we assume that each classloader will load a small number of of libraries // instead of wasting space with a map we iterate over our collection of found libraries // each element is a String[2], each array is {"libname", "libpath"} - for (Iterator libs = loadedLibraries.iterator(); libs.hasNext();) { - String[] libNameResult = (String[]) libs.next(); + for (Iterator<String[]> libs = loadedLibraries.iterator(); libs.hasNext();) { + String[] libNameResult = libs.next(); if (libNameResult[0].equals(libname)) return libNameResult[1]; } diff --git a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/framework/internal/protocol/reference/ReferenceURLConnection.java b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/framework/internal/protocol/reference/ReferenceURLConnection.java index 4c8ecc19a..f58a4b302 100644 --- a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/framework/internal/protocol/reference/ReferenceURLConnection.java +++ b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/framework/internal/protocol/reference/ReferenceURLConnection.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2003, 2009 IBM Corporation and others. + * 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 @@ -29,6 +29,7 @@ public class ReferenceURLConnection extends URLConnection { super(url); } + @SuppressWarnings("deprecation") public synchronized void connect() throws IOException { if (!connected) { // TODO assumes that reference URLs are always based on file: URLs. diff --git a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/AdaptorUtil.java b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/AdaptorUtil.java index 44e5cbaee..419850cb9 100644 --- a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/AdaptorUtil.java +++ b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/AdaptorUtil.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2009 IBM Corporation and others. + * 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 @@ -174,16 +174,16 @@ public class AdaptorUtil { * @param context the registering bundle context * @return the service registration object */ - public static ServiceRegistration register(String name, Object service, BundleContext context) { - Hashtable properties = new Hashtable(7); - Dictionary headers = context.getBundle().getHeaders(); + public static ServiceRegistration<?> register(String name, Object service, BundleContext context) { + Dictionary<String, Object> properties = new Hashtable<String, Object>(7); + Dictionary<String, String> headers = context.getBundle().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, context.getBundle().getBundleId() + "." + service.getClass().getName()); //$NON-NLS-1$ return context.registerService(name, service, properties); } - public static Dictionary loadManifestFrom(BaseData bundledata) throws BundleException { + public static Dictionary<String, String> loadManifestFrom(BaseData bundledata) throws BundleException { URL url = bundledata.getEntry(Constants.OSGI_BUNDLE_MANIFEST); if (url == null) return null; @@ -216,6 +216,7 @@ public class AdaptorUtil { return true; } + @SuppressWarnings("deprecation") public static URL encodeFileURL(File file) throws MalformedURLException { try { Method toURI = File.class.getMethod("toURI", (Class[]) null); //$NON-NLS-1$ diff --git a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/BaseClassLoadingHook.java b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/BaseClassLoadingHook.java index 0195ba21c..8431ac3f3 100644 --- a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/BaseClassLoadingHook.java +++ b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/BaseClassLoadingHook.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2009 IBM Corporation and others. + * 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 @@ -104,7 +104,7 @@ public class BaseClassLoadingHook implements ClassLoadingHook { return storageHook != null ? storageHook.getNativePaths() : null; } - public boolean addClassPathEntry(ArrayList cpEntries, String cp, ClasspathManager hostmanager, BaseData sourcedata, ProtectionDomain sourcedomain) { + public boolean addClassPathEntry(ArrayList<ClasspathEntry> cpEntries, String cp, ClasspathManager hostmanager, BaseData sourcedata, ProtectionDomain sourcedomain) { // do nothing return false; } diff --git a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/BasePermissionStorage.java b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/BasePermissionStorage.java index bbfff9d88..120861572 100644 --- a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/BasePermissionStorage.java +++ b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/BasePermissionStorage.java @@ -12,13 +12,12 @@ package org.eclipse.osgi.internal.baseadaptor; import java.io.IOException; -import java.util.HashMap; -import java.util.Iterator; +import java.util.*; import org.eclipse.osgi.framework.adaptor.PermissionStorage; public class BasePermissionStorage implements PermissionStorage { - private HashMap locations = new HashMap(); + private Map<String, String[]> locations = new HashMap<String, String[]>(); private String[] defaultInfos; private String[] condPermInfos; private BaseStorage storage; @@ -35,8 +34,8 @@ public class BasePermissionStorage implements PermissionStorage { synchronized (locations) { String[] result = new String[locations.size()]; int i = 0; - for (Iterator iLocs = locations.keySet().iterator(); iLocs.hasNext(); i++) - result[i] = (String) iLocs.next(); + for (Iterator<String> iLocs = locations.keySet().iterator(); iLocs.hasNext(); i++) + result[i] = iLocs.next(); return result; } } @@ -50,7 +49,7 @@ public class BasePermissionStorage implements PermissionStorage { synchronized (locations) { if (locations.size() == 0) return null; - return (String[]) locations.get(location); + return locations.get(location); } } diff --git a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/BaseStorage.java b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/BaseStorage.java index 5bbc97fa5..26e981380 100644 --- a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/BaseStorage.java +++ b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/BaseStorage.java @@ -159,7 +159,7 @@ public class BaseStorage implements SynchronousBundleListener { } // recursively searches a class and it's superclasses for a (potentially inaccessable) method - private static Method findMethod(Class clazz, String name, Class[] args) { + private static Method findMethod(Class<?> clazz, String name, Class<?>[] args) { if (clazz == null) return null; // ends the recursion when getSuperClass returns null try { @@ -298,12 +298,12 @@ public class BaseStorage implements SynchronousBundleListener { } } - public Dictionary loadManifest(BaseData data) throws BundleException { + public Dictionary<String, String> loadManifest(BaseData data) throws BundleException { return loadManifest(data, false); } - public Dictionary loadManifest(BaseData bundleData, boolean firstTime) throws BundleException { - Dictionary result = null; + public Dictionary<String, String> loadManifest(BaseData bundleData, boolean firstTime) throws BundleException { + Dictionary<String, String> result = null; StorageHook[] dataStorageHooks = bundleData.getStorageHooks(); for (int i = 0; i < dataStorageHooks.length && result == null; i++) result = dataStorageHooks[i].getManifest(firstTime); @@ -380,7 +380,7 @@ public class BaseStorage implements SynchronousBundleListener { } int bundleCount = in.readInt(); - ArrayList result = new ArrayList(bundleCount); + List<BaseData> result = new ArrayList<BaseData>(bundleCount); long id = -1; boolean bundleDiscarded = false; for (int i = 0; i < bundleCount; i++) { @@ -422,7 +422,7 @@ public class BaseStorage implements SynchronousBundleListener { } if (bundleDiscarded) FrameworkProperties.setProperty(EclipseStarter.PROP_REFRESH_BUNDLES, "true"); //$NON-NLS-1$ - return (BaseData[]) result.toArray(new BaseData[result.size()]); + return result.toArray(new BaseData[result.size()]); } finally { in.close(); } @@ -777,7 +777,7 @@ public class BaseStorage implements SynchronousBundleListener { AbstractBundle toAdd = (AbstractBundle) installedBundles[i]; try { // make sure we get the real manifest as if this is the first time. - Dictionary toAddManifest = loadManifest((BaseData) toAdd.getBundleData(), true); + Dictionary<String, String> toAddManifest = loadManifest((BaseData) toAdd.getBundleData(), true); BundleDescription newDescription = factory.createBundleDescription(systemState, toAddManifest, toAdd.getLocation(), toAdd.getBundleId()); systemState.addBundle(newDescription); } catch (BundleException be) { @@ -970,7 +970,7 @@ public class BaseStorage implements SynchronousBundleListener { * @throws BundleException if the extension bundle metadata is invalid */ private void validateExtension(BundleData bundleData) throws BundleException { - Dictionary extensionManifest = bundleData.getManifest(); + Dictionary<String, String> extensionManifest = bundleData.getManifest(); if (extensionManifest.get(Constants.IMPORT_PACKAGE) != null) throw new BundleException(NLS.bind(AdaptorMsg.ADAPTOR_EXTENSION_IMPORT_ERROR, bundleData.getLocation()), BundleException.MANIFEST_ERROR); if (extensionManifest.get(Constants.REQUIRE_BUNDLE) != null) @@ -1095,7 +1095,7 @@ public class BaseStorage implements SynchronousBundleListener { System.arraycopy(origPaths, 0, paths, 0, origPaths.length); System.arraycopy(devPaths, 0, paths, origPaths.length, devPaths.length); } - ArrayList results = new ArrayList(paths.length); + List<File> results = new ArrayList<File>(paths.length); for (int i = 0; i < paths.length; i++) { if (".".equals(paths[i])) //$NON-NLS-1$ results.add(bundleData.getBundleFile().getBaseFile()); @@ -1105,7 +1105,7 @@ public class BaseStorage implements SynchronousBundleListener { results.add(result); } } - return (File[]) results.toArray(new File[results.size()]); + return results.toArray(new File[results.size()]); } catch (BundleException e) { adaptor.getEventPublisher().publishFrameworkEvent(FrameworkEvent.ERROR, bundleData.getBundle(), e); } @@ -1156,7 +1156,7 @@ public class BaseStorage implements SynchronousBundleListener { } if (newDescription != null) - validateNativeCodePaths(newDescription, (BaseData) bundleData); + validateNativeCodePaths(newDescription, bundleData); } private void validateNativeCodePaths(BundleDescription newDescription, BaseData data) { diff --git a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/BaseStorageHook.java b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/BaseStorageHook.java index ffe93bc3d..aa405123c 100644 --- a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/BaseStorageHook.java +++ b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/BaseStorageHook.java @@ -78,17 +78,18 @@ public class BaseStorageHook implements StorageHook, AdaptorHook { return storageHook; } - public void initialize(Dictionary manifest) throws BundleException { + public void initialize(Dictionary<String, String> manifest) throws BundleException { BaseStorageHook.loadManifest(bundleData, manifest); } - static void loadManifest(BaseData target, Dictionary manifest) throws BundleException { + @SuppressWarnings("deprecation") + static void loadManifest(BaseData target, Dictionary<String, String> manifest) throws BundleException { try { - target.setVersion(Version.parseVersion((String) manifest.get(Constants.BUNDLE_VERSION))); + target.setVersion(Version.parseVersion(manifest.get(Constants.BUNDLE_VERSION))); } catch (IllegalArgumentException e) { - target.setVersion(new InvalidVersion((String) manifest.get(Constants.BUNDLE_VERSION))); + target.setVersion(new InvalidVersion(manifest.get(Constants.BUNDLE_VERSION))); } - ManifestElement[] bsnHeader = ManifestElement.parseHeader(Constants.BUNDLE_SYMBOLICNAME, (String) manifest.get(Constants.BUNDLE_SYMBOLICNAME)); + ManifestElement[] bsnHeader = ManifestElement.parseHeader(Constants.BUNDLE_SYMBOLICNAME, manifest.get(Constants.BUNDLE_SYMBOLICNAME)); int bundleType = 0; if (bsnHeader != null) { target.setSymbolicName(bsnHeader[0].getValue()); @@ -99,11 +100,11 @@ public class BaseStorageHook implements StorageHook, AdaptorHook { bundleType |= BundleData.TYPE_SINGLETON; } // check that the classpath is valid - String classpath = (String) manifest.get(Constants.BUNDLE_CLASSPATH); + String classpath = manifest.get(Constants.BUNDLE_CLASSPATH); ManifestElement.parseHeader(Constants.BUNDLE_CLASSPATH, classpath); target.setClassPathString(classpath); - target.setActivator((String) manifest.get(Constants.BUNDLE_ACTIVATOR)); - String host = (String) manifest.get(Constants.FRAGMENT_HOST); + target.setActivator(manifest.get(Constants.BUNDLE_ACTIVATOR)); + String host = manifest.get(Constants.FRAGMENT_HOST); if (host != null) { bundleType |= BundleData.TYPE_FRAGMENT; ManifestElement[] hostElement = ManifestElement.parseHeader(Constants.FRAGMENT_HOST, host); @@ -117,7 +118,7 @@ public class BaseStorageHook implements StorageHook, AdaptorHook { bundleType |= BundleData.TYPE_EXTCLASSPATH_EXTENSION; } } else { - String composite = (String) manifest.get(COMPOSITE_HEADER); + String composite = manifest.get(COMPOSITE_HEADER); if (composite != null) { if (COMPOSITE_BUNDLE.equals(composite)) bundleType |= BundleData.TYPE_COMPOSITEBUNDLE; @@ -126,8 +127,8 @@ public class BaseStorageHook implements StorageHook, AdaptorHook { } } target.setType(bundleType); - target.setExecutionEnvironment((String) manifest.get(Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT)); - target.setDynamicImports((String) manifest.get(Constants.DYNAMICIMPORT_PACKAGE)); + target.setExecutionEnvironment(manifest.get(Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT)); + target.setDynamicImports(manifest.get(Constants.DYNAMICIMPORT_PACKAGE)); } public StorageHook load(BaseData target, DataInputStream in) throws IOException { @@ -333,7 +334,7 @@ public class BaseStorageHook implements StorageHook, AdaptorHook { /** * @throws BundleException */ - public Dictionary getManifest(boolean firstLoad) throws BundleException { + public Dictionary<String, String> getManifest(boolean firstLoad) throws BundleException { // do nothing return null; } diff --git a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/BundleInstall.java b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/BundleInstall.java index 5a2096b45..0ffedb2fd 100644 --- a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/BundleInstall.java +++ b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/BundleInstall.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2006 IBM Corporation and others. + * 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 @@ -15,7 +15,7 @@ import java.io.*; import java.net.URL; import java.net.URLConnection; import java.util.Dictionary; -import org.eclipse.osgi.baseadaptor.*; +import org.eclipse.osgi.baseadaptor.BaseData; import org.eclipse.osgi.baseadaptor.hooks.StorageHook; import org.eclipse.osgi.framework.adaptor.BundleData; import org.eclipse.osgi.framework.adaptor.BundleOperation; @@ -79,7 +79,7 @@ public class BundleInstall implements BundleOperation { AdaptorUtil.readFile(in, outFile); } } - Dictionary manifest = storage.loadManifest(data, true); + Dictionary<String, String> manifest = storage.loadManifest(data, true); for (int i = 0; i < instanceHooks.length; i++) instanceHooks[i].initialize(manifest); } finally { diff --git a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/BundleUpdate.java b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/BundleUpdate.java index 49470a47e..455d51898 100644 --- a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/BundleUpdate.java +++ b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/BundleUpdate.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2006 IBM Corporation and others. + * 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 @@ -15,7 +15,7 @@ import java.io.*; import java.net.URL; import java.net.URLConnection; import java.util.Dictionary; -import org.eclipse.osgi.baseadaptor.*; +import org.eclipse.osgi.baseadaptor.BaseData; import org.eclipse.osgi.baseadaptor.hooks.StorageHook; import org.eclipse.osgi.framework.adaptor.BundleData; import org.eclipse.osgi.framework.adaptor.BundleOperation; @@ -88,7 +88,7 @@ public class BundleUpdate implements BundleOperation { AdaptorUtil.readFile(in, outFile); } } - Dictionary manifest = storage.loadManifest(newData, true); + Dictionary<String, String> manifest = storage.loadManifest(newData, true); for (int i = 0; i < instanceHooks.length; i++) instanceHooks[i].initialize(manifest); } finally { diff --git a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/DefaultClassLoader.java b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/DefaultClassLoader.java index c47c30515..8e125cce8 100644 --- a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/DefaultClassLoader.java +++ b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/DefaultClassLoader.java @@ -45,7 +45,8 @@ public class DefaultClassLoader extends ClassLoader implements ParallelClassLoad private final static String CLASS_LOADER_TYPE_PARALLEL = "parallel"; //$NON-NLS-1$ private static final boolean CLASS_CERTIFICATE; private static final boolean PARALLEL_CAPABLE; - private static final Enumeration EMPTY_ENUMERATION = Collections.enumeration(Collections.EMPTY_LIST); + @SuppressWarnings("unchecked") + private static final Enumeration<URL> EMPTY_ENUMERATION = Collections.enumeration(Collections.EMPTY_LIST); static { CLASS_CERTIFICATE = Boolean.valueOf(FrameworkProperties.getProperty(CLASS_CERTIFICATE_SUPPORT, "true")).booleanValue(); //$NON-NLS-1$ @@ -99,12 +100,12 @@ public class DefaultClassLoader extends ClassLoader implements ParallelClassLoad * @return The Class object. * @throws ClassNotFoundException if the class is not found. */ - protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { if (Debug.DEBUG_LOADER) Debug.println("BundleClassLoader[" + delegate + "].loadClass(" + name + ")"); //$NON-NLS-1$ //$NON-NLS-2$//$NON-NLS-3$ try { // Just ask the delegate. This could result in findLocalClass(name) being called. - Class clazz = delegate.findClass(name); + Class<?> clazz = delegate.findClass(name); // resolve the class if asked to. if (resolve) resolveClass(clazz); @@ -158,8 +159,8 @@ public class DefaultClassLoader extends ClassLoader implements ParallelClassLoad * @return An Enumeration of all resources found or null if the resource. * @throws IOException */ - protected Enumeration findResources(String name) throws IOException { - Enumeration result = delegate.findResources(name); + protected Enumeration<URL> findResources(String name) throws IOException { + Enumeration<URL> result = delegate.findResources(name); if (result == null) return EMPTY_ENUMERATION; return result; @@ -184,11 +185,11 @@ public class DefaultClassLoader extends ClassLoader implements ParallelClassLoad return new ClasspathEntry(bundlefile, createProtectionDomain(bundlefile, cpDomain)); } - public Class defineClass(String name, byte[] classbytes, ClasspathEntry classpathEntry, BundleEntry entry) { + public Class<?> defineClass(String name, byte[] classbytes, ClasspathEntry classpathEntry, BundleEntry entry) { return defineClass(name, classbytes, 0, classbytes.length, classpathEntry.getDomain()); } - public Class publicFindLoaded(String classname) { + public Class<?> publicFindLoaded(String classname) { return findLoadedClass(classname); } @@ -208,11 +209,11 @@ public class DefaultClassLoader extends ClassLoader implements ParallelClassLoad return manager.findLocalResource(resource); } - public Enumeration findLocalResources(String resource) { + public Enumeration<URL> findLocalResources(String resource) { return manager.findLocalResources(resource); } - public Class findLocalClass(String classname) throws ClassNotFoundException { + public Class<?> findLocalClass(String classname) throws ClassNotFoundException { return manager.findLocalClass(classname); } @@ -234,6 +235,7 @@ public class DefaultClassLoader extends ClassLoader implements ParallelClassLoad * @param baseDomain The source domain. * @return a ProtectionDomain which uses specified BundleFile and the permissions of the baseDomain */ + @SuppressWarnings("deprecation") public static ProtectionDomain createProtectionDomain(BundleFile bundlefile, ProtectionDomain baseDomain) { // create a protection domain which knows about the codesource for this classpath entry (bug 89904) try { diff --git a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/DevClassLoadingHook.java b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/DevClassLoadingHook.java index e008b5aeb..37da1e605 100644 --- a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/DevClassLoadingHook.java +++ b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/DevClassLoadingHook.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2009 IBM Corporation and others. + * Copyright (c) 2006, 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 @@ -33,13 +33,13 @@ public class DevClassLoadingHook implements ClassLoadingHook, HookConfigurator, return null; } - public boolean addClassPathEntry(ArrayList cpEntries, String cp, ClasspathManager hostmanager, BaseData sourcedata, ProtectionDomain sourcedomain) { + public boolean addClassPathEntry(ArrayList<ClasspathEntry> cpEntries, String cp, ClasspathManager hostmanager, BaseData sourcedata, ProtectionDomain sourcedomain) { // first check that we are in devmode for this sourcedata String[] devClassPath = !DevClassPathHelper.inDevelopmentMode() ? null : DevClassPathHelper.getDevClassPath(sourcedata.getSymbolicName()); if (devClassPath == null || devClassPath.length == 0) return false; // not in dev mode return // check that dev classpath entries have not already been added; we mark this in the first entry below - if (cpEntries.size() > 0 && ((ClasspathEntry) cpEntries.get(0)).getUserObject(KEY) != null) + if (cpEntries.size() > 0 && cpEntries.get(0).getUserObject(KEY) != null) return false; // this source has already had its dev classpath entries added. boolean result = false; for (int i = 0; i < devClassPath.length; i++) { @@ -65,7 +65,7 @@ public class DevClassLoadingHook implements ClassLoadingHook, HookConfigurator, // mark the first entry of the list. // This way we can quickly tell that dev classpath entries have been added to the list if (result && cpEntries.size() > 0) - ((ClasspathEntry) cpEntries.get(0)).addUserObject(this); + cpEntries.get(0).addUserObject(this); return result; } diff --git a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/DevClassPathHelper.java b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/DevClassPathHelper.java index de565abbb..a88966ecb 100644 --- a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/DevClassPathHelper.java +++ b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/DevClassPathHelper.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2004, 2006 IBM Corporation and others. + * 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 @@ -14,7 +14,8 @@ import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; -import java.util.*; +import java.util.Dictionary; +import java.util.Properties; import org.eclipse.osgi.framework.internal.core.FrameworkProperties; import org.eclipse.osgi.util.ManifestElement; @@ -25,7 +26,7 @@ import org.eclipse.osgi.util.ManifestElement; public final class DevClassPathHelper { static private boolean inDevelopmentMode = false; static private String[] devDefaultClasspath; - static private Dictionary devProperties = null; + static private Dictionary<String, String> devProperties = null; static { // Check the osgi.dev property to see if dev classpath entries have been defined. @@ -36,17 +37,17 @@ public final class DevClassPathHelper { URL location = new URL(osgiDev); devProperties = load(location); if (devProperties != null) - devDefaultClasspath = getArrayFromList((String) devProperties.get("*")); //$NON-NLS-1$ + devDefaultClasspath = getArrayFromList(devProperties.get("*")); //$NON-NLS-1$ } catch (MalformedURLException e) { devDefaultClasspath = getArrayFromList(osgiDev); } } } - private static String[] getDevClassPath(String id, Dictionary properties, String[] defaultClasspath) { + private static String[] getDevClassPath(String id, Dictionary<String, String> properties, String[] defaultClasspath) { String[] result = null; if (id != null && properties != null) { - String entry = (String) properties.get(id); + String entry = properties.get(id); if (entry != null) result = getArrayFromList(entry); } @@ -62,10 +63,10 @@ public final class DevClassPathHelper { * the default develoment classpath properties should be used * @return a list of development classpath elements */ - public static String[] getDevClassPath(String id, Dictionary properties) { + public static String[] getDevClassPath(String id, Dictionary<String, String> properties) { if (properties == null) return getDevClassPath(id, devProperties, devDefaultClasspath); - return getDevClassPath(id, properties, getArrayFromList((String) properties.get("*"))); //$NON-NLS-1$ + return getDevClassPath(id, properties, getArrayFromList(properties.get("*"))); //$NON-NLS-1$ } /** @@ -98,7 +99,7 @@ public final class DevClassPathHelper { /* * Load the given properties file */ - private static Properties load(URL url) { + private static Dictionary<String, String> load(URL url) { Properties props = new Properties(); try { InputStream is = null; @@ -112,6 +113,8 @@ public final class DevClassPathHelper { } catch (IOException e) { // TODO consider logging here } - return props; + @SuppressWarnings({"unchecked", "rawtypes"}) + Dictionary<String, String> result = (Dictionary) props; + return result; } } diff --git a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/SystemBundleData.java b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/SystemBundleData.java index 7723539af..8250b54fd 100644 --- a/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/SystemBundleData.java +++ b/bundles/org.eclipse.osgi/defaultAdaptor/src/org/eclipse/osgi/internal/baseadaptor/SystemBundleData.java @@ -61,7 +61,7 @@ public class SystemBundleData extends BaseData { return null; } - private Headers createManifest(File osgiBase) throws BundleException { + private Headers<String, String> createManifest(File osgiBase) throws BundleException { InputStream in = null; if (osgiBase != null && osgiBase.exists()) @@ -91,12 +91,12 @@ public class SystemBundleData extends BaseData { ClassLoader cl = getClass().getClassLoader(); try { // get all manifests in your classloader delegation - Enumeration manifests = cl != null ? cl.getResources(Constants.OSGI_BUNDLE_MANIFEST) : ClassLoader.getSystemResources(Constants.OSGI_BUNDLE_MANIFEST); + Enumeration<URL> manifests = cl != null ? cl.getResources(Constants.OSGI_BUNDLE_MANIFEST) : ClassLoader.getSystemResources(Constants.OSGI_BUNDLE_MANIFEST); while (manifests.hasMoreElements()) { - URL url = (URL) manifests.nextElement(); + URL url = manifests.nextElement(); try { // check each manifest until we find one with the Eclipse-SystemBundle: true header - Headers headers = Headers.parseManifest(url.openStream()); + Headers<String, String> headers = Headers.parseManifest(url.openStream()); if ("true".equals(headers.get(Constants.ECLIPSE_SYSTEMBUNDLE))) //$NON-NLS-1$ return url.openStream(); } catch (BundleException e) { @@ -126,7 +126,7 @@ public class SystemBundleData extends BaseData { return null; } - public Enumeration getEntryPaths(String path) { + public Enumeration<String> getEntryPaths(String path) { return null; } diff --git a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/adaptor/EclipseLog.java b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/adaptor/EclipseLog.java index 4bb4bc5d3..4c23b4cd3 100644 --- a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/adaptor/EclipseLog.java +++ b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/adaptor/EclipseLog.java @@ -70,7 +70,7 @@ public class EclipseLog implements FrameworkLog { String s = System.getProperty("line.separator"); //$NON-NLS-1$ LINE_SEPARATOR = s == null ? "\n" : s; //$NON-NLS-1$ } - private static final SecureAction secureAction = (SecureAction) AccessController.doPrivileged(SecureAction.createSecureAction()); + private static final SecureAction secureAction = AccessController.doPrivileged(SecureAction.createSecureAction()); /** Indicates if the console messages should be printed to the console (System.out) */ protected boolean consoleLog = false; diff --git a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/adaptor/EclipseStarter.java b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/adaptor/EclipseStarter.java index 4a4a7e0a1..631a317d1 100644 --- a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/adaptor/EclipseStarter.java +++ b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/adaptor/EclipseStarter.java @@ -59,9 +59,9 @@ public class EclipseStarter { public static boolean debug = false; private static boolean running = false; private static Framework framework = null; - private static ServiceRegistration defaultMonitorRegistration = null; - private static ServiceRegistration appLauncherRegistration = null; - private static ServiceRegistration splashStreamRegistration = null; + private static ServiceRegistration<?> defaultMonitorRegistration = null; + private static ServiceRegistration<?> appLauncherRegistration = null; + private static ServiceRegistration<?> splashStreamRegistration = null; // command line arguments private static final String CLEAN = "-clean"; //$NON-NLS-1$ @@ -129,9 +129,9 @@ public class EclipseStarter { private static FrameworkLog log; // directory of serch candidates keyed by directory abs path -> directory listing (bug 122024) - private static HashMap searchCandidates = new HashMap(4); + private static Map<String, String[]> searchCandidates = new HashMap<String, String[]>(4); private static EclipseAppLauncher appLauncher; - private static List shutdownHandlers; + private static List<Runnable> shutdownHandlers; private static ConsoleManager consoleMgr = null; @@ -419,7 +419,7 @@ public class EclipseStarter { } private static void ensureBundlesActive(Bundle[] bundles) { - ServiceTracker tracker = null; + ServiceTracker<StartLevel, StartLevel> tracker = null; try { for (int i = 0; i < bundles.length; i++) { if (bundles[i].getState() != Bundle.ACTIVE) { @@ -430,10 +430,10 @@ public class EclipseStarter { } // check that the startlevel allows the bundle to be active (111550) if (tracker == null) { - tracker = new ServiceTracker(context, StartLevel.class.getName(), null); + tracker = new ServiceTracker<StartLevel, StartLevel>(context, StartLevel.class.getName(), null); tracker.open(); } - StartLevel sl = (StartLevel) tracker.getService(); + StartLevel sl = tracker.getService(); if (sl != null && (sl.getBundleStartLevel(bundles[i]) <= sl.getStartLevel())) { log.log(new FrameworkLogEntry(FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME, FrameworkLogEntry.ERROR, 0, NLS.bind(EclipseAdaptorMsg.ECLIPSE_STARTUP_ERROR_BUNDLE_NOT_ACTIVE, bundles[i]), 0, null, null)); } @@ -453,7 +453,7 @@ public class EclipseStarter { // first lets look for missing leaf constraints (bug 114120) VersionConstraint[] leafConstraints = stateHelper.getUnsatisfiedLeaves(state.getBundles()); // hash the missing leaf constraints by the declaring bundles - Map missing = new HashMap(); + Map<BundleDescription, List<VersionConstraint>> missing = new HashMap<BundleDescription, List<VersionConstraint>>(); for (int i = 0; i < leafConstraints.length; i++) { // only include non-optional and non-dynamic constraint leafs if (leafConstraints[i] instanceof BundleSpecification && ((BundleSpecification) leafConstraints[i]).isOptional()) @@ -465,9 +465,9 @@ public class EclipseStarter { continue; } BundleDescription bundle = leafConstraints[i].getBundle(); - ArrayList constraints = (ArrayList) missing.get(bundle); + List<VersionConstraint> constraints = missing.get(bundle); if (constraints == null) { - constraints = new ArrayList(); + constraints = new ArrayList<VersionConstraint>(); missing.put(bundle, constraints); } constraints.add(leafConstraints[i]); @@ -477,14 +477,14 @@ public class EclipseStarter { if (missing.size() > 0) { FrameworkLogEntry[] rootChildren = new FrameworkLogEntry[missing.size()]; int rootIndex = 0; - for (Iterator iter = missing.keySet().iterator(); iter.hasNext(); rootIndex++) { - BundleDescription description = (BundleDescription) iter.next(); + for (Iterator<BundleDescription> iter = missing.keySet().iterator(); iter.hasNext(); rootIndex++) { + BundleDescription description = iter.next(); String symbolicName = description.getSymbolicName() == null ? FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME : description.getSymbolicName(); String generalMessage = NLS.bind(EclipseAdaptorMsg.ECLIPSE_STARTUP_ERROR_BUNDLE_NOT_RESOLVED, description.getLocation()); - ArrayList constraints = (ArrayList) missing.get(description); + List<VersionConstraint> constraints = missing.get(description); FrameworkLogEntry[] logChildren = new FrameworkLogEntry[constraints.size()]; for (int i = 0; i < logChildren.length; i++) - logChildren[i] = new FrameworkLogEntry(symbolicName, FrameworkLogEntry.WARNING, 0, MessageHelper.getResolutionFailureMessage((VersionConstraint) constraints.get(i)), 0, null, null); + logChildren[i] = new FrameworkLogEntry(symbolicName, FrameworkLogEntry.WARNING, 0, MessageHelper.getResolutionFailureMessage(constraints.get(i)), 0, null, null); rootChildren[rootIndex] = new FrameworkLogEntry(FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME, FrameworkLogEntry.WARNING, 0, generalMessage, 0, null, logChildren); } logService.log(new FrameworkLogEntry(FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME, FrameworkLogEntry.WARNING, 0, EclipseAdaptorMsg.ECLIPSE_STARTUP_ROOTS_NOT_RESOLVED, 0, null, rootChildren)); @@ -492,7 +492,7 @@ public class EclipseStarter { // There may be some bundles unresolved for other reasons, causing the system to be unresolved // log all unresolved constraints now - ArrayList allChildren = new ArrayList(); + List<FrameworkLogEntry> allChildren = new ArrayList<FrameworkLogEntry>(); for (int i = 0; i < bundles.length; i++) if (bundles[i].getState() == Bundle.INSTALLED) { String symbolicName = bundles[i].getSymbolicName() == null ? FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME : bundles[i].getSymbolicName(); @@ -520,7 +520,7 @@ public class EclipseStarter { allChildren.add(new FrameworkLogEntry(FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME, FrameworkLogEntry.WARNING, 0, generalMessage, 0, null, logChildren)); } if (allChildren.size() > 0) - logService.log(new FrameworkLogEntry(FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME, FrameworkLogEntry.WARNING, 0, EclipseAdaptorMsg.ECLIPSE_STARTUP_ALL_NOT_RESOLVED, 0, null, (FrameworkLogEntry[]) allChildren.toArray(new FrameworkLogEntry[allChildren.size()]))); + logService.log(new FrameworkLogEntry(FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME, FrameworkLogEntry.WARNING, 0, EclipseAdaptorMsg.ECLIPSE_STARTUP_ALL_NOT_RESOLVED, 0, null, allChildren.toArray(new FrameworkLogEntry[allChildren.size()]))); } private static void publishSplashScreen(final Runnable endSplashHandler) { @@ -531,7 +531,7 @@ public class EclipseStarter { Method method = endSplashHandler.getClass().getMethod("getOutputStream", new Class[0]); //$NON-NLS-1$ Object outputStream = method.invoke(endSplashHandler, new Object[0]); if (outputStream instanceof OutputStream) { - Dictionary osProperties = new Hashtable(); + Dictionary<String, Object> osProperties = new Hashtable<String, Object>(); osProperties.put("name", "splashstream"); //$NON-NLS-1$//$NON-NLS-2$ splashStreamRegistration = context.registerService(OutputStream.class.getName(), outputStream, osProperties); } @@ -540,7 +540,7 @@ public class EclipseStarter { } // keep this splash handler as the default startup monitor try { - Dictionary monitorProps = new Hashtable(); + Dictionary<String, Object> monitorProps = new Hashtable<String, Object>(); monitorProps.put(Constants.SERVICE_RANKING, new Integer(Integer.MIN_VALUE)); defaultMonitorRegistration = context.registerService(StartupMonitor.class.getName(), new DefaultStartupMonitor(endSplashHandler), monitorProps); } catch (IllegalStateException e) { @@ -548,6 +548,7 @@ public class EclipseStarter { } } + @SuppressWarnings("deprecation") private static URL searchForBundle(String name, String parent) throws MalformedURLException { URL url = null; File fileLocation = null; @@ -626,23 +627,23 @@ public class EclipseStarter { Bundle[] curInitBundles = getCurrentBundles(true); // list of bundles to be refreshed - List toRefresh = new ArrayList(curInitBundles.length); + List<Bundle> toRefresh = new ArrayList<Bundle>(curInitBundles.length); // uninstall any of the currently installed bundles that do not exist in the // initial bundle list from installEntries. uninstallBundles(curInitBundles, initialBundles, toRefresh); // install the initialBundles that are not already installed. - ArrayList startBundles = new ArrayList(installEntries.length); - ArrayList lazyActivationBundles = new ArrayList(installEntries.length); + List<Bundle> startBundles = new ArrayList<Bundle>(installEntries.length); + List<Bundle> lazyActivationBundles = new ArrayList<Bundle>(installEntries.length); installBundles(initialBundles, curInitBundles, startBundles, lazyActivationBundles, toRefresh); // If we installed/uninstalled something, force a refresh of all installed/uninstalled bundles - if (!toRefresh.isEmpty() && refreshPackages((Bundle[]) toRefresh.toArray(new Bundle[toRefresh.size()]))) + if (!toRefresh.isEmpty() && refreshPackages(toRefresh.toArray(new Bundle[toRefresh.size()]))) return null; // cannot continue; refreshPackages shutdown the framework // schedule all basic bundles to be started - Bundle[] startInitBundles = (Bundle[]) startBundles.toArray(new Bundle[startBundles.size()]); - Bundle[] lazyInitBundles = (Bundle[]) lazyActivationBundles.toArray(new Bundle[lazyActivationBundles.size()]); + Bundle[] startInitBundles = startBundles.toArray(new Bundle[startBundles.size()]); + Bundle[] lazyInitBundles = lazyActivationBundles.toArray(new Bundle[lazyActivationBundles.size()]); startBundles(startInitBundles, lazyInitBundles); if (debug) @@ -652,7 +653,7 @@ public class EclipseStarter { private static InitialBundle[] getInitialBundles(String[] installEntries) { searchCandidates.clear(); - ArrayList result = new ArrayList(installEntries.length); + List<InitialBundle> result = new ArrayList<InitialBundle>(installEntries.length); int defaultStartLevel = Integer.parseInt(FrameworkProperties.getProperty(PROP_BUNDLES_STARTLEVEL, DEFAULT_BUNDLES_STARTLEVEL)); String syspath = getSysPath(); // should canonicalize the syspath. @@ -698,12 +699,12 @@ public class EclipseStarter { log.log(new FrameworkLogEntry(FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME, FrameworkLogEntry.ERROR, 0, e.getMessage(), 0, e, null)); } } - return (InitialBundle[]) result.toArray(new InitialBundle[result.size()]); + return result.toArray(new InitialBundle[result.size()]); } // returns true if the refreshPackages operation caused the framework to shutdown private static boolean refreshPackages(Bundle[] bundles) { - ServiceReference packageAdminRef = context.getServiceReference(PackageAdmin.class.getName()); + ServiceReference<?> packageAdminRef = context.getServiceReference(PackageAdmin.class.getName()); PackageAdmin packageAdmin = null; if (packageAdminRef != null) packageAdmin = (PackageAdmin) context.getService(packageAdminRef); @@ -746,9 +747,9 @@ public class EclipseStarter { */ private static FrameworkAdaptor createAdaptor() throws Exception { String adaptorClassName = FrameworkProperties.getProperty(PROP_ADAPTOR, DEFAULT_ADAPTOR_CLASS); - Class adaptorClass = Class.forName(adaptorClassName); - Class[] constructorArgs = new Class[] {String[].class}; - Constructor constructor = adaptorClass.getConstructor(constructorArgs); + Class<?> adaptorClass = Class.forName(adaptorClassName); + Class<?>[] constructorArgs = new Class[] {String[].class}; + Constructor<?> constructor = adaptorClass.getConstructor(constructorArgs); return (FrameworkAdaptor) constructor.newInstance(new Object[] {new String[0]}); } @@ -993,7 +994,7 @@ public class EclipseStarter { private static Bundle[] getCurrentBundles(boolean includeInitial) { Bundle[] installed = context.getBundles(); - ArrayList initial = new ArrayList(); + List<Bundle> initial = new ArrayList<Bundle>(); for (int i = 0; i < installed.length; i++) { Bundle bundle = installed[i]; if (bundle.getLocation().startsWith(INITIAL_LOCATION)) { @@ -1002,7 +1003,7 @@ public class EclipseStarter { } else if (!includeInitial && bundle.getBundleId() != 0) initial.add(bundle); } - return (Bundle[]) initial.toArray(new Bundle[initial.size()]); + return initial.toArray(new Bundle[initial.size()]); } private static Bundle getBundleByLocation(String location, Bundle[] bundles) { @@ -1014,7 +1015,7 @@ public class EclipseStarter { return null; } - private static void uninstallBundles(Bundle[] curInitBundles, InitialBundle[] newInitBundles, List toRefresh) { + private static void uninstallBundles(Bundle[] curInitBundles, InitialBundle[] newInitBundles, List<Bundle> toRefresh) { for (int i = 0; i < curInitBundles.length; i++) { boolean found = false; for (int j = 0; j < newInitBundles.length; j++) { @@ -1034,8 +1035,8 @@ public class EclipseStarter { } } - private static void installBundles(InitialBundle[] initialBundles, Bundle[] curInitBundles, ArrayList startBundles, ArrayList lazyActivationBundles, List toRefresh) { - ServiceReference reference = context.getServiceReference(StartLevel.class.getName()); + private static void installBundles(InitialBundle[] initialBundles, Bundle[] curInitBundles, List<Bundle> startBundles, List<Bundle> lazyActivationBundles, List<Bundle> toRefresh) { + ServiceReference<?> reference = context.getServiceReference(StartLevel.class.getName()); StartLevel startService = null; if (reference != null) startService = (StartLevel) context.getService(reference); @@ -1083,15 +1084,16 @@ public class EclipseStarter { } } + @SuppressWarnings("deprecation") private static boolean hasLazyActivationPolicy(Bundle target) { // check the bundle manifest to see if it defines a lazy activation policy - Dictionary headers = target.getHeaders(""); //$NON-NLS-1$ + Dictionary<String, String> headers = target.getHeaders(""); //$NON-NLS-1$ // first check to see if this is a fragment bundle - String fragmentHost = (String) headers.get(Constants.FRAGMENT_HOST); + String fragmentHost = headers.get(Constants.FRAGMENT_HOST); if (fragmentHost != null) return false; // do not activate fragment bundles // look for the OSGi defined Bundle-ActivationPolicy header - String activationPolicy = (String) headers.get(Constants.BUNDLE_ACTIVATIONPOLICY); + String activationPolicy = headers.get(Constants.BUNDLE_ACTIVATIONPOLICY); try { if (activationPolicy != null) { ManifestElement[] elements = ManifestElement.parseHeader(Constants.BUNDLE_ACTIVATIONPOLICY, activationPolicy); @@ -1102,9 +1104,9 @@ public class EclipseStarter { } } else { // check for Eclipse specific lazy start headers "Eclipse-LazyStart" and "Eclipse-AutoStart" - String eclipseLazyStart = (String) headers.get(Constants.ECLIPSE_LAZYSTART); + String eclipseLazyStart = headers.get(Constants.ECLIPSE_LAZYSTART); if (eclipseLazyStart == null) - eclipseLazyStart = (String) headers.get(Constants.ECLIPSE_AUTOSTART); + eclipseLazyStart = headers.get(Constants.ECLIPSE_AUTOSTART); ManifestElement[] elements = ManifestElement.parseHeader(Constants.ECLIPSE_LAZYSTART, eclipseLazyStart); if (elements != null && elements.length > 0) { // if the value is true then it is lazy activated @@ -1214,16 +1216,16 @@ public class EclipseStarter { } private static void mergeProperties(Properties destination, Properties source) { - for (Enumeration e = source.keys(); e.hasMoreElements();) { + for (Enumeration<?> e = source.keys(); e.hasMoreElements();) { String key = (String) e.nextElement(); String value = source.getProperty(key); if (destination.getProperty(key) == null) - destination.put(key, value); + destination.setProperty(key, value); } } private static void setStartLevel(final int value) { - ServiceReference reference = context.getServiceReference(StartLevel.class.getName()); + ServiceReference<?> reference = context.getServiceReference(StartLevel.class.getName()); final StartLevel startLevel = reference != null ? (StartLevel) context.getService(reference) : null; if (startLevel == null) return; @@ -1258,11 +1260,11 @@ public class EclipseStarter { } private static void updateSplash(Semaphore semaphore, StartupEventListener listener) { - ServiceTracker monitorTracker = new ServiceTracker(context, StartupMonitor.class.getName(), null); + ServiceTracker<StartupMonitor, StartupMonitor> monitorTracker = new ServiceTracker<StartupMonitor, StartupMonitor>(context, StartupMonitor.class.getName(), null); monitorTracker.open(); try { while (true) { - StartupMonitor monitor = (StartupMonitor) monitorTracker.getService(); + StartupMonitor monitor = monitorTracker.getService(); if (monitor != null) { try { monitor.update(); @@ -1293,7 +1295,7 @@ public class EclipseStarter { * @param start the location to begin searching */ private static String searchFor(final String target, String start) { - String[] candidates = (String[]) searchCandidates.get(start); + String[] candidates = searchCandidates.get(start); if (candidates == null) { candidates = new File(start).list(); if (candidates != null) @@ -1424,15 +1426,14 @@ public class EclipseStarter { * @param initialProperties the initial properties to set for the platform. * @since 3.2 */ - public static void setInitialProperties(Map initialProperties) { + public static void setInitialProperties(Map<String, String> initialProperties) { if (initialProperties == null || initialProperties.isEmpty()) return; - for (Iterator it = initialProperties.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = (Map.Entry) it.next(); + for (Map.Entry<String, String> entry : initialProperties.entrySet()) { if (entry.getValue() != null) - FrameworkProperties.setProperty((String) entry.getKey(), (String) entry.getValue()); + FrameworkProperties.setProperty(entry.getKey(), entry.getValue()); else - FrameworkProperties.clearProperty((String) entry.getKey()); + FrameworkProperties.clearProperty(entry.getKey()); } } @@ -1475,7 +1476,7 @@ public class EclipseStarter { throw new IllegalStateException(EclipseAdaptorMsg.ECLIPSE_STARTUP_ALREADY_RUNNING); if (shutdownHandlers == null) - shutdownHandlers = new ArrayList(); + shutdownHandlers = new ArrayList<Runnable>(); shutdownHandlers.add(handler); } @@ -1501,8 +1502,8 @@ public class EclipseStarter { return; final Bundle systemBundle = context.getBundle(); - for (Iterator it = shutdownHandlers.iterator(); it.hasNext();) { - final Runnable handler = (Runnable) it.next(); + for (Iterator<Runnable> it = shutdownHandlers.iterator(); it.hasNext();) { + final Runnable handler = it.next(); BundleListener listener = new BundleListener() { public void bundleChanged(BundleEvent event) { if (event.getBundle() == systemBundle && event.getType() == BundleEvent.STOPPED) { diff --git a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/adaptor/LocationManager.java b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/adaptor/LocationManager.java index 354863e2c..6c8676624 100644 --- a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/adaptor/LocationManager.java +++ b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/adaptor/LocationManager.java @@ -177,6 +177,7 @@ public class LocationManager { return launcherParent == null ? null : new File(launcherParent); } + @SuppressWarnings("deprecation") private static Location buildLocation(String property, URL defaultLocation, String userDefaultAppendage, boolean readOnlyDefault, boolean computeReadOnly, String dataAreaPrefix) { String location = FrameworkProperties.clearProperty(property); // the user/product may specify a non-default readOnly setting diff --git a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/CachedManifest.java b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/CachedManifest.java index 3d4fbd899..30d428ad2 100644 --- a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/CachedManifest.java +++ b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/CachedManifest.java @@ -24,17 +24,17 @@ import org.osgi.framework.Version; /** * Internal class. */ -public class CachedManifest extends Dictionary { +public class CachedManifest extends Dictionary<String, String> { static final String SERVICE_COMPONENT = "Service-Component"; //$NON-NLS-1$ static boolean DEBUG = false; - private Dictionary manifest = null; + private Dictionary<String, String> manifest = null; private EclipseStorageHook storageHook; public CachedManifest(EclipseStorageHook storageHook) { this.storageHook = storageHook; } - public Dictionary getManifest() { + public Dictionary<String, String> getManifest() { if (manifest == null) try { if (DEBUG) @@ -47,7 +47,7 @@ public class CachedManifest extends Dictionary { return null; } if (manifest == null) { - Headers empty = new Headers(0); + Headers<String, String> empty = new Headers<String, String>(0); empty.setReadOnly(); manifest = empty; return empty; @@ -63,15 +63,16 @@ public class CachedManifest extends Dictionary { return size() == 0; } - public Enumeration elements() { + public Enumeration<String> elements() { return getManifest().elements(); } - public Enumeration keys() { + public Enumeration<String> keys() { return getManifest().keys(); } - public Object get(Object key) { + @SuppressWarnings("deprecation") + public String get(Object key) { if (manifest != null) return manifest.get(key); String keyString = (String) key; @@ -139,17 +140,17 @@ public class CachedManifest extends Dictionary { return storageHook.getBundleManifestVersion() == 0 ? null : Integer.toString(storageHook.getBundleManifestVersion()); if (SERVICE_COMPONENT.equals(keyString)) return storageHook.getServiceComponent(); - Dictionary result = getManifest(); + Dictionary<String, String> result = getManifest(); if (DEBUG) System.out.println("Manifest read because of header: " + key); //$NON-NLS-1$ return result == null ? null : result.get(key); } - public Object remove(Object key) { + public String remove(Object key) { return getManifest().remove(key); } - public Object put(Object key, Object value) { + public String put(String key, String value) { return getManifest().put(key, value); } diff --git a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/ContextFinder.java b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/ContextFinder.java index ae2a38dd1..9dbd154d0 100644 --- a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/ContextFinder.java +++ b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/ContextFinder.java @@ -17,20 +17,20 @@ import java.security.PrivilegedAction; import java.util.*; import org.eclipse.osgi.framework.adaptor.BundleClassLoader; -public class ContextFinder extends ClassLoader implements PrivilegedAction { +public class ContextFinder extends ClassLoader implements PrivilegedAction<List<ClassLoader>> { static final class Finder extends SecurityManager { - public Class[] getClassContext() { + public Class<?>[] getClassContext() { return super.getClassContext(); } } //This is used to detect cycle that could be caused while delegating the loading to other classloaders //It keeps track on a thread basis of the set of requested classes and resources - private static ThreadLocal cycleDetector = new ThreadLocal(); + private static ThreadLocal<Set<String>> cycleDetector = new ThreadLocal<Set<String>>(); static ClassLoader finderClassLoader; static Finder contextFinder; static { - AccessController.doPrivileged(new PrivilegedAction() { + AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { finderClassLoader = ContextFinder.class.getClassLoader(); contextFinder = new Finder(); @@ -50,9 +50,9 @@ public class ContextFinder extends ClassLoader implements PrivilegedAction { // ContextFinder classloader nor the boot classloader. The last classloader // in the list is either a bundle classloader or the framework's classloader // We assume that the bootclassloader never uses the context classloader to find classes in itself. - ArrayList basicFindClassLoaders() { - Class[] stack = contextFinder.getClassContext(); - ArrayList result = new ArrayList(1); + List<ClassLoader> basicFindClassLoaders() { + Class<?>[] stack = contextFinder.getClassContext(); + List<ClassLoader> result = new ArrayList<ClassLoader>(1); ClassLoader previousLoader = null; for (int i = 1; i < stack.length; i++) { ClassLoader tmp = stack[i].getClassLoader(); @@ -83,25 +83,25 @@ public class ContextFinder extends ClassLoader implements PrivilegedAction { return true; } - private ArrayList findClassLoaders() { + private List<ClassLoader> findClassLoaders() { if (System.getSecurityManager() == null) return basicFindClassLoaders(); - return (ArrayList) AccessController.doPrivileged(this); + return AccessController.doPrivileged(this); } - public Object run() { + public List<ClassLoader> run() { return basicFindClassLoaders(); } //Return whether the request for loading "name" should proceed. //False is returned when a cycle is being detected private boolean startLoading(String name) { - Set classesAndResources = (Set) cycleDetector.get(); + Set<String> classesAndResources = cycleDetector.get(); if (classesAndResources != null && classesAndResources.contains(name)) return false; if (classesAndResources == null) { - classesAndResources = new HashSet(3); + classesAndResources = new HashSet<String>(3); cycleDetector.set(classesAndResources); } classesAndResources.add(name); @@ -109,19 +109,19 @@ public class ContextFinder extends ClassLoader implements PrivilegedAction { } private void stopLoading(String name) { - ((Set) cycleDetector.get()).remove(name); + cycleDetector.get().remove(name); } - protected Class loadClass(String arg0, boolean arg1) throws ClassNotFoundException { + protected Class<?> loadClass(String arg0, boolean arg1) throws ClassNotFoundException { //Shortcut cycle if (startLoading(arg0) == false) throw new ClassNotFoundException(arg0); try { - ArrayList toConsult = findClassLoaders(); - for (Iterator loaders = toConsult.iterator(); loaders.hasNext();) + List<ClassLoader> toConsult = findClassLoaders(); + for (Iterator<ClassLoader> loaders = toConsult.iterator(); loaders.hasNext();) try { - return ((ClassLoader) loaders.next()).loadClass(arg0); + return loaders.next().loadClass(arg0); } catch (ClassNotFoundException e) { // go to the next class loader } @@ -137,9 +137,9 @@ public class ContextFinder extends ClassLoader implements PrivilegedAction { if (startLoading(arg0) == false) return null; try { - ArrayList toConsult = findClassLoaders(); - for (Iterator loaders = toConsult.iterator(); loaders.hasNext();) { - URL result = ((ClassLoader) loaders.next()).getResource(arg0); + List<ClassLoader> toConsult = findClassLoaders(); + for (Iterator<ClassLoader> loaders = toConsult.iterator(); loaders.hasNext();) { + URL result = loaders.next().getResource(arg0); if (result != null) return result; // go to the next class loader @@ -150,14 +150,17 @@ public class ContextFinder extends ClassLoader implements PrivilegedAction { } } - protected Enumeration findResources(String arg0) throws IOException { + protected Enumeration<URL> findResources(String arg0) throws IOException { //Shortcut cycle - if (startLoading(arg0) == false) - return Collections.enumeration(Collections.EMPTY_LIST); + if (startLoading(arg0) == false) { + @SuppressWarnings("unchecked") + Enumeration<URL> result = Collections.enumeration(Collections.EMPTY_LIST); + return result; + } try { - ArrayList toConsult = findClassLoaders(); - for (Iterator loaders = toConsult.iterator(); loaders.hasNext();) { - Enumeration result = ((ClassLoader) loaders.next()).getResources(arg0); + List<ClassLoader> toConsult = findClassLoaders(); + for (Iterator<ClassLoader> loaders = toConsult.iterator(); loaders.hasNext();) { + Enumeration<URL> result = loaders.next().getResources(arg0); if (result != null && result.hasMoreElements()) return result; // go to the next class loader diff --git a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/EclipseAdaptorHook.java b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/EclipseAdaptorHook.java index aa7dd741d..e5aef3db5 100644 --- a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/EclipseAdaptorHook.java +++ b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/EclipseAdaptorHook.java @@ -47,7 +47,7 @@ public class EclipseAdaptorHook implements AdaptorHook, HookConfigurator { private BaseAdaptor adaptor; private boolean noXML = false; - private ArrayList registrations = new ArrayList(10); + private List<ServiceRegistration<?>> registrations = new ArrayList<ServiceRegistration<?>>(10); /** * @throws BundleException @@ -55,7 +55,7 @@ public class EclipseAdaptorHook implements AdaptorHook, HookConfigurator { public void frameworkStart(BundleContext context) throws BundleException { registrations.clear(); registerEndorsedXMLParser(context); - Hashtable locationProperties = new Hashtable(1); + Dictionary<String, Object> locationProperties = new Hashtable<String, Object>(1); Location location = LocationManager.getUserLocation(); if (location != null) { locationProperties.put("type", LocationManager.PROP_USER_AREA); //$NON-NLS-1$ @@ -83,7 +83,7 @@ public class EclipseAdaptorHook implements AdaptorHook, HookConfigurator { registrations.add(context.registerService(Location.class.getName(), location, locationProperties)); } - Dictionary urlProperties = new Hashtable(); + Dictionary<String, Object> urlProperties = new Hashtable<String, Object>(); urlProperties.put("protocol", new String[] {"bundleentry", "bundleresource"}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ registrations.add(context.registerService(URLConverter.class.getName(), new URLConverterImpl(), urlProperties)); @@ -112,14 +112,14 @@ public class EclipseAdaptorHook implements AdaptorHook, HookConfigurator { } } - private static class ParsingService implements ServiceFactory { + private static class ParsingService implements ServiceFactory<Object> { private final boolean isSax; public ParsingService(boolean isSax) { this.isSax = isSax; } - public Object getService(Bundle bundle, ServiceRegistration registration) { + public Object getService(Bundle bundle, ServiceRegistration<Object> registration) { BundleHost host = (bundle instanceof BundleHost) ? (BundleHost) bundle : null; if (!SET_TCCL_XMLFACTORY || bundle == null) return createService(); @@ -151,7 +151,7 @@ public class EclipseAdaptorHook implements AdaptorHook, HookConfigurator { return DocumentBuilderFactory.newInstance(); } - public void ungetService(Bundle bundle, ServiceRegistration registration, Object service) { + public void ungetService(Bundle bundle, ServiceRegistration<Object> registration, Object service) { // Do nothing. } } @@ -164,8 +164,8 @@ public class EclipseAdaptorHook implements AdaptorHook, HookConfigurator { if (!noXML) PluginParser.releaseXMLParsing(); // unregister services - for (Iterator iRegistrations = registrations.iterator(); iRegistrations.hasNext();) - ((ServiceRegistration) iRegistrations.next()).unregister(); + for (ServiceRegistration<?> registration : registrations) + registration.unregister(); registrations.clear(); } diff --git a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/EclipseAppLauncher.java b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/EclipseAppLauncher.java index d39e8ad20..a4106fdb6 100644 --- a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/EclipseAppLauncher.java +++ b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/EclipseAppLauncher.java @@ -47,7 +47,7 @@ public class EclipseAppLauncher implements ApplicationLauncher { private void findRunnableService() { // look for a ParameterizedRunnable registered as a service by runtimes (3.0, 3.1) String appClass = ParameterizedRunnable.class.getName(); - ServiceReference[] runRefs = null; + ServiceReference<?>[] runRefs = null; try { runRefs = context.getServiceReferences(ParameterizedRunnable.class.getName(), "(&(objectClass=" + appClass + ")(eclipse.application=*))"); //$NON-NLS-1$//$NON-NLS-2$ } catch (InvalidSyntaxException e) { @@ -146,7 +146,7 @@ public class EclipseAppLauncher implements ApplicationLauncher { * exists that can be used to relaunch the default application. */ public Object reStart(Object argument) throws Exception { - ServiceReference ref[] = null; + ServiceReference<?> ref[] = null; ref = context.getServiceReferences("org.osgi.service.application.ApplicationDescriptor", "(eclipse.application.default=true)"); //$NON-NLS-1$//$NON-NLS-2$ if (ref != null && ref.length > 0) { Object defaultApp = context.getService(ref[0]); diff --git a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/EclipseClassLoadingHook.java b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/EclipseClassLoadingHook.java index 644b27578..c24307844 100644 --- a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/EclipseClassLoadingHook.java +++ b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/EclipseClassLoadingHook.java @@ -14,6 +14,7 @@ package org.eclipse.core.runtime.internal.adaptor; import java.io.File; import java.security.ProtectionDomain; import java.util.ArrayList; +import java.util.List; import java.util.jar.Attributes; import java.util.jar.Manifest; import org.eclipse.osgi.baseadaptor.*; @@ -44,7 +45,7 @@ public class EclipseClassLoadingHook implements ClassLoadingHook, HookConfigurat } private static String[] buildLibraryVariants() { - ArrayList result = new ArrayList(); + List<String> result = new ArrayList<String>(); EclipseEnvironmentInfo info = EclipseEnvironmentInfo.getDefault(); result.add("ws/" + info.getWS() + "/"); //$NON-NLS-1$ //$NON-NLS-2$ result.add("os/" + info.getOS() + "/" + info.getOSArch() + "/"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ @@ -57,7 +58,7 @@ public class EclipseClassLoadingHook implements ClassLoadingHook, HookConfigurat nl = (i < 0) ? "" : nl.substring(0, i); //$NON-NLS-1$ } result.add(""); //$NON-NLS-1$ - return (String[]) result.toArray(new String[result.size()]); + return result.toArray(new String[result.size()]); } public byte[] processClass(String name, byte[] classbytes, ClasspathEntry classpathEntry, BundleEntry entry, ClasspathManager manager) { @@ -127,7 +128,7 @@ public class EclipseClassLoadingHook implements ClassLoadingHook, HookConfigurat return null; } - public boolean addClassPathEntry(ArrayList cpEntries, String cp, ClasspathManager hostmanager, BaseData sourcedata, ProtectionDomain sourcedomain) { + public boolean addClassPathEntry(ArrayList<ClasspathEntry> cpEntries, String cp, ClasspathManager hostmanager, BaseData sourcedata, ProtectionDomain sourcedomain) { String var = hasPrefix(cp); if (var != null) // find internal library using eclipse predefined vars @@ -144,7 +145,7 @@ public class EclipseClassLoadingHook implements ClassLoadingHook, HookConfigurat return false; } - private boolean addInternalClassPath(String var, ArrayList cpEntries, String cp, ClasspathManager hostloader, BaseData sourcedata, ProtectionDomain sourcedomain) { + private boolean addInternalClassPath(String var, ArrayList<ClasspathEntry> cpEntries, String cp, ClasspathManager hostloader, BaseData sourcedata, ProtectionDomain sourcedomain) { if (var.equals("ws")) //$NON-NLS-1$ return ClasspathManager.addClassPathEntry(cpEntries, "ws/" + EclipseEnvironmentInfo.getDefault().getWS() + cp.substring(4), hostloader, sourcedata, sourcedomain); //$NON-NLS-1$ if (var.equals("os")) //$NON-NLS-1$ @@ -170,7 +171,7 @@ public class EclipseClassLoadingHook implements ClassLoadingHook, HookConfigurat } private static String[] buildNLJarVariants(String nl) { - ArrayList result = new ArrayList(); + List<String> result = new ArrayList<String>(); nl = nl.replace('_', '/'); while (nl.length() > 0) { result.add("nl/" + nl + "/"); //$NON-NLS-1$ //$NON-NLS-2$ @@ -178,10 +179,10 @@ public class EclipseClassLoadingHook implements ClassLoadingHook, HookConfigurat nl = (i < 0) ? "" : nl.substring(0, i); //$NON-NLS-1$ } result.add(""); //$NON-NLS-1$ - return (String[]) result.toArray(new String[result.size()]); + return result.toArray(new String[result.size()]); } - public void recordClassDefine(String name, Class clazz, byte[] classbytes, ClasspathEntry classpathEntry, BundleEntry entry, ClasspathManager manager) { + public void recordClassDefine(String name, Class<?> clazz, byte[] classbytes, ClasspathEntry classpathEntry, BundleEntry entry, ClasspathManager manager) { // do nothing } diff --git a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/EclipseCommandProvider.java b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/EclipseCommandProvider.java index 747af0007..525a83952 100644 --- a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/EclipseCommandProvider.java +++ b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/EclipseCommandProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2004, 2008 IBM Corporation and others. + * 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 @@ -61,7 +61,7 @@ public class EclipseCommandProvider implements CommandProvider { private PlatformAdmin getPlatformAdmin(CommandInterpreter ci) { if (platformAdmin == null) { - ServiceReference platformAdminRef = context.getServiceReference(PlatformAdmin.class.getName()); + ServiceReference<?> platformAdminRef = context.getServiceReference(PlatformAdmin.class.getName()); if (platformAdminRef == null) { ci.print(" "); //$NON-NLS-1$ ci.println(EclipseAdaptorMsg.ECLIPSE_CONSOLE_NO_CONSTRAINTS_NO_PLATFORM_ADMIN_MESSAGE); @@ -73,7 +73,7 @@ public class EclipseCommandProvider implements CommandProvider { } private void ungetPlatformAdmin() { - ServiceReference platformAdminRef = context.getServiceReference(PlatformAdmin.class.getName()); + ServiceReference<?> platformAdminRef = context.getServiceReference(PlatformAdmin.class.getName()); context.ungetService(platformAdminRef); } diff --git a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/EclipseLazyStarter.java b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/EclipseLazyStarter.java index 8da96de7b..6254a230e 100644 --- a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/EclipseLazyStarter.java +++ b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/EclipseLazyStarter.java @@ -37,11 +37,11 @@ public class EclipseLazyStarter implements ClassLoadingStatsHook, AdaptorHook, H private static final boolean throwErrorOnFailedStart = "true".equals(FrameworkProperties.getProperty("osgi.compatibility.errorOnFailedStart", "true")); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ private BaseAdaptor adaptor; // holds the current activation trigger class and the ClasspathManagers that need to be activated - private ThreadLocal activationStack = new ThreadLocal(); + private ThreadLocal<List<Object>> activationStack = new ThreadLocal<List<Object>>(); // used to store exceptions that occurred while activating a bundle // keyed by ClasspathManager->Exception // WeakHashMap is used to prevent pinning the ClasspathManager objects. - private final Map errors = Collections.synchronizedMap(new WeakHashMap()); + private final Map<ClasspathManager, TerminatingClassNotFoundException> errors = Collections.synchronizedMap(new WeakHashMap<ClasspathManager, TerminatingClassNotFoundException>()); public void preFindLocalClass(String name, ClasspathManager manager) throws ClassNotFoundException { AbstractBundle bundle = (AbstractBundle) manager.getBaseData().getBundle(); @@ -53,9 +53,9 @@ public class EclipseLazyStarter implements ClassLoadingStatsHook, AdaptorHook, H // The bundle is not active and does not require activation, just return the class if (!shouldActivateFor(name, manager.getBaseData(), storageHook, manager)) return; - ArrayList stack = (ArrayList) activationStack.get(); + List<Object> stack = activationStack.get(); if (stack == null) { - stack = new ArrayList(6); + stack = new ArrayList<Object>(6); activationStack.set(stack); } // the first element in the stack is the name of the trigger class, @@ -76,8 +76,8 @@ public class EclipseLazyStarter implements ClassLoadingStatsHook, AdaptorHook, H stack.add(manager); } - public void postFindLocalClass(String name, Class clazz, ClasspathManager manager) throws ClassNotFoundException { - ArrayList stack = (ArrayList) activationStack.get(); + public void postFindLocalClass(String name, Class<?> clazz, ClasspathManager manager) throws ClassNotFoundException { + List<Object> stack = activationStack.get(); if (stack == null) return; int size = stack.size(); @@ -94,7 +94,7 @@ public class EclipseLazyStarter implements ClassLoadingStatsHook, AdaptorHook, H for (int i = managers.length - 1; i >= 0; i--) { if (errors.get(managers[i]) != null) { if (throwErrorOnFailedStart) - throw (TerminatingClassNotFoundException) errors.get(managers[i]); + throw errors.get(managers[i]); continue; } @@ -137,7 +137,7 @@ public class EclipseLazyStarter implements ClassLoadingStatsHook, AdaptorHook, H // do nothing } - public void recordClassDefine(String name, Class clazz, byte[] classbytes, ClasspathEntry classpathEntry, BundleEntry entry, ClasspathManager manager) { + public void recordClassDefine(String name, Class<?> clazz, byte[] classbytes, ClasspathEntry classpathEntry, BundleEntry entry, ClasspathManager manager) { // do nothing } @@ -149,7 +149,7 @@ public class EclipseLazyStarter implements ClassLoadingStatsHook, AdaptorHook, H // Don't activate non-starting bundles if (bundledata.getBundle().getState() == Bundle.RESOLVED) { if (throwErrorOnFailedStart) { - TerminatingClassNotFoundException error = (TerminatingClassNotFoundException) errors.get(manager); + TerminatingClassNotFoundException error = errors.get(manager); if (error != null) throw error; } diff --git a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/EclipseLogHook.java b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/EclipseLogHook.java index 8fc443ab0..6b0b95c8f 100644 --- a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/EclipseLogHook.java +++ b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/EclipseLogHook.java @@ -102,8 +102,8 @@ public class EclipseLogHook implements HookConfigurator, AdaptorHook { private void registerPerformanceLog(BundleContext context) { Object service = createPerformanceLog(); String serviceName = FrameworkLog.class.getName(); - Hashtable serviceProperties = new Hashtable(7); - Dictionary headers = context.getBundle().getHeaders(); + Dictionary<String, Object> serviceProperties = new Hashtable<String, Object>(7); + Dictionary<String, String> headers = context.getBundle().getHeaders(); serviceProperties.put(Constants.SERVICE_VENDOR, headers.get(Constants.BUNDLE_VENDOR)); serviceProperties.put(Constants.SERVICE_RANKING, new Integer(Integer.MIN_VALUE)); diff --git a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/EclipseStorageHook.java b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/EclipseStorageHook.java index 4dd929b84..6a760e239 100644 --- a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/EclipseStorageHook.java +++ b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/EclipseStorageHook.java @@ -83,28 +83,29 @@ public final class EclipseStorageHook implements StorageHook, HookConfigurator { return storageHook; } - public void initialize(Dictionary manifest) throws BundleException { - String activationPolicy = (String) manifest.get(Constants.BUNDLE_ACTIVATIONPOLICY); + @SuppressWarnings("deprecation") + public void initialize(Dictionary<String, String> manifest) throws BundleException { + String activationPolicy = manifest.get(Constants.BUNDLE_ACTIVATIONPOLICY); if (activationPolicy != null) { parseActivationPolicy(this, activationPolicy); } else { - String lazyStart = (String) manifest.get(Constants.ECLIPSE_LAZYSTART); + String lazyStart = manifest.get(Constants.ECLIPSE_LAZYSTART); if (lazyStart == null) - lazyStart = (String) manifest.get(Constants.ECLIPSE_AUTOSTART); + lazyStart = manifest.get(Constants.ECLIPSE_AUTOSTART); parseLazyStart(this, lazyStart); } try { - String versionString = (String) manifest.get(Constants.BUNDLE_MANIFESTVERSION); + String versionString = manifest.get(Constants.BUNDLE_MANIFESTVERSION); bundleManfestVersion = versionString == null ? 0 : Integer.parseInt(versionString); } catch (NumberFormatException nfe) { bundleManfestVersion = 0; } - pluginClass = (String) manifest.get(Constants.PLUGIN_CLASS); - buddyList = (String) manifest.get(Constants.BUDDY_LOADER); - registeredBuddyList = (String) manifest.get(Constants.REGISTERED_POLICY); + pluginClass = manifest.get(Constants.PLUGIN_CLASS); + buddyList = manifest.get(Constants.BUDDY_LOADER); + registeredBuddyList = manifest.get(Constants.REGISTERED_POLICY); if (hasPackageInfo(bundledata.getEntry(Constants.OSGI_BUNDLE_MANIFEST))) flags |= FLAG_HAS_PACKAGE_INFO; - String genFrom = (String) manifest.get(PluginConverterImpl.GENERATED_FROM); + String genFrom = manifest.get(PluginConverterImpl.GENERATED_FROM); if (genFrom != null) { ManifestElement generatedFrom = ManifestElement.parseHeader(PluginConverterImpl.GENERATED_FROM, genFrom)[0]; if (generatedFrom != null) { @@ -117,7 +118,7 @@ public final class EclipseStorageHook implements StorageHook, HookConfigurator { if (COMPATIBILITY_LAZYSTART) bundledata.setStatus(bundledata.getStatus() | Constants.BUNDLE_STARTED | Constants.BUNDLE_ACTIVATION_POLICY); } - serviceComponent = (String) manifest.get(CachedManifest.SERVICE_COMPONENT); + serviceComponent = manifest.get(CachedManifest.SERVICE_COMPONENT); } public StorageHook load(BaseData target, DataInputStream in) throws IOException { @@ -365,8 +366,8 @@ public final class EclipseStorageHook implements StorageHook, HookConfigurator { return false; } - private Headers checkManifestAndParent(String cacheLocation, String symbolicName, String version, byte inputType) throws BundleException { - Headers result = basicCheckManifest(cacheLocation, symbolicName, version, inputType); + private Headers<String, String> checkManifestAndParent(String cacheLocation, String symbolicName, String version, byte inputType) throws BundleException { + Headers<String, String> result = basicCheckManifest(cacheLocation, symbolicName, version, inputType); if (result != null) return result; Location parentConfiguration = null; @@ -375,7 +376,7 @@ public final class EclipseStorageHook implements StorageHook, HookConfigurator { return result; } - private Headers basicCheckManifest(String cacheLocation, String symbolicName, String version, byte inputType) throws BundleException { + private Headers<String, String> basicCheckManifest(String cacheLocation, String symbolicName, String version, byte inputType) throws BundleException { File currentFile = new File(cacheLocation, symbolicName + '_' + version + ".MF"); //$NON-NLS-1$ if (PluginConverterImpl.upToDate(currentFile, bundledata.getBundleFile().getBaseFile(), inputType)) { try { @@ -387,16 +388,16 @@ public final class EclipseStorageHook implements StorageHook, HookConfigurator { return null; } - Dictionary createCachedManifest(boolean firstTime) throws BundleException { + Dictionary<String, String> createCachedManifest(boolean firstTime) throws BundleException { return firstTime ? getGeneratedManifest() : new CachedManifest(this); } - public Dictionary getGeneratedManifest() throws BundleException { + public Dictionary<String, String> getGeneratedManifest() throws BundleException { if (System.getSecurityManager() == null) return getGeneratedManifest0(); try { - return (Dictionary) AccessController.doPrivileged(new PrivilegedExceptionAction() { - public Object run() throws BundleException { + return AccessController.doPrivileged(new PrivilegedExceptionAction<Dictionary<String, String>>() { + public Dictionary<String, String> run() throws BundleException { return getGeneratedManifest0(); } }); @@ -405,12 +406,12 @@ public final class EclipseStorageHook implements StorageHook, HookConfigurator { } } - final Dictionary getGeneratedManifest0() throws BundleException { - Dictionary builtIn = AdaptorUtil.loadManifestFrom(bundledata); + final Dictionary<String, String> getGeneratedManifest0() throws BundleException { + Dictionary<String, String> builtIn = AdaptorUtil.loadManifestFrom(bundledata); if (builtIn != null) { // the bundle has a built-in manifest - we may not have to generate one if (!isComplete(builtIn)) { - Dictionary generatedManifest = generateManifest(builtIn); + Dictionary<String, String> generatedManifest = generateManifest(builtIn); if (generatedManifest != null) return generatedManifest; } @@ -423,16 +424,16 @@ public final class EclipseStorageHook implements StorageHook, HookConfigurator { manifestTimeStamp = bundledata.getBundleFile().getEntry(Constants.OSGI_BUNDLE_MANIFEST).getTime(); return builtIn; } - Dictionary result = generateManifest(null); + Dictionary<String, String> result = generateManifest(null); if (result == null) throw new BundleException(NLS.bind(EclipseAdaptorMsg.ECLIPSE_DATA_MANIFEST_NOT_FOUND, bundledata.getLocation())); return result; } - private Dictionary generateManifest(Dictionary builtIn) throws BundleException { + private Dictionary<String, String> generateManifest(Dictionary<String, String> builtIn) throws BundleException { String cacheLocation = FrameworkProperties.getProperty(LocationManager.PROP_MANIFEST_CACHE); if (bundledata.getSymbolicName() != null) { - Headers existingHeaders = checkManifestAndParent(cacheLocation, bundledata.getSymbolicName(), bundledata.getVersion().toString(), manifestType); + Headers<String, String> existingHeaders = checkManifestAndParent(cacheLocation, bundledata.getSymbolicName(), bundledata.getVersion().toString(), manifestType); if (existingHeaders != null) return existingHeaders; } @@ -441,7 +442,7 @@ public final class EclipseStorageHook implements StorageHook, HookConfigurator { if (converter == null) converter = new PluginConverterImpl(bundledata.getAdaptor(), bundledata.getAdaptor().getContext()); - Dictionary generatedManifest; + Dictionary<String, String> generatedManifest; try { generatedManifest = converter.convertManifest(bundledata.getBundleFile().getBaseFile(), true, null, true, null); } catch (PluginConversionException pce) { @@ -450,10 +451,10 @@ public final class EclipseStorageHook implements StorageHook, HookConfigurator { } //Now we know the symbolicId and the version of the bundle, we check to see if don't have a manifest for it already - Version version = Version.parseVersion((String) generatedManifest.get(Constants.BUNDLE_VERSION)); - String symbolicName = ManifestElement.parseHeader(org.osgi.framework.Constants.BUNDLE_SYMBOLICNAME, (String) generatedManifest.get(org.osgi.framework.Constants.BUNDLE_SYMBOLICNAME))[0].getValue(); - ManifestElement generatedFrom = ManifestElement.parseHeader(PluginConverterImpl.GENERATED_FROM, (String) generatedManifest.get(PluginConverterImpl.GENERATED_FROM))[0]; - Headers existingHeaders = checkManifestAndParent(cacheLocation, symbolicName, version.toString(), Byte.parseByte(generatedFrom.getAttribute(PluginConverterImpl.MANIFEST_TYPE_ATTRIBUTE))); + Version version = Version.parseVersion(generatedManifest.get(Constants.BUNDLE_VERSION)); + String symbolicName = ManifestElement.parseHeader(org.osgi.framework.Constants.BUNDLE_SYMBOLICNAME, generatedManifest.get(org.osgi.framework.Constants.BUNDLE_SYMBOLICNAME))[0].getValue(); + ManifestElement generatedFrom = ManifestElement.parseHeader(PluginConverterImpl.GENERATED_FROM, generatedManifest.get(PluginConverterImpl.GENERATED_FROM))[0]; + Headers<String, String> existingHeaders = checkManifestAndParent(cacheLocation, symbolicName, version.toString(), Byte.parseByte(generatedFrom.getAttribute(PluginConverterImpl.MANIFEST_TYPE_ATTRIBUTE))); //We don't have a manifest. manifestTimeStamp = Long.parseLong(generatedFrom.getValue()); manifestType = Byte.parseByte(generatedFrom.getAttribute(PluginConverterImpl.MANIFEST_TYPE_ATTRIBUTE)); @@ -462,9 +463,9 @@ public final class EclipseStorageHook implements StorageHook, HookConfigurator { //merge the original manifest with the generated one if (builtIn != null) { - Enumeration keysEnum = builtIn.keys(); + Enumeration<String> keysEnum = builtIn.keys(); while (keysEnum.hasMoreElements()) { - Object key = keysEnum.nextElement(); + String key = keysEnum.nextElement(); generatedManifest.put(key, builtIn.get(key)); } } @@ -480,7 +481,7 @@ public final class EclipseStorageHook implements StorageHook, HookConfigurator { } - private boolean isComplete(Dictionary manifest) { + private boolean isComplete(Dictionary<String, String> manifest) { // a manifest is complete if it has a Bundle-SymbolicName entry... if (manifest.get(org.osgi.framework.Constants.BUNDLE_SYMBOLICNAME) != null) return true; @@ -506,7 +507,7 @@ public final class EclipseStorageHook implements StorageHook, HookConfigurator { return null; } - public Dictionary getManifest(boolean firstLoad) throws BundleException { + public Dictionary<String, String> getManifest(boolean firstLoad) throws BundleException { return createCachedManifest(firstLoad); } diff --git a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/IPluginInfo.java b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/IPluginInfo.java index 0c37d8273..9520f88eb 100644 --- a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/IPluginInfo.java +++ b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/IPluginInfo.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2003, 2008 IBM Corporation and others. + * 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 @@ -18,11 +18,11 @@ import java.util.*; * <p>Internal class.</p> */ public interface IPluginInfo { - public Map getLibraries(); + public Map<String, List<String>> getLibraries(); public String[] getLibrariesName(); - public ArrayList getRequires(); + public ArrayList<PluginParser.Prerequisite> getRequires(); public String getMasterId(); @@ -38,7 +38,7 @@ public interface IPluginInfo { public boolean isFragment(); - public Set getPackageFilters(); + public Set<String> getPackageFilters(); public String getPluginName(); diff --git a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/PluginConverterImpl.java b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/PluginConverterImpl.java index 0b00ea549..fe1447f2e 100644 --- a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/PluginConverterImpl.java +++ b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/PluginConverterImpl.java @@ -54,15 +54,16 @@ public class PluginConverterImpl implements PluginConverter { private IPluginInfo pluginInfo; private File pluginManifestLocation; private ZipFile pluginZip; - private Dictionary generatedManifest; + private Dictionary<String, String> generatedManifest; private byte manifestType; private Version target; - private Dictionary devProperties; + private Dictionary<String, String> devProperties; static final Version TARGET31 = new Version(3, 1, 0); static final Version TARGET32 = new Version(3, 2, 0); private static final String MANIFEST_VERSION = "Manifest-Version"; //$NON-NLS-1$ private static final String PLUGIN_PROPERTIES_FILENAME = "plugin"; //$NON-NLS-1$ private static PluginConverterImpl instance; + @SuppressWarnings("deprecation") private static final String[] ARCH_LIST = {org.eclipse.osgi.service.environment.Constants.ARCH_PA_RISC, org.eclipse.osgi.service.environment.Constants.ARCH_PPC, org.eclipse.osgi.service.environment.Constants.ARCH_SPARC, org.eclipse.osgi.service.environment.Constants.ARCH_X86, org.eclipse.osgi.service.environment.Constants.ARCH_AMD64, org.eclipse.osgi.service.environment.Constants.ARCH_IA64}; static public final String FRAGMENT_MANIFEST = "fragment.xml"; //$NON-NLS-1$ static public final String GENERATED_FROM = "Generated-from"; //$NON-NLS-1$ @@ -92,7 +93,7 @@ public class PluginConverterImpl implements PluginConverter { pluginInfo = null; pluginManifestLocation = null; pluginZip = null; - generatedManifest = new Hashtable(10); + generatedManifest = new Hashtable<String, String>(10); manifestType = MANIFEST_TYPE_UNKNOWN; target = null; devProperties = null; @@ -126,14 +127,12 @@ public class PluginConverterImpl implements PluginConverter { throw new PluginConversionException(validation); } - private Set filterExport(Collection exportToFilter, Collection filter) { + private Set<String> filterExport(Set<String> exportToFilter, Collection<String> filter) { if (filter == null || filter.contains("*")) //$NON-NLS-1$ - return (Set) exportToFilter; - Set filteredExport = new HashSet(exportToFilter.size()); - for (Iterator iter = exportToFilter.iterator(); iter.hasNext();) { - String anExport = (String) iter.next(); - for (Iterator iter2 = filter.iterator(); iter2.hasNext();) { - String aFilter = (String) iter2.next(); + return exportToFilter; + Set<String> filteredExport = new HashSet<String>(exportToFilter.size()); + for (String anExport : exportToFilter) { + for (String aFilter : filter) { int dotStar = aFilter.indexOf(".*"); //$NON-NLS-1$ if (dotStar != -1) aFilter = aFilter.substring(0, dotStar); @@ -146,9 +145,9 @@ public class PluginConverterImpl implements PluginConverter { return filteredExport; } - private ArrayList findOSJars(File pluginRoot, String path, boolean filter) { + private List<String> findOSJars(File pluginRoot, String path, boolean filter) { path = path.substring(4); - ArrayList found = new ArrayList(0); + List<String> found = new ArrayList<String>(0); for (int i = 0; i < OS_LIST.length; i++) { //look for os/osname/path String searchedPath = "os/" + OS_LIST[i] + "/" + path; //$NON-NLS-1$ //$NON-NLS-2$ @@ -210,9 +209,9 @@ public class PluginConverterImpl implements PluginConverter { return null; } - private ArrayList findWSJars(File pluginRoot, String path, boolean filter) { + private List<String> findWSJars(File pluginRoot, String path, boolean filter) { path = path.substring(4); - ArrayList found = new ArrayList(0); + List<String> found = new ArrayList<String>(0); for (int i = 0; i < WS_LIST.length; i++) { String searchedPath = "ws/" + WS_LIST[i] + path; //$NON-NLS-1$ if (new File(pluginRoot, searchedPath).exists()) { @@ -238,7 +237,8 @@ public class PluginConverterImpl implements PluginConverter { } } - public void writeManifest(File generationLocation, Dictionary manifestToWrite, boolean compatibilityManifest) throws PluginConversionException { + @SuppressWarnings("deprecation") + public void writeManifest(File generationLocation, Dictionary<String, String> manifestToWrite, boolean compatibilityManifest) throws PluginConversionException { long start = System.currentTimeMillis(); try { File parentFile = new File(generationLocation.getParent()); @@ -249,30 +249,30 @@ public class PluginConverterImpl implements PluginConverter { throw new PluginConversionException(message); } // replaces any eventual existing file - manifestToWrite = new Hashtable((Map) manifestToWrite); + manifestToWrite = new Hashtable<String, String>((Hashtable) manifestToWrite); // MANIFEST.MF files must be written using UTF-8 out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(generationLocation), UTF_8)); - writeEntry(MANIFEST_VERSION, (String) manifestToWrite.remove(MANIFEST_VERSION)); - writeEntry(GENERATED_FROM, (String) manifestToWrite.remove(GENERATED_FROM)); //Need to do this first uptoDate check expect the generated-from tag to be in the first line + writeEntry(MANIFEST_VERSION, manifestToWrite.remove(MANIFEST_VERSION)); + writeEntry(GENERATED_FROM, manifestToWrite.remove(GENERATED_FROM)); //Need to do this first uptoDate check expect the generated-from tag to be in the first line // always attempt to write the Bundle-ManifestVersion header if it exists (bug 109863) - writeEntry(Constants.BUNDLE_MANIFESTVERSION, (String) manifestToWrite.remove(Constants.BUNDLE_MANIFESTVERSION)); - writeEntry(Constants.BUNDLE_NAME, (String) manifestToWrite.remove(Constants.BUNDLE_NAME)); - writeEntry(Constants.BUNDLE_SYMBOLICNAME, (String) manifestToWrite.remove(Constants.BUNDLE_SYMBOLICNAME)); - writeEntry(Constants.BUNDLE_VERSION, (String) manifestToWrite.remove(Constants.BUNDLE_VERSION)); - writeEntry(Constants.BUNDLE_CLASSPATH, (String) manifestToWrite.remove(Constants.BUNDLE_CLASSPATH)); - writeEntry(Constants.BUNDLE_ACTIVATOR, (String) manifestToWrite.remove(Constants.BUNDLE_ACTIVATOR)); - writeEntry(Constants.BUNDLE_VENDOR, (String) manifestToWrite.remove(Constants.BUNDLE_VENDOR)); - writeEntry(Constants.FRAGMENT_HOST, (String) manifestToWrite.remove(Constants.FRAGMENT_HOST)); - writeEntry(Constants.BUNDLE_LOCALIZATION, (String) manifestToWrite.remove(Constants.BUNDLE_LOCALIZATION)); + writeEntry(Constants.BUNDLE_MANIFESTVERSION, manifestToWrite.remove(Constants.BUNDLE_MANIFESTVERSION)); + writeEntry(Constants.BUNDLE_NAME, manifestToWrite.remove(Constants.BUNDLE_NAME)); + writeEntry(Constants.BUNDLE_SYMBOLICNAME, manifestToWrite.remove(Constants.BUNDLE_SYMBOLICNAME)); + writeEntry(Constants.BUNDLE_VERSION, manifestToWrite.remove(Constants.BUNDLE_VERSION)); + writeEntry(Constants.BUNDLE_CLASSPATH, manifestToWrite.remove(Constants.BUNDLE_CLASSPATH)); + writeEntry(Constants.BUNDLE_ACTIVATOR, manifestToWrite.remove(Constants.BUNDLE_ACTIVATOR)); + writeEntry(Constants.BUNDLE_VENDOR, manifestToWrite.remove(Constants.BUNDLE_VENDOR)); + writeEntry(Constants.FRAGMENT_HOST, manifestToWrite.remove(Constants.FRAGMENT_HOST)); + writeEntry(Constants.BUNDLE_LOCALIZATION, manifestToWrite.remove(Constants.BUNDLE_LOCALIZATION)); // always attempt to write the Export-Package header if it exists (bug 109863) - writeEntry(Constants.EXPORT_PACKAGE, (String) manifestToWrite.remove(Constants.EXPORT_PACKAGE)); + writeEntry(Constants.EXPORT_PACKAGE, manifestToWrite.remove(Constants.EXPORT_PACKAGE)); // always attempt to write the Provide-Package header if it exists (bug 109863) - writeEntry(Constants.PROVIDE_PACKAGE, (String) manifestToWrite.remove(Constants.PROVIDE_PACKAGE)); - writeEntry(Constants.REQUIRE_BUNDLE, (String) manifestToWrite.remove(Constants.REQUIRE_BUNDLE)); - Enumeration keys = manifestToWrite.keys(); + writeEntry(Constants.PROVIDE_PACKAGE, manifestToWrite.remove(Constants.PROVIDE_PACKAGE)); + writeEntry(Constants.REQUIRE_BUNDLE, manifestToWrite.remove(Constants.REQUIRE_BUNDLE)); + Enumeration<String> keys = manifestToWrite.keys(); while (keys.hasMoreElements()) { - String key = (String) keys.nextElement(); - writeEntry(key, (String) manifestToWrite.get(key)); + String key = keys.nextElement(); + writeEntry(key, manifestToWrite.get(key)); } out.flush(); } catch (IOException e) { @@ -299,9 +299,9 @@ public class PluginConverterImpl implements PluginConverter { } private boolean requireRuntimeCompatibility() { - ArrayList requireList = pluginInfo.getRequires(); - for (Iterator iter = requireList.iterator(); iter.hasNext();) { - if (((PluginParser.Prerequisite) iter.next()).getName().equalsIgnoreCase(PI_RUNTIME_COMPATIBILITY)) + ArrayList<PluginParser.Prerequisite> requireList = pluginInfo.getRequires(); + for (Iterator<PluginParser.Prerequisite> iter = requireList.iterator(); iter.hasNext();) { + if (iter.next().getName().equalsIgnoreCase(PI_RUNTIME_COMPATIBILITY)) return true; } return false; @@ -367,20 +367,22 @@ public class PluginConverterImpl implements PluginConverter { } } + @SuppressWarnings("deprecation") private void generateProvidePackage() { - Set exports = getExports(); + Set<String> exports = getExports(); if (exports != null && exports.size() != 0) { generatedManifest.put(TARGET31.compareTo(target) <= 0 ? Constants.EXPORT_PACKAGE : Constants.PROVIDE_PACKAGE, getStringFromCollection(exports, LIST_SEPARATOR)); } } + @SuppressWarnings("deprecation") private void generateRequireBundle() { - ArrayList requiredBundles = pluginInfo.getRequires(); + ArrayList<PluginParser.Prerequisite> requiredBundles = pluginInfo.getRequires(); if (requiredBundles.size() == 0) return; StringBuffer bundleRequire = new StringBuffer(); - for (Iterator iter = requiredBundles.iterator(); iter.hasNext();) { - PluginParser.Prerequisite element = (PluginParser.Prerequisite) iter.next(); + for (Iterator<PluginParser.Prerequisite> iter = requiredBundles.iterator(); iter.hasNext();) { + PluginParser.Prerequisite element = iter.next(); StringBuffer modImport = new StringBuffer(element.getName()); String versionRange = getVersionRange(element.getVersion(), element.getMatch()); if (versionRange != null) @@ -409,6 +411,7 @@ public class PluginConverterImpl implements PluginConverter { generatedManifest.put(GENERATED_FROM, Long.toString(getTimeStamp(pluginManifestLocation, manifestType)) + ";" + MANIFEST_TYPE_ATTRIBUTE + "=" + manifestType); //$NON-NLS-1$ //$NON-NLS-2$ } + @SuppressWarnings("deprecation") private void generateEclipseHeaders() { if (pluginInfo.isFragment()) return; @@ -418,8 +421,8 @@ public class PluginConverterImpl implements PluginConverter { generatedManifest.put(TARGET32.compareTo(target) <= 0 ? Constants.ECLIPSE_LAZYSTART : Constants.ECLIPSE_AUTOSTART, "true"); //$NON-NLS-1$ } - private Set getExports() { - Map libs = pluginInfo.getLibraries(); + private Set<String> getExports() { + Map<String, List<String>> libs = pluginInfo.getLibraries(); if (libs == null) return null; @@ -427,11 +430,11 @@ public class PluginConverterImpl implements PluginConverter { if (devProperties != null || DevClassPathHelper.inDevelopmentMode()) { String[] devClassPath = DevClassPathHelper.getDevClassPath(pluginInfo.getUniqueId(), devProperties); // collect export clauses - List allExportClauses = new ArrayList(libs.size()); - Set libEntries = libs.entrySet(); - for (Iterator iter = libEntries.iterator(); iter.hasNext();) { - Map.Entry element = (Map.Entry) iter.next(); - allExportClauses.addAll((List) element.getValue()); + List<String> allExportClauses = new ArrayList<String>(libs.size()); + Set<Map.Entry<String, List<String>>> libEntries = libs.entrySet(); + for (Iterator<Map.Entry<String, List<String>>> iter = libEntries.iterator(); iter.hasNext();) { + Map.Entry<String, List<String>> element = iter.next(); + allExportClauses.addAll(element.getValue()); } if (devClassPath != null) { // bug 88498 @@ -445,14 +448,14 @@ public class PluginConverterImpl implements PluginConverter { } } - Set result = new TreeSet(); - Set libEntries = libs.entrySet(); - for (Iterator iter = libEntries.iterator(); iter.hasNext();) { - Map.Entry element = (Map.Entry) iter.next(); - List filter = (List) element.getValue(); + Set<String> result = new TreeSet<String>(); + Set<Map.Entry<String, List<String>>> libEntries = libs.entrySet(); + for (Iterator<Map.Entry<String, List<String>>> iter = libEntries.iterator(); iter.hasNext();) { + Map.Entry<String, List<String>> element = iter.next(); + List<String> filter = element.getValue(); if (filter.size() == 0) //If the library is not exported, then ignore it continue; - String libEntryText = ((String) element.getKey()).trim(); + String libEntryText = element.getKey().trim(); File libraryLocation; if (libEntryText.equals(DOT)) libraryLocation = pluginManifestLocation; @@ -461,17 +464,17 @@ public class PluginConverterImpl implements PluginConverter { File libEntryAsPath = new File(libEntryText); libraryLocation = libEntryAsPath.isAbsolute() ? libEntryAsPath : new File(pluginManifestLocation, libEntryText); } - Set exports = null; + Set<String> exports = null; if (libraryLocation.exists()) { if (libraryLocation.isFile()) exports = filterExport(getExportsFromJAR(libraryLocation), filter); //TODO Need to handle $xx$ variables else if (libraryLocation.isDirectory()) exports = filterExport(getExportsFromDir(libraryLocation), filter); } else { - ArrayList expandedLibs = getLibrariesExpandingVariables((String) element.getKey(), false); - exports = new HashSet(); - for (Iterator iterator = expandedLibs.iterator(); iterator.hasNext();) { - String libName = (String) iterator.next(); + List<String> expandedLibs = getLibrariesExpandingVariables(element.getKey(), false); + exports = new HashSet<String>(); + for (Iterator<String> iterator = expandedLibs.iterator(); iterator.hasNext();) { + String libName = iterator.next(); File libFile = new File(pluginManifestLocation, libName); if (libFile.isFile()) { exports.addAll(filterExport(getExportsFromJAR(libFile), filter)); @@ -484,14 +487,14 @@ public class PluginConverterImpl implements PluginConverter { return result; } - private Set getExportsFromDir(File location) { + private Set<String> getExportsFromDir(File location) { return getExportsFromDir(location, ""); //$NON-NLS-1$ } - private Set getExportsFromDir(File location, String packageName) { + private Set<String> getExportsFromDir(File location, String packageName) { String prefix = (packageName.length() > 0) ? (packageName + '.') : ""; //$NON-NLS-1$ String[] files = location.list(); - Set exportedPaths = new HashSet(); + Set<String> exportedPaths = new HashSet<String>(); boolean containsFile = false; if (files != null) for (int i = 0; i < files.length; i++) { @@ -513,8 +516,8 @@ public class PluginConverterImpl implements PluginConverter { return exportedPaths; } - private Set getExportsFromJAR(File jarFile) { - Set names = new HashSet(); + private Set<String> getExportsFromJAR(File jarFile) { + Set<String> names = new HashSet<String>(); ZipFile file = null; try { file = new ZipFile(jarFile); @@ -524,8 +527,8 @@ public class PluginConverterImpl implements PluginConverter { return names; } //Run through the entries - for (Enumeration entriesEnum = file.entries(); entriesEnum.hasMoreElements();) { - ZipEntry entry = (ZipEntry) entriesEnum.nextElement(); + for (Enumeration<? extends ZipEntry> entriesEnum = file.entries(); entriesEnum.hasMoreElements();) { + ZipEntry entry = entriesEnum.nextElement(); String name = entry.getName(); if (!isValidPackageName(name)) continue; @@ -548,10 +551,10 @@ public class PluginConverterImpl implements PluginConverter { return names; } - private ArrayList getLibrariesExpandingVariables(String libraryPath, boolean filter) { + private List<String> getLibrariesExpandingVariables(String libraryPath, boolean filter) { String var = hasPrefix(libraryPath); if (var == null) { - ArrayList returnValue = new ArrayList(1); + List<String> returnValue = new ArrayList<String>(1); returnValue.add(libraryPath); return returnValue; } @@ -561,7 +564,7 @@ public class PluginConverterImpl implements PluginConverter { if (var.equals("os")) { //$NON-NLS-1$ return findOSJars(pluginManifestLocation, libraryPath, filter); } - return new ArrayList(0); + return new ArrayList<String>(0); } //return a String representing the string found between the $s @@ -688,10 +691,10 @@ public class PluginConverterImpl implements PluginConverter { return result.toString(); } - private String getStringFromCollection(Collection collection, String separator) { + private String getStringFromCollection(Collection<String> collection, String separator) { StringBuffer result = new StringBuffer(); boolean first = true; - for (Iterator i = collection.iterator(); i.hasNext();) { + for (Iterator<String> i = collection.iterator(); i.hasNext();) { if (first) first = false; else @@ -701,7 +704,7 @@ public class PluginConverterImpl implements PluginConverter { return result.toString(); } - public synchronized Dictionary convertManifest(File pluginBaseLocation, boolean compatibility, String targetVersion, boolean analyseJars, Dictionary devProps) throws PluginConversionException { + public synchronized Dictionary<String, String> convertManifest(File pluginBaseLocation, boolean compatibility, String targetVersion, boolean analyseJars, Dictionary<String, String> devProps) throws PluginConversionException { long start = System.currentTimeMillis(); if (DEBUG) System.out.println("Convert " + pluginBaseLocation); //$NON-NLS-1$ @@ -715,7 +718,7 @@ public class PluginConverterImpl implements PluginConverter { return generatedManifest; } - public synchronized File convertManifest(File pluginBaseLocation, File bundleManifestLocation, boolean compatibilityManifest, String targetVersion, boolean analyseJars, Dictionary devProps) throws PluginConversionException { + public synchronized File convertManifest(File pluginBaseLocation, File bundleManifestLocation, boolean compatibilityManifest, String targetVersion, boolean analyseJars, Dictionary<String, String> devProps) throws PluginConversionException { convertManifest(pluginBaseLocation, compatibilityManifest, targetVersion, analyseJars, devProps); if (bundleManifestLocation == null) { String cacheLocation = FrameworkProperties.getProperty(LocationManager.PROP_MANIFEST_CACHE); diff --git a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/PluginParser.java b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/PluginParser.java index fae1ec1ec..1448b28ff 100644 --- a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/PluginParser.java +++ b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/adaptor/PluginParser.java @@ -26,7 +26,7 @@ import org.xml.sax.helpers.DefaultHandler; * Internal class. */ public class PluginParser extends DefaultHandler implements IModel { - private static ServiceTracker xmlTracker = null; + private static ServiceTracker<SAXParserFactory, SAXParserFactory> xmlTracker = null; private PluginInfo manifestInfo = new PluginInfo(); private BundleContext context; @@ -41,19 +41,19 @@ public class PluginParser extends DefaultHandler implements IModel { String vendor; // an ordered list of library path names. - ArrayList libraryPaths; + List<String> libraryPaths; // TODO Should get rid of the libraries map and just have a // list of library export statements instead. Library paths must // preserve order. - Map libraries; //represent the libraries and their export statement - ArrayList requires; + Map<String, List<String>> libraries; //represent the libraries and their export statement + ArrayList<PluginParser.Prerequisite> requires; private boolean requiresExpanded = false; //indicates if the requires have been processed. boolean compatibilityFound = false; //set to true is the requirement list contain compatilibity String pluginClass; String masterPluginId; String masterVersion; String masterMatch; - private Set filters; + private Set<String> filters; String pluginName; boolean singleton; boolean fragment; @@ -68,23 +68,23 @@ public class PluginParser extends DefaultHandler implements IModel { return "plugin-id: " + pluginId + " version: " + version + " libraries: " + libraries + " class:" + pluginClass + " master: " + masterPluginId + " master-version: " + masterVersion + " requires: " + requires + " singleton: " + singleton; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ } - public Map getLibraries() { + public Map<String, List<String>> getLibraries() { if (libraries == null) - return new HashMap(0); + return new HashMap<String, List<String>>(0); return libraries; } - public ArrayList getRequires() { + public ArrayList<Prerequisite> getRequires() { if (!TARGET21.equals(target) && schemaVersion == null && !requiresExpanded) { requiresExpanded = true; if (requires == null) { - requires = new ArrayList(1); + requires = new ArrayList<Prerequisite>(1); requires.add(new Prerequisite(PluginConverterImpl.PI_RUNTIME, TARGET21_STRING, false, false, IModel.PLUGIN_REQUIRES_MATCH_GREATER_OR_EQUAL)); requires.add(new Prerequisite(PluginConverterImpl.PI_RUNTIME_COMPATIBILITY, null, false, false, null)); } else { //Add elements on the requirement list of ui and help. for (int i = 0; i < requires.size(); i++) { - Prerequisite analyzed = (Prerequisite) requires.get(i); + Prerequisite analyzed = requires.get(i); if ("org.eclipse.ui".equals(analyzed.getName())) { //$NON-NLS-1$ requires.add(i + 1, new Prerequisite("org.eclipse.ui.workbench.texteditor", null, true, analyzed.isExported(), null)); //$NON-NLS-1$ requires.add(i + 1, new Prerequisite("org.eclipse.jface.text", null, true, analyzed.isExported(), null)); //$NON-NLS-1$ @@ -108,7 +108,7 @@ public class PluginParser extends DefaultHandler implements IModel { } } if (requires == null) - return requires = new ArrayList(0); + return requires = new ArrayList<Prerequisite>(0); return requires; } @@ -137,14 +137,14 @@ public class PluginParser extends DefaultHandler implements IModel { return version; } - public Set getPackageFilters() { + public Set<String> getPackageFilters() { return filters; } public String[] getLibrariesName() { if (libraryPaths == null) return new String[0]; - return (String[]) libraryPaths.toArray(new String[libraryPaths.size()]); + return libraryPaths.toArray(new String[libraryPaths.size()]); } public String getPluginName() { @@ -187,10 +187,10 @@ public class PluginParser extends DefaultHandler implements IModel { } // Current State Information - Stack stateStack = new Stack(); + Stack<Integer> stateStack = new Stack<Integer>(); // Current object stack (used to hold the current object we are populating in this plugin info - Stack objectStack = new Stack(); + Stack<Object> objectStack = new Stack<Object>(); Locator locator = null; // Valid States @@ -235,7 +235,7 @@ public class PluginParser extends DefaultHandler implements IModel { } public void endElement(String uri, String elementName, String qName) { - switch (((Integer) stateStack.peek()).intValue()) { + switch (stateStack.peek().intValue()) { case IGNORED_ELEMENT_STATE : stateStack.pop(); break; @@ -271,12 +271,13 @@ public class PluginParser extends DefaultHandler implements IModel { if (elementName.equals(LIBRARY)) { String curLibrary = (String) objectStack.pop(); if (!curLibrary.trim().equals("")) { //$NON-NLS-1$ - Vector exportsVector = (Vector) objectStack.pop(); + @SuppressWarnings("unchecked") + List<String> exports = (List<String>) objectStack.pop(); if (manifestInfo.libraries == null) { - manifestInfo.libraries = new HashMap(3); - manifestInfo.libraryPaths = new ArrayList(3); + manifestInfo.libraries = new HashMap<String, List<String>>(3); + manifestInfo.libraryPaths = new ArrayList<String>(3); } - manifestInfo.libraries.put(curLibrary, exportsVector); + manifestInfo.libraries.put(curLibrary, exports); manifestInfo.libraryPaths.add(curLibrary.replace('\\', '/')); } stateStack.pop(); @@ -346,7 +347,8 @@ public class PluginParser extends DefaultHandler implements IModel { String maskValue = attributes.getValue("", LIBRARY_EXPORT_MASK); //$NON-NLS-1$ // pop off the library - already in currentLib objectStack.pop(); - Vector exportMask = (Vector) objectStack.peek(); + @SuppressWarnings("unchecked") + List<String> exportMask = (List<String>) objectStack.peek(); // push library back on objectStack.push(currentLib); //Split the export upfront @@ -355,7 +357,7 @@ public class PluginParser extends DefaultHandler implements IModel { while (tok.hasMoreTokens()) { String value = tok.nextToken(); if (!exportMask.contains(maskValue)) - exportMask.addElement(value.trim()); + exportMask.add(value.trim()); } } return; @@ -385,7 +387,7 @@ public class PluginParser extends DefaultHandler implements IModel { if (elementName.equals(PLUGIN_REQUIRES)) { stateStack.push(new Integer(PLUGIN_REQUIRES_STATE)); // Push a new vector to hold all the prerequisites - objectStack.push(new Vector()); + objectStack.push(new ArrayList<String>()); parseRequiresAttributes(attributes); return; } @@ -475,10 +477,10 @@ public class PluginParser extends DefaultHandler implements IModel { public static SAXParserFactory acquireXMLParsing(BundleContext context) { if (xmlTracker == null) { - xmlTracker = new ServiceTracker(context, "javax.xml.parsers.SAXParserFactory", null); //$NON-NLS-1$ + xmlTracker = new ServiceTracker<SAXParserFactory, SAXParserFactory>(context, "javax.xml.parsers.SAXParserFactory", null); //$NON-NLS-1$ xmlTracker.open(); } - SAXParserFactory result = (SAXParserFactory) xmlTracker.getService(); + SAXParserFactory result = xmlTracker.getService(); if (result != null) return result; // backup to using jaxp to create a new instance @@ -516,7 +518,7 @@ public class PluginParser extends DefaultHandler implements IModel { public void parseLibraryAttributes(Attributes attributes) { // Push a vector to hold the export mask - objectStack.push(new Vector()); + objectStack.push(new ArrayList<String>()); String current = attributes.getValue("", LIBRARY_NAME); //$NON-NLS-1$ objectStack.push(current); } @@ -593,7 +595,7 @@ public class PluginParser extends DefaultHandler implements IModel { public void parsePluginRequiresImport(Attributes attributes) { if (manifestInfo.requires == null) { - manifestInfo.requires = new ArrayList(); + manifestInfo.requires = new ArrayList<Prerequisite>(); // to avoid cycles // if (!manifestInfo.pluginId.equals(PluginConverterImpl.PI_RUNTIME)) //$NON-NLS-1$ // manifestInfo.requires.add(new Prerequisite(PluginConverterImpl.PI_RUNTIME, null, false, false, null)); //$NON-NLS-1$ @@ -634,7 +636,7 @@ public class PluginParser extends DefaultHandler implements IModel { } public void startElement(String uri, String elementName, String qName, Attributes attributes) { - switch (((Integer) stateStack.peek()).intValue()) { + switch (stateStack.peek().intValue()) { case INITIAL_STATE : handleInitialState(elementName, attributes); break; diff --git a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/stats/BundleStats.java b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/stats/BundleStats.java index ba6c01892..f021dfc9b 100644 --- a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/stats/BundleStats.java +++ b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/stats/BundleStats.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2006 IBM Corporation and others. + * Copyright (c) 2000, 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 @@ -11,6 +11,7 @@ package org.eclipse.core.runtime.internal.stats; import java.util.ArrayList; +import java.util.List; /** * Contains information about activated bundles and acts as the main @@ -31,7 +32,7 @@ public class BundleStats { private long traceEnd = -1; //To keep bundle parentage - private ArrayList bundlesActivated = new ArrayList(3); // TODO create lazily + private List<BundleStats> bundlesActivated = new ArrayList<BundleStats>(3); // TODO create lazily private BundleStats activatedBy = null; public BundleStats(String name, long id) { @@ -89,7 +90,7 @@ public class BundleStats { return loader == null ? 0 : loader.getClassLoadTime(); } - public ArrayList getBundlesActivated() { + public List<BundleStats> getBundlesActivated() { return bundlesActivated; } diff --git a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/stats/ClassStats.java b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/stats/ClassStats.java index 60a9701fb..092dd156e 100644 --- a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/stats/ClassStats.java +++ b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/stats/ClassStats.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2006 IBM Corporation and others. + * Copyright (c) 2000, 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 @@ -11,6 +11,7 @@ package org.eclipse.core.runtime.internal.stats; import java.util.ArrayList; +import java.util.List; /** * Maintain statistics about a loaded class. @@ -26,7 +27,7 @@ public class ClassStats { // parentage of classes loaded private ClassStats loadedBy = null; // a reference to the class that loaded this class - private ArrayList loaded = new ArrayList(2); // a reference to the classes that this class loaded + private List<ClassStats> loaded = new ArrayList<ClassStats>(2); // a reference to the classes that this class loaded private boolean duringStartup; // indicate if the class was loaded during platform startup @@ -89,7 +90,7 @@ public class ClassStats { return loadedBy; } - public ArrayList getLoadedClasses() { + public List<ClassStats> getLoadedClasses() { return loaded; } diff --git a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/stats/ClassloaderStats.java b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/stats/ClassloaderStats.java index 0e9f7813b..0a56fe7aa 100644 --- a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/stats/ClassloaderStats.java +++ b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/stats/ClassloaderStats.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 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 @@ -24,20 +24,20 @@ public class ClassloaderStats { /** * classes loaded by the plugin (key: class name, value: ClassStats) */ - private Map classes = Collections.synchronizedMap(new HashMap(20)); - private ArrayList bundles = new ArrayList(2); // bundles loaded + private Map<String, ClassStats> classes = Collections.synchronizedMap(new HashMap<String, ClassStats>(20)); + private List<ResourceBundleStats> bundles = new ArrayList<ResourceBundleStats>(2); // bundles loaded private boolean keepTraces = false; // indicate whether or not the traces of classes loaded are kept // filters to indicate which classes we want to keep the traces - private static ArrayList packageFilters = new ArrayList(4); // filters on a package basis - private static Set pluginFilters = new HashSet(5); // filters on a plugin basis + private static List<String> packageFilters = new ArrayList<String>(4); // filters on a package basis + private static Set<String> pluginFilters = new HashSet<String>(5); // filters on a plugin basis - private static Hashtable classStacks = new Hashtable(); // represents the classes that are currently being loaded + private static Hashtable<Thread, Stack<ClassStats>> classStacks = new Hashtable<Thread, Stack<ClassStats>>(); // represents the classes that are currently being loaded /** * a dictionary of the classloaderStats (key: pluginId, value: ClassloaderStats) */ - private static Map loaders = Collections.synchronizedMap(new HashMap(20)); + private static Map<String, ClassloaderStats> loaders = Collections.synchronizedMap(new HashMap<String, ClassloaderStats>(20)); public static File traceFile; static { @@ -95,7 +95,7 @@ public class ClassloaderStats { // get and create if does not exist private static ClassloaderStats findLoader(String id) { synchronized (loaders) { - ClassloaderStats result = (ClassloaderStats) loaders.get(id); + ClassloaderStats result = loaders.get(id); if (result == null) { result = new ClassloaderStats(id); loaders.put(id, result); @@ -104,10 +104,10 @@ public class ClassloaderStats { } } - public static synchronized Stack getClassStack() { - Stack result = (Stack) classStacks.get(Thread.currentThread()); + public static synchronized Stack<ClassStats> getClassStack() { + Stack<ClassStats> result = classStacks.get(Thread.currentThread()); if (result == null) { - result = new Stack(); + result = new Stack<ClassStats>(); classStacks.put(Thread.currentThread(), result); } return result; @@ -116,7 +116,7 @@ public class ClassloaderStats { public static ClassloaderStats[] getLoaders() { //the parameter to toArray is of size zero for thread safety, otherwise this //could return an array with null entries if the map shrinks concurrently - return (ClassloaderStats[]) loaders.values().toArray(new ClassloaderStats[0]); + return loaders.values().toArray(new ClassloaderStats[0]); } public static void endLoadingClass(String id, String className, boolean success) { @@ -128,7 +128,7 @@ public class ClassloaderStats { } public static ClassloaderStats getLoader(String id) { - return (ClassloaderStats) loaders.get(id); + return loaders.get(id); } public ClassloaderStats(String id) { @@ -151,7 +151,7 @@ public class ClassloaderStats { bundles.add(bundle); } - public ArrayList getBundles() { + public List<ResourceBundleStats> getBundles() { return bundles; } @@ -161,12 +161,12 @@ public class ClassloaderStats { // internal method that return the existing classStats or creates one private ClassStats findClass(String name) { - ClassStats result = (ClassStats) classes.get(name); + ClassStats result = classes.get(name); return result == null ? new ClassStats(name, this) : result; } private synchronized void endLoadClass(String name, boolean success) { - ClassStats current = (ClassStats) getClassStack().pop(); + ClassStats current = getClassStack().pop(); if (!success) { failureCount++; return; @@ -180,10 +180,10 @@ public class ClassloaderStats { traceLoad(name, current); // is there something on the load stack. if so, link them together... - Stack classStack = getClassStack(); + Stack<ClassStats> classStack = getClassStack(); if (classStack.size() != 0) { // get the time spent loading cli and subtract its load time from the class that requires loading - ClassStats previous = ((ClassStats) classStack.peek()); + ClassStats previous = classStack.peek(); previous.addTimeLoadingOthers(current.getTimeLoading()); current.setLoadedBy(previous); previous.loaded(current); @@ -197,7 +197,7 @@ public class ClassloaderStats { if (!keepTraces) { boolean found = false; for (int i = 0; !found && i < packageFilters.size(); i++) - if (name.startsWith((String) packageFilters.get(i))) + if (name.startsWith(packageFilters.get(i))) found = true; if (!found) return; @@ -211,9 +211,9 @@ public class ClassloaderStats { output.println("Loading class: " + name); //$NON-NLS-1$ output.println("Class loading stack:"); //$NON-NLS-1$ output.println("\t" + name); //$NON-NLS-1$ - Stack classStack = getClassStack(); + Stack<ClassStats> classStack = getClassStack(); for (int i = classStack.size() - 1; i >= 0; i--) - output.println("\t" + ((ClassStats) classStack.get(i)).getClassName()); //$NON-NLS-1$ + output.println("\t" + classStack.get(i).getClassName()); //$NON-NLS-1$ output.println("Stack trace:"); //$NON-NLS-1$ new Throwable().printStackTrace(output); } finally { @@ -236,7 +236,7 @@ public class ClassloaderStats { public ClassStats[] getClasses() { //the parameter to toArray is of size zero for thread safety, otherwise this //could return an array with null entries if the map shrinks concurrently - return (ClassStats[]) classes.values().toArray(new ClassStats[0]); + return classes.values().toArray(new ClassStats[0]); } public String getId() { diff --git a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/stats/ResourceBundleStats.java b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/stats/ResourceBundleStats.java index e338e503c..2c072f91c 100644 --- a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/stats/ResourceBundleStats.java +++ b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/stats/ResourceBundleStats.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2006 IBM Corporation and others. + * Copyright (c) 2000, 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 @@ -53,8 +53,8 @@ public class ResourceBundleStats { * Compute the size of bundle */ private void initialize(ResourceBundle bundle) { - for (Enumeration keys = bundle.getKeys(); keys.hasMoreElements();) { - String key = (String) keys.nextElement(); + for (Enumeration<String> keys = bundle.getKeys(); keys.hasMoreElements();) { + String key = keys.nextElement(); keySize += sizeOf(key); valueSize += sizeOf(bundle.getString(key)); keyCount++; @@ -72,7 +72,7 @@ public class ResourceBundleStats { stream = url.openStream(); fileSize = stream.available(); props.load(stream); - for (Iterator iter = props.keySet().iterator(); iter.hasNext();) { + for (Iterator<Object> iter = props.keySet().iterator(); iter.hasNext();) { String key = (String) iter.next(); keySize += sizeOf(key); valueSize += sizeOf(props.getProperty(key)); diff --git a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/stats/StatsManager.java b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/stats/StatsManager.java index 62e9d5997..8356d808e 100644 --- a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/stats/StatsManager.java +++ b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/internal/stats/StatsManager.java @@ -29,8 +29,8 @@ import org.osgi.framework.Bundle; public class StatsManager implements BundleWatcher, HookConfigurator, ClassLoadingStatsHook { // This connect bundles and their info, and so allows to access the info without running through // the bundle registry. This map only contains activated bundles. The key is the bundle Id - private Hashtable bundles = new Hashtable(20); - private Map activationStacks = new HashMap(5); + private Hashtable<Long, BundleStats> bundles = new Hashtable<Long, BundleStats>(20); + private Map<Thread, Stack<BundleStats>> activationStacks = new HashMap<Thread, Stack<BundleStats>>(5); private static boolean booting = true; // the state of the platform. This value is changed by the InternalPlatform itself. private static StatsManager defaultInstance; @@ -123,15 +123,15 @@ public class StatsManager implements BundleWatcher, HookConfigurator, ClassLoadi info.setActivationOrder(bundles.size()); info.setDuringStartup(booting); - Stack activationStack = (Stack) activationStacks.get(Thread.currentThread()); + Stack<BundleStats> activationStack = activationStacks.get(Thread.currentThread()); if (activationStack == null) { - activationStack = new Stack(); + activationStack = new Stack<BundleStats>(); activationStacks.put(Thread.currentThread(), activationStack); } // set the parentage of activation if (activationStack.size() != 0) { - BundleStats activatedBy = (BundleStats) activationStack.peek(); + BundleStats activatedBy = activationStack.peek(); activatedBy.activated(info); info.setActivatedBy(activatedBy); } @@ -143,9 +143,9 @@ public class StatsManager implements BundleWatcher, HookConfigurator, ClassLoadi } public void endActivation(Bundle symbolicName) { - Stack activationStack = (Stack) activationStacks.get(Thread.currentThread()); + Stack<BundleStats> activationStack = activationStacks.get(Thread.currentThread()); // should be called from a synchronized location to protect against concurrent updates - BundleStats info = (BundleStats) activationStack.pop(); + BundleStats info = activationStack.pop(); info.endActivation(); } @@ -156,13 +156,13 @@ public class StatsManager implements BundleWatcher, HookConfigurator, ClassLoadi long startPosition = ClassloaderStats.traceFile.length(); output.println("Activating bundle: " + bundle.getSymbolicName()); //$NON-NLS-1$ output.println("Bundle activation stack:"); //$NON-NLS-1$ - Stack activationStack = (Stack) activationStacks.get(Thread.currentThread()); + Stack<BundleStats> activationStack = activationStacks.get(Thread.currentThread()); for (int i = activationStack.size() - 1; i >= 0; i--) - output.println("\t" + ((BundleStats) activationStack.get(i)).getSymbolicName()); //$NON-NLS-1$ + output.println("\t" + activationStack.get(i).getSymbolicName()); //$NON-NLS-1$ output.println("Class loading stack:"); //$NON-NLS-1$ - Stack classStack = ClassloaderStats.getClassStack(); + Stack<ClassStats> classStack = ClassloaderStats.getClassStack(); for (int i = classStack.size() - 1; i >= 0; i--) - output.println("\t" + ((ClassStats) classStack.get(i)).getClassName()); //$NON-NLS-1$ + output.println("\t" + classStack.get(i).getClassName()); //$NON-NLS-1$ output.println("Stack trace:"); //$NON-NLS-1$ new Throwable().printStackTrace(output); info.setTraceStart(startPosition); @@ -176,7 +176,7 @@ public class StatsManager implements BundleWatcher, HookConfigurator, ClassLoadi } public BundleStats findBundle(String symbolicName, long id) { - BundleStats result = (BundleStats) bundles.get(new Long(id)); + BundleStats result = bundles.get(new Long(id)); try { if (result == null) { result = new BundleStats(symbolicName, id); @@ -189,11 +189,11 @@ public class StatsManager implements BundleWatcher, HookConfigurator, ClassLoadi } public BundleStats[] getBundles() { - return (BundleStats[]) bundles.values().toArray(new BundleStats[bundles.size()]); + return bundles.values().toArray(new BundleStats[bundles.size()]); } public BundleStats getBundle(long id) { - return (BundleStats) bundles.get(new Long(id)); + return bundles.get(new Long(id)); } /** @@ -204,7 +204,7 @@ public class StatsManager implements BundleWatcher, HookConfigurator, ClassLoadi ClassloaderStats.startLoadingClass(getClassloaderId(manager), name); } - public void postFindLocalClass(String name, Class clazz, ClasspathManager manager) { + public void postFindLocalClass(String name, Class<?> clazz, ClasspathManager manager) { if (StatsManager.MONITOR_CLASSES) ClassloaderStats.endLoadingClass(getClassloaderId(manager), name, clazz != null); } @@ -220,7 +220,7 @@ public class StatsManager implements BundleWatcher, HookConfigurator, ClassLoadi return; } - public void recordClassDefine(String name, Class clazz, byte[] classbytes, ClasspathEntry classpathEntry, BundleEntry entry, ClasspathManager manager) { + public void recordClassDefine(String name, Class<?> clazz, byte[] classbytes, ClasspathEntry classpathEntry, BundleEntry entry, ClasspathManager manager) { // do nothing } diff --git a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/osgi/service/pluginconversion/PluginConverter.java b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/osgi/service/pluginconversion/PluginConverter.java index 3e21ac664..097d58fca 100644 --- a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/osgi/service/pluginconversion/PluginConverter.java +++ b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/osgi/service/pluginconversion/PluginConverter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2003, 2005 IBM Corporation and others. + * 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 @@ -41,7 +41,7 @@ public interface PluginConverter { * generated (or already existed), <code>null</code> otherwise. * @throws PluginConversionException if an error occurs while converting the manifest */ - public File convertManifest(File pluginBaseLocation, File bundleManifestLocation, boolean compatibilityManifest, String target, boolean analyseJars, Dictionary devProperties) throws PluginConversionException; + public File convertManifest(File pluginBaseLocation, File bundleManifestLocation, boolean compatibilityManifest, String target, boolean analyseJars, Dictionary<String, String> devProperties) throws PluginConversionException; /** * Converts a plug-in/fragment manifest at the given source base location (a directory) and @@ -59,7 +59,7 @@ public interface PluginConverter { * generated, <code>null</code> otherwise * @throws PluginConversionException if an error occurs while converting the manifest */ - public Dictionary convertManifest(File pluginBaseLocation, boolean compatibility, String target, boolean analyseJars, Dictionary devProperties) throws PluginConversionException; + public Dictionary<String, String> convertManifest(File pluginBaseLocation, boolean compatibility, String target, boolean analyseJars, Dictionary<String, String> devProperties) throws PluginConversionException; /** * Construct a bundle manifest file from the given dictionary and write it out to the @@ -76,5 +76,5 @@ public interface PluginConverter { * running in backward compatibility mode * @throws PluginConversionException if an error occurs while writing the given manifest */ - public void writeManifest(File generationLocation, Dictionary manifestToWrite, boolean compatibilityManifest) throws PluginConversionException; + public void writeManifest(File generationLocation, Dictionary<String, String> manifestToWrite, boolean compatibilityManifest) throws PluginConversionException; } diff --git a/bundles/org.eclipse.osgi/resolver/src/org/eclipse/osgi/internal/resolver/BundleDeltaImpl.java b/bundles/org.eclipse.osgi/resolver/src/org/eclipse/osgi/internal/resolver/BundleDeltaImpl.java index b957747ff..7ad58d8e5 100644 --- a/bundles/org.eclipse.osgi/resolver/src/org/eclipse/osgi/internal/resolver/BundleDeltaImpl.java +++ b/bundles/org.eclipse.osgi/resolver/src/org/eclipse/osgi/internal/resolver/BundleDeltaImpl.java @@ -71,8 +71,8 @@ final class BundleDeltaImpl implements BundleDelta { return typeStr.toString(); } - public int compareTo(Object obj) { - long idcomp = getBundle().getBundleId() - ((BundleDelta) obj).getBundle().getBundleId(); + public int compareTo(BundleDelta obj) { + long idcomp = getBundle().getBundleId() - obj.getBundle().getBundleId(); return (idcomp < 0L) ? -1 : ((idcomp > 0L) ? 1 : 0); } } diff --git a/bundles/org.eclipse.osgi/resolver/src/org/eclipse/osgi/internal/resolver/NativeCodeDescriptionImpl.java b/bundles/org.eclipse.osgi/resolver/src/org/eclipse/osgi/internal/resolver/NativeCodeDescriptionImpl.java index ce9750eff..f31c7d864 100644 --- a/bundles/org.eclipse.osgi/resolver/src/org/eclipse/osgi/internal/resolver/NativeCodeDescriptionImpl.java +++ b/bundles/org.eclipse.osgi/resolver/src/org/eclipse/osgi/internal/resolver/NativeCodeDescriptionImpl.java @@ -78,9 +78,7 @@ public class NativeCodeDescriptionImpl extends BaseDescriptionImpl implements Na return supplier; } - public int compareTo(Object other) { - if (!(other instanceof NativeCodeDescription)) - return 1; + public int compareTo(NativeCodeDescription otherDesc) { State containingState = getSupplier().getContainingState(); if (containingState == null) return 0; @@ -91,7 +89,6 @@ public class NativeCodeDescriptionImpl extends BaseDescriptionImpl implements Na } catch (Exception e) { osversion = Version.emptyVersion; } - NativeCodeDescription otherDesc = (NativeCodeDescription) other; VersionRange[] thisRanges = getOSVersions(); VersionRange[] otherRanges = otherDesc.getOSVersions(); Version thisHighest = getHighestVersionMatch(osversion, thisRanges); diff --git a/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/provisional/service/security/AuthorizationEngine.java b/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/provisional/service/security/AuthorizationEngine.java index 4be1f7fae..7cbb1effd 100644 --- a/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/provisional/service/security/AuthorizationEngine.java +++ b/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/provisional/service/security/AuthorizationEngine.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2008 IBM Corporation and others. + * 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 @@ -10,6 +10,8 @@ *******************************************************************************/ package org.eclipse.osgi.internal.provisional.service.security; +import java.util.HashMap; +import java.util.Map; import org.eclipse.osgi.framework.eventmgr.*; import org.eclipse.osgi.signedcontent.SignedContent; import org.osgi.framework.BundleContext; @@ -24,11 +26,11 @@ import org.osgi.util.tracker.ServiceTracker; public abstract class AuthorizationEngine { private EventManager manager = new EventManager(); - private EventDispatcher dispatcher = new AuthEventDispatcher(); - private final ServiceTracker listenerTracker; + private EventDispatcher<AuthorizationListener, Object, AuthorizationEvent> dispatcher = new AuthEventDispatcher(); + private final ServiceTracker<AuthorizationListener, AuthorizationListener> listenerTracker; public AuthorizationEngine(BundleContext context) { - listenerTracker = new ServiceTracker(context, AuthorizationListener.class.getName(), null); + listenerTracker = new ServiceTracker<AuthorizationListener, AuthorizationListener>(context, AuthorizationListener.class.getName(), null); listenerTracker.open(); } @@ -50,9 +52,11 @@ public abstract class AuthorizationEngine { Object[] services = listenerTracker.getServices(); if (services == null) return; - CopyOnWriteIdentityMap listeners = new CopyOnWriteIdentityMap(); - listeners.putAll(services); - ListenerQueue queue = new ListenerQueue(manager); + Map<AuthorizationListener, Object> listeners = new HashMap<AuthorizationListener, Object>(); + for (Object service : services) { + listeners.put((AuthorizationListener) service, service); + } + ListenerQueue<AuthorizationListener, Object, AuthorizationEvent> queue = new ListenerQueue<AuthorizationListener, Object, AuthorizationEvent>(manager); queue.queueListeners(listeners.entrySet(), dispatcher); queue.dispatchEventSynchronous(0, event); } @@ -76,9 +80,9 @@ public abstract class AuthorizationEngine { */ abstract public int getStatus(); - class AuthEventDispatcher implements EventDispatcher { - public void dispatchEvent(Object eventListener, Object listenerObject, int eventAction, Object eventObject) { - ((AuthorizationListener) eventListener).authorizationEvent((AuthorizationEvent) eventObject); + class AuthEventDispatcher implements EventDispatcher<AuthorizationListener, Object, AuthorizationEvent> { + public void dispatchEvent(AuthorizationListener eventListener, Object listenerObject, int eventAction, AuthorizationEvent eventObject) { + eventListener.authorizationEvent(eventObject); } } } diff --git a/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/service/security/KeyStoreTrustEngine.java b/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/service/security/KeyStoreTrustEngine.java index 83fdd3646..96b4bda67 100644 --- a/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/service/security/KeyStoreTrustEngine.java +++ b/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/service/security/KeyStoreTrustEngine.java @@ -14,8 +14,7 @@ import java.io.*; import java.security.*; import java.security.cert.*; import java.security.cert.Certificate; -import java.util.ArrayList; -import java.util.Enumeration; +import java.util.*; import org.eclipse.osgi.framework.log.FrameworkLogEntry; import org.eclipse.osgi.internal.signedcontent.SignedBundleHook; import org.eclipse.osgi.internal.signedcontent.SignedContentMessages; @@ -156,8 +155,8 @@ public class KeyStoreTrustEngine extends TrustEngine { private Certificate findAlternativeRoot(X509Certificate cert, KeyStore store) throws InvalidKeyException, KeyStoreException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException, CertificateException { synchronized (store) { - for (Enumeration e = store.aliases(); e.hasMoreElements();) { - Certificate nextCert = store.getCertificate((String) e.nextElement()); + for (Enumeration<String> e = store.aliases(); e.hasMoreElements();) { + Certificate nextCert = store.getCertificate(e.nextElement()); if (nextCert instanceof X509Certificate && ((X509Certificate) nextCert).getSubjectDN().equals(cert.getIssuerDN())) { cert.verify(nextCert.getPublicKey()); return nextCert; @@ -258,12 +257,12 @@ public class KeyStoreTrustEngine extends TrustEngine { public String[] getAliases() throws IOException, GeneralSecurityException { - ArrayList returnList = new ArrayList(); + List<String> returnList = new ArrayList<String>(); try { KeyStore store = getKeyStore(); synchronized (store) { - for (Enumeration aliases = store.aliases(); aliases.hasMoreElements();) { - String currentAlias = (String) aliases.nextElement(); + for (Enumeration<String> aliases = store.aliases(); aliases.hasMoreElements();) { + String currentAlias = aliases.nextElement(); if (store.isCertificateEntry(currentAlias)) { returnList.add(currentAlias); } @@ -272,7 +271,7 @@ public class KeyStoreTrustEngine extends TrustEngine { } catch (KeyStoreException ke) { throw (CertificateException) new CertificateException(ke.getMessage()).initCause(ke); } - return (String[]) returnList.toArray(new String[] {}); + return returnList.toArray(new String[] {}); } /** diff --git a/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/LegacyVerifierFactory.java b/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/LegacyVerifierFactory.java index bbd7ac951..d0ecae651 100644 --- a/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/LegacyVerifierFactory.java +++ b/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/LegacyVerifierFactory.java @@ -12,8 +12,7 @@ import java.io.File; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.cert.*; -import java.util.ArrayList; -import java.util.Date; +import java.util.*; import org.eclipse.osgi.internal.provisional.verifier.*; import org.eclipse.osgi.signedcontent.*; import org.osgi.framework.Bundle; @@ -77,7 +76,7 @@ public class LegacyVerifierFactory implements CertificateVerifierFactory { } public String[] verifyContent() { - ArrayList invalidContent = new ArrayList(0); + List<String> invalidContent = new ArrayList<String>(0); SignedContentEntry[] entries = signedContent.getSignedEntries(); for (int i = 0; i < entries.length; i++) { try { @@ -88,7 +87,7 @@ public class LegacyVerifierFactory implements CertificateVerifierFactory { invalidContent.add(entries[i].getName()); } } - return (String[]) invalidContent.toArray(new String[invalidContent.size()]); + return invalidContent.toArray(new String[invalidContent.size()]); } } diff --git a/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/PKCS7DateParser.java b/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/PKCS7DateParser.java index 9c92a6291..29a82bfa1 100644 --- a/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/PKCS7DateParser.java +++ b/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/PKCS7DateParser.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2007 IBM Corporation and others. All rights reserved. + * Copyright (c) 2006, 2010 IBM Corporation and others. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html @@ -15,7 +15,7 @@ import java.util.*; public class PKCS7DateParser { static Date parseDate(PKCS7Processor pkcs7Processor, String signer, String file) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, SignatureException, NoSuchProviderException { - Map unsignedAttrs = pkcs7Processor.getUnsignedAttrs(); + Map<int[], byte[]> unsignedAttrs = pkcs7Processor.getUnsignedAttrs(); if (unsignedAttrs != null) { // get the timestamp construct byte[] timeStampConstruct = retrieveTimeStampConstruct(unsignedAttrs); @@ -31,13 +31,13 @@ public class PKCS7DateParser { return null; } - private static byte[] retrieveTimeStampConstruct(Map unsignedAttrs) { - Set objIDs = unsignedAttrs.keySet(); - Iterator iter = objIDs.iterator(); + private static byte[] retrieveTimeStampConstruct(Map<int[], byte[]> unsignedAttrs) { + Set<int[]> objIDs = unsignedAttrs.keySet(); + Iterator<int[]> iter = objIDs.iterator(); while (iter.hasNext()) { - int[] objID = (int[]) iter.next(); + int[] objID = iter.next(); if (Arrays.equals(SignedContentConstants.TIMESTAMP_OID, objID)) { - return (byte[]) unsignedAttrs.get(objID); + return unsignedAttrs.get(objID); } } return null; diff --git a/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/PKCS7Processor.java b/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/PKCS7Processor.java index c42e675d0..1e7ddc952 100644 --- a/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/PKCS7Processor.java +++ b/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/PKCS7Processor.java @@ -41,10 +41,10 @@ public class PKCS7Processor implements SignedContentConstants { private Certificate[] tsaCertificates; // key(object id) = value(structure) - private Map signedAttrs; + private Map<int[], byte[]> signedAttrs; // key(object id) = value(structure) - private Map unsignedAttrs; + private Map<int[], byte[]> unsignedAttrs; // store the signature of a signerinfo private byte signature[]; @@ -91,7 +91,7 @@ public class PKCS7Processor implements SignedContentConstants { this.signer = signer; this.file = file; // First grab the certificates - List certs = null; + List<Certificate> certs = null; BERProcessor bp = new BERProcessor(pkcs7, pkcs7Offset, pkcs7Length); @@ -136,7 +136,7 @@ public class PKCS7Processor implements SignedContentConstants { certs = constructCertPath(certs, signerCert); // initialize the certificates - certificates = (Certificate[]) certs.toArray(new Certificate[certs.size()]); + certificates = certs.toArray(new Certificate[certs.size()]); verifyCerts(); // if this pkcs7process is tsa asn.1 block, the signingTime should already be set if (signingTime == null) @@ -206,8 +206,8 @@ public class PKCS7Processor implements SignedContentConstants { } } - private List constructCertPath(List certs, Certificate targetCert) { - List certsList = new ArrayList(); + private List<Certificate> constructCertPath(List<Certificate> certs, Certificate targetCert) { + List<Certificate> certsList = new ArrayList<Certificate>(); certsList.add(targetCert); X509Certificate currentCert = (X509Certificate) targetCert; @@ -224,7 +224,7 @@ public class PKCS7Processor implements SignedContentConstants { } currentCert = null; - Iterator itr = certs.iterator(); + Iterator<Certificate> itr = certs.iterator(); while (itr.hasNext()) { X509Certificate tempCert = (X509Certificate) itr.next(); @@ -261,7 +261,7 @@ public class PKCS7Processor implements SignedContentConstants { } } - private Certificate processSignerInfos(BERProcessor bp, List certs) throws CertificateException, NoSuchAlgorithmException, SignatureException { + private Certificate processSignerInfos(BERProcessor bp, List<Certificate> certs) throws CertificateException, NoSuchAlgorithmException, SignatureException { // We assume there is only one SingerInfo element // PKCS7: SignerINFOS processing @@ -286,7 +286,7 @@ public class PKCS7Processor implements SignedContentConstants { // initilize the newSignerCert to the issuer cert of leaf cert Certificate newSignerCert = null; - Iterator itr = certs.iterator(); + Iterator<Certificate> itr = certs.iterator(); // PKCS7: compuare the issuers in the issuerAndSN BER equals to the issuers in Certs generated at the beginning of this method // it seems like there is no neeed, cause both ways use the same set of bytes while (itr.hasNext()) { @@ -338,7 +338,7 @@ public class PKCS7Processor implements SignedContentConstants { if (bp.classOfTag == BERProcessor.CONTEXTSPECIFIC_TAGCLASS && bp.tag == 1) { // there are some unsignedAttrs are found!! - unsignedAttrs = new HashMap(); + unsignedAttrs = new HashMap<int[], byte[]>(); // step into a set of unsigned attributes, I believe, when steps // into here, the 'poiter' is pointing to the first element @@ -349,14 +349,14 @@ public class PKCS7Processor implements SignedContentConstants { BERProcessor unsignedAttrBER = unsignedAttrsBERS.stepInto(); // check if it is timestamp attribute type - int objID[] = unsignedAttrBER.getObjId(); + int[] objID = unsignedAttrBER.getObjId(); // if(Arrays.equals(TIMESTAMP_OID, objID)) { // System.out.println("This is a timestamp type, to continue"); // } // get the structure for the attribute type unsignedAttrBER.stepOver(); - byte structure[] = unsignedAttrBER.getBytes(); + byte[] structure = unsignedAttrBER.getBytes(); unsignedAttrs.put(objID, structure); unsignedAttrsBERS.stepOver(); } while (!unsignedAttrsBERS.endOfSequence()); @@ -367,7 +367,7 @@ public class PKCS7Processor implements SignedContentConstants { if (bp.classOfTag == BERProcessor.CONTEXTSPECIFIC_TAGCLASS) { // process the signed attributes - signedAttrs = new HashMap(); + signedAttrs = new HashMap<int[], byte[]>(); BERProcessor signedAttrsBERS = bp.stepInto(); do { @@ -405,7 +405,7 @@ public class PKCS7Processor implements SignedContentConstants { * * @return map if there is any signed attributes, null otherwise */ - public Map getUnsignedAttrs() { + public Map<int[], byte[]> getUnsignedAttrs() { return unsignedAttrs; } @@ -414,7 +414,7 @@ public class PKCS7Processor implements SignedContentConstants { * * @return map if there is any signed attributes, null otherwise */ - public Map getSignedAttrs() { + public Map<int[], byte[]> getSignedAttrs() { return signedAttrs; } @@ -426,8 +426,8 @@ public class PKCS7Processor implements SignedContentConstants { * @throws CertificateException * @throws SignatureException */ - private List processCertificates(BERProcessor bp) throws CertificateException, SignatureException { - List rtvList = new ArrayList(3); + private List<Certificate> processCertificates(BERProcessor bp) throws CertificateException, SignatureException { + List<Certificate> rtvList = new ArrayList<Certificate>(3); // Step into the first certificate-element BERProcessor certsBERS = bp.stepInto(); diff --git a/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/SignatureBlockProcessor.java b/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/SignatureBlockProcessor.java index df54292ae..dc944cf59 100644 --- a/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/SignatureBlockProcessor.java +++ b/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/SignatureBlockProcessor.java @@ -14,7 +14,6 @@ import java.security.*; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.util.*; -import java.util.Map.Entry; import org.eclipse.osgi.baseadaptor.bundlefile.BundleEntry; import org.eclipse.osgi.baseadaptor.bundlefile.BundleFile; import org.eclipse.osgi.framework.log.FrameworkLogEntry; @@ -23,10 +22,10 @@ import org.eclipse.osgi.util.NLS; public class SignatureBlockProcessor implements SignedContentConstants { private final SignedBundleFile signedBundle; - private ArrayList signerInfos = new ArrayList(); - private HashMap contentMDResults = new HashMap(); + private List<SignerInfo> signerInfos = new ArrayList<SignerInfo>(); + private Map<String, Object> contentMDResults = new HashMap<String, Object>(); // map of tsa singers keyed by SignerInfo -> {tsa_SignerInfo, signingTime} - private HashMap tsaSignerInfos; + private Map<SignerInfo, Object[]> tsaSignerInfos; private final int supportFlags; public SignatureBlockProcessor(SignedBundleFile signedContent, int supportFlags) { @@ -41,10 +40,10 @@ public class SignatureBlockProcessor implements SignedContentConstants { return createUnsignedContent(); // read all the signature block file names into a list - Enumeration en = wrappedBundleFile.getEntryPaths(META_INF); - List signers = new ArrayList(2); + Enumeration<String> en = wrappedBundleFile.getEntryPaths(META_INF); + List<String> signers = new ArrayList<String>(2); while (en.hasMoreElements()) { - String name = (String) en.nextElement(); + String name = en.nextElement(); if ((name.endsWith(DOT_DSA) || name.endsWith(DOT_RSA)) && name.indexOf('/') == name.lastIndexOf('/')) signers.add(name); } @@ -55,17 +54,18 @@ public class SignatureBlockProcessor implements SignedContentConstants { byte manifestBytes[] = readIntoArray(be); // process the signers - Iterator iSigners = signers.iterator(); + Iterator<String> iSigners = signers.iterator(); for (int i = 0; iSigners.hasNext(); i++) - processSigner(wrappedBundleFile, manifestBytes, (String) iSigners.next()); + processSigner(wrappedBundleFile, manifestBytes, iSigners.next()); // done processing now create a SingedContent to return - SignerInfo[] allSigners = (SignerInfo[]) signerInfos.toArray(new SignerInfo[signerInfos.size()]); - for (Iterator iResults = contentMDResults.entrySet().iterator(); iResults.hasNext();) { - Entry entry = (Entry) iResults.next(); - ArrayList[] value = (ArrayList[]) entry.getValue(); - SignerInfo[] entrySigners = (SignerInfo[]) value[0].toArray(new SignerInfo[value[0].size()]); - byte[][] entryResults = (byte[][]) value[1].toArray(new byte[value[1].size()][]); + SignerInfo[] allSigners = signerInfos.toArray(new SignerInfo[signerInfos.size()]); + for (Iterator<Map.Entry<String, Object>> iResults = contentMDResults.entrySet().iterator(); iResults.hasNext();) { + Map.Entry<String, Object> entry = iResults.next(); + @SuppressWarnings("unchecked") + List<Object>[] value = (List<Object>[]) entry.getValue(); + SignerInfo[] entrySigners = value[0].toArray(new SignerInfo[value[0].size()]); + byte[][] entryResults = value[1].toArray(new byte[value[1].size()][]); entry.setValue(new Object[] {entrySigners, entryResults}); } SignedContentImpl result = new SignedContentImpl(allSigners, (supportFlags & SignedBundleHook.VERIFY_RUNTIME) != 0 ? contentMDResults : null); @@ -115,7 +115,7 @@ public class SignatureBlockProcessor implements SignedContentConstants { if (tsaCerts != null && signingTime != null) { SignerInfoImpl tsaSignerInfo = new SignerInfoImpl(tsaCerts, null, digAlg); if (tsaSignerInfos == null) - tsaSignerInfos = new HashMap(2); + tsaSignerInfos = new HashMap<SignerInfo, Object[]>(2); tsaSignerInfos.put(signerInfo, new Object[] {tsaSignerInfo, signingTime}); } } @@ -213,18 +213,21 @@ public class SignatureBlockProcessor implements SignedContentConstants { // throw new RuntimeException( // "Errors occurs when parsing the manifest file stream!"); //$NON-NLS-1$ // } - ArrayList[] mdResult = (ArrayList[]) contentMDResults.get(entryName); + @SuppressWarnings("unchecked") + List<Object>[] mdResult = (List<Object>[]) contentMDResults.get(entryName); if (mdResult == null) { - mdResult = new ArrayList[2]; - mdResult[0] = new ArrayList(); - mdResult[1] = new ArrayList(); + @SuppressWarnings("unchecked") + List<Object>[] arrayLists = new ArrayList[2]; + mdResult = arrayLists; + mdResult[0] = new ArrayList<Object>(); + mdResult[1] = new ArrayList<Object>(); contentMDResults.put(entryName, mdResult); } mdResult[0].add(signerInfo); mdResult[1].add(digestResult); } // could get lines of digest entries in this MF file entry } // could retrieve entry name - // increment the offset to the ending entry... + // increment the offset to the ending entry... entryStartOffset = entryEndOffset; } } diff --git a/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/SignedBundleFile.java b/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/SignedBundleFile.java index bd19bbe35..a271261c4 100644 --- a/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/SignedBundleFile.java +++ b/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/SignedBundleFile.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2008 IBM Corporation and others. + * Copyright (c) 2006, 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 @@ -122,7 +122,7 @@ public class SignedBundleFile extends BundleFile implements SignedContentConstan return new SignedBundleEntry(be); } - public Enumeration getEntryPaths(String path) { + public Enumeration<String> getEntryPaths(String path) { return wrappedBundleFile.getEntryPaths(path); } diff --git a/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/SignedBundleHook.java b/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/SignedBundleHook.java index 64fc6ba29..58e417df1 100644 --- a/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/SignedBundleHook.java +++ b/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/SignedBundleHook.java @@ -57,7 +57,7 @@ public class SignedBundleHook implements AdaptorHook, BundleFileWrapperFactoryHo //TODO: comes from configuration!; private static String CACERTS_PATH = System.getProperty("java.home") + File.separatorChar + "lib" + File.separatorChar + "security" + File.separatorChar + "cacerts"; //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$//$NON-NLS-4$ private static String CACERTS_TYPE = "JKS"; //$NON-NLS-1$ - private static ServiceTracker trustEngineTracker; + private static ServiceTracker<TrustEngine, TrustEngine> trustEngineTracker; private static BaseAdaptor ADAPTOR; private static String SIGNED_BUNDLE_SUPPORT = "osgi.support.signature.verify"; //$NON-NLS-1$ private static String SIGNED_CONTENT_SUPPORT = "osgi.signedcontent.support"; //$NON-NLS-1$ @@ -65,11 +65,11 @@ public class SignedBundleHook implements AdaptorHook, BundleFileWrapperFactoryHo private static int supportSignedBundles; private TrustEngineListener trustEngineListener; private BundleInstallListener installListener; - private ServiceRegistration signedContentFactoryReg; - private ServiceRegistration systemTrustEngineReg; - private ServiceRegistration defaultAuthEngineReg; - private List osgiTrustEngineReg; - private ServiceRegistration legacyFactoryReg; + private ServiceRegistration<?> signedContentFactoryReg; + private ServiceRegistration<?> systemTrustEngineReg; + private ServiceRegistration<?> defaultAuthEngineReg; + private List<ServiceRegistration<?>> osgiTrustEngineReg; + private ServiceRegistration<?> legacyFactoryReg; public void initialize(BaseAdaptor adaptor) { SignedBundleHook.ADAPTOR = adaptor; @@ -85,14 +85,14 @@ public class SignedBundleHook implements AdaptorHook, BundleFileWrapperFactoryHo installListener = new BundleInstallListener(); context.addBundleListener(installListener); // register the default authorization engine - Hashtable properties = new Hashtable(7); + Dictionary<String, Object> properties = new Hashtable<String, Object>(7); properties.put(Constants.SERVICE_RANKING, new Integer(Integer.MIN_VALUE)); properties.put(SignedContentConstants.AUTHORIZATION_ENGINE, SignedContentConstants.DEFAULT_AUTHORIZATION_ENGINE); defaultAuthEngineReg = context.registerService(AuthorizationEngine.class.getName(), new DefaultAuthorizationEngine(context, ADAPTOR.getState()), properties); } // always register the trust engine - Hashtable trustEngineProps = new Hashtable(7); + Dictionary<String, Object> trustEngineProps = new Hashtable<String, Object>(7); trustEngineProps.put(Constants.SERVICE_RANKING, new Integer(Integer.MIN_VALUE)); trustEngineProps.put(SignedContentConstants.TRUST_ENGINE, SignedContentConstants.DEFAULT_TRUST_ENGINE); KeyStoreTrustEngine systemTrustEngine = new KeyStoreTrustEngine(CACERTS_PATH, CACERTS_TYPE, null, "System"); //$NON-NLS-1$ @@ -104,7 +104,7 @@ public class SignedBundleHook implements AdaptorHook, BundleFileWrapperFactoryHo if ("file".equals(url.getProtocol())) { //$NON-NLS-1$ trustEngineProps.put(SignedContentConstants.TRUST_ENGINE, OSGI_KEYSTORE); String path = url.getPath(); - osgiTrustEngineReg = new ArrayList(1); + osgiTrustEngineReg = new ArrayList<ServiceRegistration<?>>(1); osgiTrustEngineReg.add(context.registerService(TrustEngine.class.getName(), new KeyStoreTrustEngine(path, CACERTS_TYPE, null, OSGI_KEYSTORE), trustEngineProps)); } } catch (MalformedURLException e) { @@ -115,7 +115,7 @@ public class SignedBundleHook implements AdaptorHook, BundleFileWrapperFactoryHo if (osgiTrustRepoPaths != null) { trustEngineProps.put(SignedContentConstants.TRUST_ENGINE, Constants.FRAMEWORK_TRUST_REPOSITORIES); StringTokenizer st = new StringTokenizer(osgiTrustRepoPaths, File.pathSeparator); - osgiTrustEngineReg = new ArrayList(1); + osgiTrustEngineReg = new ArrayList<ServiceRegistration<?>>(1); while (st.hasMoreTokens()) { String trustRepoPath = st.nextToken(); osgiTrustEngineReg.add(context.registerService(TrustEngine.class.getName(), new KeyStoreTrustEngine(trustRepoPath, CACERTS_TYPE, null, OSGI_KEYSTORE), trustEngineProps)); @@ -147,8 +147,8 @@ public class SignedBundleHook implements AdaptorHook, BundleFileWrapperFactoryHo systemTrustEngineReg = null; } if (osgiTrustEngineReg != null) { - for (Iterator it = osgiTrustEngineReg.iterator(); it.hasNext();) - ((ServiceRegistration) it.next()).unregister(); + for (Iterator<ServiceRegistration<?>> it = osgiTrustEngineReg.iterator(); it.hasNext();) + it.next().unregister(); osgiTrustEngineReg = null; } if (defaultAuthEngineReg != null) { @@ -280,8 +280,8 @@ public class SignedBundleHook implements AdaptorHook, BundleFileWrapperFactoryHo if (System.getSecurityManager() == null) return getSignedContent(((BaseData) data).getBundleFile().getBaseFile()); try { - return (SignedContent) AccessController.doPrivileged(new PrivilegedExceptionAction() { - public Object run() throws Exception { + return AccessController.doPrivileged(new PrivilegedExceptionAction<SignedContent>() { + public SignedContent run() throws Exception { return getSignedContent(((BaseData) data).getBundleFile().getBaseFile()); } }); @@ -334,9 +334,9 @@ public class SignedBundleHook implements AdaptorHook, BundleFileWrapperFactoryHo SignedBundleHook.log("Invalid trust engine filter", FrameworkLogEntry.WARNING, e); //$NON-NLS-1$ } if (filter != null) { - trustEngineTracker = new ServiceTracker(context, filter, null); + trustEngineTracker = new ServiceTracker<TrustEngine, TrustEngine>(context, filter, null); } else - trustEngineTracker = new ServiceTracker(context, TrustEngine.class.getName(), null); + trustEngineTracker = new ServiceTracker<TrustEngine, TrustEngine>(context, TrustEngine.class.getName(), null); trustEngineTracker.open(); } Object[] services = trustEngineTracker.getServices(); diff --git a/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/SignedContentFile.java b/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/SignedContentFile.java index c1bfbd590..fdf572cf7 100644 --- a/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/SignedContentFile.java +++ b/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/SignedContentFile.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008 IBM Corporation and others. + * Copyright (c) 2008, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -25,7 +25,7 @@ public class SignedContentFile implements SignedContent { private final SignedContentImpl signedContent; // a cache of verification exceptions - private HashMap entryExceptions = null; + private Map<String, Throwable> entryExceptions = null; public SignedContentFile(SignedContentImpl signedContent) { try { @@ -45,7 +45,7 @@ public class SignedContentFile implements SignedContent { if (signedContent == null) return null; SignedContentEntry[] results = new SignedContentEntry[entries.length]; - Map exceptions = getEntryExceptions(true); + Map<String, Throwable> exceptions = getEntryExceptions(true); for (int i = 0; i < entries.length; i++) { try { entries[i].verify(); @@ -86,9 +86,9 @@ public class SignedContentFile implements SignedContent { return signedContent.isSigned(); } - synchronized Map getEntryExceptions(boolean create) { + synchronized Map<String, Throwable> getEntryExceptions(boolean create) { if (create && entryExceptions == null) - entryExceptions = new HashMap(5); + entryExceptions = new HashMap<String, Throwable>(5); return entryExceptions; } @@ -113,7 +113,7 @@ public class SignedContentFile implements SignedContent { public void verify() throws IOException, InvalidContentException { // check the entry exceptions map for the entry name - Map exceptions = getEntryExceptions(false); + Map<String, Throwable> exceptions = getEntryExceptions(false); Throwable t = exceptions == null ? null : (Throwable) exceptions.get(entry.getName()); if (t == null) return; diff --git a/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/SignedContentImpl.java b/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/SignedContentImpl.java index 4753c6844..af03ea893 100644 --- a/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/SignedContentImpl.java +++ b/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/SignedContentImpl.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. All rights reserved. + * Copyright (c) 2007, 2010 IBM Corporation and others. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html @@ -12,7 +12,6 @@ import java.io.IOException; import java.io.InputStream; import java.security.cert.*; import java.util.*; -import java.util.Map.Entry; import org.eclipse.osgi.baseadaptor.bundlefile.BundleEntry; import org.eclipse.osgi.baseadaptor.bundlefile.BundleFile; import org.eclipse.osgi.signedcontent.*; @@ -24,13 +23,13 @@ public class SignedContentImpl implements SignedContent { volatile SignedBundleFile content; // TODO can this be more general? // the content entry md results used for entry content verification // keyed by entry path -> {SignerInfo[] infos, byte[][] results)} - private final HashMap contentMDResults; + private final Map<String, Object> contentMDResults; private final SignerInfo[] signerInfos; // map of tsa singers keyed by SignerInfo -> {tsa_SignerInfo, signingTime} - private HashMap tsaSignerInfos; + private Map<SignerInfo, Object[]> tsaSignerInfos; volatile private boolean checkedValid = false; - public SignedContentImpl(SignerInfo[] signerInfos, HashMap contentMDResults) { + public SignedContentImpl(SignerInfo[] signerInfos, Map<String, Object> contentMDResults) { this.signerInfos = signerInfos == null ? EMPTY_SIGNERINFO : signerInfos; this.contentMDResults = contentMDResults; } @@ -38,14 +37,13 @@ public class SignedContentImpl implements SignedContent { public SignedContentEntry[] getSignedEntries() { if (contentMDResults == null) return new SignedContentEntry[0]; - ArrayList results = new ArrayList(contentMDResults.size()); - for (Iterator iMDResults = contentMDResults.entrySet().iterator(); iMDResults.hasNext();) { - Entry entry = (Entry) iMDResults.next(); - String entryName = (String) entry.getKey(); + List<SignedContentEntry> results = new ArrayList<SignedContentEntry>(contentMDResults.size()); + for (Map.Entry<String, Object> entry : contentMDResults.entrySet()) { + String entryName = entry.getKey(); Object[] mdResult = (Object[]) entry.getValue(); results.add(new SignedContentEntryImpl(entryName, (SignerInfo[]) mdResult[0])); } - return (SignedContentEntry[]) results.toArray(new SignedContentEntry[results.size()]); + return results.toArray(new SignedContentEntry[results.size()]); } public SignedContentEntry getSignedEntry(String name) { @@ -62,14 +60,14 @@ public class SignedContentImpl implements SignedContent { public Date getSigningTime(SignerInfo signerInfo) { if (tsaSignerInfos == null) return null; - Object[] tsaInfo = (Object[]) tsaSignerInfos.get(signerInfo); + Object[] tsaInfo = tsaSignerInfos.get(signerInfo); return tsaInfo == null ? null : (Date) tsaInfo[1]; } public SignerInfo getTSASignerInfo(SignerInfo signerInfo) { if (tsaSignerInfos == null) return null; - Object[] tsaInfo = (Object[]) tsaSignerInfos.get(signerInfo); + Object[] tsaInfo = tsaSignerInfos.get(signerInfo); return tsaInfo == null ? null : (SignerInfo) tsaInfo[0]; } @@ -97,7 +95,7 @@ public class SignedContentImpl implements SignedContent { this.content = content; } - void setTSASignerInfos(HashMap tsaSignerInfos) { + void setTSASignerInfos(Map<SignerInfo, Object[]> tsaSignerInfos) { this.tsaSignerInfos = tsaSignerInfos; } @@ -106,11 +104,11 @@ public class SignedContentImpl implements SignedContent { if (!containsInfo(baseInfo)) throw new IllegalArgumentException("The baseInfo is not found"); //$NON-NLS-1$ if (tsaSignerInfos == null) - tsaSignerInfos = new HashMap(signerInfos.length); + tsaSignerInfos = new HashMap<SignerInfo, Object[]>(signerInfos.length); tsaSignerInfos.put(baseInfo, new Object[] {tsaSignerInfo, signingTime}); } - HashMap getContentMDResults() { + Map<String, Object> getContentMDResults() { return contentMDResults; } diff --git a/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/SignedStorageHook.java b/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/SignedStorageHook.java index ed77edcac..2fe55e59c 100644 --- a/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/SignedStorageHook.java +++ b/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/SignedStorageHook.java @@ -11,7 +11,6 @@ package org.eclipse.osgi.internal.signedcontent; import java.io.*; import java.security.cert.*; import java.util.*; -import java.util.Map.Entry; import org.eclipse.osgi.baseadaptor.BaseData; import org.eclipse.osgi.baseadaptor.hooks.StorageHook; import org.eclipse.osgi.framework.util.KeyedElement; @@ -24,10 +23,10 @@ public class SignedStorageHook implements StorageHook { public static final String KEY = SignedStorageHook.class.getName(); public static final int HASHCODE = KEY.hashCode(); private static final int STORAGE_VERSION = 3; - private static ArrayList savedSignerInfo = new ArrayList(5); + private static List<SignerInfo> savedSignerInfo = new ArrayList<SignerInfo>(5); private static long firstIDSaved = -1; private static long lastIDSaved = -1; - private static ArrayList loadedSignerInfo = new ArrayList(5); + private static List<SignerInfo> loadedSignerInfo = new ArrayList<SignerInfo>(5); private static long lastIDLoaded; private BaseData bundledata; @@ -49,7 +48,7 @@ public class SignedStorageHook implements StorageHook { /** * @throws BundleException */ - public void initialize(Dictionary manifest) throws BundleException { + public void initialize(Dictionary<String, String> manifest) throws BundleException { // do nothing } @@ -68,9 +67,9 @@ public class SignedStorageHook implements StorageHook { signerInfos[i] = readSignerInfo(is); int resultsSize = is.readInt(); - HashMap contentMDResults = null; + Map<String, Object> contentMDResults = null; if (resultsSize > 0) { - contentMDResults = new HashMap(resultsSize); + contentMDResults = new HashMap<String, Object>(resultsSize); for (int i = 0; i < resultsSize; i++) { String path = is.readUTF(); int numEntrySigners = is.readInt(); @@ -113,12 +112,11 @@ public class SignedStorageHook implements StorageHook { saveSignerInfo(signerInfos[i], os); // keyed by entry path -> {SignerInfo[] infos, byte[][] results)} - HashMap contentMDResults = signedContent.getContentMDResults(); + Map<String, Object> contentMDResults = signedContent.getContentMDResults(); os.writeInt(contentMDResults == null ? -1 : contentMDResults.size()); if (contentMDResults != null) - for (Iterator iResults = contentMDResults.entrySet().iterator(); iResults.hasNext();) { - Entry entry = (Entry) iResults.next(); - String path = (String) entry.getKey(); + for (Map.Entry<String, Object> entry : contentMDResults.entrySet()) { + String path = entry.getKey(); os.writeUTF(path); Object[] signerResults = (Object[]) entry.getValue(); SignerInfo[] entrySigners = (SignerInfo[]) signerResults[0]; @@ -171,7 +169,7 @@ public class SignedStorageHook implements StorageHook { private SignerInfo readSignerInfo(DataInputStream is) throws IOException { int index = is.readInt(); if (index >= 0) - return (SignerInfo) loadedSignerInfo.get(index); + return loadedSignerInfo.get(index); int numCerts = is.readInt(); Certificate[] certs = new Certificate[numCerts]; for (int i = 0; i < numCerts; i++) { @@ -211,7 +209,7 @@ public class SignedStorageHook implements StorageHook { /** * @throws BundleException */ - public Dictionary getManifest(boolean firstLoad) throws BundleException { + public Dictionary<String, String> getManifest(boolean firstLoad) throws BundleException { // do nothing return null; } diff --git a/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/TrustEngineListener.java b/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/TrustEngineListener.java index 629e447c3..e965a401f 100644 --- a/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/TrustEngineListener.java +++ b/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/signedcontent/TrustEngineListener.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. All rights reserved. + * Copyright (c) 2007, 2010 IBM Corporation and others. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html @@ -9,8 +9,7 @@ package org.eclipse.osgi.internal.signedcontent; import java.security.cert.Certificate; -import java.util.HashSet; -import java.util.Iterator; +import java.util.*; import org.eclipse.osgi.baseadaptor.BaseData; import org.eclipse.osgi.framework.internal.core.*; import org.eclipse.osgi.framework.log.FrameworkLogEntry; @@ -25,7 +24,7 @@ public class TrustEngineListener { // this is a singleton listener; see SignedBundleHook for initialization private volatile static TrustEngineListener instance; private final BundleContext context; - private final ServiceTracker authorizationTracker; + private final ServiceTracker<AuthorizationEngine, AuthorizationEngine> authorizationTracker; TrustEngineListener(BundleContext context) { this.context = context; @@ -39,9 +38,9 @@ public class TrustEngineListener { SignedBundleHook.log("Invalid authorization filter", FrameworkLogEntry.WARNING, e); //$NON-NLS-1$ } if (filter != null) - authorizationTracker = new ServiceTracker(context, filter, null); + authorizationTracker = new ServiceTracker<AuthorizationEngine, AuthorizationEngine>(context, filter, null); else - authorizationTracker = new ServiceTracker(context, AuthorizationEngine.class.getName(), null); + authorizationTracker = new ServiceTracker<AuthorizationEngine, AuthorizationEngine>(context, AuthorizationEngine.class.getName(), null); authorizationTracker.open(); instance = this; } @@ -59,7 +58,7 @@ public class TrustEngineListener { // find any SignedContent with SignerInfos that do not have an anchor; // re-evaluate trust and check authorization for these SignedContents Bundle[] bundles = context.getBundles(); - HashSet unresolved = new HashSet(); + Set<Bundle> unresolved = new HashSet<Bundle>(); for (int i = 0; i < bundles.length; i++) { SignedContentImpl signedContent = getSignedContent(bundles[i]); if (signedContent != null && signedContent.isSigned()) { @@ -84,7 +83,7 @@ public class TrustEngineListener { } // try to resolve if (unresolved.size() > 0) - resolveBundles((Bundle[]) unresolved.toArray(new Bundle[unresolved.size()]), false); + resolveBundles(unresolved.toArray(new Bundle[unresolved.size()]), false); } private void checkAuthorization(SignedContentImpl signedContent, Bundle bundle) { @@ -94,11 +93,11 @@ public class TrustEngineListener { } AuthorizationEngine getAuthorizationEngine() { - return (AuthorizationEngine) authorizationTracker.getService(); + return authorizationTracker.getService(); } private void resolveBundles(Bundle[] bundles, boolean refresh) { - ServiceReference ref = context.getServiceReference(PackageAdmin.class.getName()); + ServiceReference<?> ref = context.getServiceReference(PackageAdmin.class.getName()); if (ref == null) return; PackageAdmin pa = (PackageAdmin) context.getService(ref); @@ -118,8 +117,8 @@ public class TrustEngineListener { // find any signed content that has signerinfos with the supplied anchor // re-evaluate trust and check authorization again. Bundle[] bundles = context.getBundles(); - HashSet usingAnchor = new HashSet(); - HashSet untrustedSigners = new HashSet(); + Set<Bundle> usingAnchor = new HashSet<Bundle>(); + Set<SignerInfo> untrustedSigners = new HashSet<SignerInfo>(); for (int i = 0; i < bundles.length; i++) { SignedContentImpl signedContent = getSignedContent(bundles[i]); if (signedContent != null && signedContent.isSigned()) { @@ -141,11 +140,11 @@ public class TrustEngineListener { } } // remove trust anchors from untrusted signers - for (Iterator untrusted = untrustedSigners.iterator(); untrusted.hasNext();) + for (Iterator<SignerInfo> untrusted = untrustedSigners.iterator(); untrusted.hasNext();) ((SignerInfoImpl) untrusted.next()).setTrustAnchor(null); // re-establish trust and check authorization - for (Iterator untrustedBundles = usingAnchor.iterator(); untrustedBundles.hasNext();) { - Bundle bundle = (Bundle) untrustedBundles.next(); + for (Iterator<Bundle> untrustedBundles = usingAnchor.iterator(); untrustedBundles.hasNext();) { + Bundle bundle = untrustedBundles.next(); SignedContentImpl signedContent = getSignedContent(bundle); // found an signer using the anchor for this bundle re-evaluate trust SignedBundleFile.determineTrust(signedContent, SignedBundleHook.VERIFY_TRUST); @@ -155,7 +154,7 @@ public class TrustEngineListener { // TODO an optimization here would be to check for real DisabledInfo objects for each bundle // try to refresh if (usingAnchor.size() > 0) - resolveBundles((Bundle[]) usingAnchor.toArray(new Bundle[usingAnchor.size()]), true); + resolveBundles(usingAnchor.toArray(new Bundle[usingAnchor.size()]), true); } private SignedContentImpl getSignedContent(Bundle bundle) { diff --git a/bundles/org.eclipse.osgi/supplement/src/org/eclipse/core/runtime/internal/adaptor/LocationHelper.java b/bundles/org.eclipse.osgi/supplement/src/org/eclipse/core/runtime/internal/adaptor/LocationHelper.java index 3018e6039..ed3e6c140 100644 --- a/bundles/org.eclipse.osgi/supplement/src/org/eclipse/core/runtime/internal/adaptor/LocationHelper.java +++ b/bundles/org.eclipse.osgi/supplement/src/org/eclipse/core/runtime/internal/adaptor/LocationHelper.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006 IBM Corporation and others. + * Copyright (c) 2006, 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 @@ -24,6 +24,7 @@ public class LocationHelper { * @param trailingSlash flag to indicate a trailing slash on the spec * @return a URL */ + @SuppressWarnings("deprecation") public static URL buildURL(String spec, boolean trailingSlash) { if (spec == null) return null; diff --git a/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/debug/Debug.java b/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/debug/Debug.java index c464f07fb..b9443df43 100644 --- a/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/debug/Debug.java +++ b/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/debug/Debug.java @@ -338,7 +338,7 @@ public class Debug { Method[] methods = t.getClass().getMethods(); int size = methods.length; - Class throwable = Throwable.class; + Class<?> throwable = Throwable.class; for (int i = 0; i < size; i++) { Method method = methods[i]; diff --git a/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/debug/EclipseDebugTrace.java b/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/debug/EclipseDebugTrace.java index b1f89c984..de13dcd70 100644 --- a/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/debug/EclipseDebugTrace.java +++ b/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/debug/EclipseDebugTrace.java @@ -64,7 +64,7 @@ class EclipseDebugTrace implements DebugTrace { /** The value written to the trace file if a null object is being traced */ private final static String NULL_VALUE = "<null>"; //$NON-NLS-1$ /** */ - private final static SecureAction secureAction = (SecureAction) AccessController.doPrivileged(SecureAction.createSecureAction()); + private final static SecureAction secureAction = AccessController.doPrivileged(SecureAction.createSecureAction()); /** A lock object used to synchronize access to the trace file */ private final static Object writeLock = new Object(); @@ -117,7 +117,7 @@ class EclipseDebugTrace implements DebugTrace { * @param debugOptions Used to determine if the specified bundle symbolic name + option-path has tracing enabled * @param traceClass The class that the client is using to perform trace API calls */ - EclipseDebugTrace(final String bundleSymbolicName, final FrameworkDebugOptions debugOptions, final Class traceClass) { + EclipseDebugTrace(final String bundleSymbolicName, final FrameworkDebugOptions debugOptions, final Class<?> traceClass) { this.traceClass = traceClass != null ? traceClass.getName() : null; this.debugOptions = debugOptions; diff --git a/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/debug/FrameworkDebugOptions.java b/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/debug/FrameworkDebugOptions.java index 445ad49f8..7c245f649 100644 --- a/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/debug/FrameworkDebugOptions.java +++ b/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/debug/FrameworkDebugOptions.java @@ -14,7 +14,6 @@ import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.util.*; -import java.util.Map.Entry; import org.eclipse.osgi.framework.internal.core.FrameworkProperties; import org.eclipse.osgi.service.debug.*; import org.osgi.framework.*; @@ -28,7 +27,7 @@ import org.osgi.util.tracker.ServiceTrackerCustomizer; * * @since 3.1 */ -public class FrameworkDebugOptions implements DebugOptions, ServiceTrackerCustomizer { +public class FrameworkDebugOptions implements DebugOptions, ServiceTrackerCustomizer<DebugOptionsListener, DebugOptionsListener> { private static final String OSGI_DEBUG = "osgi.debug"; //$NON-NLS-1$ private static final String OSGI_DEBUG_VERBOSE = "osgi.debug.verbose"; //$NON-NLS-1$ @@ -44,13 +43,13 @@ public class FrameworkDebugOptions implements DebugOptions, ServiceTrackerCustom /** The default name of the .options file if loading when the -debug command-line argument is used */ private static final String OPTIONS = ".options"; //$NON-NLS-1$ /** A cache of all of the bundles <code>DebugTrace</code> in the format <key,value> --> <bundle name, DebugTrace> */ - protected final static Map debugTraceCache = new HashMap(); + protected final static Map<String, DebugTrace> debugTraceCache = new HashMap<String, DebugTrace>(); /** The File object to store messages. This value may be null. */ protected File outFile = null; /** Is verbose debugging enabled? Changing this value causes a new tracing session to start. */ protected boolean verboseDebug = true; private volatile BundleContext context; - private volatile ServiceTracker listenerTracker; + private volatile ServiceTracker<DebugOptionsListener, DebugOptionsListener> listenerTracker; /** * Internal constructor to create a <code>FrameworkDebugOptions</code> singleton object. @@ -96,15 +95,14 @@ public class FrameworkDebugOptions implements DebugOptions, ServiceTrackerCustom e.printStackTrace(System.out); } // trim off all the blanks since properties files don't do that. - for (Iterator i = options.keySet().iterator(); i.hasNext();) { - Object key = i.next(); + for (Object key : options.keySet()) { options.put(key, ((String) options.get(key)).trim()); } } public void start(BundleContext bc) { this.context = bc; - listenerTracker = new ServiceTracker(bc, DebugOptionsListener.class.getName(), this); + listenerTracker = new ServiceTracker<DebugOptionsListener, DebugOptionsListener>(bc, DebugOptionsListener.class.getName(), this); listenerTracker.open(); } @@ -126,6 +124,7 @@ public class FrameworkDebugOptions implements DebugOptions, ServiceTrackerCustom return FrameworkDebugOptions.singleton; } + @SuppressWarnings("deprecation") private static URL buildURL(String spec, boolean trailingSlash) { if (spec == null) return null; @@ -194,13 +193,14 @@ public class FrameworkDebugOptions implements DebugOptions, ServiceTrackerCustom } } - public Map getOptions() { - Properties snapShot = new Properties(); + @SuppressWarnings({"unchecked", "rawtypes"}) + public Map<String, String> getOptions() { + Map<String, String> snapShot = new HashMap<String, String>(); synchronized (lock) { if (options != null) - snapShot.putAll(options); + snapShot.putAll((Map) options); else if (disabledOptions != null) - snapShot.putAll(disabledOptions); + snapShot.putAll((Map) disabledOptions); } return snapShot; } @@ -215,10 +215,10 @@ public class FrameworkDebugOptions implements DebugOptions, ServiceTrackerCustom synchronized (lock) { if (options != null) { optionsArray = new String[options.size()]; - final Iterator entrySetIterator = options.entrySet().iterator(); + final Iterator<Map.Entry<Object, Object>> entrySetIterator = options.entrySet().iterator(); int i = 0; while (entrySetIterator.hasNext()) { - Map.Entry entry = (Map.Entry) entrySetIterator.next(); + Map.Entry<Object, Object> entry = entrySetIterator.next(); optionsArray[i] = ((String) entry.getKey()) + "=" + ((String) entry.getValue()); //$NON-NLS-1$ i++; } @@ -292,17 +292,18 @@ public class FrameworkDebugOptions implements DebugOptions, ServiceTrackerCustom return null; } - public void setOptions(Map ops) { + @SuppressWarnings("cast") + public void setOptions(Map<String, String> ops) { if (ops == null) throw new IllegalArgumentException("The options must not be null."); //$NON-NLS-1$ Properties newOptions = new Properties(); - for (Iterator entries = ops.entrySet().iterator(); entries.hasNext();) { - Entry entry = (Entry) entries.next(); + for (Iterator<Map.Entry<String, String>> entries = ops.entrySet().iterator(); entries.hasNext();) { + Map.Entry<String, String> entry = entries.next(); if (!(entry.getKey() instanceof String) || !(entry.getValue() instanceof String)) throw new IllegalArgumentException("Option keys and values must be of type String: " + entry.getKey() + "=" + entry.getValue()); //$NON-NLS-1$ //$NON-NLS-2$ - newOptions.put(entry.getKey(), ((String) entry.getValue()).trim()); + newOptions.put(entry.getKey(), entry.getValue().trim()); } - Set fireChangesTo = null; + Set<String> fireChangesTo = null; synchronized (lock) { if (options == null) { @@ -310,9 +311,9 @@ public class FrameworkDebugOptions implements DebugOptions, ServiceTrackerCustom // no events to fire return; } - fireChangesTo = new HashSet(); + fireChangesTo = new HashSet<String>(); // first check for removals - for (Iterator keys = options.keySet().iterator(); keys.hasNext();) { + for (Iterator<Object> keys = options.keySet().iterator(); keys.hasNext();) { String key = (String) keys.next(); if (!newOptions.containsKey(key)) { String symbolicName = getSymbolicName(key); @@ -321,8 +322,8 @@ public class FrameworkDebugOptions implements DebugOptions, ServiceTrackerCustom } } // now check for changes to existing values - for (Iterator newEntries = newOptions.entrySet().iterator(); newEntries.hasNext();) { - Entry entry = (Entry) newEntries.next(); + for (Iterator<Map.Entry<Object, Object>> newEntries = newOptions.entrySet().iterator(); newEntries.hasNext();) { + Map.Entry<Object, Object> entry = newEntries.next(); String existingValue = (String) options.get(entry.getKey()); if (!entry.getValue().equals(existingValue)) { String symbolicName = getSymbolicName((String) entry.getKey()); @@ -334,8 +335,8 @@ public class FrameworkDebugOptions implements DebugOptions, ServiceTrackerCustom options = newOptions; } if (fireChangesTo != null) - for (Iterator iChanges = fireChangesTo.iterator(); iChanges.hasNext();) - optionsChanged((String) iChanges.next()); + for (Iterator<String> iChanges = fireChangesTo.iterator(); iChanges.hasNext();) + optionsChanged(iChanges.next()); } /* @@ -404,11 +405,11 @@ public class FrameworkDebugOptions implements DebugOptions, ServiceTrackerCustom * (non-Javadoc) * @see org.eclipse.osgi.service.debug.DebugOptions#createTrace(java.lang.String, java.lang.Class) */ - public final DebugTrace newDebugTrace(String bundleSymbolicName, Class traceEntryClass) { + public final DebugTrace newDebugTrace(String bundleSymbolicName, Class<?> traceEntryClass) { DebugTrace debugTrace = null; synchronized (FrameworkDebugOptions.debugTraceCache) { - debugTrace = (DebugTrace) FrameworkDebugOptions.debugTraceCache.get(bundleSymbolicName); + debugTrace = FrameworkDebugOptions.debugTraceCache.get(bundleSymbolicName); if (debugTrace == null) { debugTrace = new EclipseDebugTrace(bundleSymbolicName, FrameworkDebugOptions.singleton, traceEntryClass); FrameworkDebugOptions.debugTraceCache.put(bundleSymbolicName, debugTrace); @@ -469,7 +470,7 @@ public class FrameworkDebugOptions implements DebugOptions, ServiceTrackerCustom return; // do not use the service tracker because that is only used to call all listeners initially when they are registered // here we only want the services with the specified name. - ServiceReference[] listenerRefs = null; + ServiceReference<?>[] listenerRefs = null; try { listenerRefs = bc.getServiceReferences(DebugOptionsListener.class.getName(), "(" + DebugOptions.LISTENER_SYMBOLICNAME + "=" + bundleSymbolicName + ")"); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ } catch (InvalidSyntaxException e) { @@ -491,17 +492,17 @@ public class FrameworkDebugOptions implements DebugOptions, ServiceTrackerCustom } } - public Object addingService(ServiceReference reference) { - DebugOptionsListener listener = (DebugOptionsListener) context.getService(reference); + public DebugOptionsListener addingService(ServiceReference<DebugOptionsListener> reference) { + DebugOptionsListener listener = context.getService(reference); listener.optionsChanged(this); return listener; } - public void modifiedService(ServiceReference reference, Object service) { + public void modifiedService(ServiceReference<DebugOptionsListener> reference, DebugOptionsListener service) { // nothing } - public void removedService(ServiceReference reference, Object service) { + public void removedService(ServiceReference<DebugOptionsListener> reference, DebugOptionsListener service) { context.ungetService(reference); } }
\ No newline at end of file diff --git a/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/eventmgr/CopyOnWriteIdentityMap.java b/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/eventmgr/CopyOnWriteIdentityMap.java index cc9fa78ba..71b83cebf 100644 --- a/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/eventmgr/CopyOnWriteIdentityMap.java +++ b/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/eventmgr/CopyOnWriteIdentityMap.java @@ -27,7 +27,7 @@ public class CopyOnWriteIdentityMap<K, V> implements Map<K, V> { /** * The empty array singleton instance. */ - @SuppressWarnings("unchecked") + @SuppressWarnings("rawtypes") private static final Entry[] emptyArray = new Entry[0]; /** diff --git a/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/eventmgr/EventDispatcher.java b/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/eventmgr/EventDispatcher.java index 3e6f3cb18..18327d402 100644 --- a/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/eventmgr/EventDispatcher.java +++ b/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/eventmgr/EventDispatcher.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2003, 2008 IBM Corporation and others. + * 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 @@ -19,7 +19,7 @@ package org.eclipse.osgi.framework.eventmgr; * </p> * @since 3.1 */ -public interface EventDispatcher { +public interface EventDispatcher<K, V, E> { /** * This method is called once for each listener. * This method must cast the event listener object to the appropriate listener @@ -45,5 +45,5 @@ public interface EventDispatcher { * can complete the delivery of the event to the listener. * This is typically the actual event object. */ - public void dispatchEvent(Object eventListener, Object listenerObject, int eventAction, Object eventObject); + public void dispatchEvent(K eventListener, V listenerObject, int eventAction, E eventObject); } diff --git a/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/eventmgr/EventListeners.java b/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/eventmgr/EventListeners.java index fee66aeb5..431e4be94 100644 --- a/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/eventmgr/EventListeners.java +++ b/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/eventmgr/EventListeners.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2003, 2008 IBM Corporation and others. + * 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 @@ -11,6 +11,7 @@ package org.eclipse.osgi.framework.eventmgr; +import java.util.Map; import java.util.Set; /** @@ -24,8 +25,8 @@ import java.util.Set; * @deprecated As of 3.5. Replaced by CopyOnWriteIdentityMap. * @noextend This class is not intended to be subclassed by clients. */ -public class EventListeners { - private final CopyOnWriteIdentityMap list = new CopyOnWriteIdentityMap(); +public class EventListeners<K, V> { + private final CopyOnWriteIdentityMap<K, V> list = new CopyOnWriteIdentityMap<K, V>(); /** * Creates an empty listener list. @@ -55,7 +56,7 @@ public class EventListeners { * when the listener is to be called. This may be null * @throws IllegalArgumentException If listener is null. */ - public void addListener(Object listener, Object listenerObject) { + public void addListener(K listener, V listenerObject) { list.put(listener, listenerObject); } @@ -66,7 +67,7 @@ public class EventListeners { * @param listener This is the listener object to be removed from the list. * @throws IllegalArgumentException If listener is null. */ - public void removeListener(Object listener) { + public void removeListener(V listener) { list.remove(listener); } @@ -83,7 +84,7 @@ public class EventListeners { * Get the entry Set from the internal CopyOnWriteIdentityMap. * @return The entry Set. */ - Set entrySet() { + Set<Map.Entry<K, V>> entrySet() { return list.entrySet(); } } diff --git a/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/eventmgr/EventManager.java b/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/eventmgr/EventManager.java index 2dc7188c7..9e371ee34 100644 --- a/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/eventmgr/EventManager.java +++ b/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/eventmgr/EventManager.java @@ -13,7 +13,8 @@ package org.eclipse.osgi.framework.eventmgr; import java.security.AccessController; import java.security.PrivilegedAction; -import java.util.*; +import java.util.Map; +import java.util.Set; /** * This class is the central class for the Event Manager. Each @@ -104,7 +105,7 @@ public class EventManager { * EventThread for asynchronous dispatch of events. * Access to this field must be protected by a synchronized region. */ - private EventThread thread; + private EventThread<?, ?, ?> thread; /** * Once closed, an attempt to create a new EventThread will result in an @@ -185,22 +186,25 @@ public class EventManager { * @return EventThread to use for dispatching events asynchronously for * this EventManager. */ - synchronized EventThread getEventThread() { + synchronized <K, V, E> EventThread<K, V, E> getEventThread() { if (closed) { throw new IllegalStateException(); } if (thread == null) { /* if there is no thread, then create a new one */ - thread = (EventThread) AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { - EventThread t = new EventThread(threadGroup, threadName); + thread = AccessController.doPrivileged(new PrivilegedAction<EventThread<K, V, E>>() { + public EventThread<K, V, E> run() { + EventThread<K, V, E> t = new EventThread<K, V, E>(threadGroup, threadName); return t; } }); /* start the new thread */ thread.start(); } - return thread; + + @SuppressWarnings("unchecked") + EventThread<K, V, E> result = (EventThread<K, V, E>) thread; + return result; } /** @@ -217,18 +221,17 @@ public class EventManager { * @param eventObject This object was created by the event source and * is passed to this method. This is passed on to the call back object. */ - static void dispatchEvent(Set/*<Map.Entry<Object,Object>>*/listeners, EventDispatcher dispatcher, int eventAction, Object eventObject) { - for (Iterator iter = listeners.iterator(); iter.hasNext();) { /* iterate over the list of listeners */ - Map.Entry listener = (Map.Entry) iter.next(); - Object eventListener = listener.getKey(); - Object listenerObject = listener.getValue(); + static <K, V, E> void dispatchEvent(Set<Map.Entry<K, V>> listeners, EventDispatcher<K, V, E> dispatcher, int eventAction, E eventObject) { + for (Map.Entry<K, V> listener : listeners) { /* iterate over the list of listeners */ + final K eventListener = listener.getKey(); + final V listenerObject = listener.getValue(); try { /* Call the EventDispatcher to complete the delivery of the event. */ dispatcher.dispatchEvent(eventListener, listenerObject, eventAction, eventObject); } catch (Throwable t) { /* Consume and ignore any exceptions thrown by the listener */ if (DEBUG) { - System.out.println("Exception in " + listener.getKey()); //$NON-NLS-1$ + System.out.println("Exception in " + eventListener); //$NON-NLS-1$ t.printStackTrace(); } } @@ -239,7 +242,7 @@ public class EventManager { * This package private class is used for asynchronously dispatching events. */ - static class EventThread extends Thread { + static class EventThread<K, V, E> extends Thread { private static int nextThreadNumber; /** @@ -247,17 +250,17 @@ public class EventManager { * represents the items which are placed on the asynch dispatch queue. * This class is private. */ - private static class Queued { + private static class Queued<K, V, E> { /** listener list for this event */ - final Set/*<Map.Entry<Object,Object>>*/listeners; + final Set<Map.Entry<K, V>> listeners; /** dispatcher of this event */ - final EventDispatcher dispatcher; + final EventDispatcher<K, V, E> dispatcher; /** action for this event */ final int action; /** object for this event */ - final Object object; + final E object; /** next item in event queue */ - Queued next; + Queued<K, V, E> next; /** * Constructor for event queue item @@ -267,7 +270,7 @@ public class EventManager { * @param a Action for this event * @param o Object for this event */ - Queued(Set/*<Map.Entry<Object,Object>>*/l, EventDispatcher d, int a, Object o) { + Queued(Set<Map.Entry<K, V>> l, EventDispatcher<K, V, E> d, int a, E o) { listeners = l; dispatcher = d; action = a; @@ -277,9 +280,9 @@ public class EventManager { } /** item at the head of the event queue */ - private Queued head; + private Queued<K, V, E> head; /** item at the tail of the event queue */ - private Queued tail; + private Queued<K, V, E> tail; /** if false the thread must terminate */ private volatile boolean running; @@ -330,7 +333,7 @@ public class EventManager { public void run() { try { while (true) { - Queued item = getNextEvent(); + Queued<K, V, E> item = getNextEvent(); if (item == null) { return; } @@ -363,12 +366,12 @@ public class EventManager { * @param a Action for this event * @param o Object for this event */ - synchronized void postEvent(Set/*<Map.Entry<Object,Object>>*/l, EventDispatcher d, int a, Object o) { + synchronized void postEvent(Set<Map.Entry<K, V>> l, EventDispatcher<K, V, E> d, int a, E o) { if (!isAlive()) { /* If the thread is not alive, throw an exception */ throw new IllegalStateException(); } - Queued item = new Queued(l, d, a, o); + Queued<K, V, E> item = new Queued<K, V, E>(l, d, a, o); if (head == null) /* if the queue was empty */ { @@ -391,7 +394,7 @@ public class EventManager { * @return The Queued removed from the top of the queue or null * if the thread has been requested to stop. */ - private synchronized Queued getNextEvent() { + private synchronized Queued<K, V, E> getNextEvent() { while (running && (head == null)) { try { wait(); @@ -404,7 +407,7 @@ public class EventManager { return null; } - Queued item = head; + Queued<K, V, E> item = head; head = item.next; if (head == null) { tail = null; diff --git a/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/eventmgr/ListenerQueue.java b/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/eventmgr/ListenerQueue.java index 0f63ecc18..6f1d7319d 100644 --- a/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/eventmgr/ListenerQueue.java +++ b/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/eventmgr/ListenerQueue.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2003, 2009 IBM Corporation and others. + * 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 @@ -11,7 +11,8 @@ package org.eclipse.osgi.framework.eventmgr; -import java.util.*; +import java.util.Map; +import java.util.Set; import org.eclipse.osgi.framework.eventmgr.EventManager.EventThread; /** @@ -33,7 +34,7 @@ import org.eclipse.osgi.framework.eventmgr.EventManager.EventThread; * added to the list. * @since 3.1 */ -public class ListenerQueue { +public class ListenerQueue<K, V, E> { /** * EventManager with which this queue is associated. */ @@ -41,7 +42,7 @@ public class ListenerQueue { /** * A list of listener lists. */ - private final Map /*<Set<Map.Entry<Object,Object>>,EventDispatcher>*/queue; + private final Map<Set<Map.Entry<K, V>>, EventDispatcher<K, V, E>> queue; /** * Once the listener queue has been used to dispatch an event, @@ -62,7 +63,7 @@ public class ListenerQueue { } this.manager = manager; - queue = new CopyOnWriteIdentityMap(); + queue = new CopyOnWriteIdentityMap<Set<Map.Entry<K, V>>, EventDispatcher<K, V, E>>(); readOnly = false; } @@ -79,7 +80,7 @@ public class ListenerQueue { * @throws IllegalStateException If called after one of the dispatch methods has been called. * @deprecated As of 3.5. Replaced by {@link #queueListeners(Set, EventDispatcher)}. */ - public void queueListeners(EventListeners listeners, EventDispatcher dispatcher) { + public void queueListeners(EventListeners<K, V> listeners, EventDispatcher<K, V, E> dispatcher) { queueListeners(listeners.entrySet(), dispatcher); } @@ -97,7 +98,7 @@ public class ListenerQueue { * @throws IllegalStateException If called after one of the dispatch methods has been called. * @since 3.5 */ - public synchronized void queueListeners(Set/*<Map.Entry<Object,Object>>*/listeners, EventDispatcher dispatcher) { + public synchronized void queueListeners(Set<Map.Entry<K, V>> listeners, EventDispatcher<K, V, E> dispatcher) { if (readOnly) { throw new IllegalStateException(); } @@ -115,15 +116,14 @@ public class ListenerQueue { * @param eventAction This value is passed to the EventDispatcher. * @param eventObject This object is passed to the EventDispatcher. */ - public void dispatchEventAsynchronous(int eventAction, Object eventObject) { + public void dispatchEventAsynchronous(int eventAction, E eventObject) { synchronized (this) { readOnly = true; } - EventThread eventThread = manager.getEventThread(); + EventThread<K, V, E> eventThread = manager.getEventThread(); synchronized (eventThread) { /* synchronize on the EventThread to ensure no interleaving of posting to the event thread */ - for (Iterator iter = queue.entrySet().iterator(); iter.hasNext();) { /* iterate over the list of listener lists */ - Map.Entry entry = (Map.Entry) iter.next(); - eventThread.postEvent((Set) entry.getKey(), (EventDispatcher) entry.getValue(), eventAction, eventObject); + for (Map.Entry<Set<Map.Entry<K, V>>, EventDispatcher<K, V, E>> entry : queue.entrySet()) { /* iterate over the list of listener lists */ + eventThread.postEvent(entry.getKey(), entry.getValue(), eventAction, eventObject); } } } @@ -138,15 +138,14 @@ public class ListenerQueue { * @param eventAction This value is passed to the EventDispatcher. * @param eventObject This object is passed to the EventDispatcher. */ - public void dispatchEventSynchronous(int eventAction, Object eventObject) { + public void dispatchEventSynchronous(int eventAction, E eventObject) { synchronized (this) { readOnly = true; } // We can't guarantee any delivery order for synchronous events. // Attempts to do so result in deadly embraces. - for (Iterator iter = queue.entrySet().iterator(); iter.hasNext();) { /* iterate over the list of listener lists */ - Map.Entry entry = (Map.Entry) iter.next(); - EventManager.dispatchEvent((Set) entry.getKey(), (EventDispatcher) entry.getValue(), eventAction, eventObject); + for (Map.Entry<Set<Map.Entry<K, V>>, EventDispatcher<K, V, E>> entry : queue.entrySet()) { /* iterate over the list of listener lists */ + EventManager.dispatchEvent(entry.getKey(), entry.getValue(), eventAction, eventObject); } } } diff --git a/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/internal/core/FrameworkProperties.java b/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/internal/core/FrameworkProperties.java index cb2878b0c..7cf733628 100644 --- a/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/internal/core/FrameworkProperties.java +++ b/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/internal/core/FrameworkProperties.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2008 Cognos Incorporated, IBM Corporation and others. + * 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 @@ -85,7 +85,7 @@ public class FrameworkProperties { return properties; } - public static synchronized void setProperties(Map input) { + public static synchronized void setProperties(Map<String, String> input) { if (input == null) { // just use internal props; note that this will reuse a previous set of properties if they were set internalGetProperties("false"); //$NON-NLS-1$ @@ -93,8 +93,8 @@ public class FrameworkProperties { } properties = null; Properties toSet = internalGetProperties("false"); //$NON-NLS-1$ - for (Iterator keys = input.keySet().iterator(); keys.hasNext();) { - String key = (String) keys.next(); + for (Iterator<String> keys = input.keySet().iterator(); keys.hasNext();) { + String key = keys.next(); Object value = input.get(key); if (value instanceof String) { toSet.setProperty(key, (String) value); @@ -135,7 +135,7 @@ public class FrameworkProperties { public static String decode(String urlString) { //try to use Java 1.4 method if available try { - Class clazz = URLDecoder.class; + Class<? extends URLDecoder> clazz = URLDecoder.class; Method method = clazz.getDeclaredMethod("decode", new Class[] {String.class, String.class}); //$NON-NLS-1$ //first encode '+' characters, because URLDecoder incorrectly converts //them to spaces on certain class library implementations. diff --git a/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/internal/reliablefile/ReliableFile.java b/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/internal/reliablefile/ReliableFile.java index 1f6ac61fc..1d6cba76c 100644 --- a/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/internal/reliablefile/ReliableFile.java +++ b/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/internal/reliablefile/ReliableFile.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2003, 2007 IBM Corporation and others. + * 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 @@ -126,7 +126,7 @@ public class ReliableFile { private File referenceFile; /** List of checksum file objects: File => specific ReliableFile generation */ - private static Hashtable cacheFiles = new Hashtable(20); + private static Hashtable<File, CacheInfo> cacheFiles = new Hashtable<File, CacheInfo>(20); private File inputFile = null; private File outputFile = null; @@ -193,7 +193,7 @@ public class ReliableFile { String[] files = parent.list(); if (files == null) return null; - ArrayList list = new ArrayList(defaultMaxGenerations); + List<Integer> list = new ArrayList<Integer>(defaultMaxGenerations); if (file.exists()) list.add(new Integer(0)); //base file exists for (int i = 0; i < files.length; i++) { @@ -263,7 +263,7 @@ public class ReliableFile { InputStream is = null; CacheInfo info; synchronized (cacheFiles) { - info = (CacheInfo) cacheFiles.get(file); + info = cacheFiles.get(file); long timeStamp = file.lastModified(); if (info == null || timeStamp != info.timeStamp) { try { @@ -354,7 +354,7 @@ public class ReliableFile { } try { - CacheInfo info = (CacheInfo) cacheFiles.get(inputFile); + CacheInfo info = cacheFiles.get(inputFile); appendChecksum = info.checksum; OutputStream os = new FileOutputStream(tmpFile); if (info.filetype == FILETYPE_NOSIGNATURE) { @@ -443,7 +443,7 @@ public class ReliableFile { // backup files. for (int idx = 0, count = generationCount - rmCount; idx < count; idx++) { File file = new File(parent, name + '.' + generations[idx]); - CacheInfo info = (CacheInfo) cacheFiles.get(file); + CacheInfo info = cacheFiles.get(file); if (info != null) { if (info.filetype == FILETYPE_CORRUPT) rmCount--; @@ -623,7 +623,7 @@ public class ReliableFile { if (!directory.isDirectory()) throw new IOException("Not a valid directory"); //$NON-NLS-1$ String files[] = directory.list(); - HashSet list = new HashSet(files.length / 2); + Set<String> list = new HashSet<String>(files.length / 2); for (int idx = 0; idx < files.length; idx++) { String file = files[idx]; int pos = file.lastIndexOf('.'); @@ -642,8 +642,8 @@ public class ReliableFile { } files = new String[list.size()]; int idx = 0; - for (Iterator iter = list.iterator(); iter.hasNext();) { - files[idx++] = (String) iter.next(); + for (Iterator<String> iter = list.iterator(); iter.hasNext();) { + files[idx++] = iter.next(); } return files; } @@ -695,7 +695,7 @@ public class ReliableFile { */ int getSignatureSize() throws IOException { if (inputFile != null) { - CacheInfo info = (CacheInfo) cacheFiles.get(inputFile); + CacheInfo info = cacheFiles.get(inputFile); if (info != null) { switch (info.filetype) { case FILETYPE_VALID : diff --git a/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/util/SecureAction.java b/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/util/SecureAction.java index 400218d62..2e654b16c 100644 --- a/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/util/SecureAction.java +++ b/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/framework/util/SecureAction.java @@ -30,8 +30,8 @@ public class SecureAction { private AccessControlContext controlContext; // This ClassLoader is used in loadSystemClass if System.getClassLoader() returns null - static final ClassLoader bootClassLoader = (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { + static final ClassLoader bootClassLoader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { + public ClassLoader run() { return new ClassLoader(Object.class.getClassLoader()) { /* boot class loader */}; } }); @@ -54,9 +54,9 @@ public class SecureAction { * </pre> * @return a privileged action object that can be used to construct a SecureAction object. */ - public static PrivilegedAction createSecureAction() { - return new PrivilegedAction() { - public Object run() { + public static PrivilegedAction<SecureAction> createSecureAction() { + return new PrivilegedAction<SecureAction>() { + public SecureAction run() { return new SecureAction(); } }; @@ -71,8 +71,8 @@ public class SecureAction { public String getProperty(final String property) { if (System.getSecurityManager() == null) return FrameworkProperties.getProperty(property); - return (String) AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { + return AccessController.doPrivileged(new PrivilegedAction<String>() { + public String run() { return FrameworkProperties.getProperty(property); } }, controlContext); @@ -89,8 +89,8 @@ public class SecureAction { public String getProperty(final String property, final String def) { if (System.getSecurityManager() == null) return FrameworkProperties.getProperty(property, def); - return (String) AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { + return AccessController.doPrivileged(new PrivilegedAction<String>() { + public String run() { return FrameworkProperties.getProperty(property, def); } }, controlContext); @@ -104,8 +104,8 @@ public class SecureAction { public Properties getProperties() { if (System.getSecurityManager() == null) return FrameworkProperties.getProperties(); - return (Properties) AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { + return AccessController.doPrivileged(new PrivilegedAction<Properties>() { + public Properties run() { return FrameworkProperties.getProperties(); } }, controlContext); @@ -122,8 +122,8 @@ public class SecureAction { if (System.getSecurityManager() == null) return new FileInputStream(file); try { - return (FileInputStream) AccessController.doPrivileged(new PrivilegedExceptionAction() { - public Object run() throws FileNotFoundException { + return AccessController.doPrivileged(new PrivilegedExceptionAction<FileInputStream>() { + public FileInputStream run() throws FileNotFoundException { return new FileInputStream(file); } }, controlContext); @@ -146,8 +146,8 @@ public class SecureAction { if (System.getSecurityManager() == null) return new FileOutputStream(file.getAbsolutePath(), append); try { - return (FileOutputStream) AccessController.doPrivileged(new PrivilegedExceptionAction() { - public Object run() throws FileNotFoundException { + return AccessController.doPrivileged(new PrivilegedExceptionAction<FileOutputStream>() { + public FileOutputStream run() throws FileNotFoundException { return new FileOutputStream(file.getAbsolutePath(), append); } }, controlContext); @@ -167,11 +167,11 @@ public class SecureAction { public long length(final File file) { if (System.getSecurityManager() == null) return file.length(); - return ((Long) AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { + return AccessController.doPrivileged(new PrivilegedAction<Long>() { + public Long run() { return new Long(file.length()); } - }, controlContext)).longValue(); + }, controlContext).longValue(); } /** @@ -185,8 +185,8 @@ public class SecureAction { if (System.getSecurityManager() == null) return file.getCanonicalPath(); try { - return (String) AccessController.doPrivileged(new PrivilegedExceptionAction() { - public Object run() throws IOException { + return AccessController.doPrivileged(new PrivilegedExceptionAction<String>() { + public String run() throws IOException { return file.getCanonicalPath(); } }, controlContext); @@ -206,11 +206,11 @@ public class SecureAction { public boolean exists(final File file) { if (System.getSecurityManager() == null) return file.exists(); - return ((Boolean) AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { + return AccessController.doPrivileged(new PrivilegedAction<Boolean>() { + public Boolean run() { return file.exists() ? Boolean.TRUE : Boolean.FALSE; } - }, controlContext)).booleanValue(); + }, controlContext).booleanValue(); } /** @@ -222,11 +222,11 @@ public class SecureAction { public boolean isDirectory(final File file) { if (System.getSecurityManager() == null) return file.isDirectory(); - return ((Boolean) AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { + return AccessController.doPrivileged(new PrivilegedAction<Boolean>() { + public Boolean run() { return file.isDirectory() ? Boolean.TRUE : Boolean.FALSE; } - }, controlContext)).booleanValue(); + }, controlContext).booleanValue(); } /** @@ -238,11 +238,11 @@ public class SecureAction { public long lastModified(final File file) { if (System.getSecurityManager() == null) return file.lastModified(); - return ((Long) AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { + return AccessController.doPrivileged(new PrivilegedAction<Long>() { + public Long run() { return new Long(file.lastModified()); } - }, controlContext)).longValue(); + }, controlContext).longValue(); } /** @@ -254,8 +254,8 @@ public class SecureAction { public String[] list(final File file) { if (System.getSecurityManager() == null) return file.list(); - return (String[]) AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { + return AccessController.doPrivileged(new PrivilegedAction<String[]>() { + public String[] run() { return file.list(); } }, controlContext); @@ -273,8 +273,8 @@ public class SecureAction { if (System.getSecurityManager() == null) return new ZipFile(file); try { - return (ZipFile) AccessController.doPrivileged(new PrivilegedExceptionAction() { - public Object run() throws IOException { + return AccessController.doPrivileged(new PrivilegedExceptionAction<ZipFile>() { + public ZipFile run() throws IOException { return new ZipFile(file); } }, controlContext); @@ -309,8 +309,8 @@ public class SecureAction { if (System.getSecurityManager() == null) return new URL(protocol, host, port, file, handler); try { - return (URL) AccessController.doPrivileged(new PrivilegedExceptionAction() { - public Object run() throws MalformedURLException { + return AccessController.doPrivileged(new PrivilegedExceptionAction<URL>() { + public URL run() throws MalformedURLException { return new URL(protocol, host, port, file, handler); } }, controlContext); @@ -332,8 +332,8 @@ public class SecureAction { public Thread createThread(final Runnable target, final String name, final ClassLoader contextLoader) { if (System.getSecurityManager() == null) return createThread0(target, name, contextLoader); - return (Thread) AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { + return AccessController.doPrivileged(new PrivilegedAction<Thread>() { + public Thread run() { return createThread0(target, name, contextLoader); } }, controlContext); @@ -353,11 +353,11 @@ public class SecureAction { * @param context the BundleContext * @return a service object */ - public Object getService(final ServiceReference reference, final BundleContext context) { + public <S> S getService(final ServiceReference<S> reference, final BundleContext context) { if (System.getSecurityManager() == null) return context.getService(reference); - return AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { + return AccessController.doPrivileged(new PrivilegedAction<S>() { + public S run() { return context.getService(reference); } }, controlContext); @@ -370,12 +370,12 @@ public class SecureAction { * @return a Class * @throws ClassNotFoundException */ - public Class forName(final String name) throws ClassNotFoundException { + public Class<?> forName(final String name) throws ClassNotFoundException { if (System.getSecurityManager() == null) return Class.forName(name); try { - return (Class) AccessController.doPrivileged(new PrivilegedExceptionAction() { - public Object run() throws Exception { + return AccessController.doPrivileged(new PrivilegedExceptionAction<Class<?>>() { + public Class<?> run() throws Exception { return Class.forName(name); } }, controlContext); @@ -393,14 +393,14 @@ public class SecureAction { * @return a Class * @throws ClassNotFoundException */ - public Class loadSystemClass(final String name) throws ClassNotFoundException { + public Class<?> loadSystemClass(final String name) throws ClassNotFoundException { if (System.getSecurityManager() == null) { ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader(); return (systemClassLoader != null) ? systemClassLoader.loadClass(name) : bootClassLoader.loadClass(name); } try { - return (Class) AccessController.doPrivileged(new PrivilegedExceptionAction() { - public Object run() throws Exception { + return AccessController.doPrivileged(new PrivilegedExceptionAction<Class<?>>() { + public Class<?> run() throws Exception { ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader(); return (systemClassLoader != null) ? systemClassLoader.loadClass(name) : bootClassLoader.loadClass(name); } @@ -416,12 +416,12 @@ public class SecureAction { * Opens a ServiceTracker. Same as calling tracker.open() * @param tracker the ServiceTracker to open. */ - public void open(final ServiceTracker tracker) { + public void open(final ServiceTracker<?, ?> tracker) { if (System.getSecurityManager() == null) { tracker.open(); return; } - AccessController.doPrivileged(new PrivilegedAction() { + AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { tracker.open(); return null; @@ -441,7 +441,7 @@ public class SecureAction { return; } try { - AccessController.doPrivileged(new PrivilegedExceptionAction() { + AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { public Object run() throws BundleException { bundle.start(options); return null; diff --git a/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/service/debug/DebugOptions.java b/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/service/debug/DebugOptions.java index 9e6b3bd2e..9f9bc254f 100644 --- a/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/service/debug/DebugOptions.java +++ b/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/service/debug/DebugOptions.java @@ -108,7 +108,7 @@ public interface DebugOptions { * @return a snapshot of the current options. * @since 3.6 */ - public Map /*<String, String>*/getOptions(); + public Map<String, String> getOptions(); /** * Sets the identified option to the identified value. If debug is @@ -134,7 +134,7 @@ public interface DebugOptions { * @param options the new set of options * @since 3.6 */ - public abstract void setOptions(Map /*<String, String>*/options); + public abstract void setOptions(Map<String, String> options); /** * Removes the identified option. If debug is not enabled then @@ -215,5 +215,5 @@ public interface DebugOptions { * @return A new or existing <code>DebugTrace</code> object for the specified plug-in ID * @since 3.5 */ - public abstract DebugTrace newDebugTrace(String bundleSymbolicName, Class traceEntryClass); + public abstract DebugTrace newDebugTrace(String bundleSymbolicName, Class<?> traceEntryClass); }
\ No newline at end of file diff --git a/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/storagemanager/StorageManager.java b/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/storagemanager/StorageManager.java index 3ebfe71c1..baf06cda5 100644 --- a/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/storagemanager/StorageManager.java +++ b/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/storagemanager/StorageManager.java @@ -86,7 +86,7 @@ import org.eclipse.osgi.framework.util.SecureAction; public final class StorageManager { private static final int FILETYPE_STANDARD = 0; private static final int FILETYPE_RELIABLEFILE = 1; - private static final SecureAction secure = (SecureAction) AccessController.doPrivileged(SecureAction.createSecureAction()); + private static final SecureAction secure = AccessController.doPrivileged(SecureAction.createSecureAction()); private static final boolean tempCleanup = Boolean.valueOf(secure.getProperty("osgi.embedded.cleanTempFiles")).booleanValue(); //$NON-NLS-1$ private static final boolean openCleanup = Boolean.valueOf(secure.getProperty("osgi.embedded.cleanupOnOpen")).booleanValue(); //$NON-NLS-1$ private static final String MANAGER_FOLDER = ".manager"; //$NON-NLS-1$ @@ -320,7 +320,8 @@ public final class StorageManager { public String[] getManagedFiles() { if (!open) return null; - Set set = table.keySet(); + Set<Object> set = table.keySet(); + @SuppressWarnings("cast") String[] keys = (String[]) set.toArray(new String[set.size()]); String[] result = new String[keys.length]; for (int i = 0; i < keys.length; i++) @@ -494,7 +495,7 @@ public final class StorageManager { } } tableStamp = stamp; - for (Enumeration e = diskTable.keys(); e.hasMoreElements();) { + for (Enumeration<Object> e = diskTable.keys(); e.hasMoreElements();) { String file = (String) e.nextElement(); String value = diskTable.getProperty(file); if (value != null) { @@ -531,7 +532,7 @@ public final class StorageManager { updateTable(); Properties props = new Properties(); - for (Enumeration e = table.keys(); e.hasMoreElements();) { + for (Enumeration<Object> e = table.keys(); e.hasMoreElements();) { String file = (String) e.nextElement(); Entry entry = (Entry) table.get(file); String value; @@ -610,9 +611,9 @@ public final class StorageManager { //If we are here it is because we are the last instance running. After locking the table and getting its latest content, remove all the backup files and change the table updateTable(); - Collection managedFiles = table.entrySet(); - for (Iterator iter = managedFiles.iterator(); iter.hasNext();) { - Map.Entry fileEntry = (Map.Entry) iter.next(); + Collection<Map.Entry<Object, Object>> managedFiles = table.entrySet(); + for (Iterator<Map.Entry<Object, Object>> iter = managedFiles.iterator(); iter.hasNext();) { + Map.Entry<Object, Object> fileEntry = iter.next(); String fileName = (String) fileEntry.getKey(); Entry info = (Entry) fileEntry.getValue(); if (info.getFileType() == FILETYPE_RELIABLEFILE) { diff --git a/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/util/ManifestElement.java b/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/util/ManifestElement.java index db3185ac7..f19cbd909 100644 --- a/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/util/ManifestElement.java +++ b/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/util/ManifestElement.java @@ -96,12 +96,12 @@ public class ManifestElement { /** * The table of attributes for the manifest element. */ - private Hashtable attributes; + private Hashtable<String, Object> attributes; /** * The table of directives for the manifest element. */ - private Hashtable directives; + private Hashtable<String, Object> directives; /** * Constructs an empty manifest element with no value or attributes. @@ -192,7 +192,7 @@ public class ManifestElement { * * @return the enumeration of attribute keys or null if none exist. */ - public Enumeration getKeys() { + public Enumeration<String> getKeys() { return getTableKeys(attributes); } @@ -245,7 +245,7 @@ public class ManifestElement { * * @return the enumeration of directive keys or <code>null</code> */ - public Enumeration getDirectiveKeys() { + public Enumeration<String> getDirectiveKeys() { return getTableKeys(directives); } @@ -262,7 +262,7 @@ public class ManifestElement { /* * Return the last value associated with the given key in the specified table. */ - private String getTableValue(Hashtable table, String key) { + private String getTableValue(Hashtable<String, Object> table, String key) { if (table == null) return null; Object result = table.get(key); @@ -271,15 +271,16 @@ public class ManifestElement { if (result instanceof String) return (String) result; - ArrayList valueList = (ArrayList) result; + @SuppressWarnings("unchecked") + List<String> valueList = (List<String>) result; //return the last value - return (String) valueList.get(valueList.size() - 1); + return valueList.get(valueList.size() - 1); } /* * Return the values associated with the given key in the specified table. */ - private String[] getTableValues(Hashtable table, String key) { + private String[] getTableValues(Hashtable<String, Object> table, String key) { if (table == null) return null; Object result = table.get(key); @@ -287,14 +288,15 @@ public class ManifestElement { return null; if (result instanceof String) return new String[] {(String) result}; - ArrayList valueList = (ArrayList) result; - return (String[]) valueList.toArray(new String[valueList.size()]); + @SuppressWarnings("unchecked") + List<String> valueList = (List<String>) result; + return valueList.toArray(new String[valueList.size()]); } /* * Return an enumeration of table keys for the specified table. */ - private Enumeration getTableKeys(Hashtable table) { + private Enumeration<String> getTableKeys(Hashtable<String, Object> table) { if (table == null) return null; return table.keys(); @@ -305,19 +307,20 @@ public class ManifestElement { * for this key, then create an array list from the current value (if necessary) and * append the new value to the end of the list. */ - private Hashtable addTableValue(Hashtable table, String key, String value) { + @SuppressWarnings("unchecked") + private Hashtable<String, Object> addTableValue(Hashtable<String, Object> table, String key, String value) { if (table == null) { - table = new Hashtable(7); + table = new Hashtable<String, Object>(7); } Object curValue = table.get(key); if (curValue != null) { - ArrayList newList; + List<String> newList; // create a list to contain multiple values - if (curValue instanceof ArrayList) { - newList = (ArrayList) curValue; + if (curValue instanceof List) { + newList = (List<String>) curValue; } else { - newList = new ArrayList(5); - newList.add(curValue); + newList = new ArrayList<String>(5); + newList.add((String) curValue); } newList.add(value); table.put(key, newList); @@ -342,13 +345,13 @@ public class ManifestElement { public static ManifestElement[] parseHeader(String header, String value) throws BundleException { if (value == null) return (null); - ArrayList headerElements = new ArrayList(10); + List<ManifestElement> headerElements = new ArrayList<ManifestElement>(10); Tokenizer tokenizer = new Tokenizer(value); parseloop: while (true) { String next = tokenizer.getString(";,"); //$NON-NLS-1$ if (next == null) throw new BundleException(NLS.bind(Msg.MANIFEST_INVALID_HEADER_EXCEPTION, header, value), BundleException.MANIFEST_ERROR); - ArrayList headerValues = new ArrayList(); + List<String> headerValues = new ArrayList<String>(); StringBuffer headerValue = new StringBuffer(next); headerValues.add(next); @@ -381,7 +384,7 @@ public class ManifestElement { } } // found the header value create a manifestElement for it. - ManifestElement manifestElement = new ManifestElement(headerValue.toString(), (String[]) headerValues.toArray(new String[headerValues.size()])); + ManifestElement manifestElement = new ManifestElement(headerValue.toString(), headerValues.toArray(new String[headerValues.size()])); // now add any attributes/directives for the manifestElement. while (c == '=' || c == ':') { @@ -442,7 +445,7 @@ public class ManifestElement { if (size == 0) return (null); - ManifestElement[] result = (ManifestElement[]) headerElements.toArray(new ManifestElement[size]); + ManifestElement[] result = headerElements.toArray(new ManifestElement[size]); return (result); } @@ -470,14 +473,14 @@ public class ManifestElement { public static String[] getArrayFromList(String stringList, String separator) { if (stringList == null || stringList.trim().length() == 0) return new String[0]; - ArrayList list = new ArrayList(); + List<String> list = new ArrayList<String>(); StringTokenizer tokens = new StringTokenizer(stringList, separator); while (tokens.hasMoreTokens()) { String token = tokens.nextToken().trim(); if (token.length() != 0) list.add(token); } - return (String[]) list.toArray(new String[list.size()]); + return list.toArray(new String[list.size()]); } /** @@ -495,9 +498,9 @@ public class ManifestElement { * @throws IOException if an error occurs while reading the manifest * @return the map with the header/value pairs from the bundle manifest */ - public static Map parseBundleManifest(InputStream manifest, Map headers) throws IOException, BundleException { + public static Map<String, String> parseBundleManifest(InputStream manifest, Map<String, String> headers) throws IOException, BundleException { if (headers == null) - headers = new HashMap(); + headers = new HashMap<String, String>(); BufferedReader br; try { br = new BufferedReader(new InputStreamReader(manifest, "UTF8")); //$NON-NLS-1$ @@ -561,20 +564,20 @@ public class ManifestElement { } public String toString() { - Enumeration attrKeys = getKeys(); - Enumeration directiveKeys = getDirectiveKeys(); + Enumeration<String> attrKeys = getKeys(); + Enumeration<String> directiveKeys = getDirectiveKeys(); if (attrKeys == null && directiveKeys == null) return mainValue; StringBuffer result = new StringBuffer(mainValue); if (attrKeys != null) { while (attrKeys.hasMoreElements()) { - String key = (String) attrKeys.nextElement(); + String key = attrKeys.nextElement(); addValues(false, key, getAttributes(key), result); } } if (directiveKeys != null) { while (directiveKeys.hasMoreElements()) { - String key = (String) directiveKeys.nextElement(); + String key = directiveKeys.nextElement(); addValues(true, key, getDirectives(key), result); } } diff --git a/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/util/NLS.java b/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/util/NLS.java index 76ee19bb8..c7776d2ff 100644 --- a/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/util/NLS.java +++ b/bundles/org.eclipse.osgi/supplement/src/org/eclipse/osgi/util/NLS.java @@ -135,12 +135,12 @@ public abstract class NLS { * @param baseName the base name of a fully qualified message properties file. * @param clazz the class where the constants will exist */ - public static void initializeMessages(final String baseName, final Class clazz) { + public static void initializeMessages(final String baseName, final Class<?> clazz) { if (System.getSecurityManager() == null) { load(baseName, clazz); return; } - AccessController.doPrivileged(new PrivilegedAction() { + AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { load(baseName, clazz); return null; @@ -244,7 +244,7 @@ public abstract class NLS { if (nlSuffixes == null) { //build list of suffixes for loading resource bundles String nl = Locale.getDefault().toString(); - ArrayList result = new ArrayList(4); + List<String> result = new ArrayList<String>(4); int lastSeparator; while (true) { result.add('_' + nl + EXTENSION); @@ -255,7 +255,7 @@ public abstract class NLS { } //add the empty suffix last (most general) result.add(EXTENSION); - nlSuffixes = (String[]) result.toArray(new String[result.size()]); + nlSuffixes = result.toArray(new String[result.size()]); } root = root.replace('.', '/'); String[] variants = new String[nlSuffixes.length]; @@ -264,7 +264,7 @@ public abstract class NLS { return variants; } - private static void computeMissingMessages(String bundleName, Class clazz, Map fieldMap, Field[] fieldArray, boolean isAccessible) { + private static void computeMissingMessages(String bundleName, Class<?> clazz, Map<Object, Object> fieldMap, Field[] fieldArray, boolean isAccessible) { // iterate over the fields in the class to make sure that there aren't any empty ones final int MOD_EXPECTED = Modifier.PUBLIC | Modifier.STATIC; final int MOD_MASK = MOD_EXPECTED | Modifier.FINAL; @@ -297,7 +297,7 @@ public abstract class NLS { /* * Load the given resource bundle using the specified class loader. */ - static void load(final String bundleName, Class clazz) { + static void load(final String bundleName, Class<?> clazz) { long start = System.currentTimeMillis(); final Field[] fieldArray = clazz.getDeclaredFields(); ClassLoader loader = clazz.getClassLoader(); @@ -306,7 +306,7 @@ public abstract class NLS { //build a map of field names to Field objects final int len = fieldArray.length; - Map fields = new HashMap(len * 2); + Map<Object, Object> fields = new HashMap<Object, Object>(len * 2); for (int i = 0; i < len; i++) fields.put(fieldArray[i].getName(), fieldArray[i]); @@ -387,10 +387,10 @@ public abstract class NLS { private static final long serialVersionUID = 1L; private final String bundleName; - private final Map fields; + private final Map<Object, Object> fields; private final boolean isAccessible; - public MessagesProperties(Map fieldMap, String bundleName, boolean isAccessible) { + public MessagesProperties(Map<Object, Object> fieldMap, String bundleName, boolean isAccessible) { super(); this.fields = fieldMap; this.bundleName = bundleName; |