Search in sources :

Example 1 with WeavingHook

use of org.osgi.framework.hooks.weaving.WeavingHook in project enumerable by hraberg.

the class LambdaWeavingActivator method start.

public void start(BundleContext bundleContext) throws Exception {
    debug("[osgi] " + Version.getVersionString());
    loader = new LambdaLoader();
    weavingHook = bundleContext.registerService(WeavingHook.class, this, new Hashtable<String, Object>());
}
Also used : LambdaLoader(org.enumerable.lambda.weaving.LambdaLoader) Hashtable(java.util.Hashtable) WeavingHook(org.osgi.framework.hooks.weaving.WeavingHook)

Example 2 with WeavingHook

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

the class BundleWiringImplTest method testFindClassBadWeave.

@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testFindClassBadWeave() throws Exception {
    Felix mockFramework = mock(Felix.class);
    Content mockContent = mock(Content.class);
    ServiceReference<WeavingHook> mockServiceReferenceWeavingHook = mock(ServiceReference.class);
    ServiceReference<WovenClassListener> mockServiceReferenceWovenClassListener = mock(ServiceReference.class);
    Set<ServiceReference<WeavingHook>> hooks = new HashSet<ServiceReference<WeavingHook>>();
    hooks.add(mockServiceReferenceWeavingHook);
    DummyWovenClassListener dummyWovenClassListener = new DummyWovenClassListener();
    Set<ServiceReference<WovenClassListener>> listeners = new HashSet<ServiceReference<WovenClassListener>>();
    listeners.add(mockServiceReferenceWovenClassListener);
    Class testClass = TestClass.class;
    String testClassName = testClass.getName();
    String testClassAsPath = testClassName.replace('.', '/') + ".class";
    byte[] testClassBytes = createTestClassBytes(testClass, testClassAsPath);
    List<Content> contentPath = new ArrayList<Content>();
    contentPath.add(mockContent);
    initializeSimpleBundleWiring();
    when(mockBundle.getFramework()).thenReturn(mockFramework);
    when(mockFramework.getBootPackages()).thenReturn(new String[0]);
    when(mockRevisionImpl.getContentPath()).thenReturn(contentPath);
    when(mockContent.getEntryAsBytes(testClassAsPath)).thenReturn(testClassBytes);
    HookRegistry hReg = mock(HookRegistry.class);
    when(hReg.getHooks(WeavingHook.class)).thenReturn(hooks);
    when(mockFramework.getHookRegistry()).thenReturn(hReg);
    when(mockFramework.getService(mockFramework, mockServiceReferenceWeavingHook, false)).thenReturn(new BadDummyWovenHook());
    when(hReg.getHooks(WovenClassListener.class)).thenReturn(listeners);
    when(mockFramework.getService(mockFramework, mockServiceReferenceWovenClassListener, false)).thenReturn(dummyWovenClassListener);
    BundleClassLoader bundleClassLoader = createBundleClassLoader(BundleClassLoader.class, bundleWiring);
    assertNotNull(bundleClassLoader);
    try {
        bundleClassLoader.findClass(TestClass.class.getName());
        fail("Class should throw exception");
    } catch (Error e) {
    // This is expected
    }
    assertEquals("There should be 1 state changes fired by the weaving", 1, dummyWovenClassListener.stateList.size());
    assertEquals("The only state change should be a failed transform on the class", (Object) WovenClass.TRANSFORMING_FAILED, dummyWovenClassListener.stateList.get(0));
}
Also used : BundleClassLoader(org.apache.felix.framework.BundleWiringImpl.BundleClassLoader) ArrayList(java.util.ArrayList) WovenClassListener(org.osgi.framework.hooks.weaving.WovenClassListener) ServiceReference(org.osgi.framework.ServiceReference) Content(org.apache.felix.framework.cache.Content) WovenClass(org.osgi.framework.hooks.weaving.WovenClass) WeavingHook(org.osgi.framework.hooks.weaving.WeavingHook) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 3 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 4 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 5 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)

Aggregations

WeavingHook (org.osgi.framework.hooks.weaving.WeavingHook)44 WovenClass (org.osgi.framework.hooks.weaving.WovenClass)41 Bundle (org.osgi.framework.Bundle)38 Test (org.junit.Test)36 Hashtable (java.util.Hashtable)32 Method (java.lang.reflect.Method)30 URL (java.net.URL)30 HashSet (java.util.HashSet)13 ArrayList (java.util.ArrayList)7 HashMap (java.util.HashMap)7 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)7 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 BundleClassLoader (org.apache.felix.framework.BundleWiringImpl.BundleClassLoader)3