[FELIX-3543] Upgrade to JDK 5 and OSGi 4.3

git-svn-id: https://svn.apache.org/repos/asf/felix/trunk@1583361 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/fileinstall/pom.xml b/fileinstall/pom.xml
index e3b83e4..00a7f0b 100644
--- a/fileinstall/pom.xml
+++ b/fileinstall/pom.xml
@@ -40,13 +40,13 @@
     <dependency>
       <groupId>org.osgi</groupId>
       <artifactId>org.osgi.core</artifactId>
-      <version>4.1.0</version>
+      <version>4.3.1</version>
       <scope>provided</scope>
     </dependency>
     <dependency>
       <groupId>org.osgi</groupId>
       <artifactId>org.osgi.compendium</artifactId>
-      <version>4.1.0</version>
+      <version>4.3.1</version>
       <scope>provided</scope>
     </dependency>
     <dependency>
@@ -57,12 +57,19 @@
     <dependency>
       <groupId>org.apache.felix</groupId>
       <artifactId>org.apache.felix.utils</artifactId>
-      <version>1.4.2</version>
+      <version>1.6.0</version>
     </dependency>
   </dependencies>
   <build>
     <plugins>
       <plugin>
+          <artifactId>maven-compiler-plugin</artifactId>
+          <configuration>
+              <source>1.5</source>
+              <target>1.5</target>
+          </configuration>
+      </plugin>
+      <plugin>
         <artifactId>maven-jar-plugin</artifactId>
         <configuration>
           <archive>
diff --git a/fileinstall/src/main/java/org/apache/felix/fileinstall/internal/ConfigInstaller.java b/fileinstall/src/main/java/org/apache/felix/fileinstall/internal/ConfigInstaller.java
index f7f1ae0..674121f 100644
--- a/fileinstall/src/main/java/org/apache/felix/fileinstall/internal/ConfigInstaller.java
+++ b/fileinstall/src/main/java/org/apache/felix/fileinstall/internal/ConfigInstaller.java
@@ -53,14 +53,13 @@
     {
         if (registration == null)
         {
-            Properties props = new Properties();
             registration = this.context.registerService(
                     new String[] {
                         ConfigurationListener.class.getName(),
                         ArtifactListener.class.getName(),
                         ArtifactInstaller.class.getName()
                     },
-                    this, props);
+                    this, null);
         }
     }
 
@@ -168,26 +167,14 @@
 
     boolean shouldSaveConfig()
     {
-        Object obj = this.context.getProperty( DirectoryWatcher.ENABLE_CONFIG_SAVE );
-        if (obj instanceof String)
+        String str = this.context.getProperty( DirectoryWatcher.ENABLE_CONFIG_SAVE );
+        if (str == null)
         {
-            obj = Boolean.valueOf((String) obj);
+            str = this.context.getProperty( DirectoryWatcher.DISABLE_CONFIG_SAVE );
         }
-        if (Boolean.FALSE.equals( obj ))
+        if (str != null)
         {
-            return false;
-        }
-        else if ( !Boolean.TRUE.equals( obj ))
-        {
-            obj = this.context.getProperty( DirectoryWatcher.DISABLE_CONFIG_SAVE );
-            if (obj instanceof String)
-            {
-                obj = Boolean.valueOf((String) obj);
-            }
-            if( Boolean.FALSE.equals( obj ) )
-            {
-                return false;
-            }
+            return Boolean.valueOf(str);
         }
         return true;
     }
@@ -202,12 +189,12 @@
      *
      * @param f
      *            Configuration file
-     * @return
+     * @return <code>true</code> if the configuration has been updated
      * @throws Exception
      */
     boolean setConfig(final File f) throws Exception
     {
-        final Hashtable ht = new Hashtable();
+        final Hashtable<String, Object> ht = new Hashtable<String, Object>();
         final InputStream in = new BufferedInputStream(new FileInputStream(f));
         try
         {
@@ -222,8 +209,12 @@
                 } else {
                     p.load(in);
                 }
-                InterpolationHelper.performSubstitution((Map) p, context);
-                ht.putAll(p);
+                Map<String, String> strMap = new HashMap<String, String>();
+                for (Object k : p.keySet()) {
+                    strMap.put(k.toString(), p.getProperty(k.toString()));
+                }
+                InterpolationHelper.performSubstitution(strMap, context);
+                ht.putAll(strMap);
             }
             else if ( f.getName().endsWith( ".config" ) )
             {
@@ -232,7 +223,7 @@
                 while ( i.hasMoreElements() )
                 {
                     final Object key = i.nextElement();
-                    ht.put(key, config.get(key));
+                    ht.put(key.toString(), config.get(key));
                 }
             }
         }
@@ -244,8 +235,8 @@
         String pid[] = parsePid(f.getName());
         Configuration config = getConfiguration(toConfigKey(f), pid[0], pid[1]);
 
-        Dictionary props = config.getProperties();
-        Hashtable old = props != null ? new Hashtable(new DictionaryAsMap(props)) : null;
+        Dictionary<String, Object> props = config.getProperties();
+        Hashtable<String, Object> old = props != null ? new Hashtable<String, Object>(new DictionaryAsMap<String, Object>(props)) : null;
         if (old != null) {
         	old.remove( DirectoryWatcher.FILENAME );
         	old.remove( Constants.SERVICE_PID );
@@ -272,8 +263,8 @@
      * Remove the configuration.
      *
      * @param f
-     *            File where the configuration in whas defined.
-     * @return
+     *            File where the configuration in was defined.
+     * @return <code>true</code>
      * @throws Exception
      */
     boolean deleteConfig(File f) throws Exception
diff --git a/fileinstall/src/main/java/org/apache/felix/fileinstall/internal/DirectoryWatcher.java b/fileinstall/src/main/java/org/apache/felix/fileinstall/internal/DirectoryWatcher.java
index 469be28..4b3a2b4 100644
--- a/fileinstall/src/main/java/org/apache/felix/fileinstall/internal/DirectoryWatcher.java
+++ b/fileinstall/src/main/java/org/apache/felix/fileinstall/internal/DirectoryWatcher.java
@@ -32,7 +32,6 @@
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
-import java.util.Dictionary;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Iterator;
@@ -40,6 +39,7 @@
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.jar.JarInputStream;
 import java.util.jar.Manifest;
 import java.util.regex.Pattern;
@@ -60,8 +60,9 @@
 import org.osgi.framework.BundleListener;
 import org.osgi.framework.Constants;
 import org.osgi.framework.Version;
-import org.osgi.service.packageadmin.PackageAdmin;
-import org.osgi.service.startlevel.StartLevel;
+import org.osgi.framework.startlevel.BundleStartLevel;
+import org.osgi.framework.startlevel.FrameworkStartLevel;
+import org.osgi.framework.wiring.BundleRevision;
 
 /**
  * -DirectoryWatcher-
@@ -114,7 +115,7 @@
 
     final File javaIoTmpdir = new File(System.getProperty("java.io.tmpdir"));
 
-    Dictionary properties;
+    Map<String, String> properties;
     File watchedDirectory;
     File tmpDir;
     long poll;
@@ -133,32 +134,32 @@
     String optionalScope;
 
     // Map of all installed artifacts
-    Map/* <File, Artifact> */ currentManagedArtifacts = new HashMap/* <File, Artifact> */();
+    final Map<File, Artifact> currentManagedArtifacts = new HashMap<File, Artifact>();
 
     // The scanner to report files changes
     Scanner scanner;
 
     // Represents files that could not be processed because of a missing artifact listener
-    Set/* <File> */ processingFailures = new HashSet/* <File> */();
+    final Set<File> processingFailures = new HashSet<File>();
     
     // Represents installed artifacts which need to be started later because they failed to start
-    Set/* <Artifact> */ delayedStart = new HashSet/* <Artifact> */();
+    Set<Bundle> delayedStart = new HashSet<Bundle>();
 
     // Represents artifacts that could not be installed
-    Map/* <File, Artifact> */ installationFailures = new HashMap/* <File, Artifact> */();
+    final Map<File, Artifact> installationFailures = new HashMap<File, Artifact>();
 
     // flag (acces to which must be synchronized) that indicates wheter there's a change in state of system,
     // which may result in an attempt to start the watched bundles
-    private Boolean stateChanged = Boolean.FALSE;
+    private AtomicBoolean stateChanged = new AtomicBoolean();
 
-    public DirectoryWatcher(Dictionary properties, BundleContext context)
+    public DirectoryWatcher(Map<String, String> properties, BundleContext context)
     {
         super("fileinstall-" + getThreadName(properties));
         this.properties = properties;
         this.context = context;
         poll = getLong(properties, POLL, 2000);
         logLevel = getInt(properties, LOG_LEVEL, Util.getGlobalLogLevel(context));
-        originatingFileName = (String) properties.get(FILENAME);
+        originatingFileName = properties.get(FILENAME);
         watchedDirectory = getFile(properties, DIR, new File("./load"));
         verifyWatchedDir();
         tmpDir = getFile(properties, TMPDIR, null);
@@ -166,13 +167,13 @@
         startBundles = getBoolean(properties, START_NEW_BUNDLES, true);  // by default, we start bundles.
         useStartTransient = getBoolean(properties, USE_START_TRANSIENT, false);  // by default, we start bundles persistently.
         useStartActivationPolicy = getBoolean(properties, USE_START_ACTIVATION_POLICY, true);  // by default, we start bundles using activation policy.
-        filter = (String) properties.get(FILTER);
+        filter = properties.get(FILTER);
         noInitialDelay = getBoolean(properties, NO_INITIAL_DELAY, false);
         startLevel = getInt(properties, START_LEVEL, 0);    // by default, do not touch start level
         activeLevel = getInt(properties, ACTIVE_LEVEL, 0);    // by default, always scan
         updateWithListeners = getBoolean(properties, UPDATE_WITH_LISTENERS, false); // Do not update bundles when listeners are updated
-        fragmentScope = (String) properties.get(FRAGMENT_SCOPE);
-        optionalScope = (String) properties.get(OPTIONAL_SCOPE);
+        fragmentScope = properties.get(FRAGMENT_SCOPE);
+        optionalScope = properties.get(OPTIONAL_SCOPE);
         this.context.addBundleListener(this);
 
         FilenameFilter flt;
@@ -216,12 +217,12 @@
         }
     }
 
-    public static String getThreadName(Dictionary properties)
+    public static String getThreadName(Map<String, String> properties)
     {
-        return (properties.get(DIR) != null ? properties.get(DIR) : "./load").toString();
+        return (properties.get(DIR) != null ? properties.get(DIR) : "./load");
     }
 
-    public Dictionary getProperties()
+    public Map<String, String> getProperties()
     {
         return properties;
     }
@@ -232,7 +233,7 @@
         {
             log(Logger.LOG_DEBUG, "Starting initial scan", null);
             initializeCurrentManagedBundles();
-            Set/*<File>*/ files = scanner.scan(true);
+            Set<File> files = scanner.scan(true);
             if (files != null)
             {
                 try
@@ -299,11 +300,12 @@
         {
             try
             {
+                FrameworkStartLevel startLevelSvc = context.getBundle(0).adapt(FrameworkStartLevel.class);
                 // Don't access the disk when the framework is still in a startup phase.
-                if (FileInstall.getStartLevel().getStartLevel() >= activeLevel
+                if (startLevelSvc.getStartLevel() >= activeLevel
                         && context.getBundle(0).getState() == Bundle.ACTIVE)
                 {
-                    Set/*<File>*/ files = scanner.scan(false);
+                    Set<File> files = scanner.scan(false);
                     // Check that there is a result.  If not, this means that the directory can not be listed,
                     // so it's presumably not a valid directory (it may have been deleted by someone).
                     // In such case, just sleep
@@ -360,12 +362,12 @@
         }
     }
 
-    private void process(Set files) throws InterruptedException
+    private void process(Set<File> files) throws InterruptedException
     {
-        List/*<ArtifactListener>*/ listeners = FileInstall.getListeners();
-        List/*<Artifact>*/ deleted = new ArrayList/*<Artifact>*/();
-        List/*<Artifact>*/ modified = new ArrayList/*<Artifact>*/();
-        List/*<Artifact>*/ created = new ArrayList/*<Artifact>*/();
+        List<ArtifactListener> listeners = FileInstall.getListeners();
+        List<Artifact> deleted = new ArrayList<Artifact>();
+        List<Artifact> modified = new ArrayList<Artifact>();
+        List<Artifact> created = new ArrayList<Artifact>();
 
         // Try to process again files that could not be processed
         synchronized (processingFailures)
@@ -374,68 +376,52 @@
             processingFailures.clear();
         }
 
-        for (Iterator it = files.iterator(); it.hasNext(); )
-        {
-            File file = (File) it.next();
+        for (File file : files) {
             boolean exists = file.exists();
             Artifact artifact = getArtifact(file);
             // File has been deleted
-            if (!exists)
-            {
-                if (artifact != null)
-                {
+            if (!exists) {
+                if (artifact != null) {
                     deleteJaredDirectory(artifact);
                     deleteTransformedFile(artifact);
                     deleted.add(artifact);
                 }
             }
             // File exists
-            else
-            {
-                File jar  = file;
+            else {
+                File jar = file;
                 URL jaredUrl = null;
-                try
-                {
+                try {
                     jaredUrl = file.toURI().toURL();
-                }
-                catch (MalformedURLException e)
-                {
+                } catch (MalformedURLException e) {
                     // Ignore, can't happen
                 }
                 // Jar up the directory if needed
-                if (file.isDirectory())
-                {
+                if (file.isDirectory()) {
                     prepareTempDir();
-                    try
-                    {
+                    try {
                         jar = new File(tmpDir, file.getName() + ".jar");
                         Util.jarDir(file, jar);
                         jaredUrl = new URL(JarDirUrlHandler.PROTOCOL, null, file.getPath());
 
-                    }
-                    catch (IOException e)
-                    {
+                    } catch (IOException e) {
                         // Notify user of problem, won't retry until the dir is updated.
                         log(Logger.LOG_ERROR,
-                            "Unable to create jar for: " + file.getAbsolutePath(), e);
+                                "Unable to create jar for: " + file.getAbsolutePath(), e);
                         continue;
                     }
                 }
                 // File has been modified
-                if (artifact != null)
-                {
+                if (artifact != null) {
                     artifact.setChecksum(scanner.getChecksum(file));
                     // If there's no listener, this is because this artifact has been installed before
                     // fileinstall has been restarted.  In this case, try to find a listener.
-                    if (artifact.getListener() == null)
-                    {
+                    if (artifact.getListener() == null) {
                         ArtifactListener listener = findListener(jar, listeners);
                         // If no listener can handle this artifact, we need to defer the
                         // processing for this artifact until one is found
-                        if (listener == null)
-                        {
-                            synchronized (processingFailures)
-                            {
+                        if (listener == null) {
+                            synchronized (processingFailures) {
                                 processingFailures.add(file);
                             }
                             continue;
@@ -444,40 +430,30 @@
                     }
                     // If the listener can not handle this file anymore,
                     // uninstall the artifact and try as if is was new
-                    if (!listeners.contains(artifact.getListener()) || !artifact.getListener().canHandle(jar))
-                    {
+                    if (!listeners.contains(artifact.getListener()) || !artifact.getListener().canHandle(jar)) {
                         deleted.add(artifact);
-                        artifact = null;
                     }
                     // The listener is still ok
-                    else
-                    {
+                    else {
                         deleteTransformedFile(artifact);
                         artifact.setJaredDirectory(jar);
                         artifact.setJaredUrl(jaredUrl);
-                        if (transformArtifact(artifact))
-                        {
+                        if (transformArtifact(artifact)) {
                             modified.add(artifact);
-                        }
-                        else
-                        {
+                        } else {
                             deleteJaredDirectory(artifact);
                             deleted.add(artifact);
                         }
-                        continue;
                     }
                 }
                 // File has been added
-                else
-                {
+                else {
                     // Find the listener
                     ArtifactListener listener = findListener(jar, listeners);
                     // If no listener can handle this artifact, we need to defer the
                     // processing for this artifact until one is found
-                    if (listener == null)
-                    {
-                        synchronized (processingFailures)
-                        {
+                    if (listener == null) {
+                        synchronized (processingFailures) {
                             processingFailures.add(file);
                         }
                         continue;
@@ -489,12 +465,9 @@
                     artifact.setJaredUrl(jaredUrl);
                     artifact.setListener(listener);
                     artifact.setChecksum(scanner.getChecksum(file));
-                    if (transformArtifact(artifact))
-                    {
+                    if (transformArtifact(artifact)) {
                         created.add(artifact);
-                    }
-                    else
-                    {
+                    } else {
                         deleteJaredDirectory(artifact);
                     }
                 }
@@ -503,13 +476,13 @@
         // Handle deleted artifacts
         // We do the operations in the following order:
         // uninstall, update, install, refresh & start.
-        Collection uninstalledBundles = uninstall(deleted);
-        Collection updatedBundles = update(modified);
-        Collection installedBundles = install(created);
+        Collection<Bundle> uninstalledBundles = uninstall(deleted);
+        Collection<Bundle> updatedBundles = update(modified);
+        Collection<Bundle> installedBundles = install(created);
 
         if (!uninstalledBundles.isEmpty() || !updatedBundles.isEmpty() || !installedBundles.isEmpty())
         {
-            Set toRefresh = new HashSet();
+            Set<Bundle> toRefresh = new HashSet<Bundle>();
             toRefresh.addAll(uninstalledBundles);
             toRefresh.addAll(updatedBundles);
             toRefresh.addAll(installedBundles);
@@ -518,7 +491,7 @@
             if (toRefresh.size() > 0)
             {
                 // Refresh if any bundle got uninstalled or updated.
-                refresh((Bundle[]) toRefresh.toArray(new Bundle[toRefresh.size()]));
+                refresh(toRefresh);
                 // set the state to reattempt starting managed bundles which aren't already STARTING or ACTIVE
                 setStateChanged(true);
             }
@@ -539,13 +512,10 @@
         }
     }
 
-    ArtifactListener findListener(File artifact, List/* <ArtifactListener> */ listeners)
+    ArtifactListener findListener(File artifact, List<ArtifactListener> listeners)
     {
-        for (Iterator itL = listeners.iterator(); itL.hasNext();)
-        {
-            ArtifactListener listener = (ArtifactListener) itL.next();
-            if (listener.canHandle(artifact))
-            {
+        for (ArtifactListener listener : listeners) {
+            if (listener.canHandle(artifact)) {
                 return listener;
             }
         }
@@ -688,26 +658,19 @@
 
     /**
      * Check if a bundle is a fragment.
-     *
-     * @param bundle
-     * @return
      */
     boolean isFragment(Bundle bundle)
     {
-        PackageAdmin padmin = FileInstall.getPackageAdmin();
-        if (padmin != null)
-        {
-            return padmin.getBundleType(bundle) == PackageAdmin.BUNDLE_TYPE_FRAGMENT;
-        }
-        return false;
+        BundleRevision rev = bundle.adapt(BundleRevision.class);
+        return (rev.getTypes() & BundleRevision.TYPE_FRAGMENT) != 0;
     }
 
     /**
      * Convenience to refresh the packages
      */
-    void refresh(Bundle[] bundles) throws InterruptedException
+    void refresh(Collection<Bundle> bundles) throws InterruptedException
     {
-        FileInstall.refresh(bundles);
+        FileInstall.refresh(context, bundles);
     }
 
     /**
@@ -718,9 +681,9 @@
      * @param dflt the default value
      * @return the property as a long or the default value
      */
-    int getInt(Dictionary properties, String property, int dflt)
+    int getInt(Map<String, String> properties, String property, int dflt)
     {
-        String value = (String) properties.get(property);
+        String value = properties.get(property);
         if (value != null)
         {
             try
@@ -743,9 +706,9 @@
      * @param dflt the default value
      * @return the property as a long or the default value
      */
-    long getLong(Dictionary properties, String property, long dflt)
+    long getLong(Map<String, String> properties, String property, long dflt)
     {
-        String value = (String) properties.get(property);
+        String value = properties.get(property);
         if (value != null)
         {
             try
@@ -768,9 +731,9 @@
      * @param dflt the default value
      * @return the property as a File or the default value
      */
-    File getFile(Dictionary properties, String property, File dflt)
+    File getFile(Map<String, String> properties, String property, File dflt)
     {
-        String value = (String) properties.get(property);
+        String value = properties.get(property);
         if (value != null)
         {
             return new File(value);
@@ -786,12 +749,12 @@
      * @param dflt the default value
      * @return the property as a boolean or the default value
      */
-    boolean getBoolean(Dictionary properties, String property, boolean dflt)
+    boolean getBoolean(Map<String, String> properties, String property, boolean dflt)
     {
-        String value = (String) properties.get(property);
+        String value = properties.get(property);
         if (value != null)
         {
-            return Boolean.valueOf(value).booleanValue();
+            return Boolean.valueOf(value);
         }
         return dflt;
     }
@@ -800,9 +763,7 @@
     {
         this.context.removeBundleListener(this);
         interrupt();
-        for (Iterator iter = getArtifacts().iterator(); iter.hasNext();)
-        {
-            Artifact artifact = (Artifact) iter.next();
+        for (Artifact artifact : getArtifacts()) {
             deleteTransformedFile(artifact);
             deleteJaredDirectory(artifact);
         }
@@ -825,31 +786,25 @@
     {
         Bundle[] bundles = this.context.getBundles();
         String watchedDirPath = watchedDirectory.toURI().normalize().getPath();
-        Map /*<File, Long>*/ checksums = new HashMap/*<File, Long>*/();
-        for (int i = 0; i < bundles.length; i++)
-        {
+        Map<File, Long> checksums = new HashMap<File, Long>();
+        for (Bundle bundle : bundles) {
             // Convert to a URI because the location of a bundle
             // is typically a URI. At least, that's the case for
             // autostart bundles and bundles installed by fileinstall.
             // Normalisation is needed to ensure that we don't treat (e.g.)
             // /tmp/foo and /tmp//foo differently.
-            String location = bundles[i].getLocation();
+            String location = bundle.getLocation();
             String path = null;
             if (location != null &&
-                    !location.equals(Constants.SYSTEM_BUNDLE_LOCATION))
-            {
+                    !location.equals(Constants.SYSTEM_BUNDLE_LOCATION)) {
                 URI uri;
-                try
-                {
-                    uri = new URI(bundles[i].getLocation()).normalize();
-                }
-                catch (URISyntaxException e)
-                {
+                try {
+                    uri = new URI(bundle.getLocation()).normalize();
+                } catch (URISyntaxException e) {
                     // Let's try to interpret the location as a file path
                     uri = new File(location).toURI().normalize();
                 }
-                if (uri.isOpaque() && uri.getSchemeSpecificPart() != null)
-                {
+                if (uri.isOpaque() && uri.getSchemeSpecificPart() != null) {
                     // blueprint:file:/tmp/foo/baa.jar -> file:/tmp/foo/baa.jar
                     // blueprint:mvn:foo.baa/baa/0.0.1 -> mvn:foo.baa/baa/0.0.1
                     // wrap:file:/tmp/foo/baa-1.0.jar$Symbolic-Name=baa&Version=1.0 -> file:/tmp/foo/baa-1.0.jar$Symbolic-Name=baa&Version1.0
@@ -863,31 +818,27 @@
                     // mvn:foo.baa/baa/0.0.1 -> mvn:foo.baa/baa/0.0.1
                     // file:/tmp/foo/baa-1.0.jar$Symbolic-Name=baa&Version=1.0 -> /tmp/foo/baa-1.0.jar
                     path = schemeSpecificPart.substring(offsetFileProtocol, endOfPath);
-                }
-                else
-                {
+                } else {
                     // file:/tmp/foo/baa.jar -> /tmp/foo/baa.jar
                     // mnv:foo.baa/baa/0.0.1 -> foo.baa/baa/0.0.1
                     path = uri.getPath();
                 }
             }
-            if (path == null)
-            {
+            if (path == null) {
                 // jar.getPath is null means we could not parse the location
                 // as a meaningful URI or file path.
                 // We can't do any meaningful processing for this bundle.
                 continue;
             }
             final int index = path.lastIndexOf('/');
-            if (index != -1 && path.startsWith(watchedDirPath))
-            {
+            if (index != -1 && path.startsWith(watchedDirPath)) {
                 Artifact artifact = new Artifact();
-                artifact.setBundleId(bundles[i].getBundleId());
-                artifact.setChecksum(Util.loadChecksum(bundles[i], context));
+                artifact.setBundleId(bundle.getBundleId());
+                artifact.setChecksum(Util.loadChecksum(bundle, context));
                 artifact.setListener(null);
                 artifact.setPath(new File(path));
                 setArtifact(new File(path), artifact);
-                checksums.put(new File(path), new Long(artifact.getChecksum()));
+                checksums.put(new File(path), artifact.getChecksum());
             }
         }
         scanner.initialize(checksums);
@@ -898,15 +849,12 @@
      * @param artifacts Collection of {@link Artifact}s to be installed
      * @return List of Bundles just installed
      */
-    private Collection/* <Bundle> */ install(Collection/* <Artifact> */ artifacts)
+    private Collection<Bundle> install(Collection<Artifact> artifacts)
     {
-        List bundles = new ArrayList();
-        for (Iterator iter = artifacts.iterator(); iter.hasNext();)
-        {
-            Artifact artifact = (Artifact) iter.next();
+        List<Bundle> bundles = new ArrayList<Bundle>();
+        for (Artifact artifact : artifacts) {
             Bundle bundle = install(artifact);
-            if (bundle != null)
-            {
+            if (bundle != null) {
                 bundles.add(bundle);
             }
         }
@@ -918,15 +866,12 @@
      * @param artifacts Collection of {@link Artifact}s to be uninstalled
      * @return Collection of Bundles that got uninstalled
      */
-    private Collection/* <Bundle> */ uninstall(Collection/* <Artifact> */ artifacts)
+    private Collection<Bundle> uninstall(Collection<Artifact> artifacts)
     {
-        List bundles = new ArrayList();
-        for (Iterator iter = artifacts.iterator(); iter.hasNext();)
-        {
-            Artifact artifact = (Artifact) iter.next();
+        List<Bundle> bundles = new ArrayList<Bundle>();
+        for (Artifact artifact : artifacts) {
             Bundle bundle = uninstall(artifact);
-            if (bundle != null)
-            {
+            if (bundle != null) {
                 bundles.add(bundle);
             }
         }
@@ -939,15 +884,12 @@
      * @param artifacts    Collection of {@link Artifact}s to be updated.
      * @return Collection of bundles that got updated
      */
-    private Collection/* <Bundle> */ update(Collection/* <Artifact> */ artifacts)
+    private Collection<Bundle> update(Collection<Artifact> artifacts)
     {
-        List bundles = new ArrayList();
-        for (Iterator iter = artifacts.iterator(); iter.hasNext(); )
-        {
-            Artifact artifact = (Artifact) iter.next();
+        List<Bundle> bundles = new ArrayList<Bundle>();
+        for (Artifact artifact : artifacts) {
             Bundle bundle = update(artifact);
-            if (bundle != null)
-            {
+            if (bundle != null) {
                 bundles.add(bundle);
             }
         }
@@ -981,7 +923,7 @@
             // if the listener is an url transformer
             else if (artifact.getListener() instanceof ArtifactUrlTransformer)
             {
-                Artifact badArtifact = (Artifact) installationFailures.get(path);
+                Artifact badArtifact = installationFailures.get(path);
                 if (badArtifact != null && badArtifact.getChecksum() == artifact.getChecksum())
                 {
                     return null; // Don't attempt to install it; nothing has changed.
@@ -1002,7 +944,7 @@
             // if the listener is an artifact transformer
             else if (artifact.getListener() instanceof ArtifactTransformer)
             {
-                Artifact badArtifact = (Artifact) installationFailures.get(path);
+                Artifact badArtifact = installationFailures.get(path);
                 if (badArtifact != null && badArtifact.getChecksum() == artifact.getChecksum())
                 {
                     return null; // Don't attempt to install it; nothing has changed.
@@ -1052,22 +994,18 @@
         String vStr = m.getMainAttributes().getValue(Constants.BUNDLE_VERSION);
         Version v = vStr == null ? Version.emptyVersion : Version.parseVersion(vStr);
         Bundle[] bundles = context.getBundles();
-        for (int i = 0; i < bundles.length; i++)
-        {
-            Bundle b = bundles[i];
-            if (b.getSymbolicName() != null && b.getSymbolicName().equals(sn))
-            {
-                vStr = (String) b.getHeaders().get(Constants.BUNDLE_VERSION);
+        for (Bundle b : bundles) {
+            if (b.getSymbolicName() != null && b.getSymbolicName().equals(sn)) {
+                vStr = b.getHeaders().get(Constants.BUNDLE_VERSION);
                 Version bv = vStr == null ? Version.emptyVersion : Version.parseVersion(vStr);
-                if (v.equals(bv))
-                {
+                if (v.equals(bv)) {
                     is.reset();
-                    if (Util.loadChecksum(b, context) != checksum)
-                    {
+                    if (Util.loadChecksum(b, context) != checksum) {
                         log(Logger.LOG_WARNING,
-                            "A bundle with the same symbolic name ("
-                            + sn + ") and version (" + vStr
-                            + ") is already installed.  Updating this bundle instead.", null);
+                                "A bundle with the same symbolic name ("
+                                        + sn + ") and version (" + vStr
+                                        + ") is already installed.  Updating this bundle instead.", null
+                        );
                         stopTransient(b);
                         Util.storeChecksum(b, checksum, context);
                         b.update(is);
@@ -1083,7 +1021,7 @@
         // Set default start level at install time, the user can override it if he wants
         if (startLevel != 0)
         {
-            FileInstall.getStartLevel().setBundleStartLevel(b, startLevel);
+            b.adapt(BundleStartLevel.class).setStartLevel(startLevel);
         }
         
         return b;
@@ -1237,19 +1175,15 @@
      */
     private void startAllBundles()
     {
-        List bundles = new ArrayList();
-        for (Iterator it = getArtifacts().iterator(); it.hasNext();)
-        {
-            Artifact artifact = (Artifact) it.next();
-            if (artifact.getBundleId() > 0)
-            {
+        FrameworkStartLevel startLevelSvc = context.getBundle(0).adapt(FrameworkStartLevel.class);
+        List<Bundle> bundles = new ArrayList<Bundle>();
+        for (Artifact artifact : getArtifacts()) {
+            if (artifact.getBundleId() > 0) {
                 Bundle bundle = context.getBundle(artifact.getBundleId());
-                if (bundle != null)
-                {
+                if (bundle != null) {
                     if (bundle.getState() != Bundle.STARTING && bundle.getState() != Bundle.ACTIVE
-                        && (useStartTransient || FileInstall.getStartLevel().isBundlePersistentlyStarted(bundle))
-                        && FileInstall.getStartLevel().getStartLevel() >= FileInstall.getStartLevel().getBundleStartLevel(bundle))
-                    {
+                            && (useStartTransient || bundle.adapt(BundleStartLevel.class).isPersistentlyStarted())
+                            && startLevelSvc.getStartLevel() >= bundle.adapt(BundleStartLevel.class).getStartLevel()) {
                         bundles.add(bundle);
                     }
                 }
@@ -1260,13 +1194,12 @@
 
      /**
       * Starts a bundle and removes it from the Collection when successfully started.
-      * @param bundles
       */
-    private void startBundles(Collection/* <Bundle> */ bundles)
+    private void startBundles(Collection<Bundle> bundles)
     {
-        for (Iterator b = bundles.iterator(); b.hasNext(); )
+        for (Iterator<Bundle> b = bundles.iterator(); b.hasNext(); )
         {
-            if (startBundle((Bundle) b.next()))
+            if (startBundle(b.next()))
             {
                 b.remove();
             }
@@ -1280,7 +1213,7 @@
       */
     private boolean startBundle(Bundle bundle)
     {
-        StartLevel startLevelSvc = FileInstall.getStartLevel();
+        FrameworkStartLevel startLevelSvc = context.getBundle(0).adapt(FrameworkStartLevel.class);
         // Fragments can never be started.
         // Bundles can only be started transient when the start level of the framework is high
         // enough. Persistent (i.e. non-transient) starts will simply make the framework start the
@@ -1288,7 +1221,7 @@
         if (startBundles
                 && bundle.getState() != Bundle.UNINSTALLED
                 && !isFragment(bundle)
-                && startLevelSvc.getStartLevel() >= startLevelSvc.getBundleStartLevel(bundle))
+                && startLevelSvc.getStartLevel() >= bundle.adapt(BundleStartLevel.class).getStartLevel())
         {
             try
             {
@@ -1307,16 +1240,15 @@
         return false;
     }
 
-    protected Set getScopedBundles(String scope) {
+    protected Set<Bundle> getScopedBundles(String scope) {
         // No bundles to check
         if (SCOPE_NONE.equals(scope)) {
-            return new HashSet();
+            return new HashSet<Bundle>();
         }
         // Go through managed bundles
         else if (SCOPE_MANAGED.equals(scope)) {
-            Set bundles = new HashSet();
-            for (Iterator it = getArtifacts().iterator(); it.hasNext();) {
-                Artifact artifact = (Artifact) it.next();
+            Set<Bundle> bundles = new HashSet<Bundle>();
+            for (Artifact artifact : getArtifacts()) {
                 if (artifact.getBundleId() > 0) {
                     Bundle bundle = context.getBundle(artifact.getBundleId());
                     if (bundle != null) {
@@ -1327,29 +1259,27 @@
             return bundles;
         // Go through all bundles
         } else {
-            return new HashSet(Arrays.asList(context.getBundles()));
+            return new HashSet<Bundle>(Arrays.asList(context.getBundles()));
         }
     }
 
-    protected void findBundlesWithFragmentsToRefresh(Set toRefresh) {
-        Set fragments = new HashSet();
-        Set bundles = getScopedBundles(fragmentScope);
-        for (Iterator iterator = toRefresh.iterator(); iterator.hasNext();) {
-            Bundle b = (Bundle) iterator.next();
+    protected void findBundlesWithFragmentsToRefresh(Set<Bundle> toRefresh) {
+        Set<Bundle> fragments = new HashSet<Bundle>();
+        Set<Bundle> bundles = getScopedBundles(fragmentScope);
+        for (Bundle b : toRefresh) {
             if (b.getState() != Bundle.UNINSTALLED) {
-                String hostHeader = (String) b.getHeaders().get(Constants.FRAGMENT_HOST);
+                String hostHeader = b.getHeaders().get(Constants.FRAGMENT_HOST);
                 if (hostHeader != null) {
                     Clause[] clauses = Parser.parseHeader(hostHeader);
                     if (clauses != null && clauses.length > 0) {
                         Clause path = clauses[0];
-                        for (Iterator it = bundles.iterator(); it.hasNext();) {
-                            Bundle hostBundle = (Bundle) it.next();
+                        for (Bundle hostBundle : bundles) {
                             if (hostBundle.getSymbolicName() != null &&
                                     hostBundle.getSymbolicName().equals(path.getName())) {
                                 String ver = path.getAttribute(Constants.BUNDLE_VERSION_ATTRIBUTE);
                                 if (ver != null) {
                                     VersionRange v = VersionRange.parseVersionRange(ver);
-                                    if (v.contains(VersionTable.getVersion((String) hostBundle.getHeaders().get(Constants.BUNDLE_VERSION)))) {
+                                    if (v.contains(VersionTable.getVersion(hostBundle.getHeaders().get(Constants.BUNDLE_VERSION)))) {
                                         fragments.add(hostBundle);
                                     }
                                 } else {
@@ -1364,19 +1294,19 @@
         toRefresh.addAll(fragments);
     }
 
-    protected void findBundlesWithOptionalPackagesToRefresh(Set toRefresh) {
-        Set bundles = getScopedBundles(optionalScope);
+    protected void findBundlesWithOptionalPackagesToRefresh(Set<Bundle> toRefresh) {
+        Set<Bundle> bundles = getScopedBundles(optionalScope);
         // First pass: include all bundles contained in these features
         bundles.removeAll(toRefresh);
         if (bundles.isEmpty()) {
             return;
         }
         // Second pass: for each bundle, check if there is any unresolved optional package that could be resolved
-        Map imports = new HashMap();
-        for (Iterator it = bundles.iterator(); it.hasNext(); ) {
-            Bundle b = (Bundle) it.next();
-            String importsStr = (String) b.getHeaders().get(Constants.IMPORT_PACKAGE);
-            List importsList = getOptionalImports(importsStr);
+        Map<Bundle, List<Clause>> imports = new HashMap<Bundle, List<Clause>>();
+        for (Iterator<Bundle> it = bundles.iterator(); it.hasNext(); ) {
+            Bundle b = it.next();
+            String importsStr = b.getHeaders().get(Constants.IMPORT_PACKAGE);
+            List<Clause> importsList = getOptionalImports(importsStr);
             if (importsList.isEmpty()) {
                 it.remove();
             } else {
@@ -1388,25 +1318,23 @@
         }
         // Third pass: compute a list of packages that are exported by our bundles and see if
         //             some exported packages can be wired to the optional imports
-        List exports = new ArrayList();
-        for (Iterator iterator = toRefresh.iterator(); iterator.hasNext();) {
-            Bundle b = (Bundle) iterator.next();
+        List<Clause> exports = new ArrayList<Clause>();
+        for (Bundle b : toRefresh) {
             if (b.getState() != Bundle.UNINSTALLED) {
-                String exportsStr = (String) b.getHeaders().get(Constants.EXPORT_PACKAGE);
+                String exportsStr = b.getHeaders().get(Constants.EXPORT_PACKAGE);
                 if (exportsStr != null) {
                     Clause[] exportsList = Parser.parseHeader(exportsStr);
                     exports.addAll(Arrays.asList(exportsList));
                 }
             }
         }
-        for (Iterator it = bundles.iterator(); it.hasNext(); ) {
-            Bundle b = (Bundle) it.next();
-            List importsList = (List) imports.get(b);
-            for (Iterator itpi = importsList.iterator(); itpi.hasNext(); ) {
-                Clause pi = (Clause) itpi.next();
+        for (Iterator<Bundle> it = bundles.iterator(); it.hasNext(); ) {
+            Bundle b = it.next();
+            List<Clause> importsList = imports.get(b);
+            for (Iterator<Clause> itpi = importsList.iterator(); itpi.hasNext(); ) {
+                Clause pi = itpi.next();
                 boolean matching = false;
-                for (Iterator itcl = exports.iterator(); itcl.hasNext(); ) {
-                    Clause pe = (Clause) itcl.next();
+                for (Clause pe : exports) {
                     if (pi.getName().equals(pe.getName())) {
                         String evStr = pe.getAttribute(Constants.VERSION_ATTRIBUTE);
                         String ivStr = pi.getAttribute(Constants.VERSION_ATTRIBUTE);
@@ -1435,13 +1363,16 @@
         toRefresh.addAll(bundles);
     }
 
-    protected List getOptionalImports(String importsStr) {
+    protected List<Clause> getOptionalImports(String importsStr)
+    {
         Clause[] imports = Parser.parseHeader(importsStr);
-        List result = new LinkedList();
-        for (int i = 0; i < imports.length; i++) {
-            String resolution = imports[i].getDirective(Constants.RESOLUTION_DIRECTIVE);
-            if (Constants.RESOLUTION_OPTIONAL.equals(resolution)) {
-                result.add(imports[i]);
+        List<Clause> result = new LinkedList<Clause>();
+        for (Clause anImport : imports)
+        {
+            String resolution = anImport.getDirective(Constants.RESOLUTION_DIRECTIVE);
+            if (Constants.RESOLUTION_OPTIONAL.equals(resolution))
+            {
+                result.add(anImport);
             }
         }
         return result;
@@ -1451,9 +1382,8 @@
     {
         if (updateWithListeners)
         {
-            for (Iterator it = getArtifacts().iterator(); it.hasNext(); )
+            for (Artifact artifact : getArtifacts())
             {
-                Artifact artifact = (Artifact) it.next();
                 if (artifact.getListener() == null && artifact.getBundleId() > 0)
                 {
                     Bundle bundle = context.getBundle(artifact.getBundleId());
@@ -1479,9 +1409,8 @@
 
     public void removeListener(ArtifactListener listener)
     {
-        for (Iterator it = getArtifacts().iterator(); it.hasNext(); )
+        for (Artifact artifact : getArtifacts())
         {
-            Artifact artifact = (Artifact) it.next();
             if (artifact.getListener() == listener)
             {
                 artifact.setListener(null);
@@ -1497,15 +1426,15 @@
     {
         synchronized (currentManagedArtifacts)
         {
-            return (Artifact) currentManagedArtifacts.get(file);
+            return currentManagedArtifacts.get(file);
         }
     }
 
-    private List getArtifacts()
+    private List<Artifact> getArtifacts()
     {
         synchronized (currentManagedArtifacts)
         {
-            return new ArrayList(currentManagedArtifacts.values());
+            return new ArrayList<Artifact>(currentManagedArtifacts.values());
         }
     }
 
@@ -1526,15 +1455,11 @@
     }
     
     private void setStateChanged(boolean changed) {
-        synchronized (stateChanged) {
-            this.stateChanged = Boolean.valueOf(changed);
-        }
+        this.stateChanged.set(changed);
     }
 
     private boolean isStateChanged() {
-        synchronized (stateChanged) {
-            return stateChanged.booleanValue();
-        }
+        return stateChanged.get();
     }
 
 }
diff --git a/fileinstall/src/main/java/org/apache/felix/fileinstall/internal/FileInstall.java b/fileinstall/src/main/java/org/apache/felix/fileinstall/internal/FileInstall.java
index 6ba0114..a5eea41 100644
--- a/fileinstall/src/main/java/org/apache/felix/fileinstall/internal/FileInstall.java
+++ b/fileinstall/src/main/java/org/apache/felix/fileinstall/internal/FileInstall.java
@@ -20,21 +20,27 @@
 
 import java.io.File;
 import java.util.*;
-import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
 
 import org.apache.felix.fileinstall.ArtifactInstaller;
 import org.apache.felix.fileinstall.ArtifactListener;
 import org.apache.felix.fileinstall.ArtifactTransformer;
 import org.apache.felix.fileinstall.ArtifactUrlTransformer;
 import org.apache.felix.fileinstall.internal.Util.Logger;
-import org.apache.felix.utils.collections.DictionaryAsMap;
 import org.apache.felix.utils.properties.InterpolationHelper;
-import org.osgi.framework.*;
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleActivator;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.Constants;
+import org.osgi.framework.FrameworkEvent;
+import org.osgi.framework.FrameworkListener;
+import org.osgi.framework.FrameworkUtil;
+import org.osgi.framework.ServiceReference;
+import org.osgi.framework.ServiceRegistration;
+import org.osgi.framework.wiring.FrameworkWiring;
 import org.osgi.service.cm.ConfigurationAdmin;
 import org.osgi.service.cm.ConfigurationException;
 import org.osgi.service.cm.ManagedServiceFactory;
-import org.osgi.service.packageadmin.PackageAdmin;
-import org.osgi.service.startlevel.StartLevel;
 import org.osgi.util.tracker.ServiceTracker;
 import org.osgi.util.tracker.ServiceTrackerCustomizer;
 
@@ -44,35 +50,26 @@
  * fragment).
  *
  */
-public class FileInstall implements BundleActivator, ServiceTrackerCustomizer, FrameworkListener
+public class FileInstall implements BundleActivator, ServiceTrackerCustomizer
 {
-    static ServiceTracker padmin;
-    static ServiceTracker startLevel;
     static Runnable cmSupport;
-    static final Map /* <ServiceReference, ArtifactListener> */ listeners = new TreeMap /* <ServiceReference, ArtifactListener> */();
+    static final Map<ServiceReference, ArtifactListener> listeners = new TreeMap<ServiceReference, ArtifactListener>();
     static final BundleTransformer bundleTransformer = new BundleTransformer();
     BundleContext context;
-    Map watchers = new HashMap();
+    final Map<String, DirectoryWatcher> watchers = new HashMap<String, DirectoryWatcher>();
     ServiceTracker listenersTracker;
     static boolean initialized;
     static final Object barrier = new Object();
-    static final Object refreshLock = new Object();
     ServiceRegistration urlHandlerRegistration;
 
     public void start(BundleContext context) throws Exception
     {
         this.context = context;
-        context.addFrameworkListener(this);
 
-        Hashtable props = new Hashtable();
+        Hashtable<String, Object> props = new Hashtable<String, Object>();
         props.put("url.handler.protocol", JarDirUrlHandler.PROTOCOL);
         urlHandlerRegistration = context.registerService(org.osgi.service.url.URLStreamHandlerService.class.getName(), new JarDirUrlHandler(), props);
 
-        padmin = new ServiceTracker(context, PackageAdmin.class.getName(), null);
-        padmin.open();
-        startLevel = new ServiceTracker(context, StartLevel.class.getName(), null);
-        startLevel.open();
-
         String flt = "(|(" + Constants.OBJECTCLASS + "=" + ArtifactInstaller.class.getName() + ")"
                      + "(" + Constants.OBJECTCLASS + "=" + ArtifactTransformer.class.getName() + ")"
                      + "(" + Constants.OBJECTCLASS + "=" + ArtifactUrlTransformer.class.getName() + "))";
@@ -90,7 +87,7 @@
         }
 
         // Created the initial configuration
-        Hashtable ht = new Hashtable();
+        Hashtable<String, String> ht = new Hashtable<String, String>();
 
         set(ht, DirectoryWatcher.POLL);
         set(ht, DirectoryWatcher.DIR);
@@ -103,7 +100,7 @@
         set(ht, DirectoryWatcher.START_LEVEL);
 
         // check if dir is an array of dirs
-        String dirs = (String)ht.get(DirectoryWatcher.DIR);
+        String dirs = ht.get(DirectoryWatcher.DIR);
         if ( dirs != null && dirs.indexOf(',') != -1 )
         {
             StringTokenizer st = new StringTokenizer(dirs, ",");
@@ -115,7 +112,7 @@
 
                 String name = "initial";
                 if ( index > 0 ) name = name + index;
-                updated(name, new Hashtable(ht));
+                updated(name, new Hashtable<String, String>(ht));
 
                 index++;
             }
@@ -149,9 +146,9 @@
     }
 
     // Adapted for FELIX-524
-    private void set(Hashtable ht, String key)
+    private void set(Hashtable<String, String> ht, String key)
     {
-        Object o = context.getProperty(key);
+        String o = context.getProperty(key);
         if (o == null)
         {
            o = System.getProperty(key.toUpperCase().replace('.', '_'));
@@ -169,18 +166,17 @@
             initialized = false;
         }
         urlHandlerRegistration.unregister();
-        List /*<DirectoryWatcher>*/ toClose = new ArrayList /*<DirectoryWatcher>*/();
+        List<DirectoryWatcher> toClose = new ArrayList<DirectoryWatcher>();
         synchronized (watchers)
         {
             toClose.addAll(watchers.values());
             watchers.clear();
         }
-        for (Iterator w = toClose.iterator(); w.hasNext();)
+        for (DirectoryWatcher aToClose : toClose)
         {
             try
             {
-                DirectoryWatcher dir = (DirectoryWatcher) w.next();
-                dir.close();
+                aToClose.close();
             }
             catch (Exception e)
             {
@@ -195,10 +191,6 @@
         {
             cmSupport.run();
         }
-        if (padmin != null)
-        {
-            padmin.close();
-        }
     }
 
     public void deleted(String pid)
@@ -206,7 +198,7 @@
         DirectoryWatcher watcher;
         synchronized (watchers)
         {
-            watcher = (DirectoryWatcher) watchers.remove(pid);
+            watcher = watchers.remove(pid);
         }
         if (watcher != null)
         {
@@ -214,13 +206,13 @@
         }
     }
 
-    public void updated(String pid, Dictionary properties)
+    public void updated(String pid, Map<String, String> properties)
     {
-        InterpolationHelper.performSubstitution(new DictionaryAsMap(properties), context);
-        DirectoryWatcher watcher = null;
+        InterpolationHelper.performSubstitution(properties, context);
+        DirectoryWatcher watcher;
         synchronized (watchers)
         {
-            watcher = (DirectoryWatcher) watchers.get(pid);
+            watcher = watchers.get(pid);
             if (watcher != null && watcher.getProperties().equals(properties))
             {
                 return;
@@ -241,14 +233,13 @@
 
     public void updateChecksum(File file)
     {
-        List /*<DirectoryWatcher>*/ toUpdate = new ArrayList /*<DirectoryWatcher>*/();
+        List<DirectoryWatcher> toUpdate = new ArrayList<DirectoryWatcher>();
         synchronized (watchers)
         {
             toUpdate.addAll(watchers.values());
         }
-        for (Iterator w = toUpdate.iterator(); w.hasNext();)
+        for (DirectoryWatcher watcher : toUpdate)
         {
-            DirectoryWatcher watcher = (DirectoryWatcher) w.next();
             watcher.scanner.updateChecksum(file);
         }
     }
@@ -262,15 +253,14 @@
         
         long currentStamp = reference.getBundle().getLastModified();
 
-        List /*<DirectoryWatcher>*/ toNotify = new ArrayList /*<DirectoryWatcher>*/();
+        List<DirectoryWatcher> toNotify = new ArrayList<DirectoryWatcher>();
         synchronized (watchers)
         {
             toNotify.addAll(watchers.values());
         }
-        for (Iterator w = toNotify.iterator(); w.hasNext();)
+        for (DirectoryWatcher dir : toNotify)
         {
-            DirectoryWatcher dir = (DirectoryWatcher) w.next();
-            dir.addListener( listener, currentStamp );
+            dir.addListener(listener, currentStamp);
         }
     }
 
@@ -280,23 +270,22 @@
         {
             listeners.remove(reference);
         }
-        List /*<DirectoryWatcher>*/ toNotify = new ArrayList /*<DirectoryWatcher>*/();
+        List<DirectoryWatcher> toNotify = new ArrayList<DirectoryWatcher>();
         synchronized (watchers)
         {
             toNotify.addAll(watchers.values());
         }
-        for (Iterator w = toNotify.iterator(); w.hasNext();)
+        for (DirectoryWatcher dir : toNotify)
         {
-            DirectoryWatcher dir = (DirectoryWatcher) w.next();
             dir.removeListener(listener);
         }
     }
 
-    static List getListeners()
+    static List<ArtifactListener> getListeners()
     {
         synchronized (listeners)
         {
-            List l = new ArrayList(listeners.values());
+            List<ArtifactListener> l = new ArrayList<ArtifactListener>(listeners.values());
             Collections.reverse(l);
             l.add(bundleTransformer);
             return l;
@@ -306,64 +295,16 @@
     /**
      * Convenience to refresh the packages
      */
-    static void refresh(Bundle[] bundles) throws InterruptedException
+    static void refresh(BundleContext context, Collection<Bundle> bundles) throws InterruptedException
     {
-        PackageAdmin padmin = getPackageAdmin();
-        if (padmin != null)
-        {
-            synchronized (refreshLock) {
-                padmin.refreshPackages(bundles);
-                refreshLock.wait(30000);
+        final CountDownLatch latch = new CountDownLatch(1);
+        FrameworkWiring wiring = context.getBundle(0).adapt(FrameworkWiring.class);
+        wiring.refreshBundles(bundles, new FrameworkListener() {
+            public void frameworkEvent(FrameworkEvent event) {
+                latch.countDown();
             }
-        }
-    }
-
-    public void frameworkEvent(FrameworkEvent event)
-    {
-        if (event.getType() == FrameworkEvent.PACKAGES_REFRESHED
-                || event.getType() == FrameworkEvent.ERROR)
-        {
-            synchronized (refreshLock)
-            {
-                refreshLock.notifyAll();
-            }
-        }
-    }
-
-    static PackageAdmin getPackageAdmin()
-    {
-        return getPackageAdmin(10000);
-    }
-
-    static PackageAdmin getPackageAdmin(long timeout)
-    {
-        try
-        {
-            return (PackageAdmin) padmin.waitForService(timeout);
-        }
-        catch (InterruptedException e)
-        {
-            Thread.currentThread().interrupt();
-            return null;
-        }
-    }
-
-    static StartLevel getStartLevel()
-    {
-        return getStartLevel(10000);
-    }
-
-    static StartLevel getStartLevel(long timeout)
-    {
-        try
-        {
-            return (StartLevel) startLevel.waitForService(timeout);
-        }
-        catch (InterruptedException e)
-        {
-            Thread.currentThread().interrupt();
-            return null;
-        }
+        });
+        latch.await();
     }
 
     private static class ConfigAdminSupport implements Runnable
@@ -374,7 +315,7 @@
         private ConfigAdminSupport(BundleContext context, FileInstall fileInstall)
         {
             tracker = new Tracker(context, fileInstall);
-            Hashtable props = new Hashtable();
+            Hashtable<String, Object> props = new Hashtable<String, Object>();
             props.put(Constants.SERVICE_PID, tracker.getName());
             registration = context.registerService(ManagedServiceFactory.class.getName(), tracker, props);
             tracker.open();
@@ -386,10 +327,10 @@
             tracker.close();
         }
 
-        private class Tracker extends ServiceTracker implements ManagedServiceFactory {
+        private class Tracker extends ServiceTracker<ConfigurationAdmin, ConfigurationAdmin> implements ManagedServiceFactory {
 
             private final FileInstall fileInstall;
-            private final Set configs = Collections.synchronizedSet(new HashSet());
+            private final Set<String> configs = Collections.synchronizedSet(new HashSet<String>());
             private ConfigInstaller configInstaller;
 
             private Tracker(BundleContext bundleContext, FileInstall fileInstall)
@@ -403,10 +344,15 @@
                 return "org.apache.felix.fileinstall";
             }
 
-            public void updated(String s, Dictionary dictionary) throws ConfigurationException
+            public void updated(String s, Dictionary<String, ?> dictionary) throws ConfigurationException
             {
                 configs.add(s);
-                fileInstall.updated(s, dictionary);
+                Map<String, String> props = new HashMap<String, String>();
+                for (Enumeration<String> e = dictionary.keys(); e.hasMoreElements();) {
+                    String k = e.nextElement();
+                    props.put(k, dictionary.get(k).toString());
+                }
+                fileInstall.updated(s, props);
             }
 
             public void deleted(String s)
@@ -415,15 +361,15 @@
                 fileInstall.deleted(s);
             }
 
-            public Object addingService(ServiceReference serviceReference)
+            public ConfigurationAdmin addingService(ServiceReference<ConfigurationAdmin> serviceReference)
             {
-                ConfigurationAdmin cm = (ConfigurationAdmin) super.addingService(serviceReference);
+                ConfigurationAdmin cm = super.addingService(serviceReference);
                 configInstaller = new ConfigInstaller(this.context, cm, fileInstall);
                 configInstaller.init();
                 return cm;
             }
 
-            public void removedService(ServiceReference serviceReference, Object o)
+            public void removedService(ServiceReference<ConfigurationAdmin> serviceReference, ConfigurationAdmin o)
             {
                 Iterator iterator = configs.iterator();
                 while (iterator.hasNext()) {
diff --git a/fileinstall/src/main/java/org/apache/felix/fileinstall/internal/Scanner.java b/fileinstall/src/main/java/org/apache/felix/fileinstall/internal/Scanner.java
index d3141c4..d6fa652 100644
--- a/fileinstall/src/main/java/org/apache/felix/fileinstall/internal/Scanner.java
+++ b/fileinstall/src/main/java/org/apache/felix/fileinstall/internal/Scanner.java
@@ -23,7 +23,6 @@
 import java.io.IOException;
 import java.util.HashMap;
 import java.util.HashSet;
-import java.util.Iterator;
 import java.util.Map;
 import java.util.Set;
 import java.util.zip.CRC32;
@@ -47,8 +46,8 @@
     final FilenameFilter filter;
 
     // Store checksums of files or directories
-    Map/* <File, Long> */ lastChecksums = new HashMap/* <File, Long> */();
-    Map/* <File, Long> */ storedChecksums = new HashMap/* <File, Long> */();
+    Map<File, Long> lastChecksums = new HashMap<File, Long>();
+    Map<File, Long> storedChecksums = new HashMap<File, Long>();
 
     /**
      * Create a scanner for the specified directory
@@ -80,7 +79,7 @@
      *
      * @param checksums a map of checksums
      */
-    public void initialize(Map/*<File, Long>*/ checksums)
+    public void initialize(Map<File, Long> checksums)
     {
         storedChecksums.putAll(checksums);
     }
@@ -95,33 +94,30 @@
      * @param reportImmediately report all files immediately without waiting for the checksum to be stable
      * @return a list of changes on the files included in the directory
      */
-    public Set/*<File>*/ scan(boolean reportImmediately)
+    public Set<File> scan(boolean reportImmediately)
     {
         File[] list = directory.listFiles(filter);
         if (list == null)
         {
             return null;
         }
-        Set/*<File>*/ files = new HashSet/*<File>*/();
-        Set/*<File>*/ removed = new HashSet/*<File>*/(storedChecksums.keySet());
-        for (int i = 0; i < list.length; i++)
+        Set<File> files = new HashSet<File>();
+        Set<File> removed = new HashSet<File>(storedChecksums.keySet());
+        for (File file : list)
         {
-            File file  = list[i];
-            long lastChecksum = lastChecksums.get(file) != null ? ((Long) lastChecksums.get(file)).longValue() : 0;
-            long storedChecksum = storedChecksums.get(file) != null ? ((Long) storedChecksums.get(file)).longValue() : 0;
+            long lastChecksum = lastChecksums.get(file) != null ? (Long) lastChecksums.get(file) : 0;
+            long storedChecksum = storedChecksums.get(file) != null ? (Long) storedChecksums.get(file) : 0;
             long newChecksum = checksum(file);
-            lastChecksums.put(file, new Long(newChecksum));
+            lastChecksums.put(file, newChecksum);
             // Only handle file when it does not change anymore and it has changed since last reported
-            if ((newChecksum == lastChecksum || reportImmediately) && newChecksum != storedChecksum)
-            {
-                storedChecksums.put(file, new Long(newChecksum));
+            if ((newChecksum == lastChecksum || reportImmediately) && newChecksum != storedChecksum) {
+                storedChecksums.put(file, newChecksum);
                 files.add(file);
             }
             removed.remove(file);
         }
-        for (Iterator it = removed.iterator(); it.hasNext();)
+        for (File file : removed)
         {
-            File file = (File) it.next();
             // Make sure we'll handle a file that has been deleted
             files.addAll(removed);
             // Remove no longer used checksums
@@ -151,21 +147,19 @@
      */
     public long getChecksum(File file)
     {
-        Long c = (Long) storedChecksums.get(file);
-        return c != null ? c.longValue() : 0;
+        Long c = storedChecksums.get(file);
+        return c != null ? c : 0;
     }
 
     /**
       * Update the checksum of a file if that file is already known locally.
-      *
-      * @param file
       */
     public void updateChecksum(File file)
     {
         if (file != null && storedChecksums.containsKey(file))
         {
             long newChecksum = checksum(file);
-            storedChecksums.put(file, new Long(newChecksum));
+            storedChecksums.put(file, newChecksum);
         }
     }
 
@@ -196,9 +190,9 @@
             File[] children = file.listFiles();
             if (children != null)
             {
-                for (int i = 0; i < children.length; i++)
+                for (File aChildren : children)
                 {
-                    checksum(children[i], crc);
+                    checksum(aChildren, crc);
                 }
             }
         }
diff --git a/fileinstall/src/main/java/org/apache/felix/fileinstall/internal/Util.java b/fileinstall/src/main/java/org/apache/felix/fileinstall/internal/Util.java
index 66188d5..80227e3 100644
--- a/fileinstall/src/main/java/org/apache/felix/fileinstall/internal/Util.java
+++ b/fileinstall/src/main/java/org/apache/felix/fileinstall/internal/Util.java
@@ -50,7 +50,7 @@
      */
     public static int getGlobalLogLevel(BundleContext context)
     {
-        String s = (String) context.getProperty(DirectoryWatcher.LOG_LEVEL);
+        String s = context.getProperty(DirectoryWatcher.LOG_LEVEL);
         s = (s == null)
             ? System.getProperty(DirectoryWatcher.LOG_LEVEL.toUpperCase().replace('.', '_'))
             : s;
@@ -62,6 +62,7 @@
         }
         catch (NumberFormatException ex)
         {
+            // Ignore
         }
         return logLevel;
     }
@@ -179,11 +180,10 @@
 
         private LogService getLogService()
         {
-            ServiceReference ref = context.getServiceReference(LogService.class.getName());
+            ServiceReference<LogService> ref = context.getServiceReference(LogService.class);
             if (ref != null)
             {
-                LogService log = (LogService) context.getService(ref);
-                return log;
+                return context.getService(ref);
             }
             return null;
         }
@@ -191,10 +191,6 @@
 
     /**
      * Jar up a directory
-     *
-     * @param directory
-     * @param zipName
-     * @throws IOException
      */
     public static void jarDir(File directory, File zipName) throws IOException
     {
@@ -236,22 +232,17 @@
 
     /**
      * Zip up a directory path
-     * @param directory
-     * @param zos
-     * @param path
-     * @param exclusions
-     * @throws IOException
      */
-    public static void zipDir(File directory, ZipOutputStream zos, String path, Set/* <String> */ exclusions) throws IOException
+    public static void zipDir(File directory, ZipOutputStream zos, String path, Set<String> exclusions) throws IOException
     {
         // get a listing of the directory content
         File[] dirList = directory.listFiles();
         byte[] readBuffer = new byte[8192];
-        int bytesIn = 0;
+        int bytesIn;
         // loop through dirList, and zip the files
-        for (int i = 0; i < dirList.length; i++)
+        assert dirList != null;
+        for (File f : dirList)
         {
-            File f = dirList[i];
             if (f.isDirectory())
             {
                 String prefix = path + f.getName() + "/";
@@ -347,6 +338,7 @@
                 }
                 catch ( IOException e )
                 {
+                    // Ignore
                 }
             }
         }
diff --git a/fileinstall/src/test/java/org/apache/felix/fileinstall/internal/BundleTransformerTest.java b/fileinstall/src/test/java/org/apache/felix/fileinstall/internal/BundleTransformerTest.java
index efb10e1..65a0765 100644
--- a/fileinstall/src/test/java/org/apache/felix/fileinstall/internal/BundleTransformerTest.java
+++ b/fileinstall/src/test/java/org/apache/felix/fileinstall/internal/BundleTransformerTest.java
@@ -21,7 +21,6 @@
 import java.io.File;
 
 import junit.framework.TestCase;
-import org.apache.felix.fileinstall.internal.BundleTransformer;
 
 /**
  * Test for the BundleTransformer
diff --git a/fileinstall/src/test/java/org/apache/felix/fileinstall/internal/ConfigInstallerTest.java b/fileinstall/src/test/java/org/apache/felix/fileinstall/internal/ConfigInstallerTest.java
index a3c3b8a..f9cd876 100644
--- a/fileinstall/src/test/java/org/apache/felix/fileinstall/internal/ConfigInstallerTest.java
+++ b/fileinstall/src/test/java/org/apache/felix/fileinstall/internal/ConfigInstallerTest.java
@@ -45,10 +45,10 @@
     protected void setUp() throws Exception
     {
         super.setUp();
-        mockBundleContext = (BundleContext) EasyMock.createMock(BundleContext.class);
-        mockBundle = ( Bundle ) EasyMock.createMock(Bundle.class);
-        mockConfigurationAdmin = ( ConfigurationAdmin ) EasyMock.createMock(ConfigurationAdmin.class);
-        mockConfiguration = ( Configuration ) EasyMock.createMock(Configuration.class);
+        mockBundleContext = EasyMock.createMock(BundleContext.class);
+        mockBundle = EasyMock.createMock(Bundle.class);
+        mockConfigurationAdmin = EasyMock.createMock(ConfigurationAdmin.class);
+        mockConfiguration = EasyMock.createMock(Configuration.class);
     }
 
 
@@ -77,13 +77,13 @@
                     .andReturn(null);
         EasyMock.expect(mockConfigurationAdmin.createFactoryConfiguration( "pid", null ))
                     .andReturn(mockConfiguration);
-        EasyMock.replay(new Object[]{mockConfiguration, mockConfigurationAdmin, mockBundleContext});
+        EasyMock.replay(mockConfiguration, mockConfigurationAdmin, mockBundleContext);
 
         ConfigInstaller ci = new ConfigInstaller( mockBundleContext, mockConfigurationAdmin, new FileInstall() );
 
         assertEquals( "Factory configuration retrieved", mockConfiguration, ci.getConfiguration( "pid-factoryPid.cfg", "pid", "factoryPid" ) );
 
-        EasyMock.verify(new Object[]{mockConfiguration, mockConfigurationAdmin, mockBundleContext});
+        EasyMock.verify(mockConfiguration, mockConfigurationAdmin, mockBundleContext);
     }
 
 
@@ -93,13 +93,13 @@
                         .andReturn(null);
         EasyMock.expect(mockConfigurationAdmin.createFactoryConfiguration( "pid", null ))
                         .andReturn(mockConfiguration);
-        EasyMock.replay(new Object[]{mockConfiguration, mockConfigurationAdmin, mockBundleContext});
+        EasyMock.replay(mockConfiguration, mockConfigurationAdmin, mockBundleContext);
 
         ConfigInstaller ci = new ConfigInstaller( mockBundleContext, mockConfigurationAdmin, new FileInstall() );
 
         assertEquals( "Factory configuration retrieved", mockConfiguration, ci.getConfiguration( "pid-factoryPid.cfg","pid", "factoryPid" ) );
 
-        EasyMock.verify(new Object[]{mockConfiguration, mockConfigurationAdmin, mockBundleContext});
+        EasyMock.verify(mockConfiguration, mockConfigurationAdmin, mockBundleContext);
     }
 
 
@@ -109,13 +109,13 @@
                         .andReturn(null);
         EasyMock.expect(mockConfigurationAdmin.getConfiguration( "pid", null ))
                         .andReturn(mockConfiguration);
-        EasyMock.replay(new Object[]{mockConfiguration, mockConfigurationAdmin, mockBundleContext});
+        EasyMock.replay(mockConfiguration, mockConfigurationAdmin, mockBundleContext);
 
         ConfigInstaller ci = new ConfigInstaller( mockBundleContext, mockConfigurationAdmin, new FileInstall() );
 
         assertEquals( "Factory configuration retrieved", mockConfiguration, ci.getConfiguration( "pid.cfg", "pid", null ) );
 
-        EasyMock.verify(new Object[]{mockConfiguration, mockConfigurationAdmin, mockBundleContext});
+        EasyMock.verify(mockConfiguration, mockConfigurationAdmin, mockBundleContext);
     }
 
 
@@ -126,20 +126,20 @@
                         .andReturn(null);
         EasyMock.expect(mockConfigurationAdmin.getConfiguration("pid", null ))
                         .andReturn(mockConfiguration);
-        EasyMock.replay(new Object[]{mockConfiguration, mockConfigurationAdmin, mockBundleContext});
+        EasyMock.replay(mockConfiguration, mockConfigurationAdmin, mockBundleContext);
 
         ConfigInstaller ci = new ConfigInstaller( mockBundleContext, mockConfigurationAdmin, new FileInstall() );
 
         assertTrue( ci.deleteConfig( new File( "pid.cfg" ) ) );
 
-        EasyMock.verify(new Object[]{mockConfiguration, mockConfigurationAdmin, mockBundleContext});
+        EasyMock.verify(mockConfiguration, mockConfigurationAdmin, mockBundleContext);
     }
 
 
     public void testSetConfiguration() throws Exception
     {
         EasyMock.expect(mockConfiguration.getBundleLocation()).andReturn(null);
-        EasyMock.expect(mockConfiguration.getProperties()).andReturn(new Hashtable());
+        EasyMock.expect(mockConfiguration.getProperties()).andReturn(new Hashtable<String, Object>());
         EasyMock.reportMatcher(new IArgumentMatcher()
         {
             public boolean matches( Object argument )
@@ -152,40 +152,40 @@
                 buffer.append("<Dictionary check: testkey present?>");
             }
         } );
-        mockConfiguration.update(new Hashtable());
+        mockConfiguration.update(new Hashtable<String, Object>());
         EasyMock.expect(mockConfigurationAdmin.listConfigurations((String) EasyMock.anyObject()))
                         .andReturn(null);
         EasyMock.expect(mockConfigurationAdmin.getConfiguration("firstcfg", null))
                         .andReturn(mockConfiguration);
-        EasyMock.replay(new Object[]{mockConfiguration, mockConfigurationAdmin, mockBundleContext});
+        EasyMock.replay(mockConfiguration, mockConfigurationAdmin, mockBundleContext);
 
         ConfigInstaller ci = new ConfigInstaller( mockBundleContext, mockConfigurationAdmin, new FileInstall() );
 
         assertTrue( ci.setConfig( new File( "src/test/resources/watched/firstcfg.cfg" ) ) );
 
-        EasyMock.verify(new Object[]{mockConfiguration, mockConfigurationAdmin, mockBundleContext});
+        EasyMock.verify(mockConfiguration, mockConfigurationAdmin, mockBundleContext);
     }
     
     public void testShouldSaveConfig() 
     {
-        final AtomicReference disable = new AtomicReference();
-        final AtomicReference enable = new AtomicReference();
+        final AtomicReference<Boolean> disable = new AtomicReference<Boolean>();
+        final AtomicReference<Boolean> enable = new AtomicReference<Boolean>();
         
         EasyMock.expect(mockBundleContext.getProperty(DirectoryWatcher.DISABLE_CONFIG_SAVE)).andAnswer(
-                new IAnswer() {
-                    public Object answer() throws Throwable {
+                new IAnswer<String>() {
+                    public String answer() throws Throwable {
                         return disable.get() != null ? disable.get().toString() : null;
                     }
                 }
         ).anyTimes();
         EasyMock.expect(mockBundleContext.getProperty(DirectoryWatcher.ENABLE_CONFIG_SAVE)).andAnswer(
-                new IAnswer() {
-                    public Object answer() throws Throwable {
+                new IAnswer<String>() {
+                    public String answer() throws Throwable {
                         return enable.get() != null ? enable.get().toString() : null;
                     }
                 }
         ).anyTimes();
-        EasyMock.replay(new Object[]{mockConfiguration, mockConfigurationAdmin, mockBundleContext});
+        EasyMock.replay(mockConfiguration, mockConfigurationAdmin, mockBundleContext);
 
         ConfigInstaller ci = new ConfigInstaller( mockBundleContext, mockConfigurationAdmin, new FileInstall() );
 
@@ -225,7 +225,7 @@
         enable.set(Boolean.TRUE);
         assertTrue( ci.shouldSaveConfig() );
 
-        EasyMock.verify(new Object[]{mockConfiguration, mockConfigurationAdmin, mockBundleContext});
+        EasyMock.verify(mockConfiguration, mockConfigurationAdmin, mockBundleContext);
     }
 
 }
diff --git a/fileinstall/src/test/java/org/apache/felix/fileinstall/internal/DirectoryWatcherTest.java b/fileinstall/src/test/java/org/apache/felix/fileinstall/internal/DirectoryWatcherTest.java
index 56750a6..f9d56e6 100644
--- a/fileinstall/src/test/java/org/apache/felix/fileinstall/internal/DirectoryWatcherTest.java
+++ b/fileinstall/src/test/java/org/apache/felix/fileinstall/internal/DirectoryWatcherTest.java
@@ -21,7 +21,7 @@
 
 import java.io.File;
 import java.net.URISyntaxException;
-import java.util.Dictionary;
+import java.util.Collection;
 import java.util.HashSet;
 import java.util.Hashtable;
 import java.util.Map;
@@ -34,8 +34,8 @@
 import org.osgi.framework.BundleContext;
 import org.osgi.framework.BundleListener;
 import org.osgi.framework.ServiceReference;
+import org.osgi.framework.wiring.BundleRevision;
 import org.osgi.service.log.LogService;
-import org.osgi.service.packageadmin.PackageAdmin;
 
 
 /**
@@ -45,19 +45,17 @@
 {
 
     private final static String TEST = "test.key";
-    Dictionary props = new Hashtable();
+    Map<String, String> props = new Hashtable<String, String>();
     DirectoryWatcher dw;
     BundleContext mockBundleContext;
-    PackageAdmin mockPackageAdmin;
     Bundle mockBundle;
 
 
     protected void setUp() throws Exception
     {
         super.setUp();
-        mockBundleContext = (BundleContext) EasyMock.createMock(BundleContext.class);
-        mockPackageAdmin = (PackageAdmin) EasyMock.createMock(PackageAdmin.class);
-        mockBundle = (Bundle) EasyMock.createNiceMock(Bundle.class);
+        mockBundleContext = EasyMock.createMock(BundleContext.class);
+        mockBundle = EasyMock.createNiceMock(Bundle.class);
         props.put( DirectoryWatcher.DIR, new File( "target/load" ).getAbsolutePath() );
 
         // Might get called, but most of the time it doesn't matter whether they do or don't.
@@ -71,10 +69,10 @@
     public void testGetLongWithNonExistentProperty()
     {
         mockBundleContext.addBundleListener((BundleListener) org.easymock.EasyMock.anyObject());
-        EasyMock.replay(new Object[]{mockBundleContext});
+        EasyMock.replay(mockBundleContext);
         dw = new DirectoryWatcher( props, mockBundleContext );
         assertEquals( "getLong gives the default value for non-existing properties", 100, dw.getLong( props, TEST, 100 ) );
-        EasyMock.verify(new Object[]{mockBundleContext});
+        EasyMock.verify(mockBundleContext);
     }
 
 
@@ -83,10 +81,10 @@
         props.put( TEST, "33" );
 
         mockBundleContext.addBundleListener((BundleListener) org.easymock.EasyMock.anyObject());
-        EasyMock.replay(new Object[]{mockBundleContext});
+        EasyMock.replay(mockBundleContext);
         dw = new DirectoryWatcher( props, mockBundleContext );
         assertEquals( "getLong retrieves the right property value", 33, dw.getLong( props, TEST, 100 ) );
-        EasyMock.verify(new Object[]{mockBundleContext});
+        EasyMock.verify(mockBundleContext);
     }
 
 
@@ -95,20 +93,20 @@
         props.put( TEST, "incorrect" );
 
         mockBundleContext.addBundleListener((BundleListener) org.easymock.EasyMock.anyObject());
-        EasyMock.replay(new Object[]{mockBundleContext});
+        EasyMock.replay(mockBundleContext);
         dw = new DirectoryWatcher( props, mockBundleContext );
         assertEquals( "getLong retrieves the right property value", 100, dw.getLong( props, TEST, 100 ) );
-        EasyMock.verify(new Object[]{mockBundleContext});
+        EasyMock.verify(mockBundleContext);
     }
 
 
     public void testGetBooleanWithNonExistentProperty()
     {
         mockBundleContext.addBundleListener((BundleListener) org.easymock.EasyMock.anyObject());
-        EasyMock.replay(new Object[]{mockBundleContext});
+        EasyMock.replay(mockBundleContext);
         dw = new DirectoryWatcher( props, mockBundleContext );
         assertEquals( "getBoolean gives the default value for non-existing properties", true, dw.getBoolean( props, TEST, true ) );
-        EasyMock.verify(new Object[]{mockBundleContext});
+        EasyMock.verify(mockBundleContext);
     }
 
 
@@ -117,10 +115,10 @@
         props.put( TEST, "true" );
 
         mockBundleContext.addBundleListener((BundleListener) org.easymock.EasyMock.anyObject());
-        EasyMock.replay(new Object[]{mockBundleContext});
+        EasyMock.replay(mockBundleContext);
         dw = new DirectoryWatcher( props, mockBundleContext );
         assertEquals( "getBoolean retrieves the right property value", true, dw.getBoolean( props, TEST, false ) );
-        EasyMock.verify(new Object[]{mockBundleContext});
+        EasyMock.verify(mockBundleContext);
     }
 
 
@@ -129,20 +127,20 @@
         props.put( TEST, "incorrect" );
 
         mockBundleContext.addBundleListener((BundleListener) org.easymock.EasyMock.anyObject());
-        EasyMock.replay(new Object[]{mockBundleContext});
+        EasyMock.replay(mockBundleContext);
         dw = new DirectoryWatcher( props, mockBundleContext );
         assertEquals( "getBoolean retrieves the right property value", false, dw.getBoolean( props, TEST, true ) );
-        EasyMock.verify(new Object[]{mockBundleContext});
+        EasyMock.verify(mockBundleContext);
     }
 
 
     public void testGetFileWithNonExistentProperty()
     {
         mockBundleContext.addBundleListener((BundleListener) org.easymock.EasyMock.anyObject());
-        EasyMock.replay(new Object[]{mockBundleContext});
+        EasyMock.replay(mockBundleContext);
         dw = new DirectoryWatcher( props, mockBundleContext );
         assertEquals( "getFile gives the default value for non-existing properties", new File("tmp"), dw.getFile( props, TEST, new File("tmp") ) );
-        EasyMock.verify(new Object[]{mockBundleContext});
+        EasyMock.verify(mockBundleContext);
     }
 
 
@@ -151,10 +149,10 @@
         props.put( TEST, "test" );
 
         mockBundleContext.addBundleListener((BundleListener) org.easymock.EasyMock.anyObject());
-        EasyMock.replay(new Object[]{mockBundleContext});
+        EasyMock.replay(mockBundleContext);
         dw = new DirectoryWatcher( props, mockBundleContext );
         assertEquals( "getBoolean retrieves the right property value", new File("test"), dw.getFile( props, TEST, new File("tmp") ) );
-        EasyMock.verify(new Object[]{mockBundleContext});
+        EasyMock.verify(mockBundleContext);
     }
 
 
@@ -168,7 +166,7 @@
         props.put( DirectoryWatcher.FILTER, ".*\\.cfg" );
 
         mockBundleContext.addBundleListener((BundleListener) org.easymock.EasyMock.anyObject());
-        EasyMock.replay(new Object[]{mockBundleContext});
+        EasyMock.replay(mockBundleContext);
 
         dw = new DirectoryWatcher( props, mockBundleContext );
 
@@ -180,7 +178,7 @@
             "src" + File.separatorChar + "test" + File.separatorChar + "resources" ) );
         assertEquals("START_NEW_BUNDLES parameter correctly read", false, dw.startBundles);
         assertEquals( "FILTER parameter correctly read", ".*\\.cfg", dw.filter );
-        EasyMock.verify(new Object[]{mockBundleContext});
+        EasyMock.verify(mockBundleContext);
     }
 
 
@@ -189,7 +187,7 @@
         props.put( DirectoryWatcher.DIR, new File( "src/test/resources" ).getAbsolutePath() );
 
         mockBundleContext.addBundleListener((BundleListener) org.easymock.EasyMock.anyObject());
-        EasyMock.replay(new Object[]{mockBundleContext});
+        EasyMock.replay(mockBundleContext);
 
         dw = new DirectoryWatcher( props, mockBundleContext );
 
@@ -201,25 +199,24 @@
                 new File(System.getProperty("java.io.tmpdir")).getAbsolutePath()));
         assertEquals("Default START_NEW_BUNDLES parameter correctly read", true, dw.startBundles);
         assertEquals( "Default FILTER parameter correctly read", null, dw.filter );
-        EasyMock.verify(new Object[]{mockBundleContext});
+        EasyMock.verify(mockBundleContext);
     }
 
 
     public void testIsFragment() throws Exception
     {
         mockBundleContext.addBundleListener((BundleListener) org.easymock.EasyMock.anyObject());
-        EasyMock.expect(mockBundleContext.createFilter((String) EasyMock.anyObject()))
-                        .andReturn(null);
-        EasyMock.expect(Long.valueOf(mockPackageAdmin.getBundleType(mockBundle)))
-                        .andReturn(new Long(PackageAdmin.BUNDLE_TYPE_FRAGMENT));
-        EasyMock.replay(new Object[]{mockBundleContext, mockPackageAdmin, mockBundle});
+        BundleRevision mockBundleRevision = EasyMock.createNiceMock(BundleRevision.class);
+        EasyMock.expect(mockBundle.adapt(BundleRevision.class)).andReturn(mockBundleRevision);
+        EasyMock.expect(mockBundleRevision.getTypes())
+                .andReturn(BundleRevision.TYPE_FRAGMENT);
+       EasyMock.replay(mockBundleContext, mockBundle, mockBundleRevision);
 
-        FileInstall.padmin = new MockServiceTracker( mockBundleContext, mockPackageAdmin );
         dw = new DirectoryWatcher( props, mockBundleContext );
 
         assertTrue( "Fragment type correctly retrieved from Package Admin service", dw.isFragment( mockBundle ) );
 
-        EasyMock.verify(new Object[]{mockBundleContext});
+        EasyMock.verify(mockBundleContext);
     }
     
     public void testInvalidTempDir() throws Exception
@@ -237,13 +234,14 @@
             mockBundleContext.addBundleListener((BundleListener) org.easymock.EasyMock.anyObject());
             EasyMock.expect(mockBundleContext.createFilter((String) EasyMock.anyObject()))
                     .andReturn(null);
-            EasyMock.expect(Long.valueOf(mockPackageAdmin.getBundleType(mockBundle)))
-                    .andReturn(new Long(PackageAdmin.BUNDLE_TYPE_FRAGMENT));
-            EasyMock.replay(new Object[]{mockBundleContext, mockPackageAdmin, mockBundle});
+
+            BundleRevision mockBundleRevision = EasyMock.createNiceMock(BundleRevision.class);
+            EasyMock.expect(mockBundle.adapt(BundleRevision.class)).andReturn(mockBundleRevision);
+            EasyMock.expect(mockBundleRevision.getTypes())
+                    .andReturn(BundleRevision.TYPE_FRAGMENT);
+            EasyMock.replay(mockBundleContext, mockBundle, mockBundleRevision);
     
-            FileInstall.padmin = new MockServiceTracker( mockBundleContext, mockPackageAdmin );
-            
-            try 
+            try
             {
                 dw = new DirectoryWatcher( props, mockBundleContext );
                 fail("Expected an IllegalStateException");
@@ -290,16 +288,13 @@
         EasyMock.expect(mockBundleContext.getBundles()).andReturn(new Bundle[]{mockBundle});
         EasyMock.expect(mockBundleContext.getDataFile((String) EasyMock.anyObject())).andReturn(null).anyTimes();
         EasyMock.expect(mockBundle.getLocation()).andReturn(bundleLocation).anyTimes();
-        final Map mockCurrentManagedArtifacts = (Map)EasyMock.createNiceMock(Map.class);
-        EasyMock.expect(mockCurrentManagedArtifacts.put(EasyMock.eq(bundleFile), (Artifact)EasyMock.anyObject())).andReturn(null).times(1);
 
-        EasyMock.replay(new Object[]{mockBundleContext, mockBundle, mockCurrentManagedArtifacts});
+        EasyMock.replay(mockBundleContext, mockBundle);
 
         props.put(DirectoryWatcher.DIR, watchedDirectoryPath);
 
         dw = new DirectoryWatcher(props, mockBundleContext);
         dw.noInitialDelay = true;
-        dw.currentManagedArtifacts = mockCurrentManagedArtifacts;
         dw.scanner = scanner;
         try {
             dw.start();
@@ -308,8 +303,10 @@
         {
             assertEquals(e, expectedException);
         }
+        assertEquals(1, dw.currentManagedArtifacts.size());
+        assertTrue(dw.currentManagedArtifacts.containsKey(bundleFile));
 
-        EasyMock.verify(new Object[]{mockBundleContext, mockBundle, mockCurrentManagedArtifacts});
+        EasyMock.verify(mockBundleContext, mockBundle);
     }
 
     /**
@@ -343,16 +340,13 @@
         EasyMock.expect(mockBundleContext.getBundles()).andReturn(new Bundle[]{mockBundle});
         EasyMock.expect(mockBundleContext.getDataFile((String) EasyMock.anyObject())).andReturn(null).anyTimes();
         EasyMock.expect(mockBundle.getLocation()).andReturn(bundleLocation).anyTimes();
-        Map mockCurrentManagedArtifacts = (Map)EasyMock.createNiceMock(Map.class);
-        EasyMock.expect(mockCurrentManagedArtifacts.put(EasyMock.eq(bundleFile), (Artifact)EasyMock.anyObject())).andReturn(null).times(1);
 
-        EasyMock.replay(new Object[]{mockBundleContext, mockBundle, mockCurrentManagedArtifacts});
+        EasyMock.replay(mockBundleContext, mockBundle);
 
         props.put(DirectoryWatcher.DIR, watchedDirectoryPath);
 
         dw = new DirectoryWatcher(props, mockBundleContext);
         dw.noInitialDelay = true;
-        dw.currentManagedArtifacts = mockCurrentManagedArtifacts;
         dw.scanner = scanner;
         try {
         dw.start();
@@ -361,8 +355,10 @@
         {
             assertEquals(e, expectedException);
         }
+        assertEquals(1, dw.currentManagedArtifacts.size());
+        assertTrue(dw.currentManagedArtifacts.containsKey(bundleFile));
 
-        EasyMock.verify(new Object[]{mockBundleContext, mockBundle, mockCurrentManagedArtifacts});
+        EasyMock.verify(mockBundleContext, mockBundle);
     }
 
     /**
@@ -383,17 +379,17 @@
         final Scanner scanner = new Scanner(watchedDirectoryFile)
         {
             // bypass filesystem scan and return expected bundle file
-            public Set/*<File>*/ scan(boolean reportImmediately)
+            public Set<File> scan(boolean reportImmediately)
             {
-                Set/*<File>*/ fileSet = new HashSet/*<File>*/(1);
+                Set<File> fileSet = new HashSet<File>(1);
                 fileSet.add(bundleFile);
                 return fileSet;
             }
         };
 
-        final ArtifactListener mockArtifactListener = (ArtifactListener) EasyMock.createNiceMock(ArtifactListener.class);
-        EasyMock.expect(Boolean.valueOf(mockArtifactListener.canHandle(bundleFile))).andReturn(Boolean.TRUE).anyTimes();
-        final ServiceReference mockServiceReference = (ServiceReference) EasyMock.createNiceMock(ServiceReference.class);
+        final ArtifactListener mockArtifactListener = EasyMock.createNiceMock(ArtifactListener.class);
+        EasyMock.expect(mockArtifactListener.canHandle(bundleFile)).andReturn(Boolean.TRUE).anyTimes();
+        final ServiceReference mockServiceReference = EasyMock.createNiceMock(ServiceReference.class);
 
         // simulate known/installed bundles
         mockBundleContext.addBundleListener((BundleListener) org.easymock.EasyMock.anyObject());
@@ -401,7 +397,7 @@
         EasyMock.expect(mockBundleContext.getDataFile((String) EasyMock.anyObject())).andReturn(null).anyTimes();
         EasyMock.expect(mockBundle.getLocation()).andReturn(bundleLocation).anyTimes();
 
-        EasyMock.replay(new Object[]{mockBundleContext, mockBundle,mockServiceReference, mockArtifactListener});
+        EasyMock.replay(mockBundleContext, mockBundle,mockServiceReference, mockArtifactListener);
 
         final Artifact artifact = new Artifact();
         artifact.setBundleId(42);
@@ -415,7 +411,7 @@
 
         dw = new DirectoryWatcher(props, mockBundleContext) {
 
-            void refresh(Bundle[] bundles) throws InterruptedException {
+            void refresh(Collection<Bundle> bundles) throws InterruptedException {
                 Assert.fail("bundle refresh called");
             }
             
@@ -432,7 +428,7 @@
             assertEquals(e, expectedException);
         }
 
-        EasyMock.verify(new Object[]{mockBundleContext, mockBundle,mockServiceReference, mockArtifactListener});
+        EasyMock.verify(mockBundleContext, mockBundle,mockServiceReference, mockArtifactListener);
     }
 
 }
diff --git a/fileinstall/src/test/java/org/apache/felix/fileinstall/internal/MockServiceTracker.java b/fileinstall/src/test/java/org/apache/felix/fileinstall/internal/MockServiceTracker.java
deleted file mode 100644
index 6ec40e6..0000000
--- a/fileinstall/src/test/java/org/apache/felix/fileinstall/internal/MockServiceTracker.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.felix.fileinstall.internal;
-
-
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Filter;
-import org.osgi.framework.ServiceReference;
-import org.osgi.util.tracker.ServiceTracker;
-import org.osgi.util.tracker.ServiceTrackerCustomizer;
-
-
-/**
- * Mock class to simulate a ServiceTracker 
- * Use the public constructor to set the bundleContext and the 
- * service instance to be returned
- */
-public class MockServiceTracker extends ServiceTracker
-{
-    private Object service;
-
-
-    /**
-     * Use this constructor
-     * 
-     * @param context - the bundle context
-     * @param service - the service instance returned by getService()
-     */
-    public MockServiceTracker( BundleContext context, Object service )
-    {
-        super( context, service.getClass().getName(), null );
-        this.service = service;
-    }
-
-
-    MockServiceTracker( BundleContext context, Filter filter, ServiceTrackerCustomizer customizer )
-    {
-        super( context, filter, customizer );
-    }
-
-
-    MockServiceTracker( BundleContext arg0, ServiceReference arg1, ServiceTrackerCustomizer arg2 )
-    {
-        super( arg0, arg1, arg2 );
-    }
-
-
-    MockServiceTracker( BundleContext arg0, String arg1, ServiceTrackerCustomizer arg2 )
-    {
-        super( arg0, arg1, arg2 );
-    }
-
-
-    public Object waitForService( long arg0 ) throws InterruptedException
-    {
-        return service;
-    }
-
-
-    public Object getService()
-    {
-        return service;
-    }
-
-
-    public Object getService( ServiceReference reference )
-    {
-        return getService();
-    }
-
-}