Search in sources :

Example 31 with ServiceLoader

use of java.util.ServiceLoader in project wildfly by wildfly.

the class WeldSubsystemAdd method performBoottime.

@Override
protected void performBoottime(final OperationContext context, ModelNode operation, Resource resource) throws OperationFailedException {
    final ModelNode model = resource.getModel();
    final boolean requireBeanDescriptor = REQUIRE_BEAN_DESCRIPTOR_ATTRIBUTE.resolveModelAttribute(context, model).asBoolean();
    final boolean legacyEmptyBeansXmlTreatment = LEGACY_EMPTY_BEANS_XML_TREATMENT_ATTRIBUTE.resolveModelAttribute(context, model).asBoolean();
    final boolean nonPortableMode = WeldResourceDefinition.NON_PORTABLE_MODE_ATTRIBUTE.resolveModelAttribute(context, model).asBoolean();
    final boolean developmentMode = WeldResourceDefinition.DEVELOPMENT_MODE_ATTRIBUTE.resolveModelAttribute(context, model).asBoolean();
    final int threadPoolSize = WeldResourceDefinition.THREAD_POOL_SIZE_ATTRIBUTE.resolveModelAttribute(context, model).asInt(WeldExecutorServices.DEFAULT_BOUND);
    context.addStep(new AbstractDeploymentChainStep() {

        @Override
        protected void execute(DeploymentProcessorTarget processorTarget) {
            final JBossAllXmlParserRegisteringProcessor<?> jbossAllParsers = JBossAllXmlParserRegisteringProcessor.builder().addParser(WeldJBossAll10Parser.ROOT_ELEMENT, WeldJBossAllConfiguration.ATTACHMENT_KEY, WeldJBossAll10Parser.INSTANCE).addParser(WeldJBossAll11Parser.ROOT_ELEMENT, WeldJBossAllConfiguration.ATTACHMENT_KEY, WeldJBossAll11Parser.INSTANCE).build();
            processorTarget.addDeploymentProcessor(WeldExtension.SUBSYSTEM_NAME, Phase.STRUCTURE, Phase.STRUCTURE_REGISTER_JBOSS_ALL_WELD, jbossAllParsers);
            processorTarget.addDeploymentProcessor(WeldExtension.SUBSYSTEM_NAME, Phase.PARSE, Phase.PARSE_WELD_CONFIGURATION, new WeldConfigurationProcessor(requireBeanDescriptor, nonPortableMode, developmentMode, legacyEmptyBeansXmlTreatment));
            processorTarget.addDeploymentProcessor(WeldExtension.SUBSYSTEM_NAME, Phase.PARSE, Phase.PARSE_CDI_ANNOTATIONS, new CdiAnnotationProcessor());
            processorTarget.addDeploymentProcessor(WeldExtension.SUBSYSTEM_NAME, Phase.PARSE, Phase.PARSE_CDI_BEAN_DEFINING_ANNOTATIONS, new BeanDefiningAnnotationProcessor());
            processorTarget.addDeploymentProcessor(WeldExtension.SUBSYSTEM_NAME, Phase.PARSE, Phase.PARSE_WELD_DEPLOYMENT, new BeansXmlProcessor());
            processorTarget.addDeploymentProcessor(WeldExtension.SUBSYSTEM_NAME, Phase.PARSE, Phase.PARSE_WELD_IMPLICIT_DEPLOYMENT_DETECTION, new WeldImplicitDeploymentProcessor());
            processorTarget.addDeploymentProcessor(WeldExtension.SUBSYSTEM_NAME, Phase.DEPENDENCIES, Phase.DEPENDENCIES_WELD, new WeldDependencyProcessor());
            processorTarget.addDeploymentProcessor(WeldExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_WELD_WEB_INTEGRATION, new WebIntegrationProcessor());
            processorTarget.addDeploymentProcessor(WeldExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_WELD_DEVELOPMENT_MODE, new DevelopmentModeProcessor());
            processorTarget.addDeploymentProcessor(WeldExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_WELD_BEAN_ARCHIVE, new BeanArchiveProcessor());
            processorTarget.addDeploymentProcessor(WeldExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_WELD_EXTERNAL_BEAN_ARCHIVE, new ExternalBeanArchiveProcessor());
            processorTarget.addDeploymentProcessor(WeldExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_WELD_PORTABLE_EXTENSIONS, new WeldPortableExtensionProcessor());
            // TODO add processor priority to Phase
            processorTarget.addDeploymentProcessor(WeldExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, 0x0F10, new EarApplicationScopedObserverMethodProcessor());
            processorTarget.addDeploymentProcessor(WeldExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_WELD_COMPONENT_INTEGRATION, new WeldComponentIntegrationProcessor());
            processorTarget.addDeploymentProcessor(WeldExtension.SUBSYSTEM_NAME, Phase.INSTALL, Phase.INSTALL_WELD_DEPLOYMENT, new WeldDeploymentProcessor(checkJtsEnabled(context)));
            processorTarget.addDeploymentProcessor(WeldExtension.SUBSYSTEM_NAME, Phase.INSTALL, Phase.INSTALL_WELD_BEAN_MANAGER, new WeldBeanManagerServiceProcessor());
            // note that we want to go one step before Phase.CLEANUP_EE because we use metadata that it then cleans up
            processorTarget.addDeploymentProcessor(WeldExtension.SUBSYSTEM_NAME, Phase.CLEANUP, Phase.CLEANUP_EE - 1, new WeldDeploymentCleanupProcessor());
            // Add additional deployment processors
            ServiceLoader<DeploymentUnitProcessorProvider> processorProviders = ServiceLoader.load(DeploymentUnitProcessorProvider.class, WildFlySecurityManager.getClassLoaderPrivileged(WeldSubsystemAdd.class));
            for (DeploymentUnitProcessorProvider provider : processorProviders) {
                processorTarget.addDeploymentProcessor(WeldExtension.SUBSYSTEM_NAME, provider.getPhase(), provider.getPriority(), provider.getProcessor());
            }
        }
    }, OperationContext.Stage.RUNTIME);
    context.getServiceTarget().addService(TCCLSingletonService.SERVICE_NAME).setInstance(new TCCLSingletonService()).setInitialMode(Mode.ON_DEMAND).install();
    ServiceBuilder<?> builder = context.getServiceTarget().addService(WeldExecutorServices.SERVICE_NAME);
    final Consumer<ExecutorServices> executorServicesConsumer = builder.provides(WeldExecutorServices.SERVICE_NAME);
    builder.setInstance(new WeldExecutorServices(executorServicesConsumer, threadPoolSize));
    builder.setInitialMode(Mode.ON_DEMAND);
    builder.install();
}
Also used : WeldBeanManagerServiceProcessor(org.jboss.as.weld.deployment.processors.WeldBeanManagerServiceProcessor) DeploymentUnitProcessorProvider(org.jboss.as.weld.spi.DeploymentUnitProcessorProvider) WeldPortableExtensionProcessor(org.jboss.as.weld.deployment.processors.WeldPortableExtensionProcessor) WeldImplicitDeploymentProcessor(org.jboss.as.weld.deployment.processors.WeldImplicitDeploymentProcessor) ExternalBeanArchiveProcessor(org.jboss.as.weld.deployment.processors.ExternalBeanArchiveProcessor) BeanArchiveProcessor(org.jboss.as.weld.deployment.processors.BeanArchiveProcessor) WebIntegrationProcessor(org.jboss.as.weld.deployment.processors.WebIntegrationProcessor) CdiAnnotationProcessor(org.jboss.as.weld.deployment.CdiAnnotationProcessor) WeldDependencyProcessor(org.jboss.as.weld.deployment.processors.WeldDependencyProcessor) WeldDeploymentProcessor(org.jboss.as.weld.deployment.processors.WeldDeploymentProcessor) TCCLSingletonService(org.jboss.as.weld.services.TCCLSingletonService) DevelopmentModeProcessor(org.jboss.as.weld.deployment.processors.DevelopmentModeProcessor) WeldComponentIntegrationProcessor(org.jboss.as.weld.deployment.processors.WeldComponentIntegrationProcessor) JBossAllXmlParserRegisteringProcessor(org.jboss.as.server.deployment.jbossallxml.JBossAllXmlParserRegisteringProcessor) EarApplicationScopedObserverMethodProcessor(org.jboss.as.weld.deployment.processors.EarApplicationScopedObserverMethodProcessor) WeldDeploymentCleanupProcessor(org.jboss.as.weld.deployment.processors.WeldDeploymentCleanupProcessor) WeldConfigurationProcessor(org.jboss.as.weld.deployment.processors.WeldConfigurationProcessor) ServiceLoader(java.util.ServiceLoader) WeldExecutorServices(org.jboss.as.weld.services.bootstrap.WeldExecutorServices) ExternalBeanArchiveProcessor(org.jboss.as.weld.deployment.processors.ExternalBeanArchiveProcessor) DeploymentProcessorTarget(org.jboss.as.server.DeploymentProcessorTarget) BeanDefiningAnnotationProcessor(org.jboss.as.weld.deployment.processors.BeanDefiningAnnotationProcessor) ExecutorServices(org.jboss.weld.manager.api.ExecutorServices) WeldExecutorServices(org.jboss.as.weld.services.bootstrap.WeldExecutorServices) AbstractDeploymentChainStep(org.jboss.as.server.AbstractDeploymentChainStep) ModelNode(org.jboss.dmr.ModelNode) BeansXmlProcessor(org.jboss.as.weld.deployment.processors.BeansXmlProcessor)

Example 32 with ServiceLoader

use of java.util.ServiceLoader in project powermock by powermock.

the class ServiceLoaderTest method supportsMockingServiceLoader.

@Test(expected = IllegalArgumentException.class)
public void supportsMockingServiceLoader() throws Exception {
    final ServiceLoader mock = mock(ServiceLoader.class);
    doThrow(new IllegalArgumentException("something")).when(mock).reload();
    mock.reload();
}
Also used : ServiceLoader(java.util.ServiceLoader) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 33 with ServiceLoader

use of java.util.ServiceLoader in project syndesis-qe by syndesisio.

the class CommonSteps method isProjectClean.

/**
 * Workaround for isProjectClean function from XTF. See issue: https://github.com/xtf-cz/xtf/issues/406
 * XTF cannot be update because it uses openshift-client 4.13.0 which contains kubernetes-model 4.11.2 where CRD was moved to the `v1beta1` .
 * Since Syndesis endpoints uses old kubernetes-model, the CRD is missing (`NoClassDefFoundError`)
 * When we let Syndesis endpoints to bring the old kubernetes-model with itself (remove <exclude> from parent pom.xml),
 * it causes undesired behaviour, e.g. portForwarding doesn't work correctly etc.
 * So we need to wait with bump xtf version until the Syndesis will contains newer kubernetes-model
 * <p>
 * This is implementation from XTF with workaround
 * To access to the protected methods, the JavaReflection API is used.
 */
private static Waiter isProjectClean() {
    return new SimpleWaiter(() -> {
        int crdInstances = 0;
        int removableResources = 0;
        try {
            Method privateMethodGetCRDContextProviders = OpenShift.class.getDeclaredMethod("getCRDContextProviders", null);
            privateMethodGetCRDContextProviders.setAccessible(true);
            Method privateMethodListRemovableResources = OpenShift.class.getDeclaredMethod("listRemovableResources", null);
            privateMethodListRemovableResources.setAccessible(true);
            ServiceLoader<CustomResourceDefinitionContextProvider> cRDContextProviders = (ServiceLoader<CustomResourceDefinitionContextProvider>) privateMethodGetCRDContextProviders.invoke(OpenShift.class, null);
            for (CustomResourceDefinitionContextProvider crdContextProvider : cRDContextProviders) {
                try {
                    crdInstances += ((List) (OpenShiftUtils.getInstance().customResource(crdContextProvider.getContext()).list(OpenShiftUtils.getInstance().getNamespace()).get("items"))).size();
                } catch (KubernetesClientException kce) {
                // CRD might not be installed on the cluster
                }
            }
            List<HasMetadata> removableResourcesList = (List<HasMetadata>) privateMethodListRemovableResources.invoke(OpenShiftUtils.getInstance(), null);
            removableResources = removableResourcesList.size();
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            e.printStackTrace();
        }
        return crdInstances == 0 & // <=1 because configMap can be there on OCP 4.7, see https://github.com/xtf-cz/xtf/issues/406
        removableResources <= 1;
    }, TimeUnit.MILLISECONDS, WaitingConfig.timeoutCleanup(), "Cleaning project.");
}
Also used : HasMetadata(io.fabric8.kubernetes.api.model.HasMetadata) Method(java.lang.reflect.Method) CustomResourceDefinitionContextProvider(cz.xtf.core.openshift.crd.CustomResourceDefinitionContextProvider) InvocationTargetException(java.lang.reflect.InvocationTargetException) ServiceLoader(java.util.ServiceLoader) OpenShift(cz.xtf.core.openshift.OpenShift) SimpleWaiter(cz.xtf.core.waiting.SimpleWaiter) List(java.util.List) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Example 34 with ServiceLoader

use of java.util.ServiceLoader in project flow by vaadin.

the class VaadinService method loadInstantiators.

/**
 * Loads and initializes instantiators.
 * <p>
 * A custom Vaadin service implementation can override this method to pick
 * an instantiator in some other way instead of the default implementation
 * that uses {@link ServiceLoader}.
 * <p>
 * There may be only one applicable instantiator. Otherwise
 * {@link ServiceException} will be thrown.
 *
 * @return an optional instantator, or an empty optional if no instantiator
 *         found
 * @throws ServiceException
 *             if there are multiple applicable instantiators
 * @see #createInstantiator()
 * @see Instantiator
 */
protected Optional<Instantiator> loadInstantiators() throws ServiceException {
    Lookup lookup = getContext().getAttribute(Lookup.class);
    List<Instantiator> instantiators = null;
    if (lookup != null) {
        // lookup may be null in tests
        Collection<InstantiatorFactory> factories = lookup.lookupAll(InstantiatorFactory.class);
        instantiators = new ArrayList<>(factories.size());
        for (InstantiatorFactory factory : factories) {
            Instantiator instantiator = factory.createInstantitor(this);
            // let's respect its deprecated method
            if (instantiator != null && instantiator.init(this)) {
                instantiators.add(instantiator);
            }
        }
    }
    if (instantiators == null) {
        instantiators = new ArrayList<>();
    }
    // the code to support previous way of loading instantiators
    StreamSupport.stream(ServiceLoader.load(Instantiator.class, getClassLoader()).spliterator(), false).filter(iterator -> iterator.init(this)).forEach(instantiators::add);
    if (instantiators.size() > 1) {
        throw new ServiceException("Cannot init VaadinService because there are multiple eligible instantiator implementations: " + instantiators);
    }
    return instantiators.stream().findFirst();
}
Also used : InstantiatorFactory(com.vaadin.flow.di.InstantiatorFactory) StreamRequestHandler(com.vaadin.flow.server.communication.StreamRequestHandler) URL(java.net.URL) CurrentInstance(com.vaadin.flow.internal.CurrentInstance) Registration(com.vaadin.flow.shared.Registration) LoggerFactory(org.slf4j.LoggerFactory) Json(elemental.json.Json) UidlRequestHandler(com.vaadin.flow.server.communication.UidlRequestHandler) Router(com.vaadin.flow.router.Router) Future(java.util.concurrent.Future) PushMode(com.vaadin.flow.shared.communication.PushMode) JsonUtil(elemental.json.impl.JsonUtil) Locale(java.util.Locale) Map(java.util.Map) UsageStatistics(com.vaadin.flow.internal.UsageStatistics) WebComponentBootstrapHandler(com.vaadin.flow.server.communication.WebComponentBootstrapHandler) IndexHtmlResponse(com.vaadin.flow.server.communication.IndexHtmlResponse) Lookup(com.vaadin.flow.di.Lookup) UI(com.vaadin.flow.component.UI) I18NProvider(com.vaadin.flow.i18n.I18NProvider) PrintWriter(java.io.PrintWriter) RouteData(com.vaadin.flow.router.RouteData) Servlet(javax.servlet.Servlet) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) SessionRequestHandler(com.vaadin.flow.server.communication.SessionRequestHandler) ServiceLoader(java.util.ServiceLoader) WebComponentProvider(com.vaadin.flow.server.communication.WebComponentProvider) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) Serializable(java.io.Serializable) IndexHtmlRequestListener(com.vaadin.flow.server.communication.IndexHtmlRequestListener) List(java.util.List) JavaScriptBootstrapHandler(com.vaadin.flow.server.communication.JavaScriptBootstrapHandler) Entry(java.util.Map.Entry) Optional(java.util.Optional) HeartbeatHandler(com.vaadin.flow.server.communication.HeartbeatHandler) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ApplicationConstants(com.vaadin.flow.shared.ApplicationConstants) LocaleUtil(com.vaadin.flow.internal.LocaleUtil) MessageDigest(java.security.MessageDigest) HashMap(java.util.HashMap) Constructor(java.lang.reflect.Constructor) DeploymentConfiguration(com.vaadin.flow.function.DeploymentConfiguration) ArrayList(java.util.ArrayList) OutputStreamWriter(java.io.OutputStreamWriter) StreamSupport(java.util.stream.StreamSupport) PwaHandler(com.vaadin.flow.server.communication.PwaHandler) JsonException(elemental.json.JsonException) OutputStream(java.io.OutputStream) Instantiator(com.vaadin.flow.di.Instantiator) Logger(org.slf4j.Logger) ReentrantLock(java.util.concurrent.locks.ReentrantLock) BufferedWriter(java.io.BufferedWriter) UTF_8(java.nio.charset.StandardCharsets.UTF_8) JsonConstants(com.vaadin.flow.shared.JsonConstants) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) InstantiatorFactory(com.vaadin.flow.di.InstantiatorFactory) TimeUnit(java.util.concurrent.TimeUnit) AtmospherePushConnection(com.vaadin.flow.server.communication.AtmospherePushConnection) Lock(java.util.concurrent.locks.Lock) DefaultInstantiator(com.vaadin.flow.di.DefaultInstantiator) ServletContext(javax.servlet.ServletContext) JsonObject(elemental.json.JsonObject) RequestType(com.vaadin.flow.server.HandlerHelper.RequestType) Collections(java.util.Collections) InputStream(java.io.InputStream) Lookup(com.vaadin.flow.di.Lookup) Instantiator(com.vaadin.flow.di.Instantiator) DefaultInstantiator(com.vaadin.flow.di.DefaultInstantiator)

Example 35 with ServiceLoader

use of java.util.ServiceLoader in project wildfly-swarm by wildfly-swarm.

the class StandaloneXMLParserProducer method setupFactory.

private void setupFactory(Fraction fraction) throws Exception {
    try (AutoCloseable handle = Performance.time("Setting up XML parser: " + fraction.getClass().getSimpleName())) {
        WildFlyExtension anno = fraction.getClass().getAnnotation(WildFlyExtension.class);
        if (anno == null) {
            return;
        }
        String extensionModuleName = anno.module();
        String extensionClassName = anno.classname();
        boolean noClass = anno.noClass();
        if (extensionClassName != null && extensionClassName.trim().isEmpty()) {
            extensionClassName = null;
        }
        Module extensionModule = Module.getBootModuleLoader().loadModule(extensionModuleName);
        if (noClass) {
        // ignore it all
        } else if (extensionClassName != null) {
            Class<?> extCls = extensionModule.getClassLoader().loadClass(extensionClassName);
            try {
                Extension ext = (Extension) extCls.newInstance();
                add(ext);
            } catch (InstantiationException | IllegalAccessException e) {
                SwarmConfigMessages.MESSAGES.errorCreatingExtension(extensionClassName, extensionModuleName, e);
            }
        } else {
            ServiceLoader<Extension> extensionLoader = extensionModule.loadService(Extension.class);
            Iterator<Extension> extensionIter = extensionLoader.iterator();
            List<Extension> extensions = new ArrayList<>();
            if (extensionIter.hasNext()) {
                Extension ext = extensionIter.next();
                extensions.add(ext);
            }
            if (extensions.size() > 1) {
                throw SwarmMessages.MESSAGES.fractionHasMultipleExtensions(fraction.getClass().getName(), extensions.stream().map(Objects::toString).collect(Collectors.toList()));
            }
            if (!extensions.isEmpty()) {
                add(extensions.get(0));
            }
        }
    }
}
Also used : Extension(org.jboss.as.controller.Extension) WildFlyExtension(org.wildfly.swarm.spi.api.annotations.WildFlyExtension) ServiceLoader(java.util.ServiceLoader) WildFlyExtension(org.wildfly.swarm.spi.api.annotations.WildFlyExtension) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) List(java.util.List) Module(org.jboss.modules.Module)

Aggregations

ServiceLoader (java.util.ServiceLoader)68 Iterator (java.util.Iterator)46 Test (org.junit.Test)46 HashMap (java.util.HashMap)6 ArrayList (java.util.ArrayList)5 List (java.util.List)4 NoSuchElementException (java.util.NoSuchElementException)3 Optional (java.util.Optional)3 ServiceConfigurationError (java.util.ServiceConfigurationError)3 ServletContext (javax.servlet.ServletContext)3 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)3 Logger (org.slf4j.Logger)3 LoggerFactory (org.slf4j.LoggerFactory)3 IOException (java.io.IOException)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 CharsetProvider (java.nio.charset.spi.CharsetProvider)2 Map (java.util.Map)2 Entry (java.util.Map.Entry)2 Set (java.util.Set)2 Collectors (java.util.stream.Collectors)2