org.jboss.forge.furnace.services.Imported Java Examples

The following examples show how to use org.jboss.forge.furnace.services.Imported. 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: AddonRegistryImpl.java    From furnace with Eclipse Public License 1.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> Imported<T> getServices(final Class<T> type)
{
   if (getVersion() != cacheVersion)
   {
      cacheVersion = getVersion();
      importedCache.clear();
   }

   String cacheKey = type.getName()
            + (type.getClassLoader() == null ? "SystemCL" : type.getClassLoader().toString());
   Imported<?> imported = importedCache.get(cacheKey);
   if (imported == null)
   {
      imported = new ImportedImpl<>(this, lock, type);
      importedCache.put(cacheKey, imported);
   }
   return (Imported<T>) imported;
}
 
Example #2
Source File: GraphContextImpl.java    From windup with Eclipse Public License 1.0 6 votes vote down vote up
private void fireListeners()
{
    Imported<AfterGraphInitializationListener> afterInitializationListeners = furnace.getAddonRegistry().getServices(
                AfterGraphInitializationListener.class);
    Map<String, Object> confProps = new HashMap<>();
    Iterator<?> keyIter = conf.getKeys();
    while (keyIter.hasNext())
    {
        String key = (String) keyIter.next();
        confProps.put(key, conf.getProperty(key));
    }

    if (!afterInitializationListeners.isUnsatisfied())
    {
        for (AfterGraphInitializationListener listener : afterInitializationListeners)
        {
            listener.afterGraphStarted(confProps, this);
            if (listener instanceof BeforeGraphCloseListener)
            {
                beforeGraphCloseListenerBuffer.put(listener.getClass().toString(), (BeforeGraphCloseListener) listener);
            }
        }
    }
}
 
Example #3
Source File: FurnaceServiceEnricher.java    From windup with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public <T> Collection<T> produce(final Class<T> type)
{
    final Collection<T> result = new HashSet<>();
    final Furnace furnace = FurnaceHolder.getFurnace();

    // Furnace may be not available if the ServiceLoader is called before FurnaceHolder
    // has received the Furnace PostConstruct event, so check for null and if it isStarted
    if (furnace != null && furnace.getStatus().isStarted())
    {
        final Imported<T> services = furnace.getAddonRegistry().getServices(type);
        for (final T service : services)
        {
            result.add(service);
        }
    }
    return result;
}
 
Example #4
Source File: ParserContext.java    From windup with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Initialize tag handlers based upon the provided furnace instance.
 */
public ParserContext(Furnace furnace, RuleLoaderContext ruleLoaderContext)
{
    this.ruleLoaderContext = ruleLoaderContext;

    @SuppressWarnings("rawtypes")
    Imported<ElementHandler> loadedHandlers = furnace.getAddonRegistry().getServices(ElementHandler.class);
    for (ElementHandler<?> handler : loadedHandlers)
    {
        NamespaceElementHandler annotation = Annotations.getAnnotation(handler.getClass(),
                    NamespaceElementHandler.class);
        if (annotation != null)
        {
            HandlerId handlerID = new HandlerId(annotation.namespace(), annotation.elementName());
            if (handlers.containsKey(handlerID))
            {
                String className1 = Proxies.unwrapProxyClassName(handlers.get(handlerID).getClass());
                String className2 = Proxies.unwrapProxyClassName(handler.getClass());
                throw new WindupException("Multiple handlers registered with id: " + handlerID + " Classes are: "
                            + className1 + " and " + className2);
            }
            handlers.put(handlerID, handler);
        }
    }
}
 
Example #5
Source File: WindupConfiguration.java    From windup with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns all of the {@link ConfigurationOption} in the specified {@link Addon}.
 */
public static Iterable<ConfigurationOption> getWindupConfigurationOptions(Addon addon)
{
    IdentityHashMap<ClassLoader, Addon> classLoaderToAddon = new IdentityHashMap<>();
    for (Addon loadedAddon : FurnaceHolder.getAddonRegistry().getAddons())
    {
        classLoaderToAddon.put(loadedAddon.getClassLoader(), loadedAddon);
    }

    List<ConfigurationOption> results = new ArrayList<>();
    Imported<ConfigurationOption> options = FurnaceHolder.getAddonRegistry()
                .getServices(ConfigurationOption.class);
    for (ConfigurationOption option : options)
    {
        ClassLoader optionClassLoader = option.getClass().getClassLoader();
        Addon optionAddon = classLoaderToAddon.get(optionClassLoader);
        if (optionAddon.equals(addon))
        {
            results.add(option);
        }
    }
    return results;
}
 
Example #6
Source File: ProxyMethodHandlerDispatchTest.java    From furnace with Eclipse Public License 1.0 6 votes vote down vote up
@Test
@Ignore
public void testProxyCallsDelegateAppropriately() throws Exception
{
   AddonRegistry registry = LocalServices.getFurnace(getClass().getClassLoader())
            .getAddonRegistry();

   Imported<ConcreteC> imported = registry.getServices(ConcreteC.class);
   ConcreteC c = imported.get();
   Assert.assertNotNull(c);

   String payload = "PAYLOAD";
   c.setPayload(payload);

   Assert.assertEquals(payload, c.getPayload());
   Assert.assertEquals(payload.toString(), c.toString());
}
 
Example #7
Source File: ImportedLookupTest.java    From furnace with Eclipse Public License 1.0 5 votes vote down vote up
@Test(expected = ContainerException.class)
public void testDoesNotResolveNonService() throws Exception
{
   AddonRegistry registry = LocalServices.getFurnace(getClass().getClassLoader())
            .getAddonRegistry();

   Imported<MockServiceConsumer> importedByName = registry.getServices(MockServiceConsumer.class.getName());
   Assert.assertTrue(importedByName.isUnsatisfied());
   importedByName.get();
}
 
Example #8
Source File: ServiceLookupTest.java    From furnace with Eclipse Public License 1.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void shouldResolveImpls() throws Exception
{
   AddonRegistry registry = LocalServices.getFurnace(getClass().getClassLoader())
            .getAddonRegistry();
   Imported<MockInterface> imported = registry.getServices(MockInterface.class);
   Assert.assertTrue(imported.isAmbiguous());
   Assert.assertEquals(3, Iterators.asList(imported).size());
   Assert.assertThat(registry.getExportedTypes(MockInterface.class).size(), equalTo(3));
   Assert.assertThat(imported, CoreMatchers.<MockInterface> hasItems(
            instanceOf(MockImpl1.class),
            instanceOf(MockImpl2.class),
            instanceOf(SubMockImpl1.class)));
}
 
Example #9
Source File: ImportedTest.java    From furnace with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testIsAmbiguous() throws Exception
{
   Furnace furnace = LocalServices.getFurnace(getClass().getClassLoader());
   AddonRegistry registry = furnace.getAddonRegistry();
   Imported<MockInterface> services = registry.getServices(MockInterface.class);
   Assert.assertFalse(services.isUnsatisfied());
   Assert.assertTrue(services.isAmbiguous());
}
 
Example #10
Source File: ImportedTest.java    From furnace with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testIsAmbiguousUsingClassName() throws Exception
{
   Furnace furnace = LocalServices.getFurnace(getClass().getClassLoader());
   AddonRegistry registry = furnace.getAddonRegistry();
   Imported<MockInterface> services = registry.getServices(MockInterface.class.getName());
   Assert.assertFalse(services.isUnsatisfied());
   Assert.assertTrue(services.isAmbiguous());
}
 
Example #11
Source File: CommandsResource.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
protected ResourceFactory getResourceFactory() {
    AddonRegistry addonRegistry = furnace.getAddonRegistry();
    Imported<ResourceFactory> resourceFactoryImport = addonRegistry.getServices(ResourceFactory.class);
    ResourceFactory resourceFactory = null;
    try {
        resourceFactory = resourceFactoryImport.get();
    } catch (Exception e) {
        LOG.warn("Failed to get ResourceFactory injected: " + e, e);
    }
    if (resourceFactory == null) {
        // lets try one more time - might work this time?
        resourceFactory = resourceFactoryImport.get();
    }
    return resourceFactory;
}
 
Example #12
Source File: FreeMarkerUtil.java    From windup with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Gets freemarker extensions (eg, custom functions) provided by furnace addons
 */
public static Map<String, Object> findFreeMarkerExtensions(Furnace furnace, GraphRewrite event)
{
    Imported<WindupFreeMarkerMethod> freeMarkerMethods = furnace.getAddonRegistry().getServices(
                WindupFreeMarkerMethod.class);
    Map<String, Object> results = new HashMap<>();

    for (WindupFreeMarkerMethod freeMarkerMethod : freeMarkerMethods)
    {
        freeMarkerMethod.setContext(event);
        if (results.containsKey(freeMarkerMethod.getMethodName()))
        {
            throw new WindupException(Util.WINDUP_BRAND_NAME_ACRONYM+" contains two freemarker extension providing the same name: "
                        + freeMarkerMethod.getMethodName());
        }
        results.put(freeMarkerMethod.getMethodName(), freeMarkerMethod);
    }

    Imported<WindupFreeMarkerTemplateDirective> freeMarkerDirectives = furnace.getAddonRegistry().getServices(
                WindupFreeMarkerTemplateDirective.class);
    for (WindupFreeMarkerTemplateDirective freeMarkerDirective : freeMarkerDirectives)
    {
        freeMarkerDirective.setContext(event);
        if (results.containsKey(freeMarkerDirective.getDirectiveName()))
        {
            throw new WindupException(Util.WINDUP_BRAND_NAME_ACRONYM+" contains two freemarker extension providing the same name: "
                        + freeMarkerDirective.getDirectiveName());
        }
        results.put(freeMarkerDirective.getDirectiveName(), freeMarkerDirective);
    }

    return results;
}
 
Example #13
Source File: ClassLoaderAdapterWhitelistLoaderLookupTest.java    From furnace with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testWhitelistLookupConvertsClassTypes() throws Exception
{
   ClassLoader thisLoader = ClassLoaderAdapterWhitelistLoaderLookupTest.class.getClassLoader();

   AddonRegistry registry = LocalServices.getFurnace(getClass().getClassLoader())
            .getAddonRegistry();

   ClassLoader loader1 = registry.getAddon(AddonId.from("dep1", "1")).getClassLoader();
   ClassLoader loader2 = registry.getAddon(AddonId.from("dep2", "1")).getClassLoader();
   ClassLoader loader3 = registry.getAddon(AddonId.from("dep3", "1")).getClassLoader();

   AddonRegistry enhancedRegistry = ClassLoaderAdapterBuilder.callingLoader(thisLoader)
            .delegateLoader(loader2)
            .whitelist(new HashSet<>(Arrays.asList(loader1, loader3))).enhance(registry);

   Assert.assertNotSame(MockContextConsumer.class, registry.getServices(MockContextConsumer.class.getName()).get()
            .getClass());

   Imported<MockContextConsumer> importedByName = enhancedRegistry.getServices(MockContextConsumer.class.getName());
   Assert.assertFalse(importedByName.isUnsatisfied());
   MockContextConsumer consumerByName = importedByName.get();
   Assert.assertSame(MockContextConsumer.class, consumerByName.getClass().getSuperclass());

   Imported<MockContextConsumer> importedByClass = enhancedRegistry.getServices(MockContextConsumer.class);
   Assert.assertFalse(importedByClass.isUnsatisfied());
   MockContextConsumer consumerByClass = importedByClass.get();
   Assert.assertNotSame(MockContextConsumer.class, consumerByClass.getClass());
}
 
Example #14
Source File: CommandsResource.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
public ConverterFactory getConverterFactory() {
    if (converterFactory == null) {
        AddonRegistry addonRegistry = furnace.getAddonRegistry();
        Imported<ConverterFactory> converterFactoryImport = addonRegistry.getServices(ConverterFactory.class);
        converterFactory = converterFactoryImport.get();
    }
    return converterFactory;
}
 
Example #15
Source File: AddonRegistryImpl.java    From furnace with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public <T> Imported<T> getServices(final String typeName)
{
   return new ImportedImpl<>(this, lock, typeName);
}
 
Example #16
Source File: LoadGroovyRulesTest.java    From windup with Eclipse Public License 1.0 4 votes vote down vote up
@Test
public void testGroovyRuleProviderFactory() throws Exception
{
    RuleLoaderContext ruleLoaderContext = new RuleLoaderContext();
    Imported<RuleProviderLoader> loaders = furnace.getAddonRegistry().getServices(
                RuleProviderLoader.class);

    Assert.assertNotNull(loaders);

    List<RuleProvider> allProviders = new ArrayList<>();
    for (RuleProviderLoader loader : loaders)
    {
        allProviders.addAll(loader.getProviders(ruleLoaderContext));
    }

    boolean foundRuleProviderOrigin = false;
    boolean foundRuleOrigin = false;
    boolean foundRhamtRuleProviderOrigin = false;
    boolean foundRhamtRuleOrigin = false;
    boolean foundMtaRuleProviderOrigin = false;
    boolean foundMtaRuleOrigin = false;
    for (RuleProvider provider : allProviders)
    {
        String providerOrigin = provider.getMetadata().getOrigin();
        if (providerOrigin.contains(EXAMPLE_GROOVY_WINDUP_FILE))
        {
            foundRuleProviderOrigin = true;
        }

        if (providerOrigin.contains(EXAMPLE_GROOVY_RHAMT_FILE))
        {
            foundRhamtRuleProviderOrigin = true;
        }

        if (providerOrigin.contains(EXAMPLE_GROOVY_MTA_FILE))
        {
            foundMtaRuleProviderOrigin = true;
        }

        Rule rule = RuleBuilder.define();
        Context ruleContext = (Context) rule;

        AbstractRuleProvider.enhanceRuleMetadata(provider, rule);

        String ruleOrigin = ((String) ruleContext.get(RuleMetadataType.ORIGIN));
        if (ruleOrigin.contains(EXAMPLE_GROOVY_WINDUP_FILE))
        {
            foundRuleOrigin = true;
        }
        else if (ruleOrigin.contains(EXAMPLE_GROOVY_RHAMT_FILE))
        {
            foundRhamtRuleOrigin = true;
        }
        else if (ruleOrigin.contains(EXAMPLE_GROOVY_MTA_FILE))
        {
            foundMtaRuleOrigin = true;
        }
    }
    Assert.assertTrue("Script path should have been set in Rule Metatada", foundRuleOrigin);
    Assert.assertTrue("Script path should have been set in Rule Provider Metatada", foundRuleProviderOrigin);
    Assert.assertTrue("Script path should have been set in RHAMT Rule Metatada", foundRhamtRuleOrigin);
    Assert.assertTrue("Script path should have been set in RHAMT Rule Provider Metatada", foundRhamtRuleProviderOrigin);
    Assert.assertTrue("Script path should have been set in MTA Rule Metatada", foundMtaRuleOrigin);
    Assert.assertTrue("Script path should have been set in MTA Rule Provider Metatada", foundMtaRuleProviderOrigin);
    Assert.assertTrue(allProviders.size() > 0);
}
 
Example #17
Source File: LoadGroovyRulesTest.java    From windup with Eclipse Public License 1.0 4 votes vote down vote up
@Test
public void testGroovyUserDirectoryRuleProvider() throws Exception
{
    // create a user path
    Path userRulesPath = Paths.get(FileUtils.getTempDirectory().toString(), "WindupGroovyPath");
    try
    {
        FileUtils.deleteDirectory(userRulesPath.toFile());
        Files.createDirectories(userRulesPath);
        Path exampleGroovyUserDirWindupGroovyFile = userRulesPath.resolve("ExampleUserFile.windup.groovy");
        Path exampleGroovyUserDirRhamtGroovyFile = userRulesPath.resolve("ExampleUserFile.rhamt.groovy");
        Path exampleGroovyUserDirMtaGroovyFile = userRulesPath.resolve("ExampleUserFile.mta.groovy");

        // copy a groovy rule example to it
        try (InputStream is = getClass().getResourceAsStream(EXAMPLE_GROOVY_WINDUP_FILE);
                    OutputStream os = new FileOutputStream(exampleGroovyUserDirWindupGroovyFile.toFile()))
        {
            IOUtils.copy(is, os);
        }

        try (InputStream is = getClass().getResourceAsStream(EXAMPLE_GROOVY_RHAMT_FILE);
                    OutputStream os = new FileOutputStream(exampleGroovyUserDirRhamtGroovyFile.toFile()))
        {
            IOUtils.copy(is, os);
        }

        try (InputStream is = getClass().getResourceAsStream(EXAMPLE_GROOVY_MTA_FILE);
                    OutputStream os = new FileOutputStream(exampleGroovyUserDirMtaGroovyFile.toFile()))
        {
            IOUtils.copy(is, os);
        }

        RuleLoaderContext ruleLoaderContext = new RuleLoaderContext(Collections.singleton(userRulesPath), null);

        Imported<RuleProviderLoader> loaders = furnace.getAddonRegistry().getServices(
                    RuleProviderLoader.class);

        Assert.assertNotNull(loaders);

        List<RuleProvider> allProviders = new ArrayList<>();
        for (RuleProviderLoader loader : loaders)
        {
            allProviders.addAll(loader.getProviders(ruleLoaderContext));
        }

        boolean foundScriptPath = false;
        boolean foundRhamtScriptPath = false;
        boolean foundMtaScriptPath = false;
        for (RuleProvider provider : allProviders)
        {
            Rule rule = RuleBuilder.define();
            Context ruleContext = (Context) rule;

            AbstractRuleProvider.enhanceRuleMetadata(provider, rule);

            String origin = ((String) ruleContext.get(RuleMetadataType.ORIGIN));

            if (origin.endsWith("ExampleUserFile.windup.groovy"))
            {
                // make sure we found the one from the user dir
                foundScriptPath = true;
            }
            else if (origin.endsWith("ExampleUserFile.rhamt.groovy"))
            {
                // make sure we found the one from the user dir
                foundRhamtScriptPath = true;
            }
            else if (origin.endsWith("ExampleUserFile.mta.groovy"))
            {
                // make sure we found the one from the user dir
                foundMtaScriptPath = true;
            }
        }
        Assert.assertTrue("Script path should have been set in Rule Metatada", foundScriptPath);
        Assert.assertTrue("Script path should have been set in RHAMT Rule Metatada", foundRhamtScriptPath);
        Assert.assertTrue("Script path should have been set in MTA Rule Metatada", foundMtaScriptPath);
        Assert.assertTrue(allProviders.size() > 0);
    }
    finally
    {
        FileUtils.deleteDirectory(userRulesPath.toFile());
    }
}
 
Example #18
Source File: Bootstrap.java    From windup with Eclipse Public License 1.0 4 votes vote down vote up
private void run(List<String> args)
{
    try
    {
        furnace = FurnaceFactory.getInstance();
        furnace.setServerMode(true);

        CopyOnWriteArrayList<Command> commands = new CopyOnWriteArrayList<>(processArguments(args));

        if (!executePhase(CommandPhase.PRE_CONFIGURATION, commands))
            return;

        if (!executePhase(CommandPhase.CONFIGURATION, commands))
            return;

        if (commands.isEmpty())
        {
            // no commands are available, just print the help and exit
            new DisplayHelpCommand().execute();
            return;
        }

        if (!containsMutableRepository(furnace.getRepositories()))
        {
            furnace.addRepository(AddonRepositoryMode.MUTABLE, getUserAddonsDir());
        }

        if (!executePhase(CommandPhase.POST_CONFIGURATION, commands) || commands.isEmpty())
            return;

        furnace.addContainerLifecycleListener(containerStatusListener);
        try
        {
            startFurnace();
        }
        catch (Exception e)
        {
            System.out.println("Failed to start "+ Util.WINDUP_BRAND_NAME_ACRONYM+"!");
            if (e.getMessage() != null)
                System.out.println("Failure reason: " + e.getMessage());
            e.printStackTrace();
        }

        if (!executePhase(CommandPhase.PRE_EXECUTION, commands) || commands.isEmpty())
            return;

        furnace.addContainerLifecycleListener(new GreetingListener());

        // Now see if there are any server SPIs that need to run
        Imported<WindupServerProvider> serverProviders = furnace.getAddonRegistry().getServices(WindupServerProvider.class);
        for (WindupServerProvider serverProvider : serverProviders)
        {
            String expectedArgName = serverProvider.getName();

            boolean matches = args.stream().anyMatch(arg ->
                arg.equals(expectedArgName) || arg.equals("--" + expectedArgName)
            );
            if (matches)
            {
                serverProvider.runServer(args.toArray(new String[args.size()]));
                return;
            }
        }

        if (!executePhase(CommandPhase.EXECUTION, commands) || commands.isEmpty())
            return;

        if (!executePhase(CommandPhase.POST_EXECUTION, commands) || commands.isEmpty())
            return;

    }
    catch (Throwable t)
    {
        System.err.println(Util.WINDUP_BRAND_NAME_ACRONYM +" execution failed due to: " + t.getMessage());
        t.printStackTrace();
    }
}
 
Example #19
Source File: AddonRegistry.java    From furnace with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Return an {@link Imported} instance that can be used to obtain all currently available services with
 * {@link Class#getName()} matching the given name.
 * 
 * @return the {@link Imported} (Never null.)
 */
<T> Imported<T> getServices(String clazz);
 
Example #20
Source File: AddonRegistry.java    From furnace with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Return an {@link Imported} instance that can be used to obtain all currently available services of the given
 * {@link Class} type.
 * 
 * @return the {@link Imported} (Never null.)
 */
<T> Imported<T> getServices(Class<T> clazz);