incubator-aries-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From hugh...@apache.org
Subject svn commit: r820722 [8/8] - in /incubator/aries/contrib: ./ ibm/ ibm/aries.image/ ibm/build/ ibm/build/buildtasks/ ibm/build/buildtasks/src/ ibm/build/buildtasks/src/com/ ibm/build/buildtasks/src/com/ibm/ ibm/build/buildtasks/src/com/ibm/aries/ ibm/bui...
Date Thu, 01 Oct 2009 17:19:21 GMT
Added: incubator/aries/contrib/ibm/unittest.framework/src/mocks/BundleContextMock.java
URL: http://svn.apache.org/viewvc/incubator/aries/contrib/ibm/unittest.framework/src/mocks/BundleContextMock.java?rev=820722&view=auto
==============================================================================
--- incubator/aries/contrib/ibm/unittest.framework/src/mocks/BundleContextMock.java (added)
+++ incubator/aries/contrib/ibm/unittest.framework/src/mocks/BundleContextMock.java Thu Oct
 1 17:19:13 2009
@@ -0,0 +1,719 @@
+/*
+ * (C) Copyright IBM Corp. 2009
+ */
+package mocks;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.ArrayList;
+import java.util.Dictionary;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.jar.Attributes;
+import java.util.jar.JarInputStream;
+import java.util.jar.Manifest;
+
+import junit.framework.AssertionFailedError;
+
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleException;
+import org.osgi.framework.Constants;
+import org.osgi.framework.Filter;
+import org.osgi.framework.FrameworkUtil;
+import org.osgi.framework.InvalidSyntaxException;
+import org.osgi.framework.ServiceEvent;
+import org.osgi.framework.ServiceFactory;
+import org.osgi.framework.ServiceListener;
+import org.osgi.framework.ServiceReference;
+import org.osgi.framework.ServiceRegistration;
+
+import com.ibm.aries.unittest.mocks.Skeleton;
+
+/**
+ *
+ */
+/**
+ * This class is a partial implementation of BundleContext. Its main function
+ * is to provide a service registry implementation
+ */
+public class BundleContextMock
+{
+  /** The service registry */
+  private static Map<String, List<ServiceData>> registry = new HashMap<String,
List<ServiceData>>();
+  /** A list of bundles installed into the runtime */
+  private static List<Bundle> bundles = new ArrayList<Bundle>();
+  /** A list of service listeners */
+  private static List<ServiceListener> listeners = new ArrayList<ServiceListener>();
+  /** The next service id to be assigned */
+  private static long nextId = 0;
+
+  private static class MockServiceFactory implements ServiceFactory
+  {
+    private final Object service;
+    
+    public MockServiceFactory(Object obj)
+    {
+      service = obj;
+    }
+    
+    public Object getService(Bundle arg0, ServiceRegistration arg1)
+    {
+      return service;
+    }
+
+    public void ungetService(Bundle arg0, ServiceRegistration arg1, Object arg2)
+    {
+    }
+  }
+  
+  private static class FilteredServiceListener implements ServiceListener
+  {
+    private Filter filter;
+    private final ServiceListener listener;
+    
+    public FilteredServiceListener(String f, ServiceListener l)
+    {
+      listener = l;
+      
+      if (f != null) {
+        try {
+          filter = FrameworkUtil.createFilter(f);
+        } catch (InvalidSyntaxException e) {
+          AssertionFailedError err = new AssertionFailedError("The filter " + f + " is invalid");
+          err.initCause(e);
+          
+          throw err;
+        }
+      }
+    }
+
+    public void serviceChanged(ServiceEvent arg0)
+    {
+      if (matches(arg0)) listener.serviceChanged(arg0);
+    }
+
+    private boolean matches(ServiceEvent arg0)
+    {
+      if (filter == null) return true;
+      
+      ServiceReference ref = arg0.getServiceReference();
+      
+      if (Skeleton.isSkeleton(ref)) {
+        Object template = Skeleton.getSkeleton(ref).getTemplateObject();
+        
+        if (template instanceof ServiceData) {
+          return filter.match(((ServiceData)template).getProperties());
+        }
+      }
+      
+      return filter.match(ref);
+    }
+    
+    @Override
+    public boolean equals(Object obj)
+    {
+      if (obj == null) return false;
+      else if (obj instanceof FilteredServiceListener) {
+        return listener.equals(((FilteredServiceListener)obj).listener);
+      }
+      
+      return false;
+    }
+    
+    @Override
+    public int hashCode()
+    {
+      return listener.hashCode();
+    }
+  }
+  
+  /**
+   * This class represents the information registered about a service. It also
+   * implements part of the ServiceRegistration and ServiceReference interfaces.
+   */
+  private class ServiceData
+  {
+    /** The service that was registered */
+    private ServiceFactory serviceImpl;
+    /** the service properties */
+    @SuppressWarnings("unused")
+    private final Hashtable<String, Object> serviceProps = new Hashtable<String,
Object>();
+    /** The interfaces the service publishes with */
+    private String[] interfaceNames;
+
+    /**
+     * This method unregisters the service from the registry.
+     */
+    public void unregister()
+    {
+      for (String interfaceName : interfaceNames) {
+        List<ServiceData> list = registry.get(interfaceName);
+        if (list != null) {
+          list.remove(this);
+          if (list.isEmpty()) {
+            registry.remove(interfaceName);
+          }
+        }
+      }
+      notifyAllListeners(ServiceEvent.UNREGISTERING);
+    }
+
+    /**
+     * This method is used to register the service data in the registry
+     */
+    public void register()
+    {
+      for (String interfaceName : interfaceNames) {
+        List<ServiceData> list = registry.get(interfaceName);
+        if (list == null) {
+          list = new ArrayList<ServiceData>();
+          registry.put(interfaceName, list);
+        }
+        list.add(this);
+      }
+      notifyAllListeners(ServiceEvent.REGISTERED);
+    }
+    
+    private void notifyAllListeners(int eventType) {
+      List<ServiceListener> copy = new ArrayList<ServiceListener>(listeners.size());
+      copy.addAll(listeners);
+      for(ServiceListener listener : copy) {
+        listener.serviceChanged(new ServiceEvent(eventType, Skeleton.newMock(this, ServiceReference.class)));
+      }
+    }
+    
+    /**
+     * Change the service properties
+     * @param newProps
+     */
+    public void setProperties(Dictionary<String,Object> newProps)
+    {
+      // make sure we don't overwrite framework properties
+      newProps.put(Constants.OBJECTCLASS, serviceProps.get(Constants.OBJECTCLASS));
+      newProps.put(Constants.SERVICE_ID, serviceProps.get(Constants.SERVICE_ID));
+
+      Enumeration<String> keys = newProps.keys();
+      
+      serviceProps.clear();
+      while (keys.hasMoreElements()) {
+        String key = keys.nextElement();
+        serviceProps.put(key, newProps.get(key));
+      }
+      
+      notifyAllListeners(ServiceEvent.MODIFIED);
+    }
+    
+    /**
+     * This implements the isAssignableTo method from ServiceReference.
+     * 
+     * @param b
+     * @param className
+     * @return true if the referenced service can be assigned to the requested
+     *              class name.
+     */
+    public boolean isAssignableTo(Bundle b, String className)
+    {
+      boolean result = false;
+      
+      for (String iName : interfaceNames)
+      {
+        result = iName.equals(className);
+        
+        if (result) break;
+      }
+      
+      return result;
+    }
+    
+    /**
+     * Returns the requested service property.
+     * @param key the property to return.
+     * @return the property value.
+     */
+    public Object getProperty(String key)
+    {
+      return serviceProps.get(key);
+    }
+    
+    @Override
+    public boolean equals(Object o) {
+      if(o == null) return false;
+      
+      if(o == this) return true;
+      
+      if (o instanceof ServiceData) {
+        ServiceData other = (ServiceData) o;
+        return serviceImpl == other.serviceImpl;
+      }
+      
+      return false;
+    }
+    
+    @Override
+    public int hashCode()
+    {
+      return serviceImpl.hashCode();
+    }
+    
+    /**
+     * @return the keys of all the service properties.
+     */
+    public String[] getPropertyKeys()
+    {
+      Enumeration<String> e = serviceProps.keys();
+      
+      String[] toReturn = new String[serviceProps.size()];
+      
+      for(int i = 0 ; i < serviceProps.size(); i++)
+        toReturn[i] = e.nextElement();
+      
+      return toReturn;
+    }
+    
+    /**
+     * @return the bundle this service reference was registered against.
+     */
+    public Bundle getBundle()
+    {
+      return bundle;
+    }
+    
+    /**
+     * @return a service reference for this service registration.
+     */
+    public ServiceReference getReference()
+    {
+      return Skeleton.newMock(this, ServiceReference.class);
+    }
+    
+    public Hashtable<String, Object> getProperties()
+    {
+      return new Hashtable<String, Object>(serviceProps);
+    }
+  }
+
+  /** The bundle associated with this bundle context */
+  private Bundle bundle;
+
+  /**
+   * Default constructor, widely used in the tests.
+   */
+  public BundleContextMock()
+  {
+    
+  }
+  
+  /**
+   * Constructor used by BundleMock, it ensures the bundle and its context are wired together
correctly.
+   * 
+   * TODO We have to many Bundle mocks objects for a single OSGi bundle, we need to update
this.
+   * 
+   * @param b
+   */
+  public BundleContextMock(Bundle b)
+  {
+    bundle = b;
+  }
+  
+  /**
+   * This checks that we have at least one service with this interface name.
+   * 
+   * @param interfaceName the name of the interface.
+   */
+  public static void assertServiceExists(String interfaceName)
+  {
+    assertTrue("No service registered with interface " + interfaceName + ". Services found:
" + registry.keySet(), registry.containsKey(interfaceName));
+  }
+  
+  /**
+   * This checks that we have at no services with this interface name.
+   * 
+   * @param interfaceName the name of the interface.
+   */
+  public static void assertNoServiceExists(String interfaceName)
+  {
+    assertFalse("Services registered with interface " + interfaceName + ". Services found:
" + registry.keySet(), registry.containsKey(interfaceName));
+  }
+  
+  /**
+   * This implements the registerService method from BundleContext.
+   * 
+   * @param interFace
+   * @param service
+   * @param properties
+   * @return the ServiceRegistration object for this service.
+   */
+  public ServiceRegistration registerService(String interFace, final Object service, Dictionary<String,
Object> properties)
+  {
+    // validate that the service implements interFace
+    try {
+      Class<?> clazz = Class.forName(interFace, false, service.getClass().getClassLoader());
+      
+      if (!!!clazz.isInstance(service) && !!!(service instanceof ServiceFactory))
{
+        throw new AssertionFailedError("The service " + service + " does not implement "
+ interFace);
+      }
+    } catch (ClassNotFoundException e) {
+      // TODO Auto-generated catch block
+      e.printStackTrace();
+    }
+
+    ServiceFactory factory = new MockServiceFactory(service);
+    return registerService(new String[] {interFace}, factory, properties);
+  }
+  
+  /**
+   * This implements the registerService method from BundleContext.
+   * 
+   * @param interfaces
+   * @param service
+   * @param properties
+   * @return the ServiceRegistration object for this service.
+   */
+  public ServiceRegistration registerService(String[] interfaces, Object service, Dictionary<String,
Object> properties)
+  {
+    if (properties == null) properties = new Hashtable<String, Object>();
+    
+    ServiceData data = new ServiceData();
+    // cast the service to a service factory because in our framework we only ever register
+    // a service factory. If we every put a non-service factory object in that is a failure.
+    properties.put(Constants.OBJECTCLASS, interfaces);
+    properties.put(Constants.SERVICE_ID, nextId++);
+    if (service instanceof ServiceFactory) {
+      data.serviceImpl = (ServiceFactory)service;
+    } else {
+      data.serviceImpl = new MockServiceFactory(service);
+    }
+    data.interfaceNames = interfaces;
+    
+    Enumeration<String> keys = properties.keys();
+    
+    while (keys.hasMoreElements()) {
+      String key = keys.nextElement();
+      data.serviceProps.put(key, properties.get(key));
+    }
+    
+    data.register();
+    
+    return Skeleton.newMock(data, ServiceRegistration.class);
+  }
+
+  /**
+   * This helper method is used to get the service from the registry with the
+   * given interface name.
+   * 
+   * <p>This should really return multiple services.
+   * </p>
+   * 
+   * @param interfaceName the interface name.
+   * @param bundle        the bundle name.
+   * @return the registered service.
+   */
+  public static Object getService(String interfaceName, Bundle bundle)
+  {
+    List<ServiceData> datum = registry.get(interfaceName);
+    
+    if (datum == null) return null;
+    else if (datum.isEmpty()) return null;
+    // this is safe for now, but may not be when we do other scoped components.
+    else {
+      ServiceRegistration reg = Skeleton.newMock(ServiceRegistration.class);
+      return datum.iterator().next().serviceImpl.getService(bundle, reg);
+    }
+  }
+  
+  /**
+   * A mock implementation of the getServiceReferences method. It does not currently
+   * process the filter, this is probably a bit hard, so we might cheat when we do.
+   * 
+   * <p>Note this does not check that the service classes are visible to the
+   *   caller as OSGi does. It is equivalent to getAllServiceReferences.
+   * </p>
+   * 
+   * @param className the name of the class the lookup is for.
+   * @param filter
+   * @return an array of matching service references.
+   * @throws InvalidSyntaxException
+   */
+  public ServiceReference[] getServiceReferences(String className, String filter) throws
InvalidSyntaxException
+  {
+    List<ServiceData> data = new ArrayList<ServiceData>();
+    
+    if (className != null) {
+      List<ServiceData> tmpData = registry.get(className);
+      if (tmpData != null) data.addAll(tmpData);
+    } else {
+      data = new ArrayList<ServiceData>();
+      for (List<ServiceData> value : registry.values())
+      data.addAll(value);
+    }
+    
+    ServiceReference[] refs;
+
+    if (data == null) {
+      refs = null;
+    } else {
+      
+      if (filter != null) {
+        Filter f = FrameworkUtil.createFilter(filter);
+        
+        Iterator<ServiceData> it = data.iterator();
+        
+        while (it.hasNext()) {
+          ServiceData sd = it.next();
+          
+          if (!!!f.match(sd.getProperties())) it.remove();
+        }
+      }
+      
+      if (data.isEmpty()) return null;
+      
+      refs = new ServiceReference[data.size()];
+      for (int i = 0; i < refs.length; i++) {
+        refs[i] = Skeleton.newMock(data.get(i), ServiceReference.class);
+      }
+    }
+    
+    return refs;
+  }
+  
+  /**
+   * Gets the first matching service reference.
+   * 
+   * @param className the class name wanted.
+   * @return the matchine service, or null if one cannot be found.
+   */
+  public ServiceReference getServiceReference(String className)
+  {
+    ServiceReference[] refs;
+    try {
+      refs = getServiceReferences(className, null);
+      if (refs != null) return refs[0];
+      
+      return null;
+    } catch (InvalidSyntaxException e) {
+      // should never happen.
+      e.printStackTrace();
+    }
+    return null;
+  }
+  
+  /**
+   * This method finds all the service references in the registry with the
+   * matching class name and filter.
+   * 
+   * @param className
+   * @param filter
+   * @return the matching service references.
+   * @throws InvalidSyntaxException
+   */
+  public ServiceReference[] getAllServiceReferences(String className, String filter) throws
InvalidSyntaxException
+  {
+    return getServiceReferences(className, filter);
+  }
+  
+  /**
+   * Retrieve a service from the registry.
+   * @param ref the service reference.
+   * @return    the returned service.
+   */
+  public Object getService(ServiceReference ref)
+  {
+    ServiceData data = (ServiceData)Skeleton.getSkeleton(ref).getTemplateObject();
+    
+    return data.serviceImpl.getService(getBundle(), Skeleton.newMock(data, ServiceRegistration.class));
+  }
+  
+  /**
+   * This method implements the installBundle method from BundleContext. It
+   * makes use of the java.util.jar package to parse the manifest from the input
+   * stream.
+   * 
+   * @param location the location of the bundle.
+   * @param is       the input stream to read from.
+   * @return         the created bundle.
+   * @throws BundleException
+   */
+  public Bundle installBundle(String location, InputStream is) throws BundleException
+  {
+    Bundle b;
+    JarInputStream jis;
+    try {
+      jis = new JarInputStream(is);
+
+      Manifest man = jis.getManifest();
+      
+      b = createBundle(man, null);
+      
+    } catch (IOException e) {
+      throw new BundleException(e.getMessage(), e);
+    }
+    
+    return b;
+  }
+
+  /**
+   * Create a mock bundle correctly configured using the supplied manifest and
+   * location.
+   * 
+   * @param man      the manifest to load.
+   * @param location the location on disk.
+   * @return the created bundle
+   * @throws MalformedURLException
+   */
+  private Bundle createBundle(Manifest man, String location) throws MalformedURLException
+  {
+    Attributes attribs = man.getMainAttributes();
+    String symbolicName = attribs.getValue(Constants.BUNDLE_SYMBOLICNAME);
+    
+    Hashtable<Object, Object> attribMap = new Hashtable<Object, Object>();
+    
+    for (Map.Entry<Object, Object> entry : attribs.entrySet()) {
+      Attributes.Name name = (Attributes.Name)entry.getKey();
+      attribMap.put(name.toString(), entry.getValue());
+    }
+    
+    BundleMock mock = new BundleMock(symbolicName, attribMap, location);
+
+    mock.addToClassPath(new File("build/unittest/classes").toURL());
+
+    Bundle b = Skeleton.newMock(mock, Bundle.class);
+    
+    bundles.add(b);
+
+    return b;
+  }
+  
+  /**
+   * Asks to install an OSGi bundle from the given location.
+   * 
+   * @param location the location of the bundle on the file system.
+   * @return the installed bundle.
+   * @throws BundleException
+   */
+  public Bundle installBundle(String location) throws BundleException
+  {
+    try {
+      URI uri = new URI(location.replaceAll(" ", "%20"));
+
+      File baseDir = new File(uri);
+      Manifest man = null;
+      //check if it is a directory
+      if (baseDir.isDirectory()){
+      man = new Manifest(new FileInputStream(new File(baseDir, "META-INF/MANIFEST.MF")));
+      }
+      //if it isn't assume it is a jar file
+      else{
+        InputStream is = new FileInputStream(baseDir);
+        JarInputStream jis = new JarInputStream(is);
+        man = jis.getManifest();
+        jis.close();
+        if (man == null){
+          throw new BundleException("Null manifest");
+        }
+      }
+      
+      return createBundle(man, location);
+    } catch (IOException e) {
+      throw new BundleException(e.getMessage(), e);
+    } catch (URISyntaxException e) {
+      // TODO Auto-generated catch block
+      throw new BundleException(e.getMessage(), e);
+    }
+  }
+  
+  /**
+   * @return all the bundles in the system
+   */
+    public Bundle[] getBundles()
+  {
+    return bundles.toArray(new Bundle[bundles.size()]);
+  }
+  
+  /**
+   * Add a service listener.
+   * 
+   * @param listener
+   * @param filter
+   */
+  public void addServiceListener(ServiceListener listener, String filter)
+  {
+    listeners.add(new FilteredServiceListener(filter, listener));
+  }
+
+  /**
+   * Add a service listener.
+   * 
+   * @param listener
+   */
+  public void addServiceListener(ServiceListener listener) 
+  {
+    listeners.add(listener);
+  }
+  
+  /**
+   * Remove a service listener
+   * @param listener
+   */
+  public void removeServiceListener(ServiceListener listener)
+  {
+    listeners.remove(new FilteredServiceListener(null, listener));
+  }
+  
+  public String getProperty(String name)
+  {
+    if (Constants.FRAMEWORK_VERSION.equals(name)) {
+      return "4.1";
+    }
+    /*added System.getProperty so that tests can set a system property
+     * but it is retrieved via the BundleContext.
+     * This allows tests to emulate different properties being set on the
+     * context, helpful for the feature pack launcher/kernel relationship
+     */
+    else if (System.getProperty(name) != null){
+      return System.getProperty(name);
+    }
+    
+    return "";
+  }
+  
+  /**
+   * @return the bundle associated with this bundle context (if we created one).
+   */
+  public Bundle getBundle()
+  {
+    return bundle;
+  }
+  
+  /**
+   * This method clears the service registry.
+   */
+  public static void clear()
+  {
+    registry.clear();
+    bundles.clear();
+    listeners.clear();
+    nextId = 0;
+  }
+  
+  public static List<ServiceListener> getServiceListeners()
+  {
+    return listeners;
+  }
+
+  public void addBundle(Bundle b)
+  {
+    bundles.add(b);
+  }
+}
\ No newline at end of file

Added: incubator/aries/contrib/ibm/unittest.framework/src/mocks/BundleMock.java
URL: http://svn.apache.org/viewvc/incubator/aries/contrib/ibm/unittest.framework/src/mocks/BundleMock.java?rev=820722&view=auto
==============================================================================
--- incubator/aries/contrib/ibm/unittest.framework/src/mocks/BundleMock.java (added)
+++ incubator/aries/contrib/ibm/unittest.framework/src/mocks/BundleMock.java Thu Oct  1 17:19:13
2009
@@ -0,0 +1,376 @@
+/*
+ * (C) Copyright IBM Corp. 2009
+ */
+package mocks;
+
+import java.io.File;
+import java.io.FileFilter;
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Dictionary;
+import java.util.Enumeration;
+import java.util.List;
+import java.util.Vector;
+import java.util.regex.Pattern;
+
+import junit.framework.AssertionFailedError;
+
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.BundleReference;
+import org.osgi.framework.Constants;
+import org.osgi.framework.Version;
+
+import com.ibm.aries.unittest.mocks.MethodCall;
+import com.ibm.aries.unittest.mocks.MethodCallHandler;
+import com.ibm.aries.unittest.mocks.Skeleton;
+import com.ibm.aries.unittest.mocks.annotations.Singleton;
+
+@Singleton
+public class BundleMock
+{
+  private final String symbolicName;
+  private final Dictionary<?, ?> headers;
+  private final BundleContext bc;
+  private String location;
+  private BundleClassLoader cl;
+  
+  private class BundleClassLoader extends URLClassLoader implements BundleReference
+  {
+    List<Bundle> otherBundlesToCheck = new ArrayList<Bundle>();
+    
+    public BundleClassLoader(URL[] urls)
+    {
+      super(urls);
+    }
+
+    public BundleClassLoader(URL[] urls, ClassLoader parent)
+    {
+      super(urls, parent);
+    }
+    
+    public void addBundle(Bundle ... otherBundles)
+    {
+      otherBundlesToCheck.addAll(Arrays.asList(otherBundles));
+    }
+    
+    public Bundle[] getBundles()
+    {
+      return otherBundlesToCheck.toArray(new Bundle[otherBundlesToCheck.size()]);
+    }
+
+    @Override
+    protected Class<?> findClass(String name) throws ClassNotFoundException
+    {
+      Class<?> result = null;
+      for (Bundle b : otherBundlesToCheck) {
+        try {
+          result = b.loadClass(name);
+        } catch (ClassNotFoundException e) {
+          // do nothing here.
+        }
+        
+        if (result != null) return result;
+      }
+      
+      return super.findClass(name);
+    }
+
+    public Bundle getBundle()
+    {
+      return Skeleton.newMock(BundleMock.this, Bundle.class);
+    }
+  }
+  
+  public BundleMock(String name, Dictionary<?, ?> bundleHeaders)
+  {
+    symbolicName = name;
+    headers = bundleHeaders;
+    bc = Skeleton.newMock(new BundleContextMock(Skeleton.newMock(this, Bundle.class)), BundleContext.class);
+    
+    cl = AccessController.doPrivileged(new PrivilegedAction<BundleClassLoader>() {
+
+      public BundleClassLoader run()
+      {
+        return new BundleClassLoader(new URL[0], this.getClass().getClassLoader());
+      }
+    });
+  }
+  
+  public BundleMock(String name, Dictionary<?,?> bundleHeaders, boolean dummy)
+  {
+    this(name, bundleHeaders);
+    
+    cl = null;
+  }
+  
+  public BundleMock(String name, Dictionary<?, ?> bundleHeaders, String location)
+  {
+    this(name, bundleHeaders);
+    this.location = location;
+        
+    if (location != null) {
+      String cp = (String)bundleHeaders.get(Constants.BUNDLE_CLASSPATH);
+      
+      if (cp == null) cp = ".";
+      
+      String[] cpEntries = cp.split(",");
+      
+      final List<URL> urls = new ArrayList<URL>();
+      
+      try {
+        for (String cpEntry : cpEntries) {
+          if (".".equals(cpEntry.trim())) {
+            urls.add(new URL(location));
+          } else {
+            urls.add(new URL(location + "/" + cpEntry));
+          }
+        }
+        
+        cl = AccessController.doPrivileged(new PrivilegedAction<BundleClassLoader>()
{
+          public BundleClassLoader run()
+          {
+            return new BundleClassLoader(urls.toArray(new URL[urls.size()]));
+          }
+        });
+      } catch (MalformedURLException e) {
+        Error err = new AssertionFailedError("The location was not a valid url");
+        err.initCause(e);
+        throw err;
+      }
+    }
+  }
+  
+  private static class PrivateDataFileHandler implements MethodCallHandler
+  {
+    private final File location;
+    
+    public PrivateDataFileHandler(File f)
+    {
+      this.location = f;
+    }
+    
+    public Object handle(MethodCall call, Skeleton parent)
+    {
+      File privateStorage = new File(location.getAbsolutePath(), "_private");
+      if (!!!privateStorage.exists())
+        privateStorage.mkdirs();
+      
+      return new File(privateStorage, (String) call.getArguments()[0]);
+    }
+  }
+  
+  public BundleMock(String name, Dictionary<?, ?> properties, File location) throws
Exception
+  {
+    this(name,properties,location.toURL().toExternalForm());
+    
+    Skeleton bcSkel = Skeleton.getSkeleton(bc);
+    bcSkel.registerMethodCallHandler(
+        new MethodCall(BundleContext.class,"getDataFile", new Object[] { String.class }),
+        new PrivateDataFileHandler(location)
+    );
+  }
+  
+  public String getSymbolicName()
+  {
+    return symbolicName;
+  }
+  
+  public Dictionary<?, ?> getHeaders()
+  {
+    return headers;
+  }
+  
+  public Enumeration<URL> findEntries(String baseDir, String matchRule, boolean recurse)
+  {
+    System.err.println("findEntries: " + baseDir + ", " + matchRule + ", " + recurse);
+    File base;
+    try {
+      base = new File(new File(new URL(location.replaceAll(" ", "%20")).toURI()), baseDir);
+      System.err.println("Base dir: " + base);
+    } catch (Exception e) {
+      Error err = new AssertionFailedError("Unable to findEntries from " + location);
+      err.initCause(e);
+      throw err;
+    }
+    
+    if (matchRule.equals("*.xml")) matchRule = ".*\\.xml";
+    else matchRule = matchRule.replaceAll("\\*", ".*");
+    
+    System.err.println("matchrule: " + matchRule);
+    
+    final Pattern p = Pattern.compile(matchRule);
+    
+    File[] files = base.listFiles(new FileFilter(){
+      public boolean accept(File pathname)
+      {
+        return pathname.isFile() &&
+               p.matcher(pathname.getName()).matches();
+      }
+    });
+    
+    Vector<URL> v = new Vector<URL>();
+    
+    if (files != null) {
+      for (File f : files) {
+        try {
+          v.add(f.toURL());
+        } catch (MalformedURLException e) {
+          // TODO Auto-generated catch block
+          e.printStackTrace();
+        }
+      }
+    } else {
+      System.err.println("no matching files");
+    }
+    
+    if (v.isEmpty()) {
+      return null;
+    } else {
+      System.err.println(v);
+      return v.elements();
+    }
+  }
+  
+  public URL getResource(String name)
+  {
+    if (cl != null) return cl.getResource(name);
+    
+    try {
+      File f = new File(name);
+      if(f.exists() || "Entities.jar".equals(name)) return f.toURL();
+      else return null;
+    } catch (MalformedURLException e) {
+      Error err = new AssertionFailedError("The resource " + name + " could not be found.");
+      err.initCause(e);
+      throw err;
+    }
+  }
+  
+  public Enumeration<URL> getResources(String name)
+  {
+    if (cl != null)
+    {
+      try {
+        return cl.getResources(name);
+      } catch (IOException e) {
+      // TODO Auto-generated catch block
+        e.printStackTrace();
+      }
+    }
+    else {
+      final URL resource = getResource(name);
+      
+      if(resource != null) {
+        return new Enumeration<URL>() {
+
+          boolean hasMore = true;
+          public boolean hasMoreElements()
+          {
+            return hasMore;
+          }
+
+          public URL nextElement()
+          {
+            hasMore = false;
+            return resource;
+          }
+          
+        };
+      }
+    }
+    return new Enumeration<URL>(){
+      public URL nextElement()
+      {
+        return null;
+      }
+
+      public boolean hasMoreElements()
+      {
+        return false;
+      }
+    };
+    
+  }
+  
+  public Class<?> loadClass(String name) throws ClassNotFoundException
+  {
+    if (cl != null) return Class.forName(name, false, cl);
+    
+    throw new ClassNotFoundException("Argh, things went horribly wrong trying to load " +
name);
+  }
+  
+  public String getLocation()
+  {
+    try {
+      return (location == null) ? new File(symbolicName + ".jar").toURL().toString() : location;
+    } catch (MalformedURLException e) {
+      Error err = new AssertionFailedError("We could not generate a valid url for the bundle");
+      err.initCause(e);
+      throw err;
+    }
+  }
+  
+  public BundleContext getBundleContext()
+  {
+    return bc;
+  }
+
+  public Version getVersion()
+  {
+    String res = (String) headers.get("Bundle-Version");
+    if (res != null)
+      return new Version(res);
+    else
+      return new Version("0.0.0");
+  }
+  
+  public int getState()
+  {
+    return Bundle.ACTIVE;
+  }
+
+  public void addToClassPath(URL ... urls)
+  {
+    if (cl != null) {
+      URL[] existingURLs = cl.getURLs();
+      final URL[] mergedURLs = new URL[urls.length + existingURLs.length];
+      int i = 0;
+      for (; i < existingURLs.length; i++) {
+        mergedURLs[i] = existingURLs[i];
+      }
+      
+      for (int j = 0; j < urls.length; j++, i++) {
+        mergedURLs[i] = urls[j];
+      }
+      
+      BundleClassLoader newCl = AccessController.doPrivileged(new PrivilegedAction<BundleClassLoader>()
{
+
+        public BundleClassLoader run()
+        {
+          return new BundleClassLoader(mergedURLs, cl.getParent());
+        }
+        
+      });
+      newCl.addBundle(cl.getBundles());
+      cl = newCl;
+    }
+  }
+    
+  public void addBundleToClassPath(Bundle ... bundles) {
+    if (cl != null) {
+      cl.addBundle(bundles);
+    }
+  }
+
+  public ClassLoader getClassLoader()
+  {
+    return cl;
+  }
+}
\ No newline at end of file

Added: incubator/aries/contrib/ibm/unittest.framework/src/mocks/MockInitialContextFactoryBuilder.java
URL: http://svn.apache.org/viewvc/incubator/aries/contrib/ibm/unittest.framework/src/mocks/MockInitialContextFactoryBuilder.java?rev=820722&view=auto
==============================================================================
--- incubator/aries/contrib/ibm/unittest.framework/src/mocks/MockInitialContextFactoryBuilder.java
(added)
+++ incubator/aries/contrib/ibm/unittest.framework/src/mocks/MockInitialContextFactoryBuilder.java
Thu Oct  1 17:19:13 2009
@@ -0,0 +1,41 @@
+/*
+ * (C) Copyright IBM Corp. 2009
+ */
+package mocks;
+
+import java.util.Hashtable;
+
+import javax.naming.Context;
+import javax.naming.NamingException;
+import javax.naming.spi.InitialContextFactory;
+import javax.naming.spi.InitialContextFactoryBuilder;
+import javax.naming.spi.NamingManager;
+
+import com.ibm.aries.unittest.mocks.MethodCall;
+import com.ibm.aries.unittest.mocks.Skeleton;
+
+public class MockInitialContextFactoryBuilder implements InitialContextFactoryBuilder
+{
+  private static InitialContextFactory icf;
+  
+  public InitialContextFactory createInitialContextFactory(Hashtable<?, ?> environment)
+      throws NamingException
+  {
+    return icf;
+  }
+  
+  public static void start(Context ctx) throws NamingException
+  {
+    if (icf == null) {
+      NamingManager.setInitialContextFactoryBuilder(new MockInitialContextFactoryBuilder());
+    }
+    
+    icf = Skeleton.newMock(InitialContextFactory.class);
+    getSkeleton().setReturnValue(new MethodCall(InitialContextFactory.class, "getInitialContext",
Hashtable.class), ctx);
+  }
+  
+  public static Skeleton getSkeleton()
+  {
+    return Skeleton.getSkeleton(icf);
+  }
+}
\ No newline at end of file



Mime
View raw message