com.thoughtworks.go.plugin.api.GoPlugin Java Examples

The following examples show how to use com.thoughtworks.go.plugin.api.GoPlugin. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DummyClassWithLocalInnerClass.java    From gocd with Apache License 2.0 6 votes vote down vote up
public void foo() {
    @Extension
    class DummyInnerClassWithExtension implements GoPlugin {
        @Override
        public void initializeGoApplicationAccessor(GoApplicationAccessor goApplicationAccessor) {
            throw new UnsupportedOperationException();
        }

        @Override
        public GoPluginApiResponse handle(GoPluginApiRequest requestMessage) throws UnhandledRequestTypeException {
            throw new UnsupportedOperationException();
        }

        @Override
        public GoPluginIdentifier pluginIdentifier() {
            throw new UnsupportedOperationException();
        }
    }
}
 
Example #2
Source File: FelixGoPluginOSGiFrameworkIntegrationTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
void shouldUseOldClassLoaderBehaviourWhenSystemPropertyIsSet() {
    systemEnvironment.setProperty("gocd.plugins.classloader.old", "true");
    final GoPluginDescriptor goPluginDescriptor = getPluginDescriptor("plugin.to.test.classloader", pluginToTestClassloadPluginBundleDir);
    final GoPluginBundleDescriptor descriptor = new GoPluginBundleDescriptor(goPluginDescriptor);
    registry.loadPlugin(descriptor);
    Bundle bundle = pluginOSGiFramework.loadPlugin(descriptor);
    assertThat(bundle.getState()).isEqualTo(Bundle.ACTIVE);

    ActionWithReturn<GoPlugin, Object> action = (plugin, pluginDescriptor) -> {
        assertThat(pluginDescriptor).isEqualTo(goPluginDescriptor);
        assertThat(Thread.currentThread().getContextClassLoader().getClass().getCanonicalName()).isNotEqualTo(BundleClassLoader.class.getCanonicalName());
        return null;
    };
    pluginOSGiFramework.doOn(GoPlugin.class, "plugin.to.test.classloader", "notification", action);
}
 
Example #3
Source File: FelixGoPluginOSGiFrameworkIntegrationTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
void shouldSetCurrentThreadContextClassLoaderToBundleClassLoaderToAvoidDependenciesFromApplicationClassloaderMessingAroundWithThePluginBehavior() {
    systemEnvironment.setProperty("gocd.plugins.classloader.old", "false");
    final GoPluginDescriptor goPluginDescriptor = getPluginDescriptor("plugin.to.test.classloader", pluginToTestClassloadPluginBundleDir);
    final GoPluginBundleDescriptor bundleDescriptor = new GoPluginBundleDescriptor(goPluginDescriptor);
    registry.loadPlugin(bundleDescriptor);
    Bundle bundle = pluginOSGiFramework.loadPlugin(bundleDescriptor);
    assertThat(bundle.getState()).isEqualTo(Bundle.ACTIVE);

    ActionWithReturn<GoPlugin, Object> action = (plugin, pluginDescriptor) -> {
        assertThat(pluginDescriptor).isEqualTo(goPluginDescriptor);
        assertThat(Thread.currentThread().getContextClassLoader().getClass().getCanonicalName()).isEqualTo(BundleClassLoader.class.getCanonicalName());
        plugin.pluginIdentifier();
        return null;
    };
    pluginOSGiFramework.doOn(GoPlugin.class, "plugin.to.test.classloader", "notification", action);
}
 
Example #4
Source File: FelixGoPluginOSGiFrameworkIntegrationTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
void shouldLoadAValidPluginWithMultipleExtensions_ImplementingDifferentExtensions() throws Exception {
    final GoPluginBundleDescriptor bundleDescriptor = new GoPluginBundleDescriptor(getPluginDescriptor("valid-plugin-with-multiple-extensions", validMultipleExtensionPluginBundleDir));
    registry.loadPlugin(bundleDescriptor);
    Bundle bundle = pluginOSGiFramework.loadPlugin(bundleDescriptor);
    assertThat(bundle.getState()).isEqualTo(Bundle.ACTIVE);

    BundleContext context = bundle.getBundleContext();
    String taskExtensionFilter = String.format("(&(%s=%s)(%s=%s))", "PLUGIN_ID", "valid-plugin-with-multiple-extensions", Constants.BUNDLE_CATEGORY, "task");
    String analyticsExtensionFilter = String.format("(&(%s=%s)(%s=%s))", "PLUGIN_ID", "valid-plugin-with-multiple-extensions", Constants.BUNDLE_CATEGORY, "analytics");

    ServiceReference<?>[] taskExtensionServiceReferences = context.getServiceReferences(GoPlugin.class.getCanonicalName(), taskExtensionFilter);
    assertThat(taskExtensionServiceReferences.length).isEqualTo(1);
    assertThat(((GoPlugin) context.getService(taskExtensionServiceReferences[0])).pluginIdentifier().getExtension()).isEqualTo("task");

    ServiceReference<?>[] analyticsExtensionServiceReferences = context.getServiceReferences(GoPlugin.class.getCanonicalName(), analyticsExtensionFilter);
    assertThat(analyticsExtensionServiceReferences.length).isEqualTo(1);
    assertThat(((GoPlugin) context.getService(analyticsExtensionServiceReferences[0])).pluginIdentifier().getExtension()).isEqualTo("analytics");
}
 
Example #5
Source File: FelixGoPluginOSGiFrameworkIntegrationTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
void shouldUnloadALoadedPlugin() throws Exception {
    GoPluginBundleDescriptor bundleDescriptor = new GoPluginBundleDescriptor(getPluginDescriptor(PLUGIN_ID, descriptorBundleDir));
    registry.loadPlugin(bundleDescriptor);
    Bundle bundle = pluginOSGiFramework.loadPlugin(bundleDescriptor);

    BundleContext context = bundle.getBundleContext();

    ServiceReference<?>[] allServiceReferences = context.getServiceReferences(GoPlugin.class.getCanonicalName(), null);
    assertThat(allServiceReferences.length).isEqualTo(1);
    GoPlugin service = (GoPlugin) context.getService(allServiceReferences[0]);
    assertThat(getIntField(service, "loadCalled")).as("@Load should have been called").isEqualTo(1);

    bundleDescriptor.setBundle(bundle);
    pluginOSGiFramework.unloadPlugin(bundleDescriptor);

    assertThat(bundle.getState()).isEqualTo(Bundle.UNINSTALLED);
    assertThat(getIntField(service, "unloadCalled")).as("@UnLoad should have been called").isEqualTo(1);
}
 
Example #6
Source File: FelixGoPluginOSGiFrameworkIntegrationTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
void shouldHandleErrorGeneratedByAValidGoPluginOSGiBundleAtUsageTime() {
    final GoPluginBundleDescriptor bundleDescriptor = new GoPluginBundleDescriptor(getPluginDescriptor(PLUGIN_ID, errorGeneratingDescriptorBundleDir));
    registry.loadPlugin(bundleDescriptor);
    Bundle bundle = pluginOSGiFramework.loadPlugin(bundleDescriptor);

    assertThat(bundle.getState()).isEqualTo(Bundle.ACTIVE);
    assertThat(bundleDescriptor.isInvalid()).isFalse();

    ActionWithReturn<GoPlugin, Object> action = (goPlugin, goPluginDescriptor) -> {
        goPlugin.initializeGoApplicationAccessor(null);
        return null;
    };

    try {
        pluginOSGiFramework.doOn(GoPlugin.class, PLUGIN_ID, "extension-1", action);
        fail("Should Throw An Exception");
    } catch (Exception ex) {
        ex.printStackTrace();
        assertThat(ex.getCause() instanceof AbstractMethodError).isTrue();
    }
}
 
Example #7
Source File: FelixGoPluginOSGiFrameworkIntegrationTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
void shouldLoadAValidGoPluginOSGiBundleAndShouldBeDiscoverableThroughPluginIDFilter() throws Exception {
    final GoPluginBundleDescriptor bundleDescriptor = new GoPluginBundleDescriptor(getPluginDescriptor(PLUGIN_ID, descriptorBundleDir));
    registry.loadPlugin(bundleDescriptor);
    Bundle bundle = pluginOSGiFramework.loadPlugin(bundleDescriptor);

    assertThat(bundle.getState()).isEqualTo(Bundle.ACTIVE);

    String filterByPluginID = String.format("(%s=%s)", "PLUGIN_ID", "testplugin.descriptorValidator");
    BundleContext context = bundle.getBundleContext();
    ServiceReference<?>[] allServiceReferences = context.getServiceReferences(GoPlugin.class.getCanonicalName(), filterByPluginID);
    assertThat(allServiceReferences.length).isEqualTo(1);

    try {
        GoPlugin service = (GoPlugin) context.getService(allServiceReferences[0]);
        service.pluginIdentifier();
    } catch (Exception e) {
        fail(String.format("pluginIdentifier should have been called. Exception: %s", e.getMessage()));
    }
}
 
Example #8
Source File: FelixGoPluginOSGiFrameworkIntegrationTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
void shouldLoadAValidGoPluginOSGiBundle() throws Exception {
    final GoPluginBundleDescriptor bundleDescriptor = new GoPluginBundleDescriptor(getPluginDescriptor(PLUGIN_ID, descriptorBundleDir));
    registry.loadPlugin(bundleDescriptor);
    Bundle bundle = pluginOSGiFramework.loadPlugin(bundleDescriptor);

    assertThat(bundle.getState()).isEqualTo(Bundle.ACTIVE);

    BundleContext context = bundle.getBundleContext();
    ServiceReference<?>[] allServiceReferences = context.getServiceReferences(GoPlugin.class.getCanonicalName(), null);
    assertThat(allServiceReferences.length).isEqualTo(1);

    try {
        GoPlugin service = (GoPlugin) context.getService(allServiceReferences[0]);
        service.pluginIdentifier();
        assertThat(getIntField(service, "loadCalled")).as("@Load should have been called").isEqualTo(1);
    } catch (Exception e) {
        fail(String.format("pluginIdentifier should have been called. Exception: %s", e.getMessage()));
    }
}
 
Example #9
Source File: DefaultPluginManagerTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
void shouldThrowExceptionIfMatchingExtensionVersionNotFound() {
    String pluginId = "plugin-id";
    String extensionType = "sample-extension";
    GoPlugin goPlugin = mock(GoPlugin.class);
    GoPlugginOSGiFrameworkStub osGiFrameworkStub = new GoPlugginOSGiFrameworkStub(goPlugin);
    osGiFrameworkStub.addHasReferenceFor(GoPlugin.class, pluginId, extensionType, true);
    when(goPlugin.pluginIdentifier()).thenReturn(new GoPluginIdentifier(extensionType, asList("1.0", "2.0")));

    DefaultPluginManager pluginManager = new DefaultPluginManager(monitor, registry, osGiFrameworkStub, jarChangeListener, pluginRequestProcessorRegistry, systemEnvironment, pluginLoader);
    try {
        pluginManager.resolveExtensionVersion(pluginId, extensionType, asList("3.0", "4.0"));
        fail("should have thrown exception for not finding matching extension version");
    } catch (Exception e) {
        assertThat(e.getMessage()).isEqualTo("Could not find matching extension version between Plugin[plugin-id] and Go");
    }
}
 
Example #10
Source File: DefaultPluginManagerTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
void shouldSayPluginIsOfGivenExtensionTypeWhenReferenceIsFound() {
    String pluginId = "plugin-id";
    String extensionType = "sample-extension";
    GoPluginIdentifier pluginIdentifier = new GoPluginIdentifier(extensionType, asList("1.0"));
    final GoPlugin goPlugin = mock(GoPlugin.class);
    final GoPluginDescriptor descriptor = mock(GoPluginDescriptor.class);
    when(goPluginOSGiFramework.hasReferenceFor(GoPlugin.class, pluginId, extensionType)).thenReturn(true);

    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocationOnMock) {
            ActionWithReturn<GoPlugin, GoPluginApiResponse> action = (ActionWithReturn<GoPlugin, GoPluginApiResponse>) invocationOnMock.getArguments()[2];
            return action.execute(goPlugin, descriptor);
        }
    }).when(goPluginOSGiFramework).doOn(eq(GoPlugin.class), eq(pluginId), eq(extensionType), any(ActionWithReturn.class));
    when(goPlugin.pluginIdentifier()).thenReturn(pluginIdentifier);

    DefaultPluginManager pluginManager = new DefaultPluginManager(monitor, registry, goPluginOSGiFramework, jarChangeListener, pluginRequestProcessorRegistry, systemEnvironment, pluginLoader);
    assertThat(pluginManager.isPluginOfType(extensionType, pluginId)).isTrue();
}
 
Example #11
Source File: FelixGoPluginOSGiFrameworkTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
void shouldGetExtensionsInfoForThePlugin() throws Exception {
    when(registry.getPlugin(anyString())).thenReturn(mock(GoPluginDescriptor.class));

    GoPlugin firstService = mock(GoPlugin.class);
    GoPlugin secondService = mock(GoPlugin.class);

    final GoPluginIdentifier firstPluginIdentifier = mock(GoPluginIdentifier.class);
    when(firstService.pluginIdentifier()).thenReturn(firstPluginIdentifier);
    when(firstPluginIdentifier.getExtension()).thenReturn("elastic-agent");
    when(firstPluginIdentifier.getSupportedExtensionVersions()).thenReturn(asList("1.0", "2.0"));

    final GoPluginIdentifier secondPluginIdentifier = mock(GoPluginIdentifier.class);
    when(secondService.pluginIdentifier()).thenReturn(secondPluginIdentifier);
    when(secondPluginIdentifier.getExtension()).thenReturn("authorization");
    when(secondPluginIdentifier.getSupportedExtensionVersions()).thenReturn(singletonList("1.0"));

    registerService("plugin-one", firstService, secondService);
    spy.start();

    final Map<String, List<String>> info = spy.getExtensionsInfoFromThePlugin("plugin-one");

    assertThat(info).hasSize(2)
            .containsEntry("elastic-agent", asList("1.0", "2.0"))
            .containsEntry("authorization", singletonList("1.0"));
}
 
Example #12
Source File: DummyClassProvidingAnonymousClass.java    From gocd with Apache License 2.0 6 votes vote down vote up
public static GoPlugin getAnonymousClass() {
    return new GoPlugin() {
        @Override
        public void initializeGoApplicationAccessor(GoApplicationAccessor goApplicationAccessor) {
        }

        @Override
        public GoPluginApiResponse handle(GoPluginApiRequest requestMessage) throws UnhandledRequestTypeException {
            return null;
        }

        @Override
        public GoPluginIdentifier pluginIdentifier() {
            return null;
        }
    };
}
 
Example #13
Source File: DummyClassProvidingAnonymousClass.java    From gocd with Apache License 2.0 6 votes vote down vote up
public static GoPlugin getAnonymousClass() {
    return new GoPlugin() {
        @Override
        public void initializeGoApplicationAccessor(GoApplicationAccessor goApplicationAccessor) {
        }

        @Override
        public GoPluginApiResponse handle(GoPluginApiRequest requestMessage) throws UnhandledRequestTypeException {
            return null;
        }

        @Override
        public GoPluginIdentifier pluginIdentifier() {
            return null;
        }
    };
}
 
Example #14
Source File: DefaultGoPluginActivatorIntegrationTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
void shouldRegisterOneInstanceForEachExtensionPointAnExtensionImplements() throws Exception {
    BundleContext installedBundledContext = bundleContext(installBundleWithClasses(TestGoPluginExtensionThatImplementsTwoExtensionPoints.class, DummyTestPlugin.class));

    ServiceReference<?>[] references = installedBundledContext.getServiceReferences(GoPlugin.class.getName(), null);
    String[] services = toSortedServiceClassNames(installedBundledContext, references);

    assertThat(services.length).as(Arrays.toString(services)).isEqualTo(2);
    assertThat(services[0]).isEqualTo(DummyTestPlugin.class.getName());
    assertThat(services[1]).isEqualTo(TestGoPluginExtensionThatImplementsTwoExtensionPoints.class.getName());

    references = installedBundledContext.getServiceReferences(TestGoPluginExtensionPoint.class.getName(), null);
    assertThat(references.length).isEqualTo(1);
    assertThat(installedBundledContext.getService(references[0]).getClass().getName()).isEqualTo(TestGoPluginExtensionThatImplementsTwoExtensionPoints.class.getName());
    Object testExtensionImplementation = getImplementationOfType(installedBundledContext, references, TestGoPluginExtensionThatImplementsTwoExtensionPoints.class);

    references = installedBundledContext.getServiceReferences(GoPlugin.class.getName(), null);
    assertThat(references.length).isEqualTo(2);
    Object testPluginImplementation = getImplementationOfType(installedBundledContext, references, TestGoPluginExtensionThatImplementsTwoExtensionPoints.class);

    assertThat(testPluginImplementation).isSameAs(testExtensionImplementation);
}
 
Example #15
Source File: DefaultGoPluginActivatorTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRegisterServiceWithBundleSymbolicNamePluginIDAndExtensionTypeAsProperties() throws Exception {
    setupClassesInBundle("PublicGoExtensionClassWhichWillLoadSuccessfullyAndProvideAValidIdentifier.class");
    when(bundle.loadClass("PublicGoExtensionClassWhichWillLoadSuccessfullyAndProvideAValidIdentifier")).thenReturn((Class) PublicGoExtensionClassWhichWillLoadSuccessfullyAndProvideAValidIdentifier.class);
    when(pluginRegistryService.pluginIDFor(eq(SYMBOLIC_NAME), anyString())).thenReturn(PLUGIN_ID);

    Hashtable<String, String> expectedPropertiesUponRegistration = new Hashtable<>();
    expectedPropertiesUponRegistration.put(Constants.BUNDLE_SYMBOLICNAME, PLUGIN_ID);
    expectedPropertiesUponRegistration.put(Constants.BUNDLE_CATEGORY, "test-extension");
    expectedPropertiesUponRegistration.put("PLUGIN_ID", PLUGIN_ID);

    activator.start(context);

    assertThat(activator.hasErrors(), is(false));
    verify(context).registerService(eq(GoPlugin.class), any(GoPlugin.class), eq(expectedPropertiesUponRegistration));
}
 
Example #16
Source File: DefaultGoPluginActivatorTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRegisterEachServiceWithTheCorrespondingPluginIDAsProperty() throws Exception {
    setupClassesInBundle("PublicGoExtensionClassWhichWillLoadSuccessfullyAndProvideAValidIdentifier.class", "PublicGoExtensionClassWhichWillAlsoLoadSuccessfully.class");
    when(bundle.loadClass("PublicGoExtensionClassWhichWillLoadSuccessfullyAndProvideAValidIdentifier")).thenReturn((Class) PublicGoExtensionClassWhichWillLoadSuccessfullyAndProvideAValidIdentifier.class);
    when(bundle.loadClass("PublicGoExtensionClassWhichWillAlsoLoadSuccessfully")).thenReturn((Class) PublicGoExtensionClassWhichWillAlsoLoadSuccessfully.class);

    when(pluginRegistryService.pluginIDFor(SYMBOLIC_NAME, PublicGoExtensionClassWhichWillLoadSuccessfullyAndProvideAValidIdentifier.class.getCanonicalName())).thenReturn("plugin_id_1");
    when(pluginRegistryService.pluginIDFor(SYMBOLIC_NAME, PublicGoExtensionClassWhichWillAlsoLoadSuccessfully.class.getCanonicalName())).thenReturn("plugin_id_2");

    Dictionary<String, String> expectedPropertiesUponRegistrationForPlugin1 = new Hashtable<>();
    expectedPropertiesUponRegistrationForPlugin1.put(Constants.BUNDLE_SYMBOLICNAME, SYMBOLIC_NAME);
    expectedPropertiesUponRegistrationForPlugin1.put(Constants.BUNDLE_CATEGORY, "test-extension");
    expectedPropertiesUponRegistrationForPlugin1.put("PLUGIN_ID", "plugin_id_1");

    Dictionary<String, String> expectedPropertiesUponRegistrationForPlugin2 = new Hashtable<>();
    expectedPropertiesUponRegistrationForPlugin2.put(Constants.BUNDLE_SYMBOLICNAME, SYMBOLIC_NAME);
    expectedPropertiesUponRegistrationForPlugin2.put(Constants.BUNDLE_CATEGORY, "test-extension-2");
    expectedPropertiesUponRegistrationForPlugin2.put("PLUGIN_ID", "plugin_id_2");

    activator.start(context);

    assertThat(activator.hasErrors(), is(false));
    verify(context).registerService(eq(GoPlugin.class), any(PublicGoExtensionClassWhichWillLoadSuccessfullyAndProvideAValidIdentifier.class), eq(expectedPropertiesUponRegistrationForPlugin1));
    verify(context).registerService(eq(GoPlugin.class), any(PublicGoExtensionClassWhichWillAlsoLoadSuccessfully.class), eq(expectedPropertiesUponRegistrationForPlugin2));
}
 
Example #17
Source File: DefaultGoPluginActivatorTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReportErrorsIfAPluginIDCannotBeFoundForAGivenExtensionClass() throws Exception {
    setupClassesInBundle("PublicGoExtensionClassWhichWillLoadSuccessfullyAndProvideAValidIdentifier.class", "PublicGoExtensionClassWhichWillAlsoLoadSuccessfully.class");
    when(bundle.loadClass("PublicGoExtensionClassWhichWillLoadSuccessfullyAndProvideAValidIdentifier")).thenReturn((Class) PublicGoExtensionClassWhichWillLoadSuccessfullyAndProvideAValidIdentifier.class);
    when(bundle.loadClass("PublicGoExtensionClassWhichWillAlsoLoadSuccessfully")).thenReturn((Class) PublicGoExtensionClassWhichWillAlsoLoadSuccessfully.class);

    when(pluginRegistryService.pluginIDFor(SYMBOLIC_NAME, PublicGoExtensionClassWhichWillLoadSuccessfullyAndProvideAValidIdentifier.class.getCanonicalName())).thenReturn("plugin_id_1");
    when(pluginRegistryService.pluginIDFor(SYMBOLIC_NAME, PublicGoExtensionClassWhichWillAlsoLoadSuccessfully.class.getCanonicalName())).thenReturn(null);

    Dictionary<String, String> expectedPropertiesUponRegistrationForPlugin1 = new Hashtable<>();
    expectedPropertiesUponRegistrationForPlugin1.put(Constants.BUNDLE_SYMBOLICNAME, SYMBOLIC_NAME);
    expectedPropertiesUponRegistrationForPlugin1.put(Constants.BUNDLE_CATEGORY, "test-extension");
    expectedPropertiesUponRegistrationForPlugin1.put("PLUGIN_ID", "plugin_id_1");

    activator.start(context);

    verify(pluginRegistryService, times(2)).pluginIDFor(eq(SYMBOLIC_NAME), any());
    verify(context).registerService(eq(GoPlugin.class), any(PublicGoExtensionClassWhichWillLoadSuccessfullyAndProvideAValidIdentifier.class), eq(expectedPropertiesUponRegistrationForPlugin1));
    verify(context, never()).registerService(eq(GoPlugin.class), any(PublicGoExtensionClassWhichWillAlsoLoadSuccessfully.class), any());

    assertThat(activator.hasErrors(), is(true));
    verifyErrorsReported("Unable to find plugin ID for extension class (com.thoughtworks.go.plugin.activation.PublicGoExtensionClassWhichWillAlsoLoadSuccessfully) in bundle plugin-id");
}
 
Example #18
Source File: DefaultGoPluginActivatorIntegrationTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
void shouldRegisterANestedClassImplementingGoPluginAsAnOSGiService() throws Exception {
    if (new OSChecker(OSChecker.WINDOWS).satisfy()) {
        return; // The class files in this test become too big for a Windows filesystem to handle.
    }

    File bundleWithActivator = createBundleWithActivator(BUNDLE_DIR_WHICH_HAS_PROPER_ACTIVATOR, TestPluginOuterClass.class,
            TestPluginOuterClass.NestedClass.class,
            TestPluginOuterClass.InnerClass.class,
            TestPluginOuterClass.InnerClass.SecondLevelInnerClass.class,
            TestPluginOuterClass.InnerClass.SecondLevelInnerClass.TestPluginThirdLevelInnerClass.class,
            TestPluginOuterClass.InnerClass.SecondLevelSiblingInnerClassNoDefaultConstructor.class);
    BundleContext installedBundledContext = bundleContext(installBundleFoundInDirectory(bundleWithActivator));

    ServiceReference<?>[] references = installedBundledContext.getServiceReferences(GoPlugin.class.getName(), null);
    String[] services = toSortedServiceClassNames(installedBundledContext, references);

    assertThat(services.length).as(Arrays.toString(services)).isEqualTo(4);
    assertThat(services[0]).isEqualTo(TestPluginOuterClass.class.getName());
    assertThat(services[1]).isEqualTo(TestPluginOuterClass.InnerClass.class.getName());
    assertThat(services[2]).isEqualTo(TestPluginOuterClass.InnerClass.SecondLevelInnerClass.TestPluginThirdLevelInnerClass.class.getName());
    assertThat(services[3]).isEqualTo(TestPluginOuterClass.NestedClass.class.getName());
}
 
Example #19
Source File: DefaultGoPluginActivatorTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldLoadOnlyRegisteredExtensionClassesWhenAMultiPluginBundleIsUsed() throws Exception {
    setupClassesInBundle("PublicGoExtensionClassWhichWillLoadSuccessfullyAndProvideAValidIdentifier.class", "PublicGoExtensionClassWhichWillAlsoLoadSuccessfully.class");
    when(bundle.loadClass("PublicGoExtensionClassWhichWillLoadSuccessfullyAndProvideAValidIdentifier")).thenReturn((Class) PublicGoExtensionClassWhichWillLoadSuccessfullyAndProvideAValidIdentifier.class);
    when(bundle.loadClass("PublicGoExtensionClassWhichWillAlsoLoadSuccessfully")).thenReturn((Class) PublicGoExtensionClassWhichWillAlsoLoadSuccessfully.class);

    when(pluginRegistryService.pluginIDFor(SYMBOLIC_NAME, PublicGoExtensionClassWhichWillLoadSuccessfullyAndProvideAValidIdentifier.class.getCanonicalName())).thenReturn("plugin_id_1");
    when(pluginRegistryService.extensionClassesInBundle(SYMBOLIC_NAME)).thenReturn(singletonList(PublicGoExtensionClassWhichWillLoadSuccessfullyAndProvideAValidIdentifier.class.getCanonicalName()));

    activator.start(context);

    assertThat(activator.hasErrors(), is(false));
    verify(context, times(1)).registerService(eq(GoPlugin.class), any(PublicGoExtensionClassWhichWillLoadSuccessfullyAndProvideAValidIdentifier.class), any());
    verify(context, never()).registerService(eq(GoPlugin.class), any(PublicGoExtensionClassWhichWillAlsoLoadSuccessfully.class), any());
    verify(bundle, never()).loadClass("PublicGoExtensionClassWhichWillAlsoLoadSuccessfully");
}
 
Example #20
Source File: DefaultPluginManager.java    From gocd with Apache License 2.0 6 votes vote down vote up
private void ensureInitializerInvoked(GoPluginDescriptor pluginDescriptor, GoPlugin plugin, String extensionType) {
    synchronized (initializedPluginsWithTheirExtensionTypes) {
        if (initializedPluginsWithTheirExtensionTypes.get(pluginDescriptor) == null) {
            initializedPluginsWithTheirExtensionTypes.put(pluginDescriptor, new HashSet<>());
        }

        Set<String> initializedExtensions = initializedPluginsWithTheirExtensionTypes.get(pluginDescriptor);
        if (initializedExtensions == null || initializedExtensions.contains(extensionType)) {
            return;
        }
        initializedPluginsWithTheirExtensionTypes.get(pluginDescriptor).add(extensionType);

        PluginAwareDefaultGoApplicationAccessor accessor = new PluginAwareDefaultGoApplicationAccessor(pluginDescriptor, requestProcessRegistry);
        plugin.initializeGoApplicationAccessor(accessor);
    }
}
 
Example #21
Source File: FelixGoPluginOSGiFramework.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, List<String>> getExtensionsInfoFromThePlugin(String pluginId) {
    if (framework == null) {
        LOGGER.warn("[Plugin Framework] Plugins are not enabled, so cannot do an action on all implementations of {}", GoPlugin.class);
        return null;
    }

    final BundleContext bundleContext = framework.getBundleContext();
    final ServiceQuery serviceQuery = ServiceQuery.newQuery(pluginId);
    final Collection<ServiceReference<GoPlugin>> serviceReferences = new HashSet<>(listServices(bundleContext, GoPlugin.class, serviceQuery));

    ActionWithReturn<GoPlugin, DefaultKeyValue<String, List<String>>> action = (goPlugin, descriptor) -> new DefaultKeyValue<>(goPlugin.pluginIdentifier().getExtension(), goPlugin.pluginIdentifier().getSupportedExtensionVersions());

    return serviceReferences.stream()
            .map(serviceReference -> {
                GoPlugin service = bundleContext.getService(serviceReference);
                return executeActionOnTheService(action, service, registry.getPlugin(pluginId));
            }).collect(toMap(AbstractKeyValue::getKey, AbstractKeyValue::getValue));
}
 
Example #22
Source File: DefaultPluginManagerTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
void shouldSayAPluginIsNotOfAnExtensionTypeWhenReferenceIsNotFound() {
    final String pluginThatDoesNotImplement = "plugin-that-does-not-implement";
    String extensionType = "extension-type";
    when(goPluginOSGiFramework.hasReferenceFor(GoPlugin.class, pluginThatDoesNotImplement, extensionType)).thenReturn(false);

    DefaultPluginManager pluginManager = new DefaultPluginManager(monitor, registry, goPluginOSGiFramework, jarChangeListener, pluginRequestProcessorRegistry, systemEnvironment, pluginLoader);
    boolean pluginIsOfExtensionType = pluginManager.isPluginOfType(extensionType, pluginThatDoesNotImplement);

    assertThat(pluginIsOfExtensionType).isFalse();
    verify(goPluginOSGiFramework).hasReferenceFor(GoPlugin.class, pluginThatDoesNotImplement, extensionType);
    verify(goPluginOSGiFramework, never()).doOn(eq(GoPlugin.class), eq(pluginThatDoesNotImplement), eq(extensionType), any(ActionWithReturn.class));
}
 
Example #23
Source File: DefaultGoPluginActivatorTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldFailToRegisterServiceWhenExtensionTypeCannotBeSuccessfullyRetrieved() throws Exception {
    setupClassesInBundle("PublicGoExtensionClassWhichWillLoadSuccessfullyButThrowWhenAskedForPluginIdentifier.class");
    when(bundle.loadClass("PublicGoExtensionClassWhichWillLoadSuccessfullyButThrowWhenAskedForPluginIdentifier")).thenReturn((Class) PublicGoExtensionClassWhichWillLoadSuccessfullyButThrowWhenAskedForPluginIdentifier.class);

    activator.start(context);

    assertThat(activator.hasErrors(), is(true));
    verifyErrorReportedContains("Unable to find extension type from plugin identifier in class com.thoughtworks.go.plugin.activation.PublicGoExtensionClassWhichWillLoadSuccessfullyButThrowWhenAskedForPluginIdentifier");
    verify(context, times(0)).registerService(eq(GoPlugin.class), any(GoPlugin.class), any());
}
 
Example #24
Source File: FelixGoPluginOSGiFrameworkIntegrationTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
void shouldPassInCorrectDescriptorToAction() {
    final GoPluginDescriptor goPluginDescriptor = getPluginDescriptor(PLUGIN_ID, descriptorBundleDir);
    final GoPluginBundleDescriptor bundleDescriptor = new GoPluginBundleDescriptor(goPluginDescriptor);
    registry.loadPlugin(bundleDescriptor);
    Bundle bundle = pluginOSGiFramework.loadPlugin(bundleDescriptor);
    assertThat(bundle.getState()).isEqualTo(Bundle.ACTIVE);

    ActionWithReturn<GoPlugin, Object> action = (plugin, pluginDescriptor) -> {
        assertThat(pluginDescriptor).isEqualTo(goPluginDescriptor);
        plugin.pluginIdentifier();
        return null;
    };
    pluginOSGiFramework.doOn(GoPlugin.class, PLUGIN_ID, "notification", action);
}
 
Example #25
Source File: DefaultGoPluginActivatorTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReportErrorsIfARegisteredExtensionClassCannotBeFound() throws Exception {
    setupClassesInBundle("PublicGoExtensionClassWhichWillLoadSuccessfullyAndProvideAValidIdentifier.class");
    when(bundle.loadClass("PublicGoExtensionClassWhichWillLoadSuccessfullyAndProvideAValidIdentifier")).thenReturn((Class) PublicGoExtensionClassWhichWillLoadSuccessfullyAndProvideAValidIdentifier.class);

    when(pluginRegistryService.extensionClassesInBundle(SYMBOLIC_NAME)).thenReturn(singletonList("com.some.InvalidClass"));

    activator.start(context);

    assertThat(activator.hasErrors(), is(true));
    verify(context, never()).registerService(eq(GoPlugin.class), any(PublicGoExtensionClassWhichWillLoadSuccessfullyAndProvideAValidIdentifier.class), any());
    verify(pluginRegistryService).reportErrorAndInvalidate(SYMBOLIC_NAME, singletonList("Extension class declared in plugin bundle is not found: com.some.InvalidClass"));
}
 
Example #26
Source File: DefaultPluginManager.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Override
public GoPluginApiResponse submitTo(final String pluginId, String extensionType, final GoPluginApiRequest apiRequest) {
    return goPluginOSGiFramework.doOn(GoPlugin.class, pluginId, extensionType, (plugin, pluginDescriptor) -> {
        ensureInitializerInvoked(pluginDescriptor, plugin, extensionType);
        try {
            return plugin.handle(apiRequest);
        } catch (UnhandledRequestTypeException e) {
            LOGGER.error(e.getMessage());
            LOGGER.debug(e.getMessage(), e);
            throw new RuntimeException(e);
        }
    });
}
 
Example #27
Source File: DefaultPluginManagerTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
void shouldResolveToCorrectExtensionVersion() {
    String pluginId = "plugin-id";
    String extensionType = "sample-extension";
    GoPlugin goPlugin = mock(GoPlugin.class);
    GoPlugginOSGiFrameworkStub osGiFrameworkStub = new GoPlugginOSGiFrameworkStub(goPlugin);
    osGiFrameworkStub.addHasReferenceFor(GoPlugin.class, pluginId, extensionType, true);
    when(goPlugin.pluginIdentifier()).thenReturn(new GoPluginIdentifier(extensionType, asList("1.0", "2.0")));

    DefaultPluginManager pluginManager = new DefaultPluginManager(monitor, registry, osGiFrameworkStub, jarChangeListener, pluginRequestProcessorRegistry, systemEnvironment, pluginLoader);
    assertThat(pluginManager.resolveExtensionVersion(pluginId, extensionType, asList("1.0", "2.0", "3.0"))).isEqualTo("2.0");
}
 
Example #28
Source File: DefaultGoPluginActivatorIntegrationTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
void shouldRegisterAsAnOSGiServiceADerivedClassWhoseAncestorImplementsAnExtensionPoint() throws Exception {
    BundleContext installedBundledContext = bundleContext(installBundleWithClasses(TestPluginThatIsADerivedClass.class,
            DummyTestPlugin.class, TestPluginThatIsADerivedClass.class.getSuperclass()));
    ServiceReference<?>[] references = installedBundledContext.getServiceReferences(GoPlugin.class.getName(), null);
    String[] services = toSortedServiceClassNames(installedBundledContext, references);

    assertThat(services.length).as(Arrays.toString(services)).isEqualTo(2);
    assertThat(services[0]).isEqualTo(DummyTestPlugin.class.getName());
    assertThat(services[1]).isEqualTo(TestPluginThatIsADerivedClass.class.getName());
}
 
Example #29
Source File: DefaultPluginManagerTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
void shouldSubmitPluginApiRequestToGivenPlugin() throws Exception {
    String extensionType = "sample-extension";
    GoPluginApiRequest request = mock(GoPluginApiRequest.class);
    GoPluginApiResponse expectedResponse = mock(GoPluginApiResponse.class);
    final GoPlugin goPlugin = mock(GoPlugin.class);
    final GoPluginDescriptor descriptor = mock(GoPluginDescriptor.class);

    when(goPlugin.handle(request)).thenReturn(expectedResponse);
    ArgumentCaptor<PluginAwareDefaultGoApplicationAccessor> captor = ArgumentCaptor.forClass(PluginAwareDefaultGoApplicationAccessor.class);
    doNothing().when(goPlugin).initializeGoApplicationAccessor(captor.capture());

    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocationOnMock) {
            ActionWithReturn<GoPlugin, GoPluginApiResponse> action = (ActionWithReturn<GoPlugin, GoPluginApiResponse>) invocationOnMock.getArguments()[3];
            return action.execute(goPlugin, descriptor);
        }
    }).when(goPluginOSGiFramework).doOn(eq(GoPlugin.class), eq("plugin-id"), eq(extensionType), any(ActionWithReturn.class));

    DefaultPluginManager pluginManager = new DefaultPluginManager(monitor, registry, goPluginOSGiFramework, jarChangeListener, pluginRequestProcessorRegistry, systemEnvironment, pluginLoader);
    GoPluginApiResponse actualResponse = pluginManager.submitTo("plugin-id", extensionType, request);

    assertThat(actualResponse).isEqualTo(expectedResponse);
    PluginAwareDefaultGoApplicationAccessor accessor = captor.getValue();
    assertThat(accessor.pluginDescriptor()).isEqualTo(descriptor);
}
 
Example #30
Source File: FelixGoPluginOSGiFrameworkTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
private void registerService(String pluginID, GoPlugin... someInterfaces) throws InvalidSyntaxException {
    final List<ServiceReference<GoPlugin>> serviceReferences = Arrays.stream(someInterfaces).map(someInterface -> {
        ServiceReference<GoPlugin> reference = mock(ServiceReference.class);
        when(reference.getBundle()).thenReturn(bundle);
        when(bundleContext.getService(reference)).thenReturn(someInterface);
        when(registry.getPlugin(pluginID)).thenReturn(buildExpectedDescriptor(pluginID));
        return reference;
    }).collect(Collectors.toList());

    String propertyFormat = String.format("(&(%s=%s))", "PLUGIN_ID", pluginID);
    when(bundleContext.getServiceReferences(GoPlugin.class, propertyFormat)).thenReturn(serviceReferences);
}