Search in sources :

Example 11 with WeavingHook

use of org.osgi.framework.hooks.weaving.WeavingHook in project rt.equinox.framework by eclipse.

the class ClassLoaderHookTests method testRejectTransformationFromWeavingHook.

public void testRejectTransformationFromWeavingHook() throws Exception {
    setRejectTransformation(true);
    initAndStartFramework();
    framework.getBundleContext().registerService(WeavingHook.class, new WeavingHook() {

        @Override
        public void weave(WovenClass wovenClass) {
            wovenClass.setBytes(new byte[] { 'b', 'a', 'd', 'b', 'y', 't', 'e', 's' });
            wovenClass.getDynamicImports().add("badimport");
        }
    }, null);
    Bundle b = installBundle();
    b.loadClass(TEST_CLASSNAME);
    // class load must succeed because the badbytes got rejected
    // make sure we don't have any dynamic imports added
    assertEquals("Found some imports.", 0, b.adapt(BundleRevision.class).getWiring().getRequirements(PackageNamespace.PACKAGE_NAMESPACE).size());
    // no don't reject
    setRejectTransformation(false);
    refreshBundles(Collections.singleton(b));
    try {
        b.loadClass(TEST_CLASSNAME);
        fail("Expected a ClassFormatError.");
    } catch (ClassFormatError e) {
    // expected
    }
    // class load must fail because the badbytes got used to define the class
    // make sure we have a dynamic imports added
    assertEquals("Found some imports.", 1, b.adapt(BundleRevision.class).getWiring().getRequirements(PackageNamespace.PACKAGE_NAMESPACE).size());
}
Also used : WovenClass(org.osgi.framework.hooks.weaving.WovenClass) WeavingHook(org.osgi.framework.hooks.weaving.WeavingHook)

Example 12 with WeavingHook

use of org.osgi.framework.hooks.weaving.WeavingHook in project rt.equinox.framework by eclipse.

the class ClassLoadingBundleTests method testRecursiveWeavingHookFactory.

public void testRecursiveWeavingHookFactory() {
    final ThreadLocal<Boolean> testThread = new ThreadLocal<Boolean>() {

        @Override
        protected Boolean initialValue() {
            return Boolean.FALSE;
        }
    };
    testThread.set(Boolean.TRUE);
    final Set<String> weavingHookClasses = new HashSet<String>();
    final List<WovenClass> called = new ArrayList<WovenClass>();
    final AtomicBoolean loadNewClassInWeave = new AtomicBoolean(false);
    ServiceFactory<WeavingHook> topFactory = new ServiceFactory<WeavingHook>() {

        @Override
        public WeavingHook getService(Bundle bundle, ServiceRegistration<WeavingHook> registration) {
            if (!testThread.get()) {
                return null;
            }
            WeavingHook hook = new WeavingHook() {

                @Override
                public void weave(WovenClass wovenClass) {
                    if (loadNewClassInWeave.get()) {
                        // Force a load of inner class
                        Runnable run = new Runnable() {

                            @Override
                            public void run() {
                            // nothing
                            }
                        };
                        run.run();
                        weavingHookClasses.add(run.getClass().getName());
                    }
                    called.add(wovenClass);
                }
            };
            weavingHookClasses.add(hook.getClass().getName());
            return hook;
        }

        @Override
        public void ungetService(Bundle bundle, ServiceRegistration<WeavingHook> registration, WeavingHook service) {
        // nothing
        }
    };
    ServiceRegistration<WeavingHook> reg = getContext().registerService(WeavingHook.class, topFactory, null);
    Runnable run = null;
    try {
        // force call to factory without protection of the framework recursion checks
        topFactory.getService(null, null);
        // set flag to load inner class while weaving
        loadNewClassInWeave.set(true);
        // Force a load of inner class
        run = new Runnable() {

            @Override
            public void run() {
            // nothing
            }
        };
        run.run();
    } finally {
        reg.unregister();
    }
    assertEquals("Unexpected number of woven classes.", 3, called.size());
    for (WovenClass wovenClass : called) {
        if (weavingHookClasses.contains(wovenClass.getClassName())) {
            assertNull("Did not expect to find class: " + wovenClass.getDefinedClass(), wovenClass.getDefinedClass());
        } else {
            assertEquals("Expected the inner runnable class.", run.getClass(), wovenClass.getDefinedClass());
        }
    }
}
Also used : ServiceFactory(org.osgi.framework.ServiceFactory) Bundle(org.osgi.framework.Bundle) WovenClass(org.osgi.framework.hooks.weaving.WovenClass) ArrayList(java.util.ArrayList) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) WeavingHook(org.osgi.framework.hooks.weaving.WeavingHook) HashSet(java.util.HashSet) ServiceRegistration(org.osgi.framework.ServiceRegistration)

Example 13 with WeavingHook

use of org.osgi.framework.hooks.weaving.WeavingHook in project rt.equinox.framework by eclipse.

the class SystemBundleTests method testBug413879.

public void testBug413879() {
    // $NON-NLS-1$
    File config = OSGiTestsActivator.getContext().getDataFile(getName());
    Map<String, Object> configuration = new HashMap<String, Object>();
    configuration.put(Constants.FRAMEWORK_STORAGE, config.getAbsolutePath());
    Equinox equinox = new Equinox(configuration);
    try {
        equinox.start();
    } catch (BundleException e) {
        // $NON-NLS-1$
        fail("Unexpected exception in start()", e);
    }
    BundleContext systemContext = equinox.getBundleContext();
    // $NON-NLS-1$
    assertNotNull("System context is null", systemContext);
    Bundle test1 = null;
    try {
        test1 = systemContext.installBundle(installer.getBundleLocation("substitutes.a"));
    } catch (BundleException e) {
        // $NON-NLS-1$
        fail("Unexpected error installing bundle", e);
    }
    final Bundle testFinal1 = test1;
    ServiceRegistration reg = systemContext.registerService(WeavingHook.class, new WeavingHook() {

        public void weave(WovenClass wovenClass) {
            if (!testFinal1.equals(wovenClass.getBundleWiring().getBundle()))
                return;
            if (!"substitutes.x.Ax".equals(wovenClass.getClassName()))
                return;
            List dynamicImports = wovenClass.getDynamicImports();
            dynamicImports.add("*");
        }
    }, null);
    ServiceRegistration<ResolverHookFactory> resolverHookReg = systemContext.registerService(ResolverHookFactory.class, new ResolverHookFactory() {

        @Override
        public ResolverHook begin(Collection<BundleRevision> triggers) {
            // just trying to delay the resolve so that we get two threads trying to apply off the same snapshot
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException(e);
            }
            return null;
        }
    }, null);
    final Set<Throwable> errors = Collections.newSetFromMap(new ConcurrentHashMap<Throwable, Boolean>());
    try {
        Runnable dynamicLoadClass = new Runnable() {

            @Override
            public void run() {
                try {
                    testFinal1.loadClass("substitutes.x.Ax");
                    testFinal1.loadClass("org.osgi.framework.hooks.bundle.FindHook");
                } catch (Throwable t) {
                    errors.add(t);
                }
            }
        };
        Thread t1 = new Thread(dynamicLoadClass, getName() + "-1");
        Thread t2 = new Thread(dynamicLoadClass, getName() + "-2");
        t1.start();
        t2.start();
        t1.join();
        t2.join();
    } catch (Throwable t) {
        fail("Unexpected testing bundle", t);
    } finally {
        reg.unregister();
        resolverHookReg.unregister();
    }
    // put the framework back to the RESOLVED state
    try {
        equinox.stop();
    } catch (BundleException e) {
        // $NON-NLS-1$
        fail("Unexpected error stopping framework", e);
    }
    try {
        equinox.waitForStop(10000);
    } catch (InterruptedException e) {
        // $NON-NLS-1$
        fail("Unexpected interrupted exception", e);
    }
    if (!errors.isEmpty()) {
        fail("Failed to resolve dynamic", errors.iterator().next());
    }
}
Also used : ResolverHookFactory(org.osgi.framework.hooks.resolver.ResolverHookFactory) LinkedHashMap(java.util.LinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ResolverHook(org.osgi.framework.hooks.resolver.ResolverHook) WovenClass(org.osgi.framework.hooks.weaving.WovenClass) BundleRevision(org.osgi.framework.wiring.BundleRevision) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) List(java.util.List) BundleException(org.osgi.framework.BundleException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ServiceRegistration(org.osgi.framework.ServiceRegistration) Bundle(org.osgi.framework.Bundle) Equinox(org.eclipse.osgi.launch.Equinox) File(java.io.File) WeavingHook(org.osgi.framework.hooks.weaving.WeavingHook) BundleContext(org.osgi.framework.BundleContext)

Example 14 with WeavingHook

use of org.osgi.framework.hooks.weaving.WeavingHook in project aries by apache.

the class ClientWeavingHookTest method testMultipleProviders.

@Test
public void testMultipleProviders() throws Exception {
    Bundle spiFlyBundle = mockSpiFlyBundle();
    Dictionary<String, String> headers = new Hashtable<String, String>();
    headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "*");
    Bundle consumerBundle = mockConsumerBundle(headers, spiFlyBundle);
    activator.addConsumerWeavingData(consumerBundle, SpiFlyConstants.SPI_CONSUMER_HEADER);
    WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator);
    // Weave the TestClient class.
    URL clsUrl = getClass().getResource("TestClient.class");
    WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.TestClient", consumerBundle);
    wh.weave(wc);
    Bundle providerBundle1 = mockProviderBundle("impl1", 1);
    Bundle providerBundle2 = mockProviderBundle("impl2", 2);
    activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle1, new HashMap<String, Object>());
    activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle2, new HashMap<String, Object>());
    // Invoke the woven class and check that it propertly sets the TCCL so that the
    // META-INF/services/org.apache.aries.mytest.MySPI files from impl1 and impl2 are visible.
    Class<?> cls = wc.getDefinedClass();
    Method method = cls.getMethod("test", new Class[] { String.class });
    Object result = method.invoke(cls.newInstance(), "hello");
    Set<String> expected = new HashSet<String>(Arrays.asList("olleh", "HELLO", "5"));
    Assert.assertEquals("All three services should be invoked", expected, result);
}
Also used : Bundle(org.osgi.framework.Bundle) Hashtable(java.util.Hashtable) WovenClass(org.osgi.framework.hooks.weaving.WovenClass) Method(java.lang.reflect.Method) URL(java.net.URL) WeavingHook(org.osgi.framework.hooks.weaving.WeavingHook) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 15 with WeavingHook

use of org.osgi.framework.hooks.weaving.WeavingHook in project aries by apache.

the class ClientWeavingHookTest method testAltServiceLoaderLoadUnprocessed.

@Test
public void testAltServiceLoaderLoadUnprocessed() throws Exception {
    Bundle spiFlyBundle = mockSpiFlyBundle();
    Dictionary<String, String> headers = new Hashtable<String, String>();
    headers.put(SpiFlyConstants.SPI_CONSUMER_HEADER, "*");
    Bundle consumerBundle = mockConsumerBundle(headers, spiFlyBundle);
    WeavingHook wh = new ClientWeavingHook(spiFlyBundle.getBundleContext(), activator);
    // Weave the TestClient class.
    URL clsUrl = getClass().getResource("UnaffectedTestClient.class");
    Assert.assertNotNull("Precondition", clsUrl);
    WovenClass wc = new MyWovenClass(clsUrl, "org.apache.aries.spifly.dynamic.UnaffectedTestClient", consumerBundle);
    Assert.assertEquals("Precondition", 0, wc.getDynamicImports().size());
    wh.weave(wc);
    Assert.assertEquals("The client is not affected so no additional imports should have been added", 0, wc.getDynamicImports().size());
    // ok the weaving is done, now prepare the registry for the call
    Bundle providerBundle = mockProviderBundle("impl1", 1);
    activator.registerProviderBundle("org.apache.aries.mytest.MySPI", providerBundle, new HashMap<String, Object>());
    // Invoke the woven class and check that it propertly sets the TCCL so that the
    // META-INF/services/org.apache.aries.mytest.MySPI file from impl1 is visible.
    Class<?> cls = wc.getDefinedClass();
    Method method = cls.getMethod("test", new Class[] { String.class });
    Object result = method.invoke(cls.newInstance(), "hello");
    Assert.assertEquals("impl4", result);
}
Also used : Bundle(org.osgi.framework.Bundle) Hashtable(java.util.Hashtable) WovenClass(org.osgi.framework.hooks.weaving.WovenClass) Method(java.lang.reflect.Method) URL(java.net.URL) WeavingHook(org.osgi.framework.hooks.weaving.WeavingHook) Test(org.junit.Test)

Aggregations

WeavingHook (org.osgi.framework.hooks.weaving.WeavingHook)35 Bundle (org.osgi.framework.Bundle)32 WovenClass (org.osgi.framework.hooks.weaving.WovenClass)32 Test (org.junit.Test)27 Hashtable (java.util.Hashtable)26 Method (java.lang.reflect.Method)24 URL (java.net.URL)24 HashSet (java.util.HashSet)9 HashMap (java.util.HashMap)6 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)6 ArrayList (java.util.ArrayList)4 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)4 BundleContext (org.osgi.framework.BundleContext)4 ServiceRegistration (org.osgi.framework.ServiceRegistration)4 File (java.io.File)3 URLClassLoader (java.net.URLClassLoader)3 LinkedHashMap (java.util.LinkedHashMap)3 List (java.util.List)3 CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)3 Equinox (org.eclipse.osgi.launch.Equinox)3