repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/deployment/PropertyReplacingBeansXmlParser.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment;
import java.net.URL;
import org.jboss.as.ee.structure.SpecDescriptorPropertyReplacement;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.metadata.property.PropertyReplacer;
import org.jboss.weld.xml.BeansXmlParser;
/**
* Fork of {@link org.jboss.weld.xml.BeansXmlParser} to support standard WildFly deployment descriptor expression resolution.
*
* @author Stuart Douglas
* @author Pete Muir
* @author Jozef Hartinger
*/
public class PropertyReplacingBeansXmlParser extends BeansXmlParser {
private final PropertyReplacer replacer;
public PropertyReplacingBeansXmlParser(DeploymentUnit deploymentUnit, boolean legacyEmptyBeansXmlTreatment) {
super(legacyEmptyBeansXmlTreatment);
this.replacer = SpecDescriptorPropertyReplacement.propertyReplacer(deploymentUnit);
}
protected PropertyReplacingBeansXmlHandler getHandler(final URL beansXml) {
return new PropertyReplacingBeansXmlHandler(beansXml, replacer);
}
}
| 2,042 | 39.058824 | 125 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/deployment/WeldClassIntrospector.java | package org.jboss.as.weld.deployment;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Consumer;
import java.util.function.Supplier;
import jakarta.enterprise.context.spi.CreationalContext;
import jakarta.enterprise.inject.Any;
import jakarta.enterprise.inject.spi.Bean;
import jakarta.enterprise.inject.spi.BeanManager;
import jakarta.enterprise.inject.spi.InjectionTarget;
import org.jboss.as.ee.component.EEClassIntrospector;
import org.jboss.as.naming.ManagedReference;
import org.jboss.as.naming.ManagedReferenceFactory;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.weld.WeldStartService;
import org.jboss.as.weld.injection.InjectionTargets;
import org.jboss.as.weld.services.BeanManagerService;
import org.jboss.as.weld.util.Utils;
import org.jboss.msc.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.weld.bean.builtin.BeanManagerProxy;
import org.jboss.weld.injection.producer.BasicInjectionTarget;
import org.jboss.weld.manager.BeanManagerImpl;
/**
* @author Stuart Douglas
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public class WeldClassIntrospector implements EEClassIntrospector, Service {
private static final ServiceName SERVICE_NAME = ServiceName.of("weld", "weldClassIntrospector");
private final Consumer<EEClassIntrospector> eeClassIntrospectorConsumer;
private final Supplier<BeanManager> beanManagerSupplier;
private final ConcurrentMap<Class<?>, InjectionTarget<?>> injectionTargets = new ConcurrentHashMap<>();
private WeldClassIntrospector(final Consumer<EEClassIntrospector> eeClassIntrospectorConsumer, final Supplier<BeanManager> beanManagerSupplier) {
this.eeClassIntrospectorConsumer = eeClassIntrospectorConsumer;
this.beanManagerSupplier = beanManagerSupplier;
}
public static void install(final DeploymentUnit deploymentUnit, final ServiceTarget serviceTarget) {
final ServiceName sn = serviceName(deploymentUnit);
final ServiceBuilder<?> sb = serviceTarget.addService(sn);
final Consumer<EEClassIntrospector> eeClassIntrospectorConsumer = sb.provides(sn);
final Supplier<BeanManager> beanManagerSupplier = sb.requires(BeanManagerService.serviceName(deploymentUnit));
sb.requires(Utils.getRootDeploymentUnit(deploymentUnit).getServiceName().append(WeldStartService.SERVICE_NAME));
sb.setInstance(new WeldClassIntrospector(eeClassIntrospectorConsumer, beanManagerSupplier));
sb.install();
}
public static ServiceName serviceName(DeploymentUnit deploymentUnit) {
return deploymentUnit.getServiceName().append(SERVICE_NAME);
}
@Override
public ManagedReferenceFactory createFactory(Class<?> clazz) {
final BeanManager beanManager = this.beanManagerSupplier.get();
final InjectionTarget injectionTarget = getInjectionTarget(clazz);
return new ManagedReferenceFactory() {
@Override
public ManagedReference getReference() {
final CreationalContext context = beanManager.createCreationalContext(null);
Object instance;
BasicInjectionTarget target = injectionTarget instanceof BasicInjectionTarget ? (BasicInjectionTarget) injectionTarget: null;
if(target != null && target.getBean() != null) {
instance = beanManager.getReference(target.getBean(), target.getAnnotatedType().getBaseType(), context);
} else {
instance = injectionTarget.produce(context);
}
injectionTarget.inject(instance, context);
injectionTarget.postConstruct(instance);
return new WeldManagedReference(injectionTarget, context, instance);
}
};
}
private InjectionTarget getInjectionTarget(Class<?> clazz) {
InjectionTarget<?> target = injectionTargets.get(clazz);
if (target != null) {
return target;
}
final BeanManagerImpl beanManager = BeanManagerProxy.unwrap(beanManagerSupplier.get());
Bean<?> bean = null;
Set<Bean<?>> beans = new HashSet<>(beanManager.getBeans(clazz, Any.Literal.INSTANCE));
Iterator<Bean<?>> it = beans.iterator();
//we may have resolved some sub-classes
//go through and remove them from the bean set
while (it.hasNext()) {
Bean<?> b = it.next();
if(b.getBeanClass() != clazz) {
it.remove();
}
}
if(beans.size() == 1) {
bean = beans.iterator().next();
}
InjectionTarget<?> newTarget = InjectionTargets.createInjectionTarget(clazz, bean, beanManager, true);
target = injectionTargets.putIfAbsent(clazz, newTarget);
if (target == null) {
return newTarget;
} else {
return target;
}
}
@Override
public ManagedReference createInstance(final Object instance) {
return this.getReference(instance, true);
}
@Override
public ManagedReference getInstance(Object instance) {
return this.getReference(instance, false);
}
private ManagedReference getReference(Object instance, boolean newInstance) {
final BeanManager beanManager = beanManagerSupplier.get();
final InjectionTarget injectionTarget = getInjectionTarget(instance.getClass());
final CreationalContext context = beanManager.createCreationalContext(null);
if (newInstance) {
injectionTarget.inject(instance, context);
injectionTarget.postConstruct(instance);
}
return new WeldManagedReference(injectionTarget, context, instance);
}
@Override
public void start(final StartContext startContext) throws StartException {
eeClassIntrospectorConsumer.accept(this);
}
@Override
public void stop(StopContext stopContext) {
injectionTargets.clear();
}
private static class WeldManagedReference implements ManagedReference {
private final InjectionTarget injectionTarget;
private final CreationalContext ctx;
private final Object instance;
public WeldManagedReference(InjectionTarget injectionTarget, CreationalContext ctx, Object instance) {
this.injectionTarget = injectionTarget;
this.ctx = ctx;
this.instance = instance;
}
@Override
public void release() {
try {
injectionTarget.preDestroy(instance);
} finally {
ctx.release();
}
}
@Override
public Object getInstance() {
return instance;
}
}
}
| 7,126 | 39.039326 | 149 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/deployment/ExplicitBeanArchiveMetadata.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment;
import org.jboss.as.server.deployment.module.ResourceRoot;
import org.jboss.vfs.VirtualFile;
import org.jboss.weld.bootstrap.spi.BeansXml;
/**
* Maintains information about an explicit bean archive
* <p>
* Thread Safety: This class is immutable and does not require a happens before event between construction and usage
*
* @author Stuart Douglas
*
*/
public class ExplicitBeanArchiveMetadata {
/**
* The location of the beans.xml file for this bean archive
*/
private final VirtualFile beansXmlFile;
/**
* The ResourceRoot for the archive
*/
private final ResourceRoot resourceRoot;
/**
* If this bean archive is the root of the deployment (e.g. an ear or a standalone war)
*/
private final boolean deploymentRoot;
/**
* the parsed beans.xml representation
*/
private final BeansXml beansXml;
/**
* The location of an additional beans.xml file for this bean archive. This may happen if a web archive defines
* both META-INF/beans.xml and WEB-INF/beans.xml
*/
private final VirtualFile additionalBeansXmlFile;
public ExplicitBeanArchiveMetadata(VirtualFile beansXmlFile, ResourceRoot resourceRoot, BeansXml beansXml, boolean deploymentRoot) {
this(beansXmlFile, null, resourceRoot, beansXml, deploymentRoot);
}
public ExplicitBeanArchiveMetadata(VirtualFile beansXmlFile, VirtualFile additionalBeansXmlFile, ResourceRoot resourceRoot, BeansXml beansXml, boolean deploymentRoot) {
this.beansXmlFile = beansXmlFile;
this.additionalBeansXmlFile = additionalBeansXmlFile;
this.resourceRoot = resourceRoot;
this.deploymentRoot = deploymentRoot;
this.beansXml = beansXml;
}
public VirtualFile getBeansXmlFile() {
return beansXmlFile;
}
public ResourceRoot getResourceRoot() {
return resourceRoot;
}
public boolean isDeploymentRoot() {
return deploymentRoot;
}
public BeansXml getBeansXml() {
return beansXml;
}
public VirtualFile getAdditionalBeansXmlFile() {
return additionalBeansXmlFile;
}
}
| 3,203 | 32.375 | 172 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/deployment/CdiAnnotationMarker.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment;
import static org.jboss.as.weld.util.Utils.getRootDeploymentUnit;
import org.jboss.as.server.deployment.AttachmentKey;
import org.jboss.as.server.deployment.DeploymentUnit;
/**
* Marker for deployments that have CDI annotations present
*/
public final class CdiAnnotationMarker {
/**
* Boolean attachment key.
*/
private static final AttachmentKey<Boolean> ATTACHMENT_KEY = AttachmentKey.create(Boolean.class);
/**
* Default constructor not visible.
*/
private CdiAnnotationMarker() {
}
/**
* Mark the deployment as a CDI one.
*
* @param deployment to be marked
*/
public static void mark(final DeploymentUnit deployment) {
if (deployment.getParent() != null) {
deployment.getParent().putAttachment(ATTACHMENT_KEY, true);
} else {
deployment.putAttachment(ATTACHMENT_KEY, true);
}
}
public static boolean cdiAnnotationsPresent(final DeploymentUnit deploymentUnit) {
Boolean val = getRootDeploymentUnit(deploymentUnit).getAttachment(ATTACHMENT_KEY);
return val != null && val;
}
}
| 2,186 | 34.274194 | 101 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/deployment/WeldDeployment.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import jakarta.enterprise.inject.spi.Extension;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.weld.WeldModuleResourceLoader;
import org.jboss.as.weld.deployment.BeanDeploymentArchiveImpl.BeanArchiveType;
import org.jboss.as.weld.logging.WeldLogger;
import org.jboss.as.weld.services.bootstrap.ProxyServicesImpl;
import org.jboss.as.weld.util.Reflections;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.weld.bootstrap.api.Service;
import org.jboss.weld.bootstrap.api.ServiceRegistry;
import org.jboss.weld.bootstrap.api.helpers.SimpleServiceRegistry;
import org.jboss.weld.bootstrap.spi.BeanDeploymentArchive;
import org.jboss.weld.bootstrap.spi.BeansXml;
import org.jboss.weld.bootstrap.spi.CDI11Deployment;
import org.jboss.weld.bootstrap.spi.EEModuleDescriptor;
import org.jboss.weld.bootstrap.spi.Metadata;
import org.jboss.weld.resources.spi.ResourceLoader;
import org.jboss.weld.serialization.spi.ContextualStore;
import org.jboss.weld.serialization.spi.ProxyServices;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* Abstract implementation of {@link CDI11Deployment}.
* <p>
* Thread safety: This class is thread safe, and does not require a happens before action between construction and usage
*
* @author Stuart Douglas
*
*/
public class WeldDeployment implements CDI11Deployment {
public static final String ADDITIONAL_CLASSES_BDA_SUFFIX = ".additionalClasses";
public static final String BOOTSTRAP_CLASSLOADER_BDA_ID = "bootstrapBDA" + ADDITIONAL_CLASSES_BDA_SUFFIX;
static final Set<Class<?>> NON_OVERRIDABLE_SERVICES = Set.of(ContextualStore.class);
private final Set<BeanDeploymentArchiveImpl> beanDeploymentArchives;
private final Set<Metadata<Extension>> extensions;
private final ServiceRegistry serviceRegistry;
/**
* The top level module
*/
private final Module module;
/**
* All ModuleClassLoaders in the deployment
*/
private final Set<ClassLoader> subDeploymentClassLoaders;
private final Map<ClassLoader, BeanDeploymentArchiveImpl> additionalBeanDeploymentArchivesByClassloader;
private volatile BeanDeploymentArchiveImpl bootstrapClassLoaderBeanDeploymentArchive;
private final BeanDeploymentModule rootBeanDeploymentModule;
private final Map<ModuleIdentifier, EEModuleDescriptor> eeModuleDescriptors;
public WeldDeployment(Set<BeanDeploymentArchiveImpl> beanDeploymentArchives, Collection<Metadata<Extension>> extensions,
Module module, Set<ClassLoader> subDeploymentClassLoaders, DeploymentUnit deploymentUnit, BeanDeploymentModule rootBeanDeploymentModule,
Map<ModuleIdentifier, EEModuleDescriptor> eeModuleDescriptors) {
this.subDeploymentClassLoaders = new HashSet<ClassLoader>(subDeploymentClassLoaders);
this.beanDeploymentArchives = Collections.newSetFromMap(new ConcurrentHashMap<>());
this.beanDeploymentArchives.addAll(beanDeploymentArchives);
this.extensions = new HashSet<Metadata<Extension>>(extensions);
this.serviceRegistry = new SimpleServiceRegistry() {
@Override
public <S extends Service> void add(Class<S> type, S service) {
if (!this.contains(type) || !NON_OVERRIDABLE_SERVICES.contains(type)) {
super.add(type, service);
}
}
};
this.additionalBeanDeploymentArchivesByClassloader = new ConcurrentHashMap<>();
this.module = module;
this.rootBeanDeploymentModule = rootBeanDeploymentModule;
this.eeModuleDescriptors = eeModuleDescriptors;
// add static services
this.serviceRegistry.add(ProxyServices.class, new ProxyServicesImpl(module));
this.serviceRegistry.add(ResourceLoader.class, new WeldModuleResourceLoader(module));
calculateAccessibilityGraph(this.beanDeploymentArchives);
makeTopLevelBdasVisibleFromStaticModules();
}
/**
* {@link org.jboss.as.weld.deployment.processors.WeldDeploymentProcessor} assembles a basic accessibility graph based on
* the deployment structure. Here, we complete the graph by examining classloader visibility. This allows additional
* accessibility edges caused e.g. by the Class-Path declaration in the manifest file, to be recognized.
*
* @param beanDeploymentArchives
*/
private void calculateAccessibilityGraph(Iterable<BeanDeploymentArchiveImpl> beanDeploymentArchives) {
for (BeanDeploymentArchiveImpl from : beanDeploymentArchives) {
for (BeanDeploymentArchiveImpl target : beanDeploymentArchives) {
if (from.isAccessible(target)) {
from.addBeanDeploymentArchive(target);
}
}
}
}
/**
* Adds additional edges to the accessibility graph that allow static CDI-enabled modules to inject beans from top-level deployment units
*/
private void makeTopLevelBdasVisibleFromStaticModules() {
for (BeanDeploymentArchiveImpl bda : beanDeploymentArchives) {
if (bda.getBeanArchiveType().equals(BeanDeploymentArchiveImpl.BeanArchiveType.EXTERNAL) || bda.getBeanArchiveType().equals(BeanDeploymentArchiveImpl.BeanArchiveType.SYNTHETIC)) {
for (BeanDeploymentArchiveImpl topLevelBda : rootBeanDeploymentModule.getBeanDeploymentArchives()) {
bda.addBeanDeploymentArchive(topLevelBda);
}
}
}
}
/** {@inheritDoc} */
public Collection<BeanDeploymentArchive> getBeanDeploymentArchives() {
return Collections.unmodifiableSet(new HashSet<BeanDeploymentArchive>(beanDeploymentArchives));
}
/** {@inheritDoc} */
public Iterable<Metadata<Extension>> getExtensions() {
return Collections.unmodifiableSet(extensions);
}
/** {@inheritDoc} */
public ServiceRegistry getServices() {
return serviceRegistry;
}
/** {@inheritDoc} */
public synchronized BeanDeploymentArchive loadBeanDeploymentArchive(final Class<?> beanClass) {
final BeanDeploymentArchive bda = this.getBeanDeploymentArchive(beanClass);
if (bda != null) {
return bda;
}
Module module = Module.forClass(beanClass);
if (module == null) {
// Bean class loaded by the bootstrap class loader
if (bootstrapClassLoaderBeanDeploymentArchive == null) {
bootstrapClassLoaderBeanDeploymentArchive = createAndRegisterAdditionalBeanDeploymentArchive(module, beanClass);
} else {
bootstrapClassLoaderBeanDeploymentArchive.addBeanClass(beanClass);
}
return bootstrapClassLoaderBeanDeploymentArchive;
}
/*
* No, there is no BDA for the class yet. Let's create one.
*/
return createAndRegisterAdditionalBeanDeploymentArchive(module, beanClass);
}
protected BeanDeploymentArchiveImpl createAndRegisterAdditionalBeanDeploymentArchive(Module module, Class<?> beanClass) {
String id = null;
if (module == null) {
id = BOOTSTRAP_CLASSLOADER_BDA_ID;
} else {
id = module.getIdentifier() + ADDITIONAL_CLASSES_BDA_SUFFIX;
}
BeanDeploymentArchiveImpl newBda = new BeanDeploymentArchiveImpl(Collections.singleton(beanClass.getName()),
Collections.singleton(beanClass.getName()), BeansXml.EMPTY_BEANS_XML, module, id, BeanArchiveType.SYNTHETIC, false);
WeldLogger.DEPLOYMENT_LOGGER.beanArchiveDiscovered(newBda);
newBda.addBeanClass(beanClass);
ServiceRegistry newBdaServices = newBda.getServices();
for (Entry<Class<? extends Service>, Service> entry : serviceRegistry.entrySet()) {
// Do not overwrite existing services
if (!newBdaServices.contains(entry.getKey())) {
newBdaServices.add(entry.getKey(), Reflections.cast(entry.getValue()));
}
}
if (module == null) {
// For bootstrapClassLoaderBeanDeploymentArchive always use the parent ResourceLoader
newBdaServices.add(ResourceLoader.class, serviceRegistry.get(ResourceLoader.class));
}
if (module != null && eeModuleDescriptors.containsKey(module.getIdentifier())) {
newBda.getServices().add(EEModuleDescriptor.class, eeModuleDescriptors.get(module.getIdentifier()));
}
// handle BDAs visible from the new BDA
for (BeanDeploymentArchiveImpl bda : beanDeploymentArchives) {
if (newBda.isAccessible(bda)) {
newBda.addBeanDeploymentArchive(bda);
}
}
// handle visibility of the new BDA from other BDAs
for (BeanDeploymentArchiveImpl bda : beanDeploymentArchives) {
if (bda.isAccessible(newBda)) {
bda.addBeanDeploymentArchive(newBda);
}
}
// make the top-level deployment BDAs visible from the additional archive
newBda.addBeanDeploymentArchives(rootBeanDeploymentModule.getBeanDeploymentArchives());
// Ignore beans loaded by the bootstrap class loader. This should only be JDK classes in most cases.
// See getBeanDeploymentArchive(final Class<?> beanClass), per the JavaDoc this is mean to archive which
// contains the bean class.
final ClassLoader cl = beanClass.getClassLoader();
if (cl != null) {
additionalBeanDeploymentArchivesByClassloader.put(cl, newBda);
}
beanDeploymentArchives.add(newBda);
return newBda;
}
public Module getModule() {
return module;
}
public Set<ClassLoader> getSubDeploymentClassLoaders() {
return Collections.unmodifiableSet(subDeploymentClassLoaders);
}
public synchronized <T extends Service> void addWeldService(Class<T> type, T service) {
serviceRegistry.add(type, service);
for (BeanDeploymentArchiveImpl bda : additionalBeanDeploymentArchivesByClassloader.values()) {
bda.getServices().add(type, service);
}
}
@Override
public BeanDeploymentArchive getBeanDeploymentArchive(final Class<?> beanClass) {
ClassLoader moduleClassLoader = WildFlySecurityManager.getClassLoaderPrivileged(beanClass);
if (moduleClassLoader != null) {
for (BeanDeploymentArchiveImpl bda : beanDeploymentArchives) {
// search in all known classes in that archive
if (bda.getKnownClasses().contains(beanClass.getName()) && moduleClassLoader.equals(bda.getClassLoader())) {
return bda;
}
}
}
/*
* We haven't found this class in a bean archive so probably it was added by an extension and the class itself does
* not come from a BDA. Let's try to find an existing BDA that uses the same classloader
* (and thus has the required accessibility to other BDAs)
*/
if (moduleClassLoader != null && additionalBeanDeploymentArchivesByClassloader.containsKey(moduleClassLoader)) {
return additionalBeanDeploymentArchivesByClassloader.get(moduleClassLoader);
}
return null;
}
}
| 12,586 | 44.440433 | 190 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/deployment/ExplicitBeanArchiveMetadataContainer.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment;
import java.util.Map;
import org.jboss.as.server.deployment.AttachmentKey;
import org.jboss.as.server.deployment.module.ResourceRoot;
import org.jboss.weld.util.collections.ImmutableMap;
/**
* Information about explicit CDI bean archives
* <p>
* Thread Safety: This class is immutable and does not require a happens before event between construction and usage
*
* @author Stuart Douglas
* @author Jozef Hartinger
*
*/
public class ExplicitBeanArchiveMetadataContainer {
public static final AttachmentKey<ExplicitBeanArchiveMetadataContainer> ATTACHMENT_KEY = AttachmentKey.create(ExplicitBeanArchiveMetadataContainer.class);
private final Map<ResourceRoot, ExplicitBeanArchiveMetadata> beanArchiveMetadata;
public ExplicitBeanArchiveMetadataContainer(Map<ResourceRoot, ExplicitBeanArchiveMetadata> beanArchiveMetadata) {
this.beanArchiveMetadata = ImmutableMap.copyOf(beanArchiveMetadata);
}
public Map<ResourceRoot, ExplicitBeanArchiveMetadata> getBeanArchiveMetadata() {
return beanArchiveMetadata;
}
}
| 2,115 | 38.185185 | 158 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/deployment/BeanDeploymentModule.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment;
import java.util.Collection;
import java.util.Set;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.weld.bootstrap.api.Service;
import org.jboss.weld.bootstrap.spi.EEModuleDescriptor;
import org.jboss.weld.util.collections.ImmutableSet;
/**
* A collection of Bean Deployment archives that share similar bean visibility.
* <p/>
* When the module is created all BDA's are given visibility to each other. They can then be given visibility to other bda's or
* bean modules with one operation.
*
* @author Stuart Douglas
*
*/
public class BeanDeploymentModule {
private final Set<BeanDeploymentArchiveImpl> beanDeploymentArchives;
private final EEModuleDescriptor moduleDescriptor;
public BeanDeploymentModule(String moduleId, DeploymentUnit deploymentUnit, Collection<BeanDeploymentArchiveImpl> beanDeploymentArchives) {
this.beanDeploymentArchives = ImmutableSet.copyOf(beanDeploymentArchives);
for (BeanDeploymentArchiveImpl bda : beanDeploymentArchives) {
bda.addBeanDeploymentArchives(beanDeploymentArchives);
}
this.moduleDescriptor = WeldEEModuleDescriptor.of(moduleId, deploymentUnit);
if (moduleDescriptor != null) {
addService(EEModuleDescriptor.class, moduleDescriptor);
}
}
/**
* Makes the {@link BeanDeploymentArchiveImpl} accessible to all bdas in the module
*
* @param archive The archive to make accessible
*/
public synchronized void addBeanDeploymentArchive(BeanDeploymentArchiveImpl archive) {
for (BeanDeploymentArchiveImpl bda : beanDeploymentArchives) {
bda.addBeanDeploymentArchive(archive);
}
}
/**
* Makes all {@link BeanDeploymentArchiveImpl}s in the given module accessible to all bdas in this module
*
* @param module The module to make accessible
*/
public synchronized void addBeanDeploymentModule(BeanDeploymentModule module) {
for (BeanDeploymentArchiveImpl bda : beanDeploymentArchives) {
bda.addBeanDeploymentArchives(module.beanDeploymentArchives);
}
}
/**
* Makes all {@link BeanDeploymentArchiveImpl}s in the given modules accessible to all bdas in this module
*
* @param modules The modules to make accessible
*/
public synchronized void addBeanDeploymentModules(Collection<BeanDeploymentModule> modules) {
for (BeanDeploymentArchiveImpl bda : beanDeploymentArchives) {
for (BeanDeploymentModule bdm : modules) {
bda.addBeanDeploymentArchives(bdm.beanDeploymentArchives);
}
}
}
/**
* Adds a service to all bean deployment archives in the module
* @param clazz The service type
* @param service The service
* @param <S> The service type
*/
public synchronized <S extends Service> void addService(Class<S> clazz, S service) {
for (BeanDeploymentArchiveImpl bda : beanDeploymentArchives) {
bda.getServices().add(clazz,service);
}
}
public Set<BeanDeploymentArchiveImpl> getBeanDeploymentArchives() {
return beanDeploymentArchives;
}
public EEModuleDescriptor getModuleDescriptor() {
return moduleDescriptor;
}
}
| 4,330 | 37.669643 | 143 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/deployment/WeldEEModuleDescriptor.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2015, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment;
import static org.jboss.as.ee.structure.Attachments.DEPLOYMENT_TYPE;
import org.jboss.as.ee.structure.DeploymentType;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.EjbDeploymentMarker;
import org.jboss.weld.bootstrap.spi.EEModuleDescriptor;
import org.jboss.weld.bootstrap.spi.helpers.EEModuleDescriptorImpl;
/**
* Implementation of Weld's {@link EEModuleDescriptor}
*
* @author Jozef Hartinger
*
*/
public class WeldEEModuleDescriptor extends EEModuleDescriptorImpl implements EEModuleDescriptor {
public static WeldEEModuleDescriptor of(String id, DeploymentUnit deploymentUnit) {
final DeploymentType deploymentType = deploymentUnit.getAttachment(DEPLOYMENT_TYPE);
if (deploymentType == null) {
if (EjbDeploymentMarker.isEjbDeployment(deploymentUnit)) {
return new WeldEEModuleDescriptor(id, ModuleType.EJB_JAR);
}
return null;
}
switch (deploymentType) {
case WAR:
return new WeldEEModuleDescriptor(id, ModuleType.WEB);
case EAR:
return new WeldEEModuleDescriptor(id, ModuleType.EAR);
case EJB_JAR:
return new WeldEEModuleDescriptor(id, ModuleType.EJB_JAR);
case APPLICATION_CLIENT:
return new WeldEEModuleDescriptor(id, ModuleType.APPLICATION_CLIENT);
default:
throw new IllegalArgumentException("Unknown deployment type " + deploymentType);
}
}
private WeldEEModuleDescriptor(String id, ModuleType moduleType) {
super(id, moduleType);
}
}
| 2,712 | 39.492537 | 98 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/deployment/WeldAttachments.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment;
import org.jboss.as.server.deployment.AttachmentKey;
import org.jboss.as.server.deployment.AttachmentList;
import org.jboss.as.server.deployment.module.ResourceRoot;
import org.jboss.as.weld.discovery.AnnotationType;
/**
* {@link AttachmentKey}s for weld attachments
*
* @author Stuart Douglas
*
*/
public class WeldAttachments {
/**
* The {@link BeanDeploymentModule} for a deployment
*/
public static final AttachmentKey<BeanDeploymentModule> BEAN_DEPLOYMENT_MODULE = AttachmentKey.create(BeanDeploymentModule.class);
/**
* top level list of all additional bean deployment modules
*/
public static final AttachmentKey<AttachmentList<BeanDeploymentArchiveImpl>> ADDITIONAL_BEAN_DEPLOYMENT_MODULES = AttachmentKey.createList(BeanDeploymentArchiveImpl.class);
/**
* The {@link BeanDeploymentArchiveImpl} that corresponds to the main resource root of a deployment or sub deployment. For
* consistency, the bean manager that corresponds to this bda is always bound to the java:comp namespace for web modules.
*/
public static final AttachmentKey<BeanDeploymentArchiveImpl> DEPLOYMENT_ROOT_BEAN_DEPLOYMENT_ARCHIVE = AttachmentKey.create(BeanDeploymentArchiveImpl.class);
/**
* A set of bean defining annotations, as defined by the CDI specification.
* @see CdiAnnotationProcessor
*/
public static final AttachmentKey<AttachmentList<AnnotationType>> BEAN_DEFINING_ANNOTATIONS = AttachmentKey.createList(AnnotationType.class);
/**
* The {@link ResourceRoot} for WEB-INF/classes of a web archive.
*/
public static final AttachmentKey<ResourceRoot> CLASSES_RESOURCE_ROOT = AttachmentKey.create(ResourceRoot.class);
}
| 2,776 | 41.723077 | 176 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/deployment/BeanDeploymentArchiveImpl.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment;
import java.security.PrivilegedAction;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.CopyOnWriteArraySet;
import org.jboss.as.weld.WeldModuleResourceLoader;
import org.jboss.as.weld.spi.WildFlyBeanDeploymentArchive;
import org.jboss.as.weld.util.Reflections;
import org.jboss.as.weld.util.ServiceLoaders;
import org.jboss.modules.DependencySpec;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleDependencySpec;
import org.jboss.modules.ModuleLoadException;
import org.jboss.modules.ModuleLoader;
import org.jboss.weld.bootstrap.api.Service;
import org.jboss.weld.bootstrap.api.ServiceRegistry;
import org.jboss.weld.bootstrap.api.helpers.SimpleServiceRegistry;
import org.jboss.weld.bootstrap.spi.BeanDeploymentArchive;
import org.jboss.weld.bootstrap.spi.BeansXml;
import org.jboss.weld.ejb.spi.EjbDescriptor;
import org.jboss.weld.resources.spi.ResourceLoader;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* Implementation of {@link BeanDeploymentArchive}.
* <p>
* Thread Safety: This class is thread safe and does not require a happens before action between construction and usage
*
* @author Stuart Douglas
*
*/
public class BeanDeploymentArchiveImpl implements WildFlyBeanDeploymentArchive {
public enum BeanArchiveType {
IMPLICIT, EXPLICIT, EXTERNAL, SYNTHETIC;
}
private final Set<String> beanClasses;
private final Set<String> allKnownClasses;
private final Set<BeanDeploymentArchive> beanDeploymentArchives;
private final BeansXml beansXml;
private final String id;
private final ServiceRegistry serviceRegistry;
private final Module module;
private final WeldModuleResourceLoader resourceLoader;
private final Set<EjbDescriptor<?>> ejbDescriptors;
private final boolean root; // indicates whether this is a root BDA
private final BeanArchiveType beanArchiveType;
public BeanDeploymentArchiveImpl(Set<String> beanClasses, Set<String> allClasses, BeansXml beansXml, Module module, String id, BeanArchiveType beanArchiveType) {
this(beanClasses, allClasses, beansXml, module, id, beanArchiveType, false);
}
public BeanDeploymentArchiveImpl(Set<String> beanClasses, Set<String> allClasses, BeansXml beansXml, Module module, String id, BeanArchiveType beanArchiveType, boolean root) {
this.beanClasses = new ConcurrentSkipListSet<String>(beanClasses);
this.allKnownClasses = new ConcurrentSkipListSet<String>(allClasses);
this.beanDeploymentArchives = new CopyOnWriteArraySet<BeanDeploymentArchive>();
this.beansXml = beansXml;
this.id = id;
this.serviceRegistry = new SimpleServiceRegistry();
this.resourceLoader = new WeldModuleResourceLoader(module);
this.serviceRegistry.add(ResourceLoader.class, resourceLoader);
for (Entry<Class<? extends Service>, Service> entry : ServiceLoaders.loadBeanDeploymentArchiveServices(BeanDeploymentArchiveImpl.class, this)
.entrySet()) {
this.serviceRegistry.add(entry.getKey(), Reflections.cast(entry.getValue()));
}
this.module = module;
this.ejbDescriptors = new HashSet<EjbDescriptor<?>>();
this.beanArchiveType = beanArchiveType;
this.root = root;
}
/**
* Adds an accessible {@link BeanDeploymentArchive}.
*/
public void addBeanDeploymentArchive(BeanDeploymentArchive archive) {
if (archive == this) {
return;
}
beanDeploymentArchives.add(archive);
}
/**
* Adds multiple accessible {@link BeanDeploymentArchive}s
*/
public void addBeanDeploymentArchives(Collection<? extends BeanDeploymentArchive> archives) {
for (BeanDeploymentArchive bda : archives) {
if (bda != this) {
beanDeploymentArchives.add(bda);
}
}
}
public void addBeanClass(String clazz) {
this.beanClasses.add(clazz);
this.allKnownClasses.add(clazz);
}
public void addBeanClass(Class<?> clazz) {
this.resourceLoader.addAdditionalClass(clazz);
}
/**
* returns an unmodifiable copy of the bean classes in this BDA
*/
@Override
public Collection<String> getBeanClasses() {
return Collections.unmodifiableSet(new HashSet<String>(beanClasses));
}
/**
* Returns an unmodifiable copy of the bean deployment archives set
*/
@Override
public Collection<BeanDeploymentArchive> getBeanDeploymentArchives() {
return Collections.unmodifiableCollection(new HashSet<BeanDeploymentArchive>(beanDeploymentArchives));
}
@Override
public BeansXml getBeansXml() {
return beansXml;
}
public void addEjbDescriptor(EjbDescriptor<?> descriptor) {
ejbDescriptors.add(descriptor);
}
@Override
public Collection<EjbDescriptor<?>> getEjbs() {
return Collections.unmodifiableSet(ejbDescriptors);
}
@Override
public String getId() {
return id;
}
@Override
public ServiceRegistry getServices() {
return serviceRegistry;
}
public Module getModule() {
return module;
}
public ClassLoader getClassLoader() {
if (module != null) {
if(WildFlySecurityManager.isChecking()) {
return WildFlySecurityManager.doUnchecked(new PrivilegedAction<ClassLoader>() {
@Override
public ClassLoader run() {
return module.getClassLoader();
}
});
} else {
return module.getClassLoader();
}
}
return null;
}
public boolean isRoot() {
return root;
}
/**
* Determines if a class from this {@link BeanDeploymentArchiveImpl} instance can access a class in the
* {@link BeanDeploymentArchive} instance represented by the specified <code>BeanDeploymentArchive</code> parameter
* according to the Jakarta EE class accessibility requirements.
*
* @param target
* @return true if an only if a class this archive can access a class from the archive represented by the specified parameter
*/
public boolean isAccessible(BeanDeploymentArchive target) {
if (this == target) {
return true;
}
BeanDeploymentArchiveImpl that = (BeanDeploymentArchiveImpl) target;
if (that.getModule() == null) {
/*
* The target BDA is the bootstrap BDA - it bundles classes loaded by the bootstrap classloader.
* Everyone can see the bootstrap classloader.
*/
return true;
}
if (module == null) {
/*
* This BDA is the bootstrap BDA - it bundles classes loaded by the bootstrap classloader. We assume that a
* bean whose class is loaded by the bootstrap classloader can only see other beans in the "bootstrap BDA".
*/
return that.getModule() == null;
}
if (module.equals(that.getModule())) {
return true;
}
final String thatIdentifier = that.getModule().getName();
// basic check whether the module is our dependency
for (DependencySpec dependency : module.getDependencies()) {
if (dependency instanceof ModuleDependencySpec) {
ModuleDependencySpec moduleDependency = (ModuleDependencySpec) dependency;
if (moduleDependency.getName().equals(thatIdentifier)) {
return true;
}
}
}
for (DependencySpec dependency : module.getDependencies()) {
if (dependency instanceof ModuleDependencySpec) {
ModuleDependencySpec moduleDependency = (ModuleDependencySpec) dependency;
// moduleDependency might be an alias - try to load it to get lined module
Module module = loadModule(moduleDependency);
if (module != null && module.getName().equals(thatIdentifier)) {
return true;
}
}
}
/*
* full check - we try to load a class from the target bean archive and check whether its module
* is the same as the one of the bean archive
* See WFLY-4250 for more info
*/
Iterator<String> iterator = target.getBeanClasses().iterator();
if (iterator.hasNext()) {
Class<?> clazz = Reflections.loadClass(iterator.next(), module.getClassLoader());
if (clazz != null) {
Module classModule = Module.forClass(clazz);
return classModule != null && classModule.equals(that.getModule());
}
}
return false;
}
private Module loadModule(ModuleDependencySpec moduleDependency) {
try {
ModuleLoader moduleLoader = moduleDependency.getModuleLoader();
if (moduleLoader == null) {
return null;
} else {
return moduleLoader.loadModule(moduleDependency.getIdentifier());
}
} catch (ModuleLoadException e) {
return null;
}
}
public BeanArchiveType getBeanArchiveType() {
return beanArchiveType;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder(this.beanArchiveType.toString());
builder.append(" BeanDeploymentArchive (");
builder.append(this.id);
builder.append(")");
return builder.toString();
}
@Override
public Collection<String> getKnownClasses(){
return allKnownClasses;
}
}
| 11,009 | 34.401929 | 179 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/deployment/PropertyReplacingBeansXmlHandler.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment;
import java.net.URL;
import org.jboss.as.weld.logging.WeldLogger;
import org.jboss.metadata.property.PropertyReplacer;
import org.jboss.weld.xml.BeansXmlHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
/**
* {@link BeansXmlHandler} with AS7-specific logging and property replacement support.
*
* @author Jozef Hartinger
*
*/
class PropertyReplacingBeansXmlHandler extends BeansXmlHandler {
private static final String ROOT_ELEMENT_NAME = "beans";
// See also https://www.w3.org/TR/xmlschema-1/#cvc-elt
private static final String VALIDATION_ERROR_CODE_CVC_ELT_1 = "cvc-elt.1";
private final PropertyReplacer replacer;
public PropertyReplacingBeansXmlHandler(URL file, PropertyReplacer replacer) {
super(file);
this.replacer = replacer;
}
@Override
public void warning(SAXParseException e) throws SAXException {
WeldLogger.DEPLOYMENT_LOGGER.beansXmlValidationWarning(file, e.getLineNumber(), e.getMessage());
}
@Override
public void error(SAXParseException e) throws SAXException {
if (e.getMessage().startsWith(VALIDATION_ERROR_CODE_CVC_ELT_1) && e.getMessage().contains(ROOT_ELEMENT_NAME)) {
// Ignore the errors we get when there is no schema defined
return;
}
WeldLogger.DEPLOYMENT_LOGGER.beansXmlValidationError(file, e.getLineNumber(), e.getMessage());
}
@Override
protected String interpolate(String text) {
if(text == null) {
return null;
}
return replacer.replaceProperties(text);
}
}
| 2,668 | 35.067568 | 119 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/deployment/CdiAnnotationProcessor.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.annotation.CompositeIndex;
import org.jboss.as.weld.CdiAnnotations;
/**
* CdiAnnotationProcessor class. Used to verify the presence of CDI annotations.
*/
public class CdiAnnotationProcessor implements DeploymentUnitProcessor {
@Override
public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final CompositeIndex index = deploymentUnit.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX);
for (final CdiAnnotations annotation : CdiAnnotations.values()) {
if (!index.getAnnotations(annotation.getDotName()).isEmpty()) {
CdiAnnotationMarker.mark(deploymentUnit);
return;
}
}
}
}
| 2,204 | 42.235294 | 108 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/deployment/processors/WeldImplicitDeploymentProcessor.java | package org.jboss.as.weld.deployment.processors;
import static org.jboss.as.weld.util.Utils.getRootDeploymentUnit;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.ServiceLoader;
import java.util.Set;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.ee.component.EEModuleDescription;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.annotation.AnnotationIndexUtils;
import org.jboss.as.server.deployment.module.ResourceRoot;
import org.jboss.as.weld._private.WeldDeploymentMarker;
import org.jboss.as.weld.deployment.ExplicitBeanArchiveMetadataContainer;
import org.jboss.as.weld.deployment.WeldAttachments;
import org.jboss.as.weld.discovery.AnnotationType;
import org.jboss.as.weld.spi.ImplicitBeanArchiveDetector;
import org.jboss.as.weld.util.Utils;
import org.jboss.jandex.Index;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* Deployment processor that finds implicit bean archives (as defined by the CDI spec). If the deployment unit contains any such
* archive, the deployment unit is marked using {@link WeldDeploymentMarker}.
*
* @author Jozef Hartinger
*
*/
public class WeldImplicitDeploymentProcessor implements DeploymentUnitProcessor {
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
if (WeldDeploymentMarker.isWeldDeployment(deploymentUnit)) {
return;
}
if (Utils.getRootDeploymentUnit(deploymentUnit).getAttachment(WeldConfiguration.ATTACHMENT_KEY).isRequireBeanDescriptor()) {
// if running in the require-bean-descriptor mode then bean archives are found by BeansXmlProcessor
return;
}
/*
* look for classes with bean defining annotations
*/
final Set<AnnotationType> beanDefiningAnnotations = new HashSet<>(getRootDeploymentUnit(deploymentUnit).getAttachment(WeldAttachments.BEAN_DEFINING_ANNOTATIONS));
final Map<ResourceRoot, Index> indexes = AnnotationIndexUtils.getAnnotationIndexes(deploymentUnit);
final ExplicitBeanArchiveMetadataContainer explicitBeanArchiveMetadata = deploymentUnit.getAttachment(ExplicitBeanArchiveMetadataContainer.ATTACHMENT_KEY);
final ResourceRoot classesRoot = deploymentUnit.getAttachment(WeldAttachments.CLASSES_RESOURCE_ROOT);
final ResourceRoot deploymentRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);
for (Entry<ResourceRoot, Index> entry : indexes.entrySet()) {
ResourceRoot resourceRoot = entry.getKey();
if (resourceRoot == classesRoot) {
// BDA for WEB-INF/classes is keyed under deploymentRoot in explicitBeanArchiveMetadata
resourceRoot = deploymentRoot;
}
/*
* Make sure bean defining annotations used in archives with bean-discovery-mode="none" are not considered here
* WFLY-4388
*/
if (explicitBeanArchiveMetadata != null && explicitBeanArchiveMetadata.getBeanArchiveMetadata().containsKey(resourceRoot)) {
continue;
}
for (final AnnotationType annotation : beanDefiningAnnotations) {
if (!entry.getValue().getAnnotations(annotation.getName()).isEmpty()) {
WeldDeploymentMarker.mark(deploymentUnit);
return;
}
}
}
/*
* look for session beans and managed beans
*/
final EEModuleDescription eeModuleDescription = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION);
final Iterable<ImplicitBeanArchiveDetector> detectors = ServiceLoader.load(ImplicitBeanArchiveDetector.class,
WildFlySecurityManager.getClassLoaderPrivileged(WeldImplicitDeploymentProcessor.class));
for (ComponentDescription component : eeModuleDescription.getComponentDescriptions()) {
for (ImplicitBeanArchiveDetector detector : detectors) {
if (detector.isImplicitBeanArchiveRequired(component)) {
WeldDeploymentMarker.mark(deploymentUnit);
return;
}
}
}
}
}
| 4,675 | 46.714286 | 170 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/deployment/processors/DefaultModuleServiceProvider.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment.processors;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.jboss.as.ee.structure.DeploymentType;
import org.jboss.as.ee.structure.DeploymentTypeMarker;
import org.jboss.as.ee.structure.EJBAnnotationPropertyReplacement;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.annotation.CompositeIndex;
import org.jboss.as.server.deployment.module.ResourceRoot;
import org.jboss.as.weld.discovery.WeldClassFileServices;
import org.jboss.as.weld.services.bootstrap.WeldResourceInjectionServices;
import org.jboss.as.weld.spi.ModuleServicesProvider;
import org.jboss.modules.Module;
import org.jboss.weld.bootstrap.api.Service;
/**
*
* @author Martin Kouba
*/
public class DefaultModuleServiceProvider implements ModuleServicesProvider {
@Override
public Collection<Service> getServices(DeploymentUnit rootDeploymentUnit, DeploymentUnit deploymentUnit, Module module, ResourceRoot resourceRoot) {
List<Service> services = new ArrayList<>();
// ResourceInjectionServices
// TODO I'm not quite sure we should use rootDeploymentUnit here
services.add(new WeldResourceInjectionServices(rootDeploymentUnit.getServiceRegistry(),
rootDeploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION),
EJBAnnotationPropertyReplacement.propertyReplacer(deploymentUnit),
module, DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit)));
// ClassFileServices
final CompositeIndex index = deploymentUnit.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX);
if (index != null) {
services.add(new WeldClassFileServices(index, module.getClassLoader()));
}
return services;
}
}
| 2,932 | 42.776119 | 152 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/deployment/processors/EarApplicationScopedObserverMethodProcessor.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment.processors;
import org.jboss.as.controller.capability.CapabilityServiceSupport;
import org.jboss.as.ee.structure.DeploymentType;
import org.jboss.as.ee.structure.DeploymentTypeMarker;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.SetupAction;
import org.jboss.as.weld.WeldCapability;
import org.jboss.as.weld.deployment.BeanDeploymentArchiveImpl;
import org.jboss.as.weld.deployment.BeanDeploymentModule;
import org.jboss.as.weld.deployment.WeldAttachments;
import org.jboss.as.weld.logging.WeldLogger;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.context.BeforeDestroyed;
import jakarta.enterprise.context.Destroyed;
import jakarta.enterprise.context.Initialized;
import jakarta.enterprise.event.Observes;
import jakarta.enterprise.event.Reception;
import jakarta.enterprise.event.TransactionPhase;
import jakarta.enterprise.inject.spi.Extension;
import jakarta.enterprise.inject.spi.ObserverMethod;
import jakarta.enterprise.inject.spi.ProcessObserverMethod;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Set;
import static org.jboss.as.weld.Capabilities.WELD_CAPABILITY_NAME;
/**
* Processor that registers a CDI portable extension for EAR deployments, which adds support for EE facilities, to CDI app context lifecycle event handlers.
*
* @author emmartins
*/
public class EarApplicationScopedObserverMethodProcessor implements DeploymentUnitProcessor {
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
if (!DeploymentTypeMarker.isType(DeploymentType.EAR, deploymentUnit)) {
// ear deployment only processor
return;
}
final CapabilityServiceSupport support = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT);
if (support.hasCapability(WELD_CAPABILITY_NAME)) {
final WeldCapability api = support.getOptionalCapabilityRuntimeAPI(WELD_CAPABILITY_NAME, WeldCapability.class).get();
if (api.isPartOfWeldDeployment(deploymentUnit)) {
api.registerExtensionInstance(new PortableExtension(deploymentUnit), deploymentUnit);
}
}
}
private static class PortableExtension implements Extension {
private final DeploymentUnit deploymentUnit;
private PortableExtension(DeploymentUnit deploymentUnit) {
this.deploymentUnit = deploymentUnit;
}
public <Object, X> void processObserverMethod(@Observes ProcessObserverMethod<Object, X> event) {
final ObserverMethod<Object> method = event.getObserverMethod();
for (Annotation a : method.getObservedQualifiers()) {
// only process @Initialized(ApplicationScoped.class), @BeforeDestroyed(ApplicationScoped.class) and @Destroyed(ApplicationScoped.class)
if ((a instanceof Initialized && ((Initialized) a).value().equals(ApplicationScoped.class)) || (a instanceof BeforeDestroyed && ((BeforeDestroyed) a).value().equals(ApplicationScoped.class)) || (a instanceof Destroyed && ((Destroyed) a).value().equals(ApplicationScoped.class))) {
// if there are setup actions for the bean's class deployable unit wrap the observer method
final DeploymentUnit beanDeploymentUnit = getBeanDeploymentUnit(method.getBeanClass().getName());
if (beanDeploymentUnit != null) {
final List<SetupAction> setupActions = WeldDeploymentProcessor.getSetupActions(beanDeploymentUnit);
if (!setupActions.isEmpty()) {
event.setObserverMethod(new ObserverMethod<Object>() {
@Override
public Class<?> getBeanClass() {
return method.getBeanClass();
}
@Override
public Type getObservedType() {
return method.getObservedType();
}
@Override
public Set<Annotation> getObservedQualifiers() {
return method.getObservedQualifiers();
}
@Override
public Reception getReception() {
return method.getReception();
}
@Override
public TransactionPhase getTransactionPhase() {
return method.getTransactionPhase();
}
@Override
public void notify(Object event) {
try {
for (SetupAction action : setupActions) {
action.setup(null);
}
method.notify(event);
} finally {
for (SetupAction action : setupActions) {
try {
action.teardown(null);
} catch (Exception e) {
WeldLogger.DEPLOYMENT_LOGGER.exceptionClearingThreadState(e);
}
}
}
}
});
}
}
}
}
}
private DeploymentUnit getBeanDeploymentUnit(String beanClass) {
for (DeploymentUnit subDeploymentUnit : deploymentUnit.getAttachmentList(Attachments.SUB_DEPLOYMENTS)) {
final BeanDeploymentModule beanDeploymentModule = subDeploymentUnit.getAttachment(WeldAttachments.BEAN_DEPLOYMENT_MODULE);
if (beanDeploymentModule != null) {
for (BeanDeploymentArchiveImpl beanDeploymentArchive : beanDeploymentModule.getBeanDeploymentArchives()) {
if (beanDeploymentArchive.getBeanClasses().contains(beanClass)) {
return subDeploymentUnit;
}
}
}
}
return null;
}
}
}
| 8,150 | 48.70122 | 296 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/deployment/processors/SimpleEnvEntryCdiResourceInjectionProcessor.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment.processors;
import static org.jboss.as.weld.Capabilities.WELD_CAPABILITY_NAME;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import jakarta.annotation.Resource;
import jakarta.enterprise.event.Observes;
import jakarta.enterprise.inject.spi.AnnotatedField;
import jakarta.enterprise.inject.spi.AnnotatedMethod;
import jakarta.enterprise.inject.spi.AnnotatedType;
import jakarta.enterprise.inject.spi.Extension;
import jakarta.enterprise.inject.spi.ProcessAnnotatedType;
import jakarta.enterprise.inject.spi.configurator.AnnotatedFieldConfigurator;
import jakarta.enterprise.inject.spi.configurator.AnnotatedMethodConfigurator;
import jakarta.enterprise.inject.spi.configurator.AnnotatedTypeConfigurator;
import jakarta.enterprise.util.AnnotationLiteral;
import org.jboss.as.controller.capability.CapabilityServiceSupport;
import org.jboss.as.ee.component.Attachments;
import org.jboss.as.ee.component.DeploymentDescriptorEnvironment;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.weld.WeldCapability;
import org.jboss.as.weld.logging.WeldLogger;
import org.jboss.metadata.javaee.spec.EnvironmentEntriesMetaData;
import org.jboss.metadata.javaee.spec.EnvironmentEntryMetaData;
import org.jboss.metadata.javaee.spec.ResourceInjectionTargetMetaData;
import org.jboss.modules.Module;
/**
* Processes deployment descriptor env-entry configurations looking for cases where an injection target
* is specified and the env-entry-type is one of the 'Simple Environment Entry' Java types listed in Section 5.4
* of the Jakarta EE 9.1 Platform specification. If any are found, adds a CDI @{link Extension} that observes CDI
* {@link ProcessAnnotatedType} events in order to ensure that the annotated type's resource injection configuration
* reflects any env-entry that was found. Specifically, if the class name for the annotated type matches the
* {@code injection-target-class} of a found env-entry, and the name of a field or name of a property with a setter
* method matches the {@code injection-target-name} of that env-entry, and the type of the field or setter parameter
* {@link Class#isAssignableFrom(Class) is assignable from} the specified {@code env-entry-type} of that env-entry:
* <ol>
* <li>
* If the {@code env-entry-value} for the env-entry is not specified, but the field or method is annotated
* with an {@code @Resource} annotation with no {@link Resource#lookup() lookup()} or
* {@link Resource#mappedName() mappedName()}, configured, CDI is instructed to remove the @Resource annotation,
* thus disabling injection, as discussed in section 5.4.1.3 of the Jakarta EE 9.1 Platform specification.
* </li>
* <li>
* If the {@code env-entry-value} for the env-entry is specified,, but the field or method is not annotated
* with an {@code @Resource} annotation, CDI is instructed to add the @Resource annotation,
* thus enabling injection, as discussed in section 5.4.1.3 of the Jakarta EE 9.1 Platform specification.
* </li>
* </ol>
*/
public class SimpleEnvEntryCdiResourceInjectionProcessor implements DeploymentUnitProcessor {
private static final Map<String, Class<?>> SIMPLE_ENTRY_TYPES;
private static final Map<Class<?>, Class<?>> PRIMITIVE_TYPES;
static {
Map<Class<?>, Class<?>> primitives = new HashMap<>();
primitives.put(byte.class, Byte.class);
primitives.put(short.class, Short.class);
primitives.put(int.class, Integer.class);
primitives.put(long.class, Long.class);
primitives.put(char.class, Character.class);
primitives.put(boolean.class, Boolean.class);
primitives.put(float.class, Float.class);
primitives.put(double.class, Double.class);
PRIMITIVE_TYPES = Collections.unmodifiableMap(primitives);
Map<String, Class<?>> types = new HashMap<>();
store(String.class, types);
store(Character.class, types);
store(Byte.class, types);
store(Short.class, types);
store(Integer.class, types);
store(Long.class, types);
store(Boolean.class, types);
store(Double.class, types);
store(Float.class, types);
store(Class.class, types);
primitives.forEach((k, v) -> types.put(k.getName(), v));
SIMPLE_ENTRY_TYPES = Collections.unmodifiableMap(types);
}
private static void store(Class<?> clazz, Map<String, Class<?>> map) {
map.put(clazz.getName(), clazz);
}
@Override
public void deploy(DeploymentPhaseContext deploymentPhaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = deploymentPhaseContext.getDeploymentUnit();
final CapabilityServiceSupport support = deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.CAPABILITY_SERVICE_SUPPORT);
final Optional<WeldCapability> optional = support.getOptionalCapabilityRuntimeAPI(WELD_CAPABILITY_NAME, WeldCapability.class);
if (optional.isPresent() && optional.get().isPartOfWeldDeployment(deploymentUnit)) {
// See if any of the env-entry entries for this deployment require our CDI extension
final Module module = deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.MODULE);
EnvEntryCdiExtension extension = getEnvEntryCdiExtension(deploymentUnit, module.getClassLoader());
if (extension != null) {
optional.get().registerExtensionInstance(extension, deploymentUnit);
WeldLogger.DEPLOYMENT_LOGGER.debugf("Registered CDI Extension %s", extension);
}
}
}
private EnvEntryCdiExtension getEnvEntryCdiExtension(DeploymentUnit deploymentUnit, ClassLoader classLoader) {
EnvEntryCdiExtension extension = null;
final DeploymentDescriptorEnvironment environment = deploymentUnit.getAttachment(Attachments.MODULE_DEPLOYMENT_DESCRIPTOR_ENVIRONMENT);
final EnvironmentEntriesMetaData envEntries = environment == null ? null : environment.getEnvironment().getEnvironmentEntries();
if (envEntries != null) {
Map<String, Map<String, InjectionData>> entriesWithoutValues = new HashMap<>();
Map<String, Map<String, InjectionData>> envEntryInjections = new HashMap<>();
for (EnvironmentEntryMetaData eemd : envEntries) {
Set<ResourceInjectionTargetMetaData> rimds = eemd.isDependencyIgnored() ? null : eemd.getInjectionTargets();
if (rimds == null) {
continue;
}
Class<?> entryType = null;
if (eemd.getType() != null) {
entryType = getSimpleEntryType(eemd.getType(), classLoader);
if (entryType == null) {
// A type was configured but it is not one of the specified simple env-entry types,
// so not relevant here.
continue;
}
}
for (ResourceInjectionTargetMetaData rimd : rimds) {
Map<String, InjectionData> toPut;
String value = eemd.getValue();
String lookup = eemd.getLookupName();
if ((value == null || value.isEmpty()) && (lookup == null || lookup.isEmpty())) {
toPut = entriesWithoutValues.computeIfAbsent(rimd.getInjectionTargetClass(), k -> new HashMap<>());
WeldLogger.DEPLOYMENT_LOGGER.debugf("Adding %s/%s to injection disabled map", eemd.getEnvEntryName(), entryType);
} else {
toPut = envEntryInjections.computeIfAbsent(rimd.getInjectionTargetClass(), k -> new HashMap<>());
WeldLogger.DEPLOYMENT_LOGGER.debugf("Adding %s/%s to injection added map", eemd.getEnvEntryName(), entryType);
}
toPut.put(rimd.getInjectionTargetName(), new InjectionData(eemd, rimd, entryType));
}
}
if (!entriesWithoutValues.isEmpty() || !envEntryInjections.isEmpty()) {
extension = new EnvEntryCdiExtension(
entriesWithoutValues.isEmpty() ? Collections.emptyMap() : entriesWithoutValues,
envEntryInjections.isEmpty() ? Collections.emptyMap() : envEntryInjections
);
}
}
return extension;
}
private static Class<?> getSimpleEntryType(String type, ClassLoader classLoader) {
assert type != null;
Class<?> result = SIMPLE_ENTRY_TYPES.get(type);
if (result == null && !type.equals(void.class.getName())) {
try {
Class<?> clazz = Class.forName(type, false, classLoader);
if (clazz.isEnum()) {
result = clazz;
}
} catch (ClassNotFoundException e) {
throw WeldLogger.ROOT_LOGGER.cannotLoadClass(type, e);
}
}
return result;
}
private static class InjectionData {
private final EnvironmentEntryMetaData eemd;
private final ResourceInjectionTargetMetaData rimd;
private final Class<?> envType;
private InjectionData(EnvironmentEntryMetaData eemd, ResourceInjectionTargetMetaData rimd, Class<?> envType) {
this.eemd = eemd;
this.rimd = rimd;
this.envType = envType;
}
private boolean isEntryNameTargetName() {
String concat = rimd.getInjectionTargetClass() + "/" + rimd.getInjectionTargetName();
return concat.equals(eemd.getEnvEntryName());
}
}
private static class EnvEntryCdiExtension implements Extension {
private final Map<String, Map<String, InjectionData>> entriesWithoutValues;
private final Map<String, Map<String, InjectionData>> envEntryInjections;
private EnvEntryCdiExtension(Map<String, Map<String, InjectionData>> entriesWithoutValues, Map<String, Map<String, InjectionData>> envEntryInjections) {
this.entriesWithoutValues = entriesWithoutValues;
this.envEntryInjections = envEntryInjections;
}
@SuppressWarnings("unused")
public <X> void processAnnotatedType(@Observes ProcessAnnotatedType<X> event) {
processEntriesWithoutValues(event);
processEnvEntryInjections(event);
}
/**
* Look for fields or setters annotated with @Resource where neither mappedName nor lookup are set.
* If found see if there was an env-entry without a value; if so remove the annotation to disable injection
* @param event the event to process
* @param <X> the class being annotated
*/
private <X> void processEntriesWithoutValues(ProcessAnnotatedType<X> event) {
AnnotatedType<X> annotatedType = event.getAnnotatedType();
String typeName = annotatedType.getBaseType().getTypeName();
Map<String, InjectionData> membersWithoutValues = entriesWithoutValues.get(typeName);
if (membersWithoutValues != null) {
AnnotatedTypeConfigurator<X> typeConfigurator = event.configureAnnotatedType();
Set<AnnotatedFieldConfigurator<? super X>> annotatedFields = typeConfigurator.fields();
for (AnnotatedFieldConfigurator<? super X> annotatedFieldCfg : annotatedFields) {
AnnotatedField<? super X> annotatedField = annotatedFieldCfg.getAnnotated();
Field field = annotatedField.getJavaMember();
InjectionData injectionData = membersWithoutValues.get(field.getName());
// Remove the annotation if it exists, an env-entry does too and they match
annotatedFieldCfg.remove(a -> testNoValueAnnotation(a, injectionData, field.getType()));
}
Set<AnnotatedMethodConfigurator<? super X>> annotatedMethods = typeConfigurator.methods();
for (AnnotatedMethodConfigurator<? super X> annotatedMethodCfg : annotatedMethods) {
AnnotatedMethod<? super X> annotatedMethod = annotatedMethodCfg.getAnnotated();
Method method = annotatedMethod.getJavaMember();
Class<?>[] params = method.getParameterTypes();
if (params.length == 1) {
String asField = methodNameAsField(method);
if (asField != null) {
InjectionData injectionData = membersWithoutValues.get(asField);
// Remove the annotation if it exists, an env-entry does too and they match
annotatedMethodCfg.remove(a -> testNoValueAnnotation(a, injectionData, params[0]));
}
}
}
} else {
WeldLogger.DEPLOYMENT_LOGGER.tracef("%s is not in the injection disabled map", typeName);
}
}
/**
* Look for fields or setters not annotated with @Resource whose name matches an env-entry injection target.
* If found, add the annotation so injection will be performed
* @param event the event to process
* @param <X> the class being annotated
*/
private <X> void processEnvEntryInjections(ProcessAnnotatedType<X> event) {
AnnotatedType<X> annotatedType = event.getAnnotatedType();
String typeName = annotatedType.getBaseType().getTypeName();
Map<String, InjectionData> envEntryInjection = envEntryInjections.get(typeName);
if (envEntryInjection != null) {
AnnotatedTypeConfigurator<X> typeConfigurator = event.configureAnnotatedType();
Set<AnnotatedFieldConfigurator<? super X>> annotatedFields = typeConfigurator.fields();
for (AnnotatedFieldConfigurator<? super X> annotatedFieldCfg : annotatedFields) {
AnnotatedField<? super X> annotatedField = annotatedFieldCfg.getAnnotated();
if (annotatedField.getAnnotations(Resource.class).isEmpty()) {
Field field = annotatedField.getJavaMember();
InjectionData injectionData = envEntryInjection.get(field.getName());
if (injectionData != null && isMatchingType(field.getType(), injectionData.envType)) {
annotatedFieldCfg.add(new UnmappedResourceLiteral(injectionData));
WeldLogger.DEPLOYMENT_LOGGER.debugf("Added injection into %s", field);
} else if (injectionData != null && injectionData.envType != null) {
WeldLogger.DEPLOYMENT_LOGGER.debugf("Entry type %s cannot be assigned to %s", injectionData.envType, field);
}
}
}
Set<AnnotatedMethodConfigurator<? super X>> annotatedMethods = typeConfigurator.methods();
for (AnnotatedMethodConfigurator<? super X> annotatedMethodCfg : annotatedMethods) {
AnnotatedMethod<? super X> annotatedMethod = annotatedMethodCfg.getAnnotated();
if (annotatedMethod.getAnnotations(Resource.class).isEmpty()) {
Method method = annotatedMethod.getJavaMember();
Class<?>[] params = method.getParameterTypes();
if (params.length == 1) {
String asField = methodNameAsField(method);
if (asField != null) {
InjectionData injectionData = envEntryInjection.get(asField);
if (injectionData != null && isMatchingType(params[0], injectionData.envType)) {
annotatedMethodCfg.add(new UnmappedResourceLiteral(injectionData));
WeldLogger.DEPLOYMENT_LOGGER.debugf("Added injection into %s", method);
} else if (injectionData != null && injectionData.envType != null) {
WeldLogger.DEPLOYMENT_LOGGER.debugf("Entry type %s cannot be passed to %s", injectionData.envType, method);
}
}
}
}
}
} else {
WeldLogger.DEPLOYMENT_LOGGER.tracef("%s is not in the env-entry injection map", typeName);
}
}
}
private static String methodNameAsField(Method method) {
String result = null;
String methodName = method.getName();
if (methodName.startsWith("set") && methodName.length() > 3) {
String withoutSet = methodName.substring(3);
char initial = Character.toLowerCase(withoutSet.charAt(0));
result = withoutSet.length() > 1 ? initial + withoutSet.substring(1) : String.valueOf(initial);
}
return result;
}
private static boolean isMatchingType(Class<?> memberType, Class<?> entryType) {
assert memberType != null;
// If no env-entry-type was provided, just confirm the target member's type is a legal simple env entry target.
// If it was provided, confirm it is compatible with the target member's type
return (entryType == null && (SIMPLE_ENTRY_TYPES.containsKey(memberType.getName()) || memberType.isEnum()))
|| (entryType != null && (memberType.isAssignableFrom(entryType) || entryType.equals(PRIMITIVE_TYPES.get(memberType))));
}
private static boolean testNoValueAnnotation(Annotation a, InjectionData injectionData, Class<?> targetType) {
return injectionData != null && a instanceof Resource && testNoValueResource((Resource) a, injectionData, targetType);
}
private static boolean testNoValueResource(Resource resource, InjectionData injectionData, Class<?> targetType) {
boolean result = injectionData != null
&& (resource.lookup().isEmpty() && resource.mappedName().isEmpty())
&& isMatchingType(targetType, injectionData.envType)
&& (resource.name().equals(injectionData.eemd.getEnvEntryName())
|| (resource.name().isEmpty() && injectionData.isEntryNameTargetName()));
WeldLogger.DEPLOYMENT_LOGGER.debugf("Disable injection into %s? %s", resource, result);
return result;
}
private static class UnmappedResourceLiteral extends AnnotationLiteral<Resource> implements Resource {
private static final long serialVersionUID = 1L;
private final InjectionData injectionData;
private UnmappedResourceLiteral(InjectionData injectionData) {
this.injectionData = injectionData;
}
@Override
public String name() {
String name = injectionData.eemd.getEnvEntryName();
return name == null ? "" : name;
}
@Override
public String lookup() {
String lookup = injectionData.eemd.getLookupName();
return lookup == null ? "" : lookup;
}
@Override
public Class<?> type() {
Class<?> type = injectionData.envType;
return type == null ? Object.class : type;
}
@Override
public AuthenticationType authenticationType() {
return AuthenticationType.CONTAINER;
}
@Override
public boolean shareable() {
return true;
}
@Override
public String mappedName() {
return "";
}
@Override
public String description() {
return "";
}
}
}
| 21,395 | 50.064439 | 160 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/deployment/processors/WeldConfiguration.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment.processors;
import org.jboss.as.server.deployment.AttachmentKey;
/**
* The final configuration for Weld where the global configuration defined in the model is combined in per-deployment configuration specified in
* <code>jboss-all.xml</code>
*
* @author Jozef Hartinger
*
*/
class WeldConfiguration {
public static final AttachmentKey<WeldConfiguration> ATTACHMENT_KEY = AttachmentKey.create(WeldConfiguration.class);
private final boolean requireBeanDescriptor;
private final boolean nonPortableMode;
private final boolean developmentMode;
private final boolean legacyEmptyBeansXmlTreatment;
public WeldConfiguration(boolean requireBeanDescriptor, boolean nonPortableMode, boolean developmentMode, boolean legacyEmptyBeansXmlTreatment) {
this.requireBeanDescriptor = requireBeanDescriptor;
this.nonPortableMode = nonPortableMode;
this.developmentMode = developmentMode;
this.legacyEmptyBeansXmlTreatment = legacyEmptyBeansXmlTreatment;
}
public boolean isNonPortableMode() {
return nonPortableMode;
}
public boolean isRequireBeanDescriptor() {
return requireBeanDescriptor;
}
public boolean isDevelopmentMode() {
return developmentMode;
}
public boolean isLegacyEmptyBeansXmlTreatment() {
return legacyEmptyBeansXmlTreatment;
}
@Override
public String toString() {
return "WeldConfiguration [requireBeanDescriptor=" + requireBeanDescriptor + ", nonPortableMode=" + nonPortableMode + ", developmentMode="
+ developmentMode + ", legacyEmptyBeansXmlTreatment=" + legacyEmptyBeansXmlTreatment + "]";
}
}
| 2,731 | 36.944444 | 149 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/deployment/processors/SecurityBootstrapDependencyInstaller.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment.processors;
import org.jboss.as.controller.capability.CapabilityServiceSupport;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.weld.services.bootstrap.WeldSecurityServices;
import org.jboss.as.weld.spi.BootstrapDependencyInstaller;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.weld.security.spi.SecurityServices;
import java.util.function.Consumer;
/**
* @author Martin Kouba
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public class SecurityBootstrapDependencyInstaller implements BootstrapDependencyInstaller {
@Override
public ServiceName install(ServiceTarget serviceTarget, DeploymentUnit deploymentUnit, boolean jtsEnabled) {
final ServiceName serviceName = deploymentUnit.getServiceName().append(WeldSecurityServices.SERVICE_NAME);
final CapabilityServiceSupport capabilities = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT);
final ServiceBuilder<?> sb = serviceTarget.addService(serviceName);
final Consumer<SecurityServices> securityServicesConsumer = sb.provides(serviceName);
sb.setInstance(new WeldSecurityServices(securityServicesConsumer));
sb.install();
return serviceName;
}
}
| 2,449 | 43.545455 | 123 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/deployment/processors/WildFlyWeldEnvironment.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment.processors;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.jboss.weld.bootstrap.api.Environment;
import org.jboss.weld.bootstrap.api.Environments;
import org.jboss.weld.bootstrap.api.Service;
import org.jboss.weld.injection.spi.ResourceInjectionServices;
import org.jboss.weld.resources.spi.ResourceLoader;
import org.jboss.weld.security.spi.SecurityServices;
/**
* Since not all Weld subsystem submodules must be always present (e.g. when using WildFly Swarm) we cannot use {@link Environments#EE_INJECT}.
*
* @author Martin Kouba
*/
class WildFlyWeldEnvironment implements Environment {
static final WildFlyWeldEnvironment INSTANCE = new WildFlyWeldEnvironment();
private final Set<Class<? extends Service>> requiredDeploymentServices;
private final Set<Class<? extends Service>> requiredBeanDeploymentArchiveServices;
private WildFlyWeldEnvironment() {
this.requiredDeploymentServices = Collections.singleton(SecurityServices.class);
Set<Class<? extends Service>> beanDeploymentArchiveServices = new HashSet<>();
beanDeploymentArchiveServices.add(ResourceLoader.class);
beanDeploymentArchiveServices.add(ResourceInjectionServices.class);
this.requiredBeanDeploymentArchiveServices = Collections.unmodifiableSet(beanDeploymentArchiveServices);
}
@Override
public Set<Class<? extends Service>> getRequiredDeploymentServices() {
return requiredDeploymentServices;
}
@Override
public Set<Class<? extends Service>> getRequiredBeanDeploymentArchiveServices() {
return requiredBeanDeploymentArchiveServices;
}
}
| 2,717 | 39.567164 | 143 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/deployment/processors/CompositeClassLoader.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment.processors;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
/**
* A {@link ClassLoader} that delegates loading of classes and resources to a list of delegate class loaders.
* @author Paul Ferraro
*/
class CompositeClassLoader extends ClassLoader {
private List<ClassLoader> loaders;
CompositeClassLoader(List<ClassLoader> loaders) {
super(null);
this.loaders = loaders;
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
for (ClassLoader loader : this.loaders) {
try {
return loader.loadClass(name);
} catch (ClassNotFoundException e) {
// Ignore
}
}
return super.findClass(name);
}
@Override
public Enumeration<URL> getResources(String name) throws IOException {
List<Enumeration<URL>> results = new ArrayList<>(this.loaders.size());
for (ClassLoader loader : this.loaders) {
results.add(loader.getResources(name));
}
Iterator<Enumeration<URL>> iterator = results.iterator();
return new Enumeration<>() {
private Enumeration<URL> urls = Collections.emptyEnumeration();
@Override
public boolean hasMoreElements() {
return this.getURLs().hasMoreElements();
}
@Override
public URL nextElement() {
return this.getURLs().nextElement();
}
private Enumeration<URL> getURLs() {
if (!this.urls.hasMoreElements() && iterator.hasNext()) {
this.urls = iterator.next();
}
return this.urls;
}
};
}
@Override
protected URL findResource(String name) {
for (ClassLoader loader : this.loaders) {
URL resource = loader.getResource(name);
if (resource != null) {
return resource;
}
}
return super.findResource(name);
}
}
| 3,249 | 32.505155 | 109 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/deployment/processors/BeanDefiningAnnotationProcessor.java | package org.jboss.as.weld.deployment.processors;
import static org.jboss.as.weld.discovery.AnnotationType.FOR_CLASSINFO;
import static org.jboss.as.weld.util.Indices.ANNOTATION_PREDICATE;
import static org.jboss.as.weld.util.Indices.getAnnotatedClasses;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import jakarta.transaction.TransactionScoped;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.annotation.CompositeIndex;
import org.jboss.as.weld.CdiAnnotations;
import org.jboss.as.weld.deployment.WeldAttachments;
import org.jboss.as.weld.discovery.AnnotationType;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
/**
* Determines the set of bean defining annotations as defined by the CDI specification and attaches them under
* {@link WeldAttachments#BEAN_DEFINING_ANNOTATIONS}.
*
* @author Jozef Hartinger
*
*/
public class BeanDefiningAnnotationProcessor implements DeploymentUnitProcessor {
private static final DotName VIEW_SCOPED_NAME = DotName.createSimple("jakarta.faces.view.ViewScoped");
private static final DotName FLOW_SCOPED_NAME = DotName.createSimple("jakarta.faces.flow.FlowScoped");
private static final DotName CLIENT_WINDOW_SCOPED = DotName.createSimple("jakarta.faces.lifecycle.ClientWindowScoped");
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
if (deploymentUnit.getParent() != null) {
return; // only run for top-level deployments
}
final CompositeIndex index = deploymentUnit.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX);
// CDI built-in normal scopes plus @Dependent
addAnnotations(deploymentUnit, CdiAnnotations.BEAN_DEFINING_ANNOTATIONS);
// CDI @Model stereotype
addAnnotation(deploymentUnit, new AnnotationType(CdiAnnotations.MODEL.getDotName(), false));
// EE7 built-in normal scopes and stereotypes
addAnnotation(deploymentUnit, new AnnotationType(TransactionScoped.class));
addAnnotation(deploymentUnit, new AnnotationType(VIEW_SCOPED_NAME, true));
addAnnotation(deploymentUnit, new AnnotationType(FLOW_SCOPED_NAME, true));
addAnnotation(deploymentUnit, new AnnotationType(CLIENT_WINDOW_SCOPED, true));
for (AnnotationType annotationType : CdiAnnotations.BEAN_DEFINING_META_ANNOTATIONS) {
addAnnotations(deploymentUnit, getAnnotationsAnnotatedWith(index, annotationType.getName()));
}
}
private static void addAnnotations(final DeploymentUnit deploymentUnit, Collection<AnnotationType> annotations) {
for(AnnotationType annotation : annotations){
addAnnotation(deploymentUnit, annotation);
}
}
private static void addAnnotation(final DeploymentUnit deploymentUnit, AnnotationType annotation) {
deploymentUnit.addToAttachmentList(WeldAttachments.BEAN_DEFINING_ANNOTATIONS, annotation);
}
private Collection<AnnotationType> getAnnotationsAnnotatedWith(CompositeIndex index, DotName annotationName) {
Set<AnnotationType> annotations = new HashSet<>();
for (ClassInfo classInfo : getAnnotatedClasses(index.getAnnotations(annotationName))) {
if (ANNOTATION_PREDICATE.test(classInfo)) {
annotations.add(FOR_CLASSINFO.apply(classInfo));
}
}
return annotations;
}
@Override
public void undeploy(DeploymentUnit deploymentUnit) {
deploymentUnit.removeAttachment(WeldAttachments.BEAN_DEFINING_ANNOTATIONS);
}
}
| 3,963 | 44.045455 | 123 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/deployment/processors/BeanArchiveProcessor.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment.processors;
import static org.jboss.as.weld.util.Utils.getDeploymentUnitId;
import static org.jboss.as.weld.util.Utils.getRootDeploymentUnit;
import static org.jboss.as.weld.util.Utils.isClassesRoot;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.ServiceLoader;
import java.util.Set;
import jakarta.enterprise.inject.build.compatible.spi.BuildCompatibleExtension;
import jakarta.enterprise.inject.spi.Extension;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.ee.structure.DeploymentType;
import org.jboss.as.ee.structure.DeploymentTypeMarker;
import org.jboss.as.ee.weld.InjectionTargetDefiningAnnotations;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.SubDeploymentMarker;
import org.jboss.as.server.deployment.annotation.AnnotationIndexUtils;
import org.jboss.as.server.deployment.module.ModuleRootMarker;
import org.jboss.as.server.deployment.module.ResourceRoot;
import org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex;
import org.jboss.as.weld._private.WeldDeploymentMarker;
import org.jboss.as.weld.deployment.BeanDeploymentArchiveImpl;
import org.jboss.as.weld.deployment.BeanDeploymentArchiveImpl.BeanArchiveType;
import org.jboss.as.weld.deployment.BeanDeploymentModule;
import org.jboss.as.weld.deployment.ExplicitBeanArchiveMetadata;
import org.jboss.as.weld.deployment.ExplicitBeanArchiveMetadataContainer;
import org.jboss.as.weld.deployment.WeldAttachments;
import org.jboss.as.weld.discovery.AnnotationType;
import org.jboss.as.weld.logging.WeldLogger;
import org.jboss.as.weld.spi.ComponentDescriptionProcessor;
import org.jboss.as.weld.util.Indices;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.Index;
import org.jboss.modules.Module;
import org.jboss.vfs.VirtualFile;
import org.jboss.weld.bootstrap.spi.BeanDiscoveryMode;
import org.jboss.weld.bootstrap.spi.BeansXml;
import org.jboss.weld.util.collections.Multimap;
import org.jboss.weld.util.collections.SetMultimap;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* Deployment processor that builds bean archives and attaches them to the deployment
* <p/>
* Currently this is done by pulling the information out of the jandex {@link Index}.
* <p/>
*
* @author Stuart Douglas
* @author Jozef Hartinger
*/
public class BeanArchiveProcessor implements DeploymentUnitProcessor {
private static final DotName BUILD_COMPAT_EXTENSION_NAME = DotName.createSimple(BuildCompatibleExtension.class);
private static final DotName EXTENSION_NAME = DotName.createSimple(Extension.class.getName());
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
if (!WeldDeploymentMarker.isPartOfWeldDeployment(deploymentUnit)) {
return;
}
WeldLogger.DEPLOYMENT_LOGGER.processingWeldDeployment(deploymentUnit.getName());
final Map<ResourceRoot, Index> indexes = AnnotationIndexUtils.getAnnotationIndexes(deploymentUnit);
final Map<ResourceRoot, BeanDeploymentArchiveImpl> bdaMap = new HashMap<>();
final Components components = new Components(deploymentUnit, indexes);
final ResourceRootHandler handler = new ResourceRootHandler(deploymentUnit, components, indexes);
for (ResourceRoot resourceRoot : deploymentUnit.getAttachmentList(Attachments.RESOURCE_ROOTS)) {
if (ModuleRootMarker.isModuleRoot(resourceRoot) && !SubDeploymentMarker.isSubDeployment(resourceRoot)) {
if (isClassesRoot(resourceRoot)) {
continue; // this is handled below
}
handler.handleResourceRoot(bdaMap, resourceRoot);
}
}
if (!DeploymentTypeMarker.isType(DeploymentType.EAR, deploymentUnit)) {
handler.handleResourceRoot(bdaMap, handler.deploymentResourceRoot);
}
if (!bdaMap.containsKey(handler.deploymentResourceRoot)) {
// there is not root bda, let's create one
BeanDeploymentArchiveImpl bda = new BeanDeploymentArchiveImpl(Collections.emptySet(), Collections.emptySet(), BeansXml.EMPTY_BEANS_XML, handler.module, getDeploymentUnitId(deploymentUnit), BeanArchiveType.SYNTHETIC, true);
WeldLogger.DEPLOYMENT_LOGGER.beanArchiveDiscovered(bda);
bdaMap.put(handler.deploymentResourceRoot, bda);
}
deploymentUnit.putAttachment(WeldAttachments.DEPLOYMENT_ROOT_BEAN_DEPLOYMENT_ARCHIVE, bdaMap.get(handler.deploymentResourceRoot));
/*
* Finish EE component processing
*/
for (Entry<ResourceRoot, Collection<ComponentDescription>> entry : components.componentDescriptions.entrySet()) {
BeanDeploymentArchiveImpl bda = bdaMap.get(entry.getKey());
String id;
if (bda != null) {
id = bda.getId();
} else {
id = deploymentUnit.getAttachment(WeldAttachments.DEPLOYMENT_ROOT_BEAN_DEPLOYMENT_ARCHIVE).getId();
}
for (ComponentDescription componentDescription : entry.getValue()) {
componentDescription.setBeanDeploymentArchiveId(id);
}
}
final BeanDeploymentModule bdm = new BeanDeploymentModule(handler.module.getIdentifier().toString(), deploymentUnit, bdaMap.values());
deploymentUnit.putAttachment(WeldAttachments.BEAN_DEPLOYMENT_MODULE, bdm);
}
@Override
public void undeploy(DeploymentUnit context) {
context.removeAttachment(WeldAttachments.BEAN_DEPLOYMENT_MODULE);
context.removeAttachment(WeldAttachments.DEPLOYMENT_ROOT_BEAN_DEPLOYMENT_ARCHIVE);
}
/**
* Arranges component descriptions into maps keyed on the resource root a component is located under.
*/
private static class Components {
private final Multimap<ResourceRoot, ComponentDescription> componentDescriptions = SetMultimap.newSetMultimap();
private final List<ComponentDescription> implicitComponentDescriptions = new ArrayList<>();
private final Iterable<ComponentDescriptionProcessor> componentDescriptionProcessors;
public Components(DeploymentUnit deploymentUnit, Map<ResourceRoot, Index> indexes) {
componentDescriptionProcessors = ServiceLoader.load(ComponentDescriptionProcessor.class,
WildFlySecurityManager.getClassLoaderPrivileged(BeanArchiveProcessor.class));
for (ComponentDescription component : deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION).getComponentDescriptions()) {
ResourceRoot resourceRoot = null;
DotName componentClassName = DotName.createSimple(component.getComponentClassName());
for (Entry<ResourceRoot, Index> entry : indexes.entrySet()) {
final Index index = entry.getValue();
if (index != null
&& index.getClassByName(componentClassName) != null) {
resourceRoot = entry.getKey();
break;
}
}
if (resourceRoot == null) {
implicitComponentDescriptions.add(component);
}
if (resourceRoot == null || isClassesRoot(resourceRoot)) {
// special handling
resourceRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);
}
componentDescriptions.put(resourceRoot, component);
// Process component descriptions
for (ComponentDescriptionProcessor processor : componentDescriptionProcessors) {
processor.processComponentDescription(resourceRoot, component);
}
}
}
boolean hasBeanComponents(ResourceRoot resourceRoot) {
for (ComponentDescriptionProcessor processor : componentDescriptionProcessors) {
if (processor.hasBeanComponents(resourceRoot)) {
return true;
}
}
return false;
}
}
private static class ResourceRootHandler {
private final DeploymentUnit deploymentUnit;
private final Module module;
private final Map<ResourceRoot, Index> indexes;
private final Components components;
private final DeploymentReflectionIndex reflectionIndex;
private final ResourceRoot deploymentResourceRoot;
private final ResourceRoot classesResourceRoot;
private final ExplicitBeanArchiveMetadataContainer explicitBeanArchives;
private final Set<AnnotationType> beanDefiningAnnotations;
private final boolean requireBeanDescriptor;
private ResourceRootHandler(DeploymentUnit deploymentUnit, Components components, Map<ResourceRoot, Index> indexes) {
this.deploymentUnit = deploymentUnit;
this.explicitBeanArchives = deploymentUnit.getAttachment(ExplicitBeanArchiveMetadataContainer.ATTACHMENT_KEY);
this.module = deploymentUnit.getAttachment(Attachments.MODULE);
this.indexes = indexes;
this.components = components;
this.reflectionIndex = deploymentUnit.getAttachment(Attachments.REFLECTION_INDEX);
this.deploymentResourceRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);
this.classesResourceRoot = deploymentUnit.getAttachment(WeldAttachments.CLASSES_RESOURCE_ROOT);
HashSet<AnnotationType> annotationTypes = new HashSet<>(getRootDeploymentUnit(deploymentUnit).getAttachment(WeldAttachments.BEAN_DEFINING_ANNOTATIONS));
List<DotName> definingAnnotations = getRootDeploymentUnit(deploymentUnit).getAttachmentList(InjectionTargetDefiningAnnotations.INJECTION_TARGET_DEFINING_ANNOTATIONS);
for(DotName annotation : definingAnnotations) {
annotationTypes.add(new AnnotationType(annotation, false));
}
this.beanDefiningAnnotations = annotationTypes;
this.requireBeanDescriptor = getRootDeploymentUnit(deploymentUnit).getAttachment(WeldConfiguration.ATTACHMENT_KEY).isRequireBeanDescriptor();
}
private void handleResourceRoot(Map<ResourceRoot, BeanDeploymentArchiveImpl> bdaMap, ResourceRoot resourceRoot) {
BeanDeploymentArchiveImpl bda = processResourceRoot(resourceRoot);
if (bda != null) {
bdaMap.put(resourceRoot, bda);
}
}
/**
* Process a resource root eventually creating a bean archive out of it if it matches requirements for either an
* implicit or explicit bean archive. There requirements are laid down by the CDI spec.
*
* If the resource root does not represent a bean archive, null is returned.
*/
private BeanDeploymentArchiveImpl processResourceRoot(ResourceRoot resourceRoot) {
ExplicitBeanArchiveMetadata metadata = null;
if (explicitBeanArchives != null) {
metadata = explicitBeanArchives.getBeanArchiveMetadata().get(resourceRoot);
}
BeanDeploymentArchiveImpl bda;
if (metadata == null && requireBeanDescriptor) {
/*
* For compatibility with Contexts and Dependency 1.0, products must contain an option to cause an archive to be ignored by the
* container when no beans.xml is present.
*/
return null;
}
if (metadata == null || metadata.getBeansXml().getBeanDiscoveryMode().equals(BeanDiscoveryMode.ANNOTATED)) {
// this is either an implicit bean archive or not a bean archive at all!
final boolean isRootBda = resourceRoot.equals(deploymentResourceRoot);
ResourceRoot indexResourceRoot = resourceRoot;
if (resourceRoot == deploymentResourceRoot && classesResourceRoot != null) {
// this is WEB-INF/classes BDA
indexResourceRoot = classesResourceRoot;
}
final Index index = indexes.get(indexResourceRoot);
if (index == null) {
return null; // index may be null for some resource roots
}
/*
* An archive which contains an extension and no beans.xml file is not a bean archive.
* An archive which contains a build compatible extension and no beans.xml file is not a bean archive.
*/
if (metadata == null &&
(!index.getAllKnownImplementors(EXTENSION_NAME).isEmpty() || !index.getAllKnownImplementors(BUILD_COMPAT_EXTENSION_NAME).isEmpty())) {
return null;
}
Set<String> beans = getImplicitBeanClasses(index, resourceRoot);
Set<String> allKnownClasses = getAllKnownClasses(index);
if (beans.isEmpty() && !components.hasBeanComponents(resourceRoot)) {
return null;
}
BeansXml beansXml = null;
if (metadata != null) {
beansXml = metadata.getBeansXml();
}
bda = new BeanDeploymentArchiveImpl(beans, allKnownClasses, beansXml, module, createBeanArchiveId(resourceRoot), BeanArchiveType.IMPLICIT, isRootBda);
WeldLogger.DEPLOYMENT_LOGGER.beanArchiveDiscovered(bda);
} else if (metadata.getBeansXml().getBeanDiscoveryMode().equals(BeanDiscoveryMode.NONE)) {
// scanning suppressed per spec in this archive
return null;
} else {
boolean isRootBda = metadata.isDeploymentRoot();
bda = createExplicitBeanDeploymentArchive(indexes.get(metadata.getResourceRoot()), metadata, isRootBda);
WeldLogger.DEPLOYMENT_LOGGER.beanArchiveDiscovered(bda);
}
// Register processed components
for (ComponentDescriptionProcessor processor : components.componentDescriptionProcessors) {
processor.registerComponents(resourceRoot, bda, reflectionIndex);
}
return bda;
}
private Set<String> getAllKnownClasses(Index index) {
Set<String> allKnownClasses = new HashSet<>();
// index may be null if a war has a beans.xml but no WEB-INF/classes
if (index != null) {
for (ClassInfo classInfo : index.getKnownClasses()) {
allKnownClasses.add(Indices.CLASS_INFO_TO_FQCN.apply(classInfo));
}
}
return allKnownClasses;
}
private Set<String> getImplicitBeanClasses(Index index, ResourceRoot resourceRoot) {
Set<String> implicitBeanClasses = new HashSet<>();
for (AnnotationType beanDefiningAnnotation : beanDefiningAnnotations) {
List<AnnotationInstance> annotationInstances = index.getAnnotations(beanDefiningAnnotation.getName());
for (ClassInfo classInfo : Indices.getAnnotatedClasses(annotationInstances)) {
implicitBeanClasses.add(Indices.CLASS_INFO_TO_FQCN.apply(classInfo));
}
}
// Make all explicit components into implicit beans so they will support injection
for(ComponentDescription description : components.componentDescriptions.get(resourceRoot)) {
if(!components.implicitComponentDescriptions.contains(description)) {
implicitBeanClasses.add(description.getComponentClassName());
}
}
return implicitBeanClasses;
}
private BeanDeploymentArchiveImpl createExplicitBeanDeploymentArchive(final Index index, ExplicitBeanArchiveMetadata beanArchiveMetadata, boolean root) {
Set<String> classNames = getAllKnownClasses(index);
return new BeanDeploymentArchiveImpl(classNames, classNames, beanArchiveMetadata.getBeansXml(), module, createBeanArchiveId(beanArchiveMetadata.getResourceRoot()), BeanArchiveType.EXPLICIT, root);
}
private String createBeanArchiveId(ResourceRoot resourceRoot) {
String beanArchiveId = getDeploymentUnitId(deploymentUnit);
if (resourceRoot != null) {
final VirtualFile deploymentRootResource = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT).getRoot();
beanArchiveId += "/" + resourceRoot.getRoot().getPathNameRelativeTo(deploymentRootResource);
}
return beanArchiveId;
}
}
}
| 18,453 | 49.837466 | 234 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/deployment/processors/UrlScanner.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment.processors;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.function.BiConsumer;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import org.jboss.as.weld.logging.WeldLogger;
import org.jboss.vfs.VFS;
import org.jboss.vfs.VirtualFile;
class UrlScanner {
@FunctionalInterface
interface ClassFile {
InputStream openStream() throws IOException;
}
private final URL beansXmlUrl;
private final BiConsumer<String, ClassFile> classConsumer;
UrlScanner(URL beansXmlUrl, BiConsumer<String, ClassFile> classConsumer) {
this.beansXmlUrl = beansXmlUrl;
this.classConsumer = classConsumer;
}
boolean scan() {
String urlPath = beansXmlUrl.toExternalForm();
// determin resource type (eg: jar, file, bundle)
String urlType = "file";
int colonIndex = urlPath.indexOf(":");
if (colonIndex != -1) {
urlType = urlPath.substring(0, colonIndex);
}
// Extra built-in support for simple file-based resources
if ("file".equals(urlType) || "jar".equals(urlType)) {
// switch to using getPath() instead of toExternalForm()
urlPath = beansXmlUrl.getPath();
if (urlPath.indexOf('!') > 0) {
urlPath = urlPath.substring(0, urlPath.indexOf('!'));
} else {
// hack for /META-INF/beans.xml
File dirOrArchive = new File(urlPath);
dirOrArchive = dirOrArchive.getParentFile();
urlPath = dirOrArchive.getParent();
}
try {
urlPath = URLDecoder.decode(urlPath, "UTF-8");
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException(ex);
}
handle(urlPath);
return true;
} else if ("vfs".equals(urlType)) {
try {
VirtualFile vfsRoot = VFS.getChild(beansXmlUrl).getParent().getParent();
handle(vfsRoot);
return true;
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
} else {
WeldLogger.DEPLOYMENT_LOGGER.doNotUnderstandProtocol(beansXmlUrl);
return false;
}
}
private void handle(VirtualFile urlPath) {
WeldLogger.DEPLOYMENT_LOGGER.tracef("scanning: %s", urlPath);
handleDirectory(urlPath, null);
}
private void handle(String urlPath) {
try {
WeldLogger.DEPLOYMENT_LOGGER.tracef("scanning: %s", urlPath);
if (urlPath.startsWith("file:")) {
urlPath = urlPath.substring(5);
}
if (urlPath.indexOf('!') > 0) {
urlPath = urlPath.substring(0, urlPath.indexOf('!'));
}
File file = new File(urlPath);
if (file.isDirectory()) {
handleDirectory(file, null);
} else {
handleArchiveByFile(file);
}
} catch (IOException ioe) {
WeldLogger.DEPLOYMENT_LOGGER.couldNotReadEntries(ioe);
}
}
private void handleArchiveByFile(File file) throws IOException {
try {
WeldLogger.DEPLOYMENT_LOGGER.trace("archive: " + file);
try (ZipFile zip = new ZipFile(file)) {
Enumeration<? extends ZipEntry> entries = zip.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
String name = entry.getName();
handleFile(name, () -> zip.getInputStream(entry));
}
}
} catch (ZipException e) {
throw new RuntimeException("Error handling file " + file, e);
}
}
private void handleDirectory(File file, String path) {
WeldLogger.DEPLOYMENT_LOGGER.tracef("handling directory: %s", file);
for (File child : file.listFiles()) {
String newPath = (path == null) ? child.getName() : (path + '/' + child.getName());
if (child.isDirectory()) {
handleDirectory(child, newPath);
} else {
handleFile(newPath, () -> child.toURI().toURL().openStream());
}
}
}
private void handleDirectory(VirtualFile file, String path) {
WeldLogger.DEPLOYMENT_LOGGER.tracef("handling directory: %s", file);
for (VirtualFile child : file.getChildren()) {
String newPath = (path == null) ? child.getName() : (path + '/' + child.getName());
if (child.isDirectory()) {
handleDirectory(child, newPath);
} else {
handleFile(newPath, () -> child.toURL().openStream());
}
}
}
protected void handleFile(String name, ClassFile loader) {
if (name.endsWith(".class")) {
classConsumer.accept(filenameToClassname(name), loader);
}
}
/**
* Convert a path to a class file to a class name
*/
public static String filenameToClassname(String filename) {
return filename.substring(0, filename.lastIndexOf(".class")).replace('/', '.').replace('\\', '.');
}
}
| 6,562 | 33.005181 | 106 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/deployment/processors/WebIntegrationProcessor.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment.processors;
import static org.jboss.as.weld.util.Utils.registerAsComponent;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import org.jboss.as.ee.component.Attachments;
import org.jboss.as.ee.component.EEApplicationClasses;
import org.jboss.as.ee.component.EEModuleDescription;
import org.jboss.as.ee.structure.DeploymentType;
import org.jboss.as.ee.structure.DeploymentTypeMarker;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.web.common.ExpressionFactoryWrapper;
import org.jboss.as.web.common.WarMetaData;
import org.jboss.as.weld._private.WeldDeploymentMarker;
import org.jboss.as.weld.WeldStartService;
import org.jboss.as.weld.logging.WeldLogger;
import org.jboss.as.weld.webtier.jsp.WeldJspExpressionFactoryWrapper;
import org.jboss.metadata.javaee.spec.ParamValueMetaData;
import org.jboss.metadata.web.jboss.JBossWebMetaData;
import org.jboss.metadata.web.spec.FilterMappingMetaData;
import org.jboss.metadata.web.spec.FilterMetaData;
import org.jboss.metadata.web.spec.FiltersMetaData;
import org.jboss.metadata.web.spec.ListenerMetaData;
import org.jboss.msc.service.ServiceName;
import org.jboss.weld.module.web.servlet.ConversationFilter;
import org.jboss.weld.module.web.servlet.WeldInitialListener;
import org.jboss.weld.module.web.servlet.WeldTerminalListener;
import org.jboss.weld.servlet.api.InitParameters;
/**
* Deployment processor that integrates weld into the web tier
*
* @author Stuart Douglas
*/
public class WebIntegrationProcessor implements DeploymentUnitProcessor {
private final ListenerMetaData INITIAL_LISTENER_METADATA;
private final ListenerMetaData TERMINAL_LISTENER_MEDATADA;
private final FilterMetaData conversationFilterMetadata;
private static final String WELD_INITIAL_LISTENER = WeldInitialListener.class.getName();
private static final String WELD_TERMINAL_LISTENER = WeldTerminalListener.class.getName();
private static final String WELD_SERVLET_LISTENER = "org.jboss.weld.environment.servlet.Listener";
private static final String CONVERSATION_FILTER_CLASS = ConversationFilter.class.getName();
private static final String CONVERSATION_FILTER_NAME = "CDI Conversation Filter";
private static final ParamValueMetaData CONVERSATION_FILTER_INITIALIZED = new ParamValueMetaData();
public WebIntegrationProcessor() {
// create wbl listener
INITIAL_LISTENER_METADATA = new ListenerMetaData();
INITIAL_LISTENER_METADATA.setListenerClass(WELD_INITIAL_LISTENER);
TERMINAL_LISTENER_MEDATADA = new ListenerMetaData();
TERMINAL_LISTENER_MEDATADA.setListenerClass(WELD_TERMINAL_LISTENER);
conversationFilterMetadata = new FilterMetaData();
conversationFilterMetadata.setFilterClass(CONVERSATION_FILTER_CLASS);
conversationFilterMetadata.setFilterName(CONVERSATION_FILTER_NAME);
conversationFilterMetadata.setAsyncSupported(true);
CONVERSATION_FILTER_INITIALIZED.setParamName(ConversationFilter.CONVERSATION_FILTER_REGISTERED);
CONVERSATION_FILTER_INITIALIZED.setParamValue(Boolean.TRUE.toString());
}
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final EEModuleDescription module = deploymentUnit.getAttachment(Attachments.EE_MODULE_DESCRIPTION);
final EEApplicationClasses applicationClasses = deploymentUnit.getAttachment(Attachments.EE_APPLICATION_CLASSES_DESCRIPTION);
if (!DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit)) {
return; // Skip non web deployments
}
WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY);
if (warMetaData == null) {
WeldLogger.DEPLOYMENT_LOGGER.debug("Not installing Weld web tier integration as no war metadata found");
return;
}
JBossWebMetaData webMetaData = warMetaData.getMergedJBossWebMetaData();
if (webMetaData == null) {
WeldLogger.DEPLOYMENT_LOGGER.debug("Not installing Weld web tier integration as no merged web metadata found");
return;
}
if(!WeldDeploymentMarker.isWeldDeployment(deploymentUnit)) {
if (WeldDeploymentMarker.isPartOfWeldDeployment(deploymentUnit)) {
createDependency(deploymentUnit, warMetaData);
}
return;
}
createDependency(deploymentUnit, warMetaData);
List<ListenerMetaData> listeners = webMetaData.getListeners();
if (listeners == null) {
listeners = new ArrayList<ListenerMetaData>();
webMetaData.setListeners(listeners);
} else {
//if the weld servlet listener is present remove it
//this should allow wars to be portable between AS7 and servlet containers
final ListIterator<ListenerMetaData> iterator = listeners.listIterator();
while (iterator.hasNext()) {
final ListenerMetaData listener = iterator.next();
if (listener.getListenerClass().trim().equals(WELD_SERVLET_LISTENER)) {
WeldLogger.DEPLOYMENT_LOGGER.debugf("Removing weld servlet listener %s from web config, as it is not needed in EE6 environments", WELD_SERVLET_LISTENER);
iterator.remove();
break;
}
}
}
listeners.add(0, INITIAL_LISTENER_METADATA);
listeners.add(TERMINAL_LISTENER_MEDATADA);
//These listeners use resource injection, so they need to be components
registerAsComponent(WELD_INITIAL_LISTENER, deploymentUnit);
registerAsComponent(WELD_TERMINAL_LISTENER, deploymentUnit);
deploymentUnit.addToAttachmentList(ExpressionFactoryWrapper.ATTACHMENT_KEY, WeldJspExpressionFactoryWrapper.INSTANCE);
if (webMetaData.getContextParams() == null) {
webMetaData.setContextParams(new ArrayList<ParamValueMetaData>());
}
final List<ParamValueMetaData> contextParams = webMetaData.getContextParams();
setupWeldContextIgnores(contextParams, InitParameters.CONTEXT_IGNORE_FORWARD);
setupWeldContextIgnores(contextParams, InitParameters.CONTEXT_IGNORE_INCLUDE);
if (webMetaData.getFilterMappings() != null) {
// register ConversationFilter
boolean filterMappingFound = false;
for (FilterMappingMetaData mapping : webMetaData.getFilterMappings()) {
if (CONVERSATION_FILTER_NAME.equals(mapping.getFilterName())) {
filterMappingFound = true;
break;
}
}
if (filterMappingFound) { // otherwise WeldListener will take care of conversation context activation
boolean filterFound = false;
// register ConversationFilter
if (webMetaData.getFilters() == null) {
webMetaData.setFilters(new FiltersMetaData());
}
for (FilterMetaData filter : webMetaData.getFilters()) {
if (CONVERSATION_FILTER_CLASS.equals(filter.getFilterClass())) {
filterFound = true;
break;
}
}
if (!filterFound) {
webMetaData.getFilters().add(conversationFilterMetadata);
registerAsComponent(CONVERSATION_FILTER_CLASS, deploymentUnit);
webMetaData.getContextParams().add(CONVERSATION_FILTER_INITIALIZED);
}
}
}
}
private void createDependency(DeploymentUnit deploymentUnit, WarMetaData warMetaData) {
final ServiceName weldStartService = (deploymentUnit.getParent() != null ? deploymentUnit.getParent() : deploymentUnit).getServiceName().append(WeldStartService.SERVICE_NAME);
warMetaData.addAdditionalDependency(weldStartService);
}
private void setupWeldContextIgnores(List<ParamValueMetaData> contextParams, String parameterName) {
for (ParamValueMetaData param : contextParams) {
if (parameterName.equals(param.getParamName())) {
return;
}
}
ParamValueMetaData parameter = new ParamValueMetaData();
parameter.setParamName(parameterName);
parameter.setParamValue("false");
contextParams.add(parameter);
}
} | 9,838 | 47.46798 | 183 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/deployment/processors/WeldDeploymentProcessor.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment.processors;
import static org.jboss.as.weld.util.Utils.putIfValueNotNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.function.Consumer;
import java.util.function.Supplier;
import jakarta.enterprise.inject.spi.Extension;
import org.jboss.as.controller.capability.CapabilityServiceSupport;
import org.jboss.as.ee.concurrent.ConcurrentContextSetupAction;
import org.jboss.as.ee.naming.JavaNamespaceSetup;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.as.naming.deployment.JndiNamingDependencyProcessor;
import org.jboss.as.naming.service.DefaultNamespaceContextSelectorService;
import org.jboss.as.naming.service.NamingService;
import org.jboss.as.server.Services;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.SetupAction;
import org.jboss.as.server.deployment.module.ModuleDependency;
import org.jboss.as.server.deployment.module.ModuleSpecification;
import org.jboss.as.server.deployment.module.ResourceRoot;
import org.jboss.as.weld.ServiceNames;
import org.jboss.as.weld.WeldBootstrapService;
import org.jboss.as.weld._private.WeldDeploymentMarker;
import org.jboss.as.weld.WeldStartService;
import org.jboss.as.weld.deployment.BeanDeploymentArchiveImpl;
import org.jboss.as.weld.deployment.BeanDeploymentModule;
import org.jboss.as.weld.deployment.CdiAnnotationMarker;
import org.jboss.as.weld.deployment.WeldAttachments;
import org.jboss.as.weld.deployment.WeldDeployment;
import org.jboss.as.weld.deployment.WeldPortableExtensions;
import org.jboss.as.weld.logging.WeldLogger;
import org.jboss.as.weld.services.TCCLSingletonService;
import org.jboss.as.weld.services.bootstrap.WeldExecutorServices;
import org.jboss.as.weld.spi.BootstrapDependencyInstaller;
import org.jboss.as.weld.spi.DeploymentUnitDependenciesProvider;
import org.jboss.as.weld.spi.ModuleServicesProvider;
import org.jboss.as.weld.util.Reflections;
import org.jboss.as.weld.util.ServiceLoaders;
import org.jboss.as.weld.util.Utils;
import org.jboss.metadata.ear.spec.EarMetaData;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.weld.bootstrap.api.Service;
import org.jboss.weld.bootstrap.spi.EEModuleDescriptor;
import org.jboss.weld.bootstrap.spi.Metadata;
import org.jboss.weld.config.ConfigurationKey;
import org.jboss.weld.configuration.spi.ExternalConfiguration;
import org.jboss.weld.configuration.spi.helpers.ExternalConfigurationBuilder;
import org.jboss.weld.manager.api.ExecutorServices;
import org.jboss.weld.security.spi.SecurityServices;
import org.jboss.weld.transaction.spi.TransactionServices;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* Deployment processor that installs the weld services and all other required services
*
* @author Stuart Douglas
* @author <a href="mailto:[email protected]">Tomasz Adamski</a>
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public class WeldDeploymentProcessor implements DeploymentUnitProcessor {
private final boolean jtsEnabled;
public WeldDeploymentProcessor(final boolean jtsEnabled) {
this.jtsEnabled = jtsEnabled;
}
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final DeploymentUnit parent = Utils.getRootDeploymentUnit(deploymentUnit);
final ServiceTarget serviceTarget = phaseContext.getServiceTarget();
final ResourceRoot deploymentRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);
if (!WeldDeploymentMarker.isPartOfWeldDeployment(deploymentUnit)) {
//if there are CDI annotation present and this is the top level deployment we log a warning
if (deploymentUnit.getParent() == null && CdiAnnotationMarker.cdiAnnotationsPresent(deploymentUnit)) {
WeldLogger.DEPLOYMENT_LOGGER.cdiAnnotationsButNotBeanArchive(deploymentUnit.getName());
}
return;
}
//add a dependency on the weld service to web deployments
final ServiceName weldBootstrapServiceName = parent.getServiceName().append(WeldBootstrapService.SERVICE_NAME);
final ServiceName weldBootstrapServiceInternalName = parent.getServiceName().append(WeldBootstrapService.INTERNAL_SERVICE_NAME);
ServiceName weldStartServiceName = parent.getServiceName().append(WeldStartService.SERVICE_NAME);
deploymentUnit.addToAttachmentList(Attachments.WEB_DEPENDENCIES, weldStartServiceName);
final Set<ServiceName> dependencies = new HashSet<ServiceName>();
// we only start weld on top level deployments
if (deploymentUnit.getParent() != null) {
return;
}
WeldLogger.DEPLOYMENT_LOGGER.startingServicesForCDIDeployment(phaseContext.getDeploymentUnit().getName());
final Module module = deploymentUnit.getAttachment(Attachments.MODULE);
final ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION);
final Set<BeanDeploymentArchiveImpl> beanDeploymentArchives = new HashSet<BeanDeploymentArchiveImpl>();
final Map<ModuleIdentifier, BeanDeploymentModule> bdmsByIdentifier = new HashMap<ModuleIdentifier, BeanDeploymentModule>();
final Map<ModuleIdentifier, ModuleSpecification> moduleSpecByIdentifier = new HashMap<ModuleIdentifier, ModuleSpecification>();
final Map<ModuleIdentifier, EEModuleDescriptor> eeModuleDescriptors = new HashMap<>();
// the root module only has access to itself. For most deployments this will be the only module
// for ear deployments this represents the ear/lib directory.
// war and jar deployment visibility will depend on the dependencies that
// exist in the application, and mirror inter module dependencies
final BeanDeploymentModule rootBeanDeploymentModule = deploymentUnit.getAttachment(WeldAttachments.BEAN_DEPLOYMENT_MODULE);
putIfValueNotNull(eeModuleDescriptors, module.getIdentifier(), rootBeanDeploymentModule.getModuleDescriptor());
bdmsByIdentifier.put(module.getIdentifier(), rootBeanDeploymentModule);
moduleSpecByIdentifier.put(module.getIdentifier(), moduleSpecification);
beanDeploymentArchives.addAll(rootBeanDeploymentModule.getBeanDeploymentArchives());
final List<DeploymentUnit> subDeployments = deploymentUnit.getAttachmentList(Attachments.SUB_DEPLOYMENTS);
final Set<ClassLoader> subDeploymentLoaders = new HashSet<ClassLoader>();
final ServiceLoader<DeploymentUnitDependenciesProvider> dependenciesProviders = ServiceLoader.load(DeploymentUnitDependenciesProvider.class,
WildFlySecurityManager.getClassLoaderPrivileged(WeldDeploymentProcessor.class));
List<ClassLoader> loaders = new ArrayList<>(subDeployments.size() + 2);
loaders.add(WildFlySecurityManager.getClassLoaderPrivileged(WeldDeploymentProcessor.class));
loaders.add(module.getClassLoader());
for (DeploymentUnit subDeployment : subDeployments) {
loaders.add(subDeployment.getAttachment(Attachments.MODULE).getClassLoader());
}
Iterable<ModuleServicesProvider> moduleServicesProviders = ServiceLoader.load(ModuleServicesProvider.class, new CompositeClassLoader(loaders));
getDependencies(deploymentUnit, dependencies, dependenciesProviders);
for (DeploymentUnit subDeployment : subDeployments) {
getDependencies(subDeployment, dependencies, dependenciesProviders);
final Module subDeploymentModule = subDeployment.getAttachment(Attachments.MODULE);
if (subDeploymentModule == null) {
continue;
}
subDeploymentLoaders.add(subDeploymentModule.getClassLoader());
final ModuleSpecification subDeploymentModuleSpec = subDeployment.getAttachment(Attachments.MODULE_SPECIFICATION);
final BeanDeploymentModule bdm = subDeployment.getAttachment(WeldAttachments.BEAN_DEPLOYMENT_MODULE);
if (bdm == null) {
continue;
}
// add the modules bdas to the global set of bdas
beanDeploymentArchives.addAll(bdm.getBeanDeploymentArchives());
bdmsByIdentifier.put(subDeploymentModule.getIdentifier(), bdm);
moduleSpecByIdentifier.put(subDeploymentModule.getIdentifier(), subDeploymentModuleSpec);
putIfValueNotNull(eeModuleDescriptors, subDeploymentModule.getIdentifier(), bdm.getModuleDescriptor());
//we have to do this here as the aggregate components are not available in earlier phases
final ResourceRoot subDeploymentRoot = subDeployment.getAttachment(Attachments.DEPLOYMENT_ROOT);
// Add module services to bean deployment module
for (Entry<Class<? extends Service>, Service> entry : ServiceLoaders.loadModuleServices(moduleServicesProviders, deploymentUnit, subDeployment, subDeploymentModule, subDeploymentRoot).entrySet()) {
bdm.addService(entry.getKey(), Reflections.cast(entry.getValue()));
}
}
for (Map.Entry<ModuleIdentifier, BeanDeploymentModule> entry : bdmsByIdentifier.entrySet()) {
final ModuleSpecification bdmSpec = moduleSpecByIdentifier.get(entry.getKey());
final BeanDeploymentModule bdm = entry.getValue();
if (bdm == rootBeanDeploymentModule) {
continue; // the root module only has access to itself
}
for (ModuleDependency dependency : bdmSpec.getSystemDependencies()) {
BeanDeploymentModule other = bdmsByIdentifier.get(dependency.getIdentifier());
if (other != null && other != bdm) {
bdm.addBeanDeploymentModule(other);
}
}
}
Map<Class<? extends Service>, Service> rootModuleServices = ServiceLoaders.loadModuleServices(moduleServicesProviders, deploymentUnit, deploymentUnit,
module, deploymentRoot);
// Add root module services to root bean deployment module
for (Entry<Class<? extends Service>, Service> entry : rootModuleServices.entrySet()) {
rootBeanDeploymentModule.addService(entry.getKey(), Reflections.cast(entry.getValue()));
}
// Add root module services to additional bean deployment archives
for (final BeanDeploymentArchiveImpl additional : deploymentUnit.getAttachmentList(WeldAttachments.ADDITIONAL_BEAN_DEPLOYMENT_MODULES)) {
beanDeploymentArchives.add(additional);
for (Entry<Class<? extends Service>, Service> entry : rootModuleServices.entrySet()) {
additional.getServices().add(entry.getKey(), Reflections.cast(entry.getValue()));
}
}
final Collection<Metadata<Extension>> extensions = WeldPortableExtensions.getPortableExtensions(deploymentUnit).getExtensions();
final WeldDeployment deployment = new WeldDeployment(beanDeploymentArchives, extensions, module, subDeploymentLoaders, deploymentUnit, rootBeanDeploymentModule, eeModuleDescriptors);
installBootstrapConfigurationService(deployment, parent);
// add the weld service
final ServiceBuilder<?> weldBootstrapServiceBuilder = serviceTarget.addService(weldBootstrapServiceInternalName);
final Consumer<WeldBootstrapService> weldBootstrapServiceConsumer = weldBootstrapServiceBuilder.provides(weldBootstrapServiceInternalName);
weldBootstrapServiceBuilder.requires(TCCLSingletonService.SERVICE_NAME);
final Supplier<ExecutorServices> executorServicesSupplier = weldBootstrapServiceBuilder.requires(WeldExecutorServices.SERVICE_NAME);
final Supplier<ExecutorService> serverExecutorSupplier = weldBootstrapServiceBuilder.requires(Services.JBOSS_SERVER_EXECUTOR);
Supplier<SecurityServices> securityServicesSupplier = null;
Supplier<TransactionServices> weldTransactionServicesSupplier = null;
// Install additional services
final ServiceLoader<BootstrapDependencyInstaller> installers = ServiceLoader.load(BootstrapDependencyInstaller.class,
WildFlySecurityManager.getClassLoaderPrivileged(WeldDeploymentProcessor.class));
for (BootstrapDependencyInstaller installer : installers) {
ServiceName serviceName = installer.install(serviceTarget, deploymentUnit, jtsEnabled);
if (serviceName == null) {
continue;
}
// Add dependency for recognized services
if (ServiceNames.WELD_SECURITY_SERVICES_SERVICE_NAME.getSimpleName().equals(serviceName.getSimpleName())) {
securityServicesSupplier = weldBootstrapServiceBuilder.requires(serviceName);
} else if (ServiceNames.WELD_TRANSACTION_SERVICES_SERVICE_NAME.getSimpleName().equals(serviceName.getSimpleName())) {
weldTransactionServicesSupplier = weldBootstrapServiceBuilder.requires(serviceName);
}
}
ServiceName deploymentServiceName = Utils.getRootDeploymentUnit(deploymentUnit).getServiceName();
final WeldBootstrapService weldBootstrapService = new WeldBootstrapService(deployment, WildFlyWeldEnvironment.INSTANCE, deploymentUnit.getName(),
weldBootstrapServiceConsumer, executorServicesSupplier, serverExecutorSupplier, securityServicesSupplier, weldTransactionServicesSupplier, deploymentServiceName, weldBootstrapServiceName);
// Add root module services to WeldDeployment
for (Entry<Class<? extends Service>, Service> entry : rootModuleServices.entrySet()) {
weldBootstrapService.addWeldService(entry.getKey(), Reflections.cast(entry.getValue()));
}
weldBootstrapServiceBuilder.setInstance(weldBootstrapService);
weldBootstrapServiceBuilder.install();
final List<SetupAction> setupActions = getSetupActions(deploymentUnit);
ServiceBuilder<?> startService = serviceTarget.addService(weldStartServiceName);
for (final ServiceName dependency : dependencies) {
startService.requires(dependency);
}
// make sure JNDI bindings are up
startService.requires(JndiNamingDependencyProcessor.serviceName(deploymentUnit));
final CapabilityServiceSupport capabilities = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT);
boolean tx = capabilities.hasCapability("org.wildfly.transactions");
// [WFLY-5232]
for (final ServiceName jndiSubsystemDependency : getJNDISubsytemDependencies(tx)) {
startService.requires(jndiSubsystemDependency);
}
final EarMetaData earConfig = deploymentUnit.getAttachment(org.jboss.as.ee.structure.Attachments.EAR_METADATA);
if (earConfig == null || !earConfig.getInitializeInOrder()) {
// in-order install of sub-deployments may result in service dependencies deadlocks if the jndi dependency services of subdeployments are added as dependencies
for (DeploymentUnit sub : subDeployments) {
startService.requires(JndiNamingDependencyProcessor.serviceName(sub));
}
}
final Supplier<WeldBootstrapService> bootstrapSupplier = startService.requires(weldBootstrapServiceName);
startService.setInstance(new WeldStartService(bootstrapSupplier, setupActions, module.getClassLoader(), deploymentServiceName));
startService.install();
}
private List<ServiceName> getJNDISubsytemDependencies(boolean tx) {
List<ServiceName> dependencies = new ArrayList<>();
if (tx) {
dependencies.add(ContextNames.JBOSS_CONTEXT_SERVICE_NAME.append(ServiceName.of("UserTransaction")));
dependencies.add(ContextNames.JBOSS_CONTEXT_SERVICE_NAME.append(ServiceName.of("TransactionSynchronizationRegistry")));
}
dependencies.add(NamingService.SERVICE_NAME);
dependencies.add(DefaultNamespaceContextSelectorService.SERVICE_NAME);
return dependencies;
}
private void installBootstrapConfigurationService(WeldDeployment deployment, DeploymentUnit parentDeploymentUnit) {
final boolean nonPortableMode = parentDeploymentUnit.getAttachment(WeldConfiguration.ATTACHMENT_KEY).isNonPortableMode();
final ExternalConfiguration configuration = new ExternalConfigurationBuilder()
.add(ConfigurationKey.NON_PORTABLE_MODE.get(), nonPortableMode)
.add(ConfigurationKey.ALLOW_OPTIMIZED_CLEANUP.get(), true)
.build();
deployment.getServices().add(ExternalConfiguration.class, configuration);
}
private void getDependencies(DeploymentUnit deploymentUnit, Set<ServiceName> dependencies, ServiceLoader<DeploymentUnitDependenciesProvider> providers) {
for (DeploymentUnitDependenciesProvider provider : providers) {
dependencies.addAll(provider.getDependencies(deploymentUnit));
}
}
@Override
public void undeploy(DeploymentUnit context) {
final ServiceName weldTransactionServiceName = context.getServiceName().append(ServiceNames.WELD_TRANSACTION_SERVICES_SERVICE_NAME);
final ServiceController<?> serviceController = context.getServiceRegistry().getService(weldTransactionServiceName);
if (serviceController != null) {
serviceController.setMode(ServiceController.Mode.REMOVE);
}
}
static List<SetupAction> getSetupActions(DeploymentUnit deploymentUnit) {
final List<SetupAction> setupActions = new ArrayList<SetupAction>();
JavaNamespaceSetup naming = deploymentUnit.getAttachment(org.jboss.as.ee.naming.Attachments.JAVA_NAMESPACE_SETUP_ACTION);
if (naming != null) {
setupActions.add(naming);
}
final ConcurrentContextSetupAction concurrentContext = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.CONCURRENT_CONTEXT_SETUP_ACTION);
if (concurrentContext != null) {
setupActions.add(concurrentContext);
}
return setupActions;
}
}
| 19,973 | 55.905983 | 209 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/deployment/processors/BeansXmlProcessor.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment.processors;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.jboss.as.ee.structure.DeploymentType;
import org.jboss.as.ee.structure.DeploymentTypeMarker;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.SubDeploymentMarker;
import org.jboss.as.server.deployment.module.ModuleRootMarker;
import org.jboss.as.server.deployment.module.ResourceRoot;
import org.jboss.as.weld._private.WeldDeploymentMarker;
import org.jboss.as.weld.deployment.ExplicitBeanArchiveMetadata;
import org.jboss.as.weld.deployment.ExplicitBeanArchiveMetadataContainer;
import org.jboss.as.weld.deployment.PropertyReplacingBeansXmlParser;
import org.jboss.as.weld.deployment.WeldAttachments;
import org.jboss.as.weld.logging.WeldLogger;
import org.jboss.as.weld.util.Utils;
import org.jboss.vfs.VirtualFile;
import org.jboss.weld.bootstrap.spi.BeanDiscoveryMode;
import org.jboss.weld.bootstrap.spi.BeansXml;
import org.jboss.weld.xml.BeansXmlParser;
/**
* Deployment processor that finds <literal>beans.xml</literal> files and attaches the information to the deployment
*
* @author Stuart Douglas
*/
public class BeansXmlProcessor implements DeploymentUnitProcessor {
private static final String WEB_INF_BEANS_XML = "WEB-INF/beans.xml";
private static final String META_INF_BEANS_XML = "META-INF/beans.xml";
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
Map<ResourceRoot, ExplicitBeanArchiveMetadata> beanArchiveMetadata = new HashMap<ResourceRoot, ExplicitBeanArchiveMetadata>();
ResourceRoot deploymentRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);
if (deploymentRoot == null) {
return;
}
BeansXmlParser parser = new PropertyReplacingBeansXmlParser(deploymentUnit,
Utils.getRootDeploymentUnit(deploymentUnit).getAttachment(WeldConfiguration.ATTACHMENT_KEY)
.isLegacyEmptyBeansXmlTreatment());
ResourceRoot classesRoot = null;
List<ResourceRoot> structure = deploymentUnit.getAttachmentList(Attachments.RESOURCE_ROOTS);
for (ResourceRoot resourceRoot : structure) {
if (ModuleRootMarker.isModuleRoot(resourceRoot) && !SubDeploymentMarker.isSubDeployment(resourceRoot)) {
if (resourceRoot.getRootName().equals("classes")) {
// hack for dealing with war modules
classesRoot = resourceRoot;
deploymentUnit.putAttachment(WeldAttachments.CLASSES_RESOURCE_ROOT, resourceRoot);
} else {
VirtualFile beansXml = resourceRoot.getRoot().getChild(META_INF_BEANS_XML);
if (beansXml.exists() && beansXml.isFile()) {
WeldLogger.DEPLOYMENT_LOGGER.debugf("Found beans.xml: %s", beansXml.toString());
beanArchiveMetadata.put(resourceRoot, new ExplicitBeanArchiveMetadata(beansXml, resourceRoot, parseBeansXml(beansXml, parser), false));
}
}
}
}
if (DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit)) {
final VirtualFile rootBeansXml = deploymentRoot.getRoot().getChild(WEB_INF_BEANS_XML);
final boolean rootBeansXmlPresent = rootBeansXml.exists() && rootBeansXml.isFile();
VirtualFile beansXml = null;
if (classesRoot != null) {
beansXml = classesRoot.getRoot().getChild(META_INF_BEANS_XML);
}
final boolean beansXmlPresent = beansXml != null && beansXml.exists() && beansXml.isFile();
if (rootBeansXmlPresent) {
if (beansXmlPresent) {
// warn that it is not portable to use both locations at the same time
WeldLogger.DEPLOYMENT_LOGGER.duplicateBeansXml();
beanArchiveMetadata.put(deploymentRoot, new ExplicitBeanArchiveMetadata(rootBeansXml, beansXml, classesRoot, parseBeansXml(rootBeansXml, parser), true));
} else {
WeldLogger.DEPLOYMENT_LOGGER.debugf("Found beans.xml: %s", rootBeansXml);
beanArchiveMetadata.put(deploymentRoot, new ExplicitBeanArchiveMetadata(rootBeansXml, classesRoot, parseBeansXml(rootBeansXml, parser), true));
}
} else if (beansXmlPresent) {
WeldLogger.DEPLOYMENT_LOGGER.debugf("Found beans.xml: %s", beansXml);
beanArchiveMetadata.put(deploymentRoot, new ExplicitBeanArchiveMetadata(beansXml, classesRoot, parseBeansXml(beansXml, parser), true));
}
} else if (!DeploymentTypeMarker.isType(DeploymentType.EAR, deploymentUnit)) {
final VirtualFile rootBeansXml = deploymentRoot.getRoot().getChild(META_INF_BEANS_XML);
if (rootBeansXml.exists() && rootBeansXml.isFile()) {
WeldLogger.DEPLOYMENT_LOGGER.debugf("Found beans.xml: %s", rootBeansXml.toString());
beanArchiveMetadata.put(deploymentRoot, new ExplicitBeanArchiveMetadata(rootBeansXml, deploymentRoot, parseBeansXml(rootBeansXml, parser), true));
}
}
if (!beanArchiveMetadata.isEmpty()) {
ExplicitBeanArchiveMetadataContainer deploymentMetadata = new ExplicitBeanArchiveMetadataContainer(beanArchiveMetadata);
deploymentUnit.putAttachment(ExplicitBeanArchiveMetadataContainer.ATTACHMENT_KEY, deploymentMetadata);
for (Iterator<Entry<ResourceRoot, ExplicitBeanArchiveMetadata>> iterator = beanArchiveMetadata.entrySet().iterator(); iterator.hasNext(); ) {
if (BeanDiscoveryMode.NONE != iterator.next().getValue().getBeansXml().getBeanDiscoveryMode()) {
// mark the deployment as requiring CDI integration as long as it contains at least one bean archive with bean-discovery-mode other than "none"
WeldDeploymentMarker.mark(deploymentUnit);
break;
}
}
}
}
@Override
public void undeploy(DeploymentUnit deploymentUnit) {
deploymentUnit.removeAttachment(WeldAttachments.CLASSES_RESOURCE_ROOT);
deploymentUnit.removeAttachment(ExplicitBeanArchiveMetadataContainer.ATTACHMENT_KEY);
}
private BeansXml parseBeansXml(VirtualFile beansXmlFile, BeansXmlParser parser) throws DeploymentUnitProcessingException {
try {
return parser.parse(beansXmlFile.asFileURL());
} catch (MalformedURLException e) {
throw WeldLogger.ROOT_LOGGER.couldNotGetBeansXmlAsURL(beansXmlFile.toString(), e);
} catch (RuntimeException e) {
throw new DeploymentUnitProcessingException(e);
}
}
} | 8,304 | 52.237179 | 173 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/deployment/processors/WeldDeploymentCleanupProcessor.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2018, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.weld.deployment.processors;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.ee.component.EEModuleDescription;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.weld.WeldBootstrapService;
import org.jboss.as.weld._private.WeldDeploymentMarker;
import org.jboss.as.weld.WeldStartCompletionService;
import org.jboss.as.weld.WeldStartService;
import org.jboss.as.weld.util.Utils;
import org.jboss.modules.Module;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceRegistry;
import org.jboss.msc.service.ServiceTarget;
/**
* A processor which takes care of after boot cleanup for Weld. The idea is to invoke
* {@code org.jboss.weld.bootstrap.WeldStartup.endInitialization()} after all EE components are installed.
*
* This allows Weld to do metadata cleanup on unused items.
*
* @author <a href="mailto:[email protected]">Matej Novotny</a>
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public class WeldDeploymentCleanupProcessor implements DeploymentUnitProcessor {
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final DeploymentUnit parent = Utils.getRootDeploymentUnit(deploymentUnit);
final Module module = deploymentUnit.getAttachment(Attachments.MODULE);
final ServiceTarget serviceTarget = phaseContext.getServiceTarget();
// obtain service names
ServiceName weldStartCompletionServiceName = parent.getServiceName().append(WeldStartCompletionService.SERVICE_NAME);
ServiceName weldBootstrapServiceName = parent.getServiceName().append(WeldBootstrapService.SERVICE_NAME);
ServiceName weldStartServiceName = parent.getServiceName().append(WeldStartService.SERVICE_NAME);
// if it is not Weld deployment, we skip it
if (!WeldDeploymentMarker.isPartOfWeldDeployment(deploymentUnit)) {
return;
}
// only register this on top level deployments
if (deploymentUnit.getParent() != null) {
return;
}
// add dependency on our WeldBootstrapService and WeldStartService to ensure this goes after them
ServiceBuilder<?> weldStartCompletionServiceBuilder = serviceTarget.addService(weldStartCompletionServiceName);
final Supplier<WeldBootstrapService> bootstrapSupplier = weldStartCompletionServiceBuilder.requires(weldBootstrapServiceName);
weldStartCompletionServiceBuilder.requires(weldStartServiceName);
// require component start services from top level deployment
for (ServiceName componentStartSN : getComponentStartServiceNames(deploymentUnit)) {
weldStartCompletionServiceBuilder.requires(componentStartSN);
}
// require component start services from sub-deployments
final List<DeploymentUnit> subDeployments = deploymentUnit.getAttachmentList(Attachments.SUB_DEPLOYMENTS);
for (DeploymentUnit sub : subDeployments) {
ServiceRegistry registry = sub.getServiceRegistry();
List<ServiceName> componentStartServiceNames = getComponentStartServiceNames(sub);
for (ServiceName componentStartSN : componentStartServiceNames) {
weldStartCompletionServiceBuilder.requires(componentStartSN);
}
}
weldStartCompletionServiceBuilder.setInstance(new WeldStartCompletionService(bootstrapSupplier,
WeldDeploymentProcessor.getSetupActions(deploymentUnit), module.getClassLoader()));
weldStartCompletionServiceBuilder.install();
}
private List<ServiceName> getComponentStartServiceNames(DeploymentUnit deploymentUnit) {
List<ServiceName> serviceNames = new ArrayList<>();
final EEModuleDescription eeModuleDescription = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION);
if (eeModuleDescription == null) {
return serviceNames;
}
for (ComponentDescription component : eeModuleDescription.getComponentDescriptions()) {
serviceNames.add(component.getStartServiceName());
}
return serviceNames;
}
}
| 5,477 | 49.256881 | 146 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/deployment/processors/WeldConfigurationProcessor.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment.processors;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.weld.WeldJBossAllConfiguration;
/**
* Merges the per-deployment configuration defined in <code>jboss-all.xml</code> with the global configuration and attaches the result under
* {@link WeldConfiguration#ATTACHMENT_KEY}.
*
* @author Jozef Hartinger
*
*/
public class WeldConfigurationProcessor implements DeploymentUnitProcessor {
private final boolean requireBeanDescriptorGlobal;
private final boolean nonPortableModeGlobal;
private final boolean developmentModeGlobal;
private final boolean legacyEmptyBeansXmlTreatmentGlobal;
public WeldConfigurationProcessor(boolean requireBeanDescriptorGlobal, boolean nonPortableModeGlobal, boolean developmentModeGlobal, boolean legacyEmptyBeansXmlTreatmentGlobal) {
this.requireBeanDescriptorGlobal = requireBeanDescriptorGlobal;
this.nonPortableModeGlobal = nonPortableModeGlobal;
this.developmentModeGlobal = developmentModeGlobal;
this.legacyEmptyBeansXmlTreatmentGlobal = legacyEmptyBeansXmlTreatmentGlobal;
}
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
if (deploymentUnit.getParent() != null) {
return; // only attach the configuration to the root deployment
}
boolean requireBeanDescriptor = requireBeanDescriptorGlobal;
boolean nonPortableMode = nonPortableModeGlobal;
boolean developmentMode = developmentModeGlobal;
boolean legacyEmptyBeansXmlTreatment = legacyEmptyBeansXmlTreatmentGlobal;
WeldJBossAllConfiguration configuration = deploymentUnit.getAttachment(WeldJBossAllConfiguration.ATTACHMENT_KEY);
if (configuration != null) {
requireBeanDescriptor = getValue(configuration.getRequireBeanDescriptor(), requireBeanDescriptorGlobal);
nonPortableMode = getValue(configuration.getNonPortableMode(), nonPortableModeGlobal);
developmentMode = getValue(configuration.getDevelopmentMode(), developmentModeGlobal);
legacyEmptyBeansXmlTreatment = getValue(configuration.getLegacyEmptyBeansXmlTreatment(), legacyEmptyBeansXmlTreatmentGlobal);
}
WeldConfiguration mergedConfiguration = new WeldConfiguration(requireBeanDescriptor, nonPortableMode, developmentMode, legacyEmptyBeansXmlTreatment);
deploymentUnit.putAttachment(WeldConfiguration.ATTACHMENT_KEY, mergedConfiguration);
}
private static boolean getValue(Boolean value, boolean globalValue) {
if (value != null) {
return value;
} else {
return globalValue;
}
}
}
| 4,039 | 47.095238 | 182 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/deployment/processors/WeldDependencyProcessor.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment.processors;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.module.ModuleDependency;
import org.jboss.as.server.deployment.module.ModuleSpecification;
import org.jboss.as.weld._private.WeldDeploymentMarker;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleLoader;
import org.jboss.modules.filter.PathFilters;
/**
* Deployment processor which adds a module dependencies for modules needed for weld deployments.
*
* @author Stuart Douglas
*/
public class WeldDependencyProcessor implements DeploymentUnitProcessor {
private static final String JAVAX_PERSISTENCE_API_ID = "jakarta.persistence.api";
private static final String JBOSS_AS_WELD_ID = "org.jboss.as.weld";
private static final String JBOSS_AS_WELD_EJB_ID = "org.jboss.as.weld.ejb";
private static final String WELD_CORE_ID = "org.jboss.weld.core";
private static final String WELD_API_ID = "org.jboss.weld.api";
private static final String WELD_SPI_ID = "org.jboss.weld.spi";
private static final String JAVAX_ENTERPRISE_API = "jakarta.enterprise.api";
private static final String JAVAX_INJECT_API = "jakarta.inject.api";
/**
* Add dependencies for modules required for weld deployments, if managed weld configurations are attached to the deployment
*
*/
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION);
final ModuleLoader moduleLoader = Module.getBootModuleLoader();
addDependency(moduleSpecification, moduleLoader, JAVAX_ENTERPRISE_API);
addDependency(moduleSpecification, moduleLoader, JAVAX_INJECT_API);
if (!WeldDeploymentMarker.isPartOfWeldDeployment(deploymentUnit)) {
return; // Skip if there are no beans.xml files in the deployment
}
addDependency(moduleSpecification, moduleLoader, JAVAX_PERSISTENCE_API_ID);
addDependency(moduleSpecification, moduleLoader, WELD_CORE_ID);
addDependency(moduleSpecification, moduleLoader, WELD_API_ID);
addDependency(moduleSpecification, moduleLoader, WELD_SPI_ID);
ModuleDependency weldSubsystemDependency = new ModuleDependency(moduleLoader, JBOSS_AS_WELD_ID, false, false, false, false);
weldSubsystemDependency.addImportFilter(PathFilters.getMetaInfFilter(), true);
weldSubsystemDependency.addImportFilter(PathFilters.is("org/jboss/as/weld/injection"), true);
weldSubsystemDependency.addImportFilter(PathFilters.acceptAll(), false);
weldSubsystemDependency.addExportFilter(PathFilters.getMetaInfFilter(), true);
moduleSpecification.addSystemDependency(weldSubsystemDependency);
// Due to serialization of Jakarta Enterprise Beans
ModuleDependency weldEjbDependency = new ModuleDependency(moduleLoader, JBOSS_AS_WELD_EJB_ID, true, false, false, false);
weldEjbDependency.addImportFilter(PathFilters.is("org/jboss/as/weld/ejb"), true);
weldEjbDependency.addImportFilter(PathFilters.acceptAll(), false);
moduleSpecification.addSystemDependency(weldEjbDependency);
}
private void addDependency(ModuleSpecification moduleSpecification, ModuleLoader moduleLoader,
String moduleIdentifier) {
addDependency(moduleSpecification, moduleLoader, moduleIdentifier, false);
}
private void addDependency(ModuleSpecification moduleSpecification, ModuleLoader moduleLoader,
String moduleIdentifier, boolean optional) {
moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, moduleIdentifier, optional, false, true, false));
}
}
| 5,190 | 51.969388 | 132 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/deployment/processors/WeldPortableExtensionProcessor.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment.processors;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.List;
import jakarta.enterprise.inject.build.compatible.spi.BuildCompatibleExtension;
import jakarta.enterprise.inject.spi.Extension;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.weld._private.WeldDeploymentMarker;
import org.jboss.as.weld.deployment.WeldPortableExtensions;
import org.jboss.as.weld.logging.WeldLogger;
import org.jboss.modules.Module;
import org.jboss.vfs.VFSUtils;
import org.jboss.weld.lite.extension.translator.LiteExtensionTranslator;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* Deployment processor that loads Jakarta Contexts and Dependency Injection portable extensions.
* It also loads Build Compatible extensions for CDI 4+
*
* @author Stuart Douglas
* @author Ales Justin
*/
public class WeldPortableExtensionProcessor implements DeploymentUnitProcessor {
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
// for war modules we require a beans.xml to load portable extensions
if (!WeldDeploymentMarker.isPartOfWeldDeployment(deploymentUnit)) {
// if any deployments have a beans.xml we need to load portable extensions
// even if this one does not.
return;
}
WeldPortableExtensions extensions = WeldPortableExtensions.getPortableExtensions(deploymentUnit);
final Module module = deploymentUnit.getAttachment(Attachments.MODULE);
ClassLoader oldCl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
try {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(module.getClassLoader());
loadAttachments(module, deploymentUnit, extensions);
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldCl);
}
}
private void loadAttachments(Module module, DeploymentUnit deploymentUnit, WeldPortableExtensions extensions) throws DeploymentUnitProcessingException {
// now load extensions
try {
// load portable extension services
final List<String> portableExtensionServices = loadServices(module, Extension.class.getName());
// load build compatible extension services
final List<String> buildCompatibleExtensionServices = loadServices(module, BuildCompatibleExtension.class.getName());
// load class and register for portable extensions
Collection<Class<?>> loadedPortableExtensions = loadExtensions(module, portableExtensionServices, Object.class);
registerPortableExtensions(deploymentUnit, extensions, loadedPortableExtensions);
// load class and register for portable extensions
// if there is at least one, add a portable extension processing them
List<Class<? extends BuildCompatibleExtension>> loadedBuildCompatExtensions =
loadExtensions(module, buildCompatibleExtensionServices, BuildCompatibleExtension.class);
if (!loadedBuildCompatExtensions.isEmpty()) {
Extension extension = new LiteExtensionTranslator(loadedBuildCompatExtensions, module.getClassLoader());
// NOTE: I chose to register it under the same dep. unit as other extensions, not sure if this is correct
extensions.registerExtensionInstance(extension, deploymentUnit);
}
} catch (IOException e) {
throw new DeploymentUnitProcessingException(e);
}
}
private static <T> List<Class<? extends T>> loadExtensions(Module module, List<String> services, Class<T> type) {
List<Class<? extends T>> result = new ArrayList<>();
for (String service : services) {
final Class<? extends T> extensionClass = loadExtension(service, module.getClassLoader(), type);
if (extensionClass == null) {
continue;
}
result.add(extensionClass);
}
return result;
}
private void registerPortableExtensions(DeploymentUnit deploymentUnit, WeldPortableExtensions extensions, Collection<Class<?>> loadedExtensions) throws DeploymentUnitProcessingException {
for (Class<?> loadedExtension : loadedExtensions) {
extensions.tryRegisterExtension(loadedExtension, deploymentUnit);
}
}
private List<String> loadServices(Module module, String resourceSuffix) throws IOException {
Enumeration<URL> resources = module.getClassLoader().getResources("META-INF/services/" + resourceSuffix);
final List<String> services = new ArrayList<>();
while (resources.hasMoreElements()) {
URL resource = resources.nextElement();
final InputStream stream = resource.openStream();
try {
final BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
String line;
while ((line = reader.readLine()) != null) {
final int commentIdx = line.indexOf('#');
final String className;
if (commentIdx == -1) {
className = line.trim();
} else {
className = line.substring(0, commentIdx).trim();
}
if (className.length() == 0) {
continue;
}
services.add(className);
}
} finally {
VFSUtils.safeClose(stream);
}
}
return services;
}
private static <T> Class<? extends T> loadExtension(String serviceClassName, final ClassLoader loader, Class<T> type) {
try {
return loader.loadClass(serviceClassName).asSubclass(type);
} catch (Exception | LinkageError e) {
WeldLogger.DEPLOYMENT_LOGGER.couldNotLoadPortableExceptionClass(serviceClassName, e);
}
return null;
}
@Override
public void undeploy(DeploymentUnit deploymentUnit) {
if (deploymentUnit.getParent() == null) {
deploymentUnit.removeAttachment(WeldPortableExtensions.ATTACHMENT_KEY);
}
}
}
| 7,949 | 45.22093 | 191 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/deployment/processors/DefaultImplicitBeanArchiveDetector.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment.processors;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.ee.managedbean.component.ManagedBeanComponentDescription;
import org.jboss.as.weld.spi.ImplicitBeanArchiveDetector;
/**
*
* @author Martin Kouba
*/
public class DefaultImplicitBeanArchiveDetector implements ImplicitBeanArchiveDetector {
@Override
public boolean isImplicitBeanArchiveRequired(ComponentDescription description) {
return description instanceof ManagedBeanComponentDescription;
}
}
| 1,562 | 38.075 | 88 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/deployment/processors/WeldBeanManagerServiceProcessor.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment.processors;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Supplier;
import jakarta.enterprise.inject.spi.BeanManager;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.ee.component.ComponentNamingMode;
import org.jboss.as.ee.component.EEModuleDescription;
import org.jboss.as.ee.structure.DeploymentType;
import org.jboss.as.ee.structure.DeploymentTypeMarker;
import org.jboss.as.naming.ContextListManagedReferenceFactory;
import org.jboss.as.naming.ManagedReference;
import org.jboss.as.naming.ServiceBasedNamingStore;
import org.jboss.as.naming.ValueManagedReference;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.as.naming.service.BinderService;
import org.jboss.as.server.deployment.AttachmentKey;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.SetupAction;
import org.jboss.as.weld.WeldBootstrapService;
import org.jboss.as.weld._private.WeldDeploymentMarker;
import org.jboss.as.weld.arquillian.WeldContextSetup;
import org.jboss.as.weld.deployment.BeanDeploymentArchiveImpl;
import org.jboss.as.weld.deployment.WeldAttachments;
import org.jboss.as.weld.logging.WeldLogger;
import org.jboss.as.weld.services.BeanManagerService;
import org.jboss.as.weld.util.Utils;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.value.InjectedValue;
/**
* {@link DeploymentUnitProcessor} that binds the bean manager to JNDI
*
* @author Stuart Douglas
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public class WeldBeanManagerServiceProcessor implements DeploymentUnitProcessor {
private static final AttachmentKey<SetupAction> ATTACHMENT_KEY = AttachmentKey.create(SetupAction.class);
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final DeploymentUnit topLevelDeployment = Utils.getRootDeploymentUnit(deploymentUnit);
final ServiceTarget serviceTarget = phaseContext.getServiceTarget();
if (!WeldDeploymentMarker.isPartOfWeldDeployment(topLevelDeployment)) {
return;
}
BeanDeploymentArchiveImpl rootBda = deploymentUnit
.getAttachment(WeldAttachments.DEPLOYMENT_ROOT_BEAN_DEPLOYMENT_ARCHIVE);
if (rootBda == null) {
// this archive is not actually a bean archive.
// then use the top level root bda
rootBda = topLevelDeployment.getAttachment(WeldAttachments.DEPLOYMENT_ROOT_BEAN_DEPLOYMENT_ARCHIVE);
}
if (rootBda == null) {
WeldLogger.DEPLOYMENT_LOGGER.couldNotFindBeanManagerForDeployment(deploymentUnit.getName());
return;
}
final ServiceName weldServiceName = topLevelDeployment.getServiceName().append(WeldBootstrapService.SERVICE_NAME);
// add the BeanManager service
final ServiceName beanManagerServiceName = BeanManagerService.serviceName(deploymentUnit);
final ServiceBuilder<?> builder = serviceTarget.addService(beanManagerServiceName);
final Consumer<BeanManager> beanManagerConsumer = builder.provides(beanManagerServiceName);
final Supplier<WeldBootstrapService> weldContainerSupplier = builder.requires(weldServiceName);
builder.setInstance(new BeanManagerService(rootBda.getId(), beanManagerConsumer, weldContainerSupplier));
builder.install();
final EEModuleDescription moduleDescription = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION);
if (moduleDescription == null) {
return;
}
//hack to set up a java:comp binding for jar deployments as well as wars
if (DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit) || deploymentUnit.getName().endsWith(".jar")) {
// bind the bean manager to JNDI
final ServiceName moduleContextServiceName = ContextNames.contextServiceNameOfModule(moduleDescription.getApplicationName(), moduleDescription.getModuleName());
bindBeanManager(deploymentUnit, serviceTarget, beanManagerServiceName, moduleContextServiceName);
}
//bind the bm into java:comp for all components that require it
for (ComponentDescription component : moduleDescription.getComponentDescriptions()) {
if (component.getNamingMode() == ComponentNamingMode.CREATE) {
final ServiceName compContextServiceName = ContextNames.contextServiceNameOfComponent(moduleDescription.getApplicationName(), moduleDescription.getModuleName(), component.getComponentName());
bindBeanManager(deploymentUnit, serviceTarget, beanManagerServiceName, compContextServiceName);
}
}
SetupAction action = new WeldContextSetup();
deploymentUnit.putAttachment(ATTACHMENT_KEY, action);
deploymentUnit.addToAttachmentList(Attachments.SETUP_ACTIONS, action);
}
private void bindBeanManager(DeploymentUnit deploymentUnit, ServiceTarget serviceTarget, ServiceName beanManagerServiceName, ServiceName contextServiceName) {
final ServiceName beanManagerBindingServiceName = contextServiceName.append("BeanManager");
BinderService beanManagerBindingService = new BinderService("BeanManager");
final BeanManagerManagedReferenceFactory referenceFactory = new BeanManagerManagedReferenceFactory();
beanManagerBindingService.getManagedObjectInjector().inject(referenceFactory);
serviceTarget.addService(beanManagerBindingServiceName, beanManagerBindingService)
.addDependency(contextServiceName, ServiceBasedNamingStore.class, beanManagerBindingService.getNamingStoreInjector())
.addDependency(beanManagerServiceName, BeanManager.class, referenceFactory.beanManager)
.install();
final Map<ServiceName, Set<ServiceName>> jndiComponentDependencies = deploymentUnit.getAttachment(Attachments.COMPONENT_JNDI_DEPENDENCIES);
Set<ServiceName> jndiDependencies = jndiComponentDependencies.get(contextServiceName);
if (jndiDependencies == null) {
jndiComponentDependencies.put(contextServiceName, jndiDependencies = new HashSet<>());
}
jndiDependencies.add(beanManagerBindingServiceName);
}
@Override
public void undeploy(DeploymentUnit deploymentUnit) {
SetupAction action = deploymentUnit.removeAttachment(ATTACHMENT_KEY);
if (action != null) {
deploymentUnit.getAttachmentList(Attachments.SETUP_ACTIONS).remove(action);
}
}
private static class BeanManagerManagedReferenceFactory implements ContextListManagedReferenceFactory {
private final InjectedValue<BeanManager> beanManager = new InjectedValue<BeanManager>();
@Override
public ManagedReference getReference() {
BeanManager bm = beanManager.getOptionalValue();
if (bm == null) {
return null;
}
return new ValueManagedReference(bm);
}
@Override
public String getInstanceClassName() {
return BeanManager.class.getName();
}
}
}
| 8,748 | 49.281609 | 207 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/deployment/processors/WeldComponentIntegrationProcessor.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment.processors;
import static org.jboss.as.weld.interceptors.Jsr299BindingsInterceptor.factory;
import static org.jboss.as.weld.util.Utils.getRootDeploymentUnit;
import java.util.HashSet;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Supplier;
import jakarta.enterprise.inject.spi.InterceptionType;
import org.jboss.as.ee.component.BasicComponentInstance;
import org.jboss.as.ee.component.ComponentConfiguration;
import org.jboss.as.ee.component.ComponentConfigurator;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.ee.component.ComponentInstance;
import org.jboss.as.ee.component.ComponentStartService;
import org.jboss.as.ee.component.DependencyConfigurator;
import org.jboss.as.ee.component.EEModuleDescription;
import org.jboss.as.ee.component.InterceptorDescription;
import org.jboss.as.ee.component.ViewConfiguration;
import org.jboss.as.ee.component.interceptors.InterceptorOrder;
import org.jboss.as.ee.component.interceptors.UserInterceptorFactory;
import org.jboss.as.ee.utils.ClassLoadingUtils;
import org.jboss.as.naming.ManagedReference;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.weld.ServiceNames;
import org.jboss.as.weld.WeldBootstrapService;
import org.jboss.as.weld._private.WeldDeploymentMarker;
import org.jboss.as.weld.WeldStartService;
import org.jboss.as.weld.deployment.WeldClassIntrospector;
import org.jboss.as.weld.ejb.EjbRequestScopeActivationInterceptor;
import org.jboss.as.weld.ejb.WeldInterceptorBindingsService;
import org.jboss.as.weld.injection.WeldComponentService;
import org.jboss.as.weld.injection.WeldConstructionStartInterceptor;
import org.jboss.as.weld.injection.WeldInjectionContextInterceptor;
import org.jboss.as.weld.injection.WeldInjectionInterceptor;
import org.jboss.as.weld.injection.WeldInterceptorInjectionInterceptor;
import org.jboss.as.weld.injection.WeldManagedReferenceFactory;
import org.jboss.as.weld.interceptors.Jsr299BindingsCreateInterceptor;
import org.jboss.as.weld.logging.WeldLogger;
import org.jboss.as.weld.spi.ComponentIntegrator;
import org.jboss.as.weld.spi.ComponentIntegrator.DefaultInterceptorIntegrationAction;
import org.jboss.as.weld.spi.ComponentInterceptorSupport;
import org.jboss.as.weld.util.ServiceLoaders;
import org.jboss.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleClassLoader;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.weld.ejb.spi.InterceptorBindings;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* Deployment unit processor that add the {@link org.jboss.as.weld.injection.WeldManagedReferenceFactory} instantiator
* to components that are part of a bean archive.
*
* @author Stuart Douglas
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public class WeldComponentIntegrationProcessor implements DeploymentUnitProcessor {
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
if (!WeldDeploymentMarker.isWeldDeployment(deploymentUnit)) {
return;
}
final DeploymentUnit topLevelDeployment = getRootDeploymentUnit(deploymentUnit);
final EEModuleDescription eeModuleDescription = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION);
final ServiceName weldBootstrapService = topLevelDeployment.getServiceName().append(WeldBootstrapService.SERVICE_NAME);
final ServiceName weldStartService = topLevelDeployment.getServiceName().append(WeldStartService.SERVICE_NAME);
final ServiceName beanManagerService = ServiceNames.beanManagerServiceName(deploymentUnit);
final Iterable<ComponentIntegrator> componentIntegrators = ServiceLoader.load(ComponentIntegrator.class,
WildFlySecurityManager.getClassLoaderPrivileged(WeldComponentIntegrationProcessor.class));
final ComponentInterceptorSupport componentInterceptorSupport = ServiceLoaders.loadSingle(ComponentInterceptorSupport.class,
WeldComponentIntegrationProcessor.class).orElse(null);
WeldClassIntrospector.install(deploymentUnit, phaseContext.getServiceTarget());
eeModuleDescription.setDefaultClassIntrospectorServiceName(WeldClassIntrospector.serviceName(deploymentUnit));
for (ComponentDescription component : eeModuleDescription.getComponentDescriptions()) {
final String beanName;
if (isBeanNameRequired(component, componentIntegrators)) {
beanName = component.getComponentName();
} else {
beanName = null;
}
component.getConfigurators().add((context, description, configuration) -> {
//add interceptor to activate the request scope if required
final EjbRequestScopeActivationInterceptor.Factory requestFactory = new EjbRequestScopeActivationInterceptor.Factory(beanManagerService);
for(ViewConfiguration view : configuration.getViews()) {
view.addViewInterceptor(requestFactory, InterceptorOrder.View.CDI_REQUEST_SCOPE);
}
configuration.addTimeoutViewInterceptor(requestFactory, InterceptorOrder.View.CDI_REQUEST_SCOPE);
});
component.getConfigurators().addFirst(new ComponentConfigurator() {
@Override
public void configure(final DeploymentPhaseContext context, final ComponentDescription description, final ComponentConfiguration configuration) throws DeploymentUnitProcessingException {
final Class<?> componentClass = configuration.getComponentClass();
final DeploymentUnit deploymentUnit = context.getDeploymentUnit();
final Module module = deploymentUnit.getAttachment(Attachments.MODULE);
final ModuleClassLoader classLoader = module.getClassLoader();
//get the interceptors so they can be injected as well
final Set<Class<?>> interceptorClasses = new HashSet<Class<?>>();
for (InterceptorDescription interceptorDescription : description.getAllInterceptors()) {
try {
interceptorClasses.add(ClassLoadingUtils.loadClass(interceptorDescription.getInterceptorClassName(), module));
} catch (ClassNotFoundException e) {
throw WeldLogger.ROOT_LOGGER.couldNotLoadInterceptorClass(interceptorDescription.getInterceptorClassName(), e);
}
}
addWeldIntegration(componentIntegrators, componentInterceptorSupport, context.getServiceTarget(), configuration, description,
componentClass, beanName, weldBootstrapService, weldStartService, beanManagerService,
interceptorClasses, classLoader, description.getBeanDeploymentArchiveId());
}
});
}
}
private boolean isBeanNameRequired(ComponentDescription component, Iterable<ComponentIntegrator> integrators) {
for (ComponentIntegrator integrator : integrators) {
if (integrator.isBeanNameRequired(component)) {
return true;
}
}
return false;
}
private boolean isComponentWithView(ComponentDescription component, Iterable<ComponentIntegrator> integrators) {
for (ComponentIntegrator integrator : integrators) {
if (integrator.isComponentWithView(component)) {
return true;
}
}
return false;
}
/**
* As the weld based instantiator needs access to the bean manager it is installed as a service.
*/
private void addWeldIntegration(final Iterable<ComponentIntegrator> componentIntegrators, final ComponentInterceptorSupport componentInterceptorSupport, final ServiceTarget target, final ComponentConfiguration configuration, final ComponentDescription description, final Class<?> componentClass, final String beanName, final ServiceName weldServiceName, final ServiceName weldStartService, final ServiceName beanManagerService, final Set<Class<?>> interceptorClasses, final ClassLoader classLoader, final String beanDeploymentArchiveId) {
final ServiceName serviceName = configuration.getComponentDescription().getServiceName().append("WeldInstantiator");
final ServiceBuilder<?> builder = target.addService(serviceName);
builder.requires(weldStartService);
configuration.setInstanceFactory(WeldManagedReferenceFactory.INSTANCE);
configuration.getStartDependencies().add(new DependencyConfigurator<ComponentStartService>() {
@Override
public void configureDependency(final ServiceBuilder<?> serviceBuilder, ComponentStartService service) throws DeploymentUnitProcessingException {
serviceBuilder.requires(serviceName);
}
});
boolean isComponentIntegrationPerformed = false;
for (ComponentIntegrator componentIntegrator : componentIntegrators) {
Supplier<ServiceName> bindingServiceNameSupplier = () -> {
if (componentInterceptorSupport == null) {
throw WeldLogger.DEPLOYMENT_LOGGER.componentInterceptorSupportNotAvailable(componentClass);
}
return addWeldInterceptorBindingService(target, configuration, componentClass, beanName, weldServiceName, weldStartService,
beanDeploymentArchiveId, componentInterceptorSupport);
};
DefaultInterceptorIntegrationAction integrationAction = (bindingServiceName) -> {
if (componentInterceptorSupport == null) {
throw WeldLogger.DEPLOYMENT_LOGGER.componentInterceptorSupportNotAvailable(componentClass);
}
addJsr299BindingsCreateInterceptor(configuration, description, beanName, weldServiceName, builder, bindingServiceName,
componentInterceptorSupport);
addCommonLifecycleInterceptionSupport(configuration, builder, bindingServiceName, beanManagerService, componentInterceptorSupport);
configuration.addComponentInterceptor(
new UserInterceptorFactory(factory(InterceptionType.AROUND_INVOKE, builder, bindingServiceName, componentInterceptorSupport),
factory(InterceptionType.AROUND_TIMEOUT, builder, bindingServiceName, componentInterceptorSupport)),
InterceptorOrder.Component.CDI_INTERCEPTORS, false);
};
if (componentIntegrator.integrate(beanManagerService, configuration, description, builder, bindingServiceNameSupplier, integrationAction,
componentInterceptorSupport)) {
isComponentIntegrationPerformed = true;
break;
}
}
final Supplier<WeldBootstrapService> weldContainerSupplier = builder.requires(weldServiceName);
final WeldComponentService weldComponentService =
new WeldComponentService(weldContainerSupplier, componentClass, beanName, interceptorClasses, classLoader,
beanDeploymentArchiveId, description.isCDIInterceptorEnabled(),
description, isComponentWithView(description, componentIntegrators));
builder.setInstance(weldComponentService);
if (!isComponentIntegrationPerformed) {
description.setIgnoreLifecycleInterceptors(true); //otherwise they will be called twice
// for components with no view register interceptors that delegate to InjectionTarget lifecycle methods to trigger lifecycle interception
configuration.addPostConstructInterceptor(new ImmediateInterceptorFactory(new AbstractInjectionTargetDelegatingInterceptor() {
@Override
protected void run(Object instance) {
weldComponentService.getInjectionTarget().postConstruct(instance);
}
}), InterceptorOrder.ComponentPostConstruct.CDI_INTERCEPTORS);
configuration.addPreDestroyInterceptor(new ImmediateInterceptorFactory(new AbstractInjectionTargetDelegatingInterceptor() {
@Override
protected void run(Object instance) {
weldComponentService.getInjectionTarget().preDestroy(instance);
}
}), InterceptorOrder.ComponentPreDestroy.CDI_INTERCEPTORS);
}
builder.install();
configuration.addPostConstructInterceptor(new ImmediateInterceptorFactory(new WeldInjectionContextInterceptor(weldComponentService)), InterceptorOrder.ComponentPostConstruct.WELD_INJECTION_CONTEXT_INTERCEPTOR);
configuration.addPostConstructInterceptor(new ImmediateInterceptorFactory(new WeldInterceptorInjectionInterceptor(interceptorClasses)), InterceptorOrder.ComponentPostConstruct.INTERCEPTOR_WELD_INJECTION);
configuration.addPostConstructInterceptor(WeldInjectionInterceptor.FACTORY, InterceptorOrder.ComponentPostConstruct.COMPONENT_WELD_INJECTION);
}
private static ServiceName addWeldInterceptorBindingService(final ServiceTarget target, final ComponentConfiguration configuration, final Class<?> componentClass, final String beanName, final ServiceName weldServiceName, final ServiceName weldStartService, final String beanDeploymentArchiveId, final ComponentInterceptorSupport componentInterceptorSupport) {
ServiceName bindingServiceName = configuration.getComponentDescription().getServiceName().append(WeldInterceptorBindingsService.SERVICE_NAME);
final ServiceBuilder<?> sb = target.addService(bindingServiceName);
final Consumer<InterceptorBindings> interceptorBindingsConsumer = sb.provides(bindingServiceName);
final Supplier<WeldBootstrapService> weldContainerSupplier = sb.requires(weldServiceName);
sb.requires(weldStartService);
sb.setInstance(new WeldInterceptorBindingsService(interceptorBindingsConsumer, weldContainerSupplier, beanDeploymentArchiveId, beanName, componentClass, componentInterceptorSupport));
sb.install();
return bindingServiceName;
}
private static void addJsr299BindingsCreateInterceptor(final ComponentConfiguration configuration, final ComponentDescription description, final String beanName, final ServiceName weldServiceName, ServiceBuilder<?> builder, final ServiceName bindingServiceName, final ComponentInterceptorSupport componentInterceptorSupport) {
//add the create interceptor that creates the Jakarta Contexts and Dependency Injection Interceptors
final Supplier<WeldBootstrapService> weldContainerSupplier = builder.requires(weldServiceName);
final Supplier<InterceptorBindings> interceptorBindingsSupplier = builder.requires(bindingServiceName);
final Jsr299BindingsCreateInterceptor createInterceptor = new Jsr299BindingsCreateInterceptor(weldContainerSupplier, interceptorBindingsSupplier, description.getBeanDeploymentArchiveId(), beanName, componentInterceptorSupport);
configuration.addPostConstructInterceptor(new ImmediateInterceptorFactory(createInterceptor), InterceptorOrder.ComponentPostConstruct.CREATE_CDI_INTERCEPTORS);
}
private static void addCommonLifecycleInterceptionSupport(final ComponentConfiguration configuration, ServiceBuilder<?> builder, final ServiceName bindingServiceName, final ServiceName beanManagerServiceName, final ComponentInterceptorSupport componentInterceptorSupport) {
configuration.addPreDestroyInterceptor(factory(InterceptionType.PRE_DESTROY, builder, bindingServiceName, componentInterceptorSupport), InterceptorOrder.ComponentPreDestroy.CDI_INTERCEPTORS);
configuration.addAroundConstructInterceptor(factory(InterceptionType.AROUND_CONSTRUCT, builder, bindingServiceName, componentInterceptorSupport), InterceptorOrder.AroundConstruct.WELD_AROUND_CONSTRUCT_INTERCEPTORS);
configuration.addPostConstructInterceptor(factory(InterceptionType.POST_CONSTRUCT, builder, bindingServiceName, componentInterceptorSupport), InterceptorOrder.ComponentPostConstruct.CDI_INTERCEPTORS);
/*
* Add interceptor to activate the request scope for the @PostConstruct callback.
* See https://issues.jboss.org/browse/CDI-219 for details
*/
final EjbRequestScopeActivationInterceptor.Factory postConstructRequestContextActivationFactory = new EjbRequestScopeActivationInterceptor.Factory(beanManagerServiceName);
configuration.addPostConstructInterceptor(postConstructRequestContextActivationFactory, InterceptorOrder.ComponentPostConstruct.REQUEST_SCOPE_ACTIVATING_INTERCEPTOR);
// @AroundConstruct support
configuration.addAroundConstructInterceptor(new ImmediateInterceptorFactory(WeldConstructionStartInterceptor.INSTANCE), InterceptorOrder.AroundConstruct.CONSTRUCTION_START_INTERCEPTOR);
}
/**
* Retrieves ManagedReference from the interceptor context and performs an InjectionTarget operation on the instance
*/
private abstract static class AbstractInjectionTargetDelegatingInterceptor implements Interceptor {
@Override
public Object processInvocation(InterceptorContext context) throws Exception {
ManagedReference reference = (ManagedReference) context.getPrivateData(ComponentInstance.class).getInstanceData(BasicComponentInstance.INSTANCE_KEY);
if (reference != null) {
run(reference.getInstance());
}
return context.proceed();
}
protected abstract void run(Object instance);
}
}
| 19,468 | 63.042763 | 542 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/deployment/processors/ExternalBeanArchiveProcessor.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment.processors;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.function.BiConsumer;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.ee.component.EEModuleDescription;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.weld._private.WeldDeploymentMarker;
import org.jboss.as.weld.deployment.BeanDeploymentArchiveImpl;
import org.jboss.as.weld.deployment.BeanDeploymentArchiveImpl.BeanArchiveType;
import org.jboss.as.weld.deployment.ExplicitBeanArchiveMetadata;
import org.jboss.as.weld.deployment.ExplicitBeanArchiveMetadataContainer;
import org.jboss.as.weld.deployment.PropertyReplacingBeansXmlParser;
import org.jboss.as.weld.deployment.WeldAttachments;
import org.jboss.as.weld.deployment.processors.UrlScanner.ClassFile;
import org.jboss.as.weld.discovery.AnnotationType;
import org.jboss.as.weld.logging.WeldLogger;
import org.jboss.as.weld.spi.ComponentSupport;
import org.jboss.as.weld.spi.ModuleServicesProvider;
import org.jboss.as.weld.util.Reflections;
import org.jboss.as.weld.util.ServiceLoaders;
import org.jboss.as.weld.util.Utils;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.Index;
import org.jboss.jandex.IndexReader;
import org.jboss.modules.DependencySpec;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleDependencySpec;
import org.jboss.modules.ModuleLoadException;
import org.jboss.modules.ModuleLoader;
import org.jboss.weld.bootstrap.api.Service;
import org.jboss.weld.bootstrap.spi.BeanDiscoveryMode;
import org.jboss.weld.bootstrap.spi.BeansXml;
import org.jboss.weld.xml.BeansXmlParser;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* Deployment processor that builds bean archives from external deployments.
* <p/>
* This is only run at the top level, as multiple sub deployments can reference the same
* beans.xml information, so we have to iterate through all bean deployment archives in this processor, to prevent
* beans.xml from being potentially parsed twice.
* <p/>
*
* @author Stuart Douglas
* @author Jozef Hartinger
*/
public class ExternalBeanArchiveProcessor implements DeploymentUnitProcessor {
private static final String META_INF_BEANS_XML = "META-INF/beans.xml";
private static final String META_INF_JANDEX_IDX = "META-INF/jandex.idx";
private final String ALL_KNOWN_CLASSES = "ALL_KNOWN_CLASSES";
private final String BEAN_CLASSES = "BEAN_CLASSES";
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
if (!WeldDeploymentMarker.isPartOfWeldDeployment(deploymentUnit)) {
return;
}
if (deploymentUnit.getParent() != null) {
return;
}
final Set<String> componentClassNames = new HashSet<>();
final ServiceLoader<ComponentSupport> supportServices = ServiceLoader.load(ComponentSupport.class,
WildFlySecurityManager.getClassLoaderPrivileged(ExternalBeanArchiveProcessor.class));
final String beanArchiveIdPrefix = deploymentUnit.getName() + ".external.";
// This set is used for external bean archives with annotated discovery mode
final Set<AnnotationType> beanDefiningAnnotations = new HashSet<>(deploymentUnit.getAttachment(WeldAttachments.BEAN_DEFINING_ANNOTATIONS));
List<DeploymentUnit> subDeployments = deploymentUnit.getAttachmentList(Attachments.SUB_DEPLOYMENTS);
List<DeploymentUnit> deploymentUnits = new ArrayList<>(subDeployments.size() + 1);
deploymentUnits.add(deploymentUnit);
deploymentUnits.addAll(subDeployments);
List<ClassLoader> loaders = new ArrayList<>(deploymentUnits.size() + 1);
loaders.add(WildFlySecurityManager.getClassLoaderPrivileged(WeldDeploymentProcessor.class));
for (DeploymentUnit unit : deploymentUnits) {
loaders.add(unit.getAttachment(Attachments.MODULE).getClassLoader());
}
BeansXmlParser parser = new PropertyReplacingBeansXmlParser(deploymentUnit,
Utils.getRootDeploymentUnit(deploymentUnit).getAttachment(WeldConfiguration.ATTACHMENT_KEY)
.isLegacyEmptyBeansXmlTreatment());
final HashSet<URL> existing = new HashSet<URL>();
// build a set of all deployment unit names, used later on to skip processing of some dependencies
final Set<String> depUnitNames = new HashSet<>();
final String prefix = "deployment.";
for (DeploymentUnit deployment : deploymentUnits) {
depUnitNames.add(prefix + deployment.getName());
try {
final ExplicitBeanArchiveMetadataContainer weldDeploymentMetadata = deployment.getAttachment(ExplicitBeanArchiveMetadataContainer.ATTACHMENT_KEY);
if (weldDeploymentMetadata != null) {
for (ExplicitBeanArchiveMetadata md : weldDeploymentMetadata.getBeanArchiveMetadata().values()) {
existing.add(md.getBeansXmlFile().toURL());
if (md.getAdditionalBeansXmlFile() != null) {
existing.add(md.getAdditionalBeansXmlFile().toURL());
}
}
}
} catch (MalformedURLException e) {
throw new DeploymentUnitProcessingException(e);
}
EEModuleDescription moduleDesc = deployment.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION);
if(moduleDesc != null) {
for(ComponentDescription component : moduleDesc.getComponentDescriptions()) {
for (ComponentSupport support : supportServices) {
if (!support.isDiscoveredExternalType(component)) {
componentClassNames.add(component.getComponentClassName());
break;
}
}
}
}
}
Iterable<ModuleServicesProvider> moduleServicesProviders = ServiceLoader.load(ModuleServicesProvider.class, new CompositeClassLoader(loaders));
// This map is a cache that allows us to avoid repeated introspection of Module's exported resources
// it is of little importance for small deployment, but makes a difference in massive ones, see WFLY-14055
Map<String, Map<URL, URL>> exportedResourcesCache = new HashMap<>();
for (DeploymentUnit deployment : deploymentUnits) {
final Module module = deployment.getAttachment(Attachments.MODULE);
if (module == null) {
return;
}
for (DependencySpec dep : module.getDependencies()) {
if (!(dep instanceof ModuleDependencySpec)) {
continue;
}
if (depUnitNames.contains(((ModuleDependencySpec) dep).getName())) {
// dep.getName() returns something like deployment.123abc.ear
// we want to skip processing this as it will be (or already was) processed as another dep. unit
continue;
}
final Module dependency = loadModuleDependency(dep);
if (dependency == null) {
continue;
}
Map<URL, URL> resourcesMap = findExportedResources(dependency, exportedResourcesCache);
if (!resourcesMap.isEmpty()) {
List<BeanDeploymentArchiveImpl> moduleBdas = new ArrayList<>();
for (Entry<URL,URL> entry : resourcesMap.entrySet()) {
URL beansXmlUrl = entry.getKey();
if (existing.contains(beansXmlUrl)) {
continue;
}
/*
* Workaround for http://java.net/jira/browse/JAVASERVERFACES-2837
*/
if (beansXmlUrl.toString().contains("jsf-impl-2.2")) {
continue;
}
/*
* Workaround for resteasy-cdi bundling beans.xml
*/
if (beansXmlUrl.toString().contains("resteasy-cdi")) {
continue;
}
/*
* check if the dependency processes META-INF, if it doesn't we don't want to pick up beans
* See https://docs.wildfly.org/17/Developer_Guide.html#CDI_Reference
*/
if (!dep.getImportFilter().accept("META-INF")) {
continue;
}
WeldLogger.DEPLOYMENT_LOGGER.debugf("Found external beans.xml: %s", beansXmlUrl.toString());
final BeansXml beansXml = parseBeansXml(beansXmlUrl, parser, deploymentUnit);
if (BeanDiscoveryMode.NONE.equals(beansXml.getBeanDiscoveryMode())) {
// Scanning suppressed per spec
continue;
}
Map<String, List<String>> allAndBeanClasses = discover(beansXml.getBeanDiscoveryMode(), beansXmlUrl, entry.getValue(),
beanDefiningAnnotations);
Collection<String> discoveredBeanClasses = allAndBeanClasses.get(BEAN_CLASSES);
Collection<String> allKnownClasses = allAndBeanClasses.get(ALL_KNOWN_CLASSES);
if (discoveredBeanClasses == null) {
// URL scanner probably does not understand the protocol
continue;
}
discoveredBeanClasses.removeAll(componentClassNames);
final BeanDeploymentArchiveImpl bda = new BeanDeploymentArchiveImpl(new HashSet<String>(discoveredBeanClasses), new HashSet<String>(allKnownClasses), beansXml, dependency, beanArchiveIdPrefix + beansXmlUrl.toExternalForm(), BeanArchiveType.EXTERNAL);
WeldLogger.DEPLOYMENT_LOGGER.beanArchiveDiscovered(bda);
// Add module services to external bean deployment archive
for (Entry<Class<? extends Service>, Service> moduleService : ServiceLoaders
.loadModuleServices(moduleServicesProviders, deploymentUnit, deployment, module, null).entrySet()) {
bda.getServices().add(moduleService.getKey(), Reflections.cast(moduleService.getValue()));
}
deploymentUnit.addToAttachmentList(WeldAttachments.ADDITIONAL_BEAN_DEPLOYMENT_MODULES, bda);
moduleBdas.add(bda);
// make sure that if this beans.xml is seen by some other module, it is not processed twice
existing.add(beansXmlUrl);
}
//BDA's from inside the same module have visibility on each other
for(BeanDeploymentArchiveImpl i : moduleBdas) {
for(BeanDeploymentArchiveImpl j : moduleBdas) {
if(i != j) {
i.addBeanDeploymentArchive(j);
}
}
}
}
}
}
}
/**
*
* @param beanDiscoveryMode
* @param beansXmlUrl
* @param indexUrl
* @param beanDefiningAnnotations
* @return the set of discovered bean classes or null if unable to handle the provided beans.xml url
*/
private Map<String, List<String>> discover(BeanDiscoveryMode beanDiscoveryMode, URL beansXmlUrl, URL indexUrl, Set<AnnotationType> beanDefiningAnnotations) {
List<String> discoveredBeanClasses = new ArrayList<String>();
List<String> allKnownClasses = new ArrayList<String>();
BiConsumer<String, ClassFile> consumer;
if (BeanDiscoveryMode.ANNOTATED.equals(beanDiscoveryMode)) {
// We must only consider types with bean defining annotations
Index index = tryLoadIndex(indexUrl);
if (index != null) {
// Use the provided index to find ClassInfo
consumer = (name, classFile) -> {
ClassInfo classInfo = index.getClassByName(DotName.createSimple(name));
allKnownClasses.add(name);
if (classInfo != null && hasBeanDefiningAnnotation(classInfo, beanDefiningAnnotations)) {
discoveredBeanClasses.add(name);
}
};
} else {
// Build ClassInfo on the fly
consumer = (name, classFile) -> {
try (InputStream in = classFile.openStream()) {
ClassInfo classInfo = Index.singleClass(in);
allKnownClasses.add(name);
if (classInfo != null && hasBeanDefiningAnnotation(classInfo, beanDefiningAnnotations)) {
discoveredBeanClasses.add(name);
}
} catch (IOException e) {
WeldLogger.DEPLOYMENT_LOGGER.cannotIndexClassName(name, beansXmlUrl);
}
};
}
} else {
// Bean discovery mode ALL
consumer = (name, classFile) -> {
allKnownClasses.add(name);
discoveredBeanClasses.add(name);
};
}
Map<String, List<String>> result = new HashMap<>();
result.put(ALL_KNOWN_CLASSES, allKnownClasses);
result.put(BEAN_CLASSES, discoveredBeanClasses);
UrlScanner scanner = new UrlScanner(beansXmlUrl, consumer);
return scanner.scan() ? result : Collections.emptyMap();
}
private Index tryLoadIndex(URL indexUrl) {
if (indexUrl == null) {
return null;
}
try (InputStream in = indexUrl.openStream()) {
return new IndexReader(in).read();
} catch (Exception e) {
WeldLogger.DEPLOYMENT_LOGGER.cannotLoadAnnotationIndexOfExternalBeanArchive(indexUrl);
return null;
}
}
/**
* The entry key is bean.xml URL, value is (optional) jandex index URL.
*
* @param dependencyModule
* @return the map of exported resources
*/
private Map<URL, URL> findExportedResources(Module dependencyModule, Map<String, Map<URL, URL>> exportedResourcesCache) {
if (exportedResourcesCache.containsKey(dependencyModule.getName())) {
return exportedResourcesCache.get(dependencyModule.getName());
}
Set<URL> beanXmls = findExportedResource(dependencyModule, META_INF_BEANS_XML);
if (beanXmls.isEmpty()) {
exportedResourcesCache.put(dependencyModule.getName(), Collections.emptyMap());
return Collections.emptyMap();
}
Set<URL> indexes = findExportedResource(dependencyModule, META_INF_JANDEX_IDX);
Map<URL, URL> ret = new HashMap<>();
for (URL beansXml : beanXmls) {
String urlBase = beansXml.toString().substring(0, beansXml.toString().length() - META_INF_BEANS_XML.length());
URL idx = null;
for (URL index : indexes) {
if (index.toString().startsWith(urlBase)) {
idx = index;
break;
}
}
ret.put(beansXml, idx);
}
exportedResourcesCache.put(dependencyModule.getName(), ret);
return ret;
}
private Set<URL> findExportedResource(Module dependencyModule, String name) {
Enumeration<URL> exported = dependencyModule.getExportedResources(name);
return new HashSet<>(Collections.list(exported));
}
private boolean hasBeanDefiningAnnotation(ClassInfo classInfo, Set<AnnotationType> beanDefiningAnnotations) {
Map<DotName, List<AnnotationInstance>> annotationsMap = classInfo.annotationsMap();
for (AnnotationType beanDefiningAnnotation : beanDefiningAnnotations) {
List<AnnotationInstance> annotations = annotationsMap.get(beanDefiningAnnotation.getName());
if (annotations != null) {
for (AnnotationInstance annotationInstance : annotations) {
if (annotationInstance.target().equals(classInfo)) {
return true;
}
}
}
}
return false;
}
private Module loadModuleDependency(DependencySpec dep) {
if (dep instanceof ModuleDependencySpec) {
ModuleDependencySpec dependency = (ModuleDependencySpec) dep;
final ModuleLoader loader = dependency.getModuleLoader();
if (loader != null) {
try {
return dependency.getModuleLoader().loadModule(dependency.getIdentifier());
} catch (ModuleLoadException e) {
return null;
}
}
}
return null;
}
private BeansXml parseBeansXml(URL beansXmlFile, BeansXmlParser parser, final DeploymentUnit deploymentUnit) throws DeploymentUnitProcessingException {
return parser.parse(beansXmlFile);
}
}
| 19,368 | 46.943069 | 274 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/services/TCCLSingletonService.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.services;
import org.jboss.as.server.Services;
import org.jboss.msc.Service;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.weld.bootstrap.api.SingletonProvider;
/**
* Service that manages the weld {@link SingletonProvider}
*
* @author Stuart Douglas
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public class TCCLSingletonService implements Service {
public static final ServiceName SERVICE_NAME = Services.JBOSS_AS.append("weld", "singleton");
@Override
public void start(final StartContext context) throws StartException {
SingletonProvider.initialize(new ModuleGroupSingletonProvider());
}
@Override
public void stop(final StopContext context) {
SingletonProvider.reset();
}
}
| 1,942 | 35.660377 | 97 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/services/ModuleGroupSingletonProvider.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2020, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.services;
import java.util.Collections;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.jboss.as.weld.logging.WeldLogger;
import org.jboss.modules.ModuleClassLoader;
import org.jboss.weld.bootstrap.api.Singleton;
import org.jboss.weld.bootstrap.api.SingletonProvider;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* Singleton Provider that uses the TCCL to figure out the current application.
*
* @author Stuart Douglas
*/
public class ModuleGroupSingletonProvider extends SingletonProvider {
/**
* Map of the top level class loader to all class loaders in a deployment
*/
public static final Map<ClassLoader, Set<ClassLoader>> deploymentClassLoaders = new ConcurrentHashMap<ClassLoader, Set<ClassLoader>>();
/**
* Maps a top level class loader to all CL's in the deployment
*/
public static void addClassLoaders(ClassLoader topLevel, Set<ClassLoader> allClassLoaders) {
deploymentClassLoaders.put(topLevel, allClassLoaders);
}
/**
* Removes the class loader mapping
*/
public static void removeClassLoader(ClassLoader topLevel) {
deploymentClassLoaders.remove(topLevel);
}
@Override
public <T> Singleton<T> create(Class<? extends T> type) {
return new TCCLSingleton<T>();
}
@SuppressWarnings("unused")
private static class TCCLSingleton<T> implements Singleton<T> {
private volatile Map<ClassLoader, T> store = Collections.emptyMap();
private volatile Map<String, T> contextIdStore = Collections.emptyMap();
public T get() {
T instance = store.get(findParentModuleCl(WildFlySecurityManager.getCurrentContextClassLoaderPrivileged()));
if (instance == null) {
throw WeldLogger.ROOT_LOGGER.singletonNotSet(WildFlySecurityManager.getCurrentContextClassLoaderPrivileged());
}
return instance;
}
public synchronized void set(T object) {
final Map<ClassLoader, T> store = new IdentityHashMap<ClassLoader, T>(this.store);
ClassLoader classLoader = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
store.put(classLoader, object);
if (deploymentClassLoaders.containsKey(classLoader)) {
for (ClassLoader cl : deploymentClassLoaders.get(classLoader)) {
store.put(cl, object);
}
}
this.store = store;
}
public synchronized void clear() {
ClassLoader classLoader = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
final Map<ClassLoader, T> store = new IdentityHashMap<ClassLoader, T>(this.store);
store.remove(classLoader);
if (deploymentClassLoaders.containsKey(classLoader)) {
for (ClassLoader cl : deploymentClassLoaders.get(classLoader)) {
store.remove(cl);
}
}
this.store = store;
}
public boolean isSet() {
return store.containsKey(findParentModuleCl(WildFlySecurityManager.getCurrentContextClassLoaderPrivileged()));
}
/**
* If a custom CL is in use we want to get the module CL it delegates to
* @param classLoader The current CL
* @returnThe corresponding module CL
*/
private ClassLoader findParentModuleCl(ClassLoader classLoader) {
ClassLoader c = classLoader;
while (c != null && !(c instanceof ModuleClassLoader)) {
c = c.getParent();
}
return c;
}
/*
* Default implementation of the Weld 1.2 API
*
* This provides forward binary compatibility with Weld 1.2 (OSGi integration).
* It is OK to ignore the id parameter as TCCL is still used to identify the singleton in Jakarta EE.
*/
public T get(String id) {
T val = contextIdStore.get(id);
if(val != null) {
return val;
}
return get();
}
public boolean isSet(String id) {
T val = contextIdStore.get(id);
if(val != null) {
return true;
}
return isSet();
}
public synchronized void set(String id, T object) {
set(object);
final HashMap<String, T> store = new HashMap<String, T>(this.contextIdStore);
store.put(id, object);
this.contextIdStore = store;
}
public synchronized void clear(String id) {
clear();
final HashMap<String, T> store = new HashMap<String, T>(this.contextIdStore);
store.remove(id);
this.contextIdStore = store;
}
}
}
| 5,994 | 36.46875 | 139 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/services/BeanManagerService.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.services;
import java.util.function.Consumer;
import java.util.function.Supplier;
import jakarta.enterprise.inject.spi.BeanManager;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.weld.ServiceNames;
import org.jboss.as.weld.WeldBootstrapService;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.weld.bean.builtin.BeanManagerProxy;
/**
* Service that provides access to the BeanManger for a (sub)deployment
*
* @author Stuart Douglas
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public final class BeanManagerService implements Service<BeanManager> {
public static final ServiceName NAME = ServiceNames.BEAN_MANAGER_SERVICE_NAME;
private final Consumer<BeanManager> beanManagerConsumer;
private final Supplier<WeldBootstrapService> weldContainerSupplier;
private final String beanDeploymentArchiveId;
private volatile BeanManagerProxy beanManager;
public BeanManagerService(final String beanDeploymentArchiveId,
final Consumer<BeanManager> beanManagerConsumer,
final Supplier<WeldBootstrapService> weldContainerSupplier) {
this.beanDeploymentArchiveId = beanDeploymentArchiveId;
this.beanManagerConsumer = beanManagerConsumer;
this.weldContainerSupplier = weldContainerSupplier;
}
@Override
public void start(final StartContext context) throws StartException {
beanManager = new BeanManagerProxy(weldContainerSupplier.get().getBeanManager(beanDeploymentArchiveId));
beanManagerConsumer.accept(beanManager);
}
@Override
public void stop(final StopContext context) {
beanManagerConsumer.accept(null);
beanManager = null;
}
@Override
public BeanManager getValue() {
return beanManager;
}
/**
* Gets the Bean Manager MSC service name relative to the Deployment Unit.
* <p>
* Modules outside of weld subsystem should use WeldCapability instead to get the name of the Bean Manager service
* associated to the deployment unit.
*
* @param deploymentUnit The deployment unit to be used.
*
* @return The Bean Manager service name.
*/
public static ServiceName serviceName(final DeploymentUnit deploymentUnit) {
return ServiceNames.beanManagerServiceName(deploymentUnit);
}
}
| 3,601 | 38.152174 | 118 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/services/bootstrap/ProxyServicesImpl.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.services.bootstrap;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.security.ProtectionDomain;
import java.util.Arrays;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.jboss.as.server.moduleservice.ServiceModuleLoader;
import org.jboss.as.weld.logging.WeldLogger;
import org.jboss.as.weld.util.Reflections;
import org.jboss.modules.ClassDefiner;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleClassLoader;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.weld.interceptor.proxy.LifecycleMixin;
import org.jboss.weld.logging.BeanLogger;
import org.jboss.weld.proxy.WeldConstruct;
import org.jboss.weld.serialization.spi.BeanIdentifier;
import org.jboss.weld.serialization.spi.ProxyServices;
import org.wildfly.security.manager.WildFlySecurityManager;
import static java.security.AccessController.doPrivileged;
/**
* {@link ProxyServices} implementation that delegates to the module class loader if the bean class loader cannot be determined
*
* @author Stuart Douglas
* @author Jozef Hartinger
*
*/
public class ProxyServicesImpl implements ProxyServices {
private static String[] REQUIRED_WELD_DEPENDENCIES = new String[]{
"org.jboss.weld.core",
"org.jboss.weld.spi",
"org.jboss.weld.api"
};
// these are used to check whether a classloader is capable of loading Weld proxies
private static String[] WELD_CLASSES = new String[]{
BeanIdentifier.class.getName(), // Weld SPI
LifecycleMixin.class.getName(), // Weld core
WeldConstruct.class.getName() // Weld API
};
private final Module module;
private final ConcurrentMap<ModuleIdentifier, Boolean> processedStaticModules = new ConcurrentHashMap<>();
private final ClassDefiner classDefiner;
public ProxyServicesImpl(Module module) {
this.module = module;
this.classDefiner = ClassDefiner.getInstance();
}
public ClassLoader getClassLoader(final Class<?> proxiedBeanType) {
if (WildFlySecurityManager.isChecking()) {
return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
public ClassLoader run() {
return _getClassLoader(proxiedBeanType);
}
});
} else {
return _getClassLoader(proxiedBeanType);
}
}
private ClassLoader _getClassLoader(Class<?> proxiedBeanType) {
if (proxiedBeanType.getName().startsWith("java")) {
return module.getClassLoader();
} else if (proxiedBeanType.getClassLoader() instanceof ModuleClassLoader) {
final ModuleClassLoader loader = (ModuleClassLoader) proxiedBeanType.getClassLoader();
//even though this is not strictly spec compliant if a class from the app server is
//being proxied we use the deployment CL to prevent a memory leak
//in theory this means that package private methods will not work correctly
//however the application does not have access to package private methods anyway
//as it is in a different class loader
if (loader.getModule().getModuleLoader() instanceof ServiceModuleLoader) {
//this is a dynamic module
//we can use it to load the proxy
return proxiedBeanType.getClassLoader();
} else {
// this class comes from a static module
// first, check if we can use its classloader to load proxy classes
final Module definingModule = loader.getModule();
Boolean hasWeldDependencies = processedStaticModules.get(definingModule.getIdentifier());
boolean logWarning = false; // only log for the first class in the module
if (hasWeldDependencies == null) {
hasWeldDependencies = canLoadWeldProxies(definingModule); // may be run multiple times but that does not matter
logWarning = processedStaticModules.putIfAbsent(definingModule.getIdentifier(), hasWeldDependencies) == null;
}
if (hasWeldDependencies) {
// this module declares weld dependencies - we can use module's classloader to load the proxy class
// pros: package-private members will work fine
// cons: proxy classes will remain loaded by the module's classloader after undeployment (nothing else leaks)
return proxiedBeanType.getClassLoader();
} else {
// no weld dependencies - we use deployment's classloader to load the proxy class
// pros: proxy classes unloaded with undeployment
// cons: package-private methods and constructors will yield IllegalAccessException
if (logWarning) {
WeldLogger.ROOT_LOGGER.loadingProxiesUsingDeploymentClassLoader(definingModule.getIdentifier(), Arrays.toString(REQUIRED_WELD_DEPENDENCIES));
}
return this.module.getClassLoader();
}
}
} else {
return proxiedBeanType.getClassLoader();
}
}
/**
* This method corresponds to the original {@code _getClassLoader()} method and returns
* {@link Module} based on original class. This module is then used when defining proxy classes.
*
* Most likely we want to return a {@link Module} into which the originalClass belongs but in case such a module
* doesn't know Weld dependencies, we need to return different module, one that was used by the deployment.
*/
private Module getModule(Class<?> originalClass) {
if (originalClass.getName().startsWith("java")) {
return module;
} else {
Module definingModule = Module.forClass(originalClass);
Boolean hasWeldDependencies = processedStaticModules.get(definingModule.getIdentifier());
boolean logWarning = false; // only log for the first class in the module
if (hasWeldDependencies == null) {
hasWeldDependencies = canLoadWeldProxies(definingModule); // may be run multiple times but that does not matter
logWarning = processedStaticModules.putIfAbsent(definingModule.getIdentifier(), hasWeldDependencies) == null;
}
if (hasWeldDependencies) {
// this module declares Weld dependencies - we can use module's classloader to load the proxy class
// pros: package-private members will work fine
// cons: proxy classes will remain loaded by the module's classloader after undeployment (nothing else leaks)
return definingModule;
} else {
// no weld dependencies - we use deployment's classloader to load the proxy class
// pros: proxy classes unloaded with undeployment
// cons: package-private methods and constructors will yield IllegalAccessException
if (logWarning) {
WeldLogger.ROOT_LOGGER.loadingProxiesUsingDeploymentClassLoader(definingModule.getIdentifier(), Arrays.toString(REQUIRED_WELD_DEPENDENCIES));
}
return this.module;
}
}
}
private static boolean canLoadWeldProxies(Module module) {
for (String weldClass : WELD_CLASSES) {
if (!Reflections.isAccessible(weldClass, module.getClassLoader())) {
return false;
}
}
return true;
}
public void cleanup() {
processedStaticModules.clear();
}
public Class<?> loadBeanClass(final String className) {
try {
return (Class<?>) AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
public Object run() throws Exception {
return Class.forName(className, true, getClassLoader(this.getClass()));
}
});
} catch (PrivilegedActionException pae) {
throw BeanLogger.LOG.cannotLoadClass(className, pae.getException());
}
}
@Override
public Class<?> defineClass(Class<?> originalClass, String s, byte[] bytes, int i, int i1) throws ClassFormatError {
return defineClass(originalClass, s, bytes, i, i1, getProtectionDomain(originalClass));
}
@Override
public Class<?> defineClass(Class<?> originalClass, String s, byte[] bytes, int i, int i1, ProtectionDomain protectionDomain) throws ClassFormatError {
return classDefiner.defineClass(getModule(originalClass), s, protectionDomain, bytes, i, i1);
}
@Override
public Class<?> loadClass(Class<?> originalClass, String classBinaryName) throws ClassNotFoundException {
Module module = getModule(originalClass);
if (module == null) {
throw new IllegalArgumentException("Original " + originalClass + " does not have a module");
}
return module.getClassLoader().loadClass(classBinaryName);
}
//@Override unused in Weld 3/4 and removed in Weld 5 so don't annotate it
// TODO to be removed once Weld 5 is a direct dependency of non-preview WFLY
public boolean supportsClassDefining() {
return true;
}
// copied over from ClassDefiner as it's missing a method that would allow to define class based on module but
// without ProtectionDomain
private ProtectionDomain getProtectionDomain(final Class<?> clazz) {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
return doPrivileged((PrivilegedAction<ProtectionDomain>) clazz::getProtectionDomain);
} else {
return clazz.getProtectionDomain();
}
}
}
| 11,082 | 46.566524 | 165 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/services/bootstrap/WeldExecutorServices.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2015, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.services.bootstrap;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import org.jboss.as.naming.context.NamespaceContextSelector;
import org.jboss.as.server.Services;
import org.jboss.msc.Service;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.threads.JBossThreadFactory;
import org.jboss.weld.Container;
import org.jboss.weld.ContainerState;
import org.jboss.weld.executor.AbstractExecutorServices;
import org.jboss.weld.manager.api.ExecutorServices;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* Weld's ExecutorServices implementation. The executor is shared across all Jakarta Contexts and Dependency Injection enabled deployments and used primarily for parallel Weld bootstrap.
*
* @author Jozef Hartinger
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public class WeldExecutorServices extends AbstractExecutorServices implements Service {
public static final int DEFAULT_BOUND = Runtime.getRuntime().availableProcessors() + 1;
public static final ServiceName SERVICE_NAME = Services.JBOSS_AS.append("weld", "executor");
private static final String THREAD_NAME_PATTERN = "Weld Thread Pool -- %t";
private final int bound;
private final Consumer<ExecutorServices> executorServicesConsumer;
private ExecutorService executor;
public WeldExecutorServices() {
this(null, DEFAULT_BOUND);
}
public WeldExecutorServices(final Consumer<ExecutorServices> executorServicesConsumer, int bound) {
this.executorServicesConsumer = executorServicesConsumer;
this.bound = bound;
}
@Override
public void start(final StartContext context) throws StartException {
final ThreadGroup threadGroup = new ThreadGroup("Weld ThreadGroup");
final ThreadFactory factory = new JBossThreadFactory(threadGroup, Boolean.FALSE, null, THREAD_NAME_PATTERN, null, null);
// set TCCL to null for new threads to make sure no deployment classloader leaks through this executor's TCCL
// Weld does not mind having null TCCL in this executor
this.executor = new WeldExecutor(bound, runnable -> {
Thread thread = factory.newThread(runnable);
if (WildFlySecurityManager.isChecking()) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
thread.setContextClassLoader(null);
return null;
}
});
} else {
thread.setContextClassLoader(null);
}
return thread;
}
);
if (executorServicesConsumer != null) executorServicesConsumer.accept(this);
}
@Override
public void stop(final StopContext context) {
if (executorServicesConsumer != null) executorServicesConsumer.accept(null);
if (executor != null) {
context.asynchronous();
new Thread(() -> {
super.shutdown();
executor = null;
context.complete();
}).start();
}
}
@Override
protected synchronized int getThreadPoolSize() {
return bound;
}
@Override
public synchronized ExecutorService getTaskExecutor() {
return executor;
}
@Override
public void cleanup() {
// noop on undeploy - the executor is a service shared across multiple deployments
}
static class WeldExecutor extends ThreadPoolExecutor {
WeldExecutor(int nThreads, ThreadFactory threadFactory) {
super(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory);
}
@Override
protected void beforeExecute(Thread t, Runnable r) {
if (r instanceof WeldTaskWrapper) {
NamespaceContextSelector.pushCurrentSelector(((WeldTaskWrapper) r).currentSelector);
}
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
if (r instanceof WeldTaskWrapper) {
NamespaceContextSelector.popCurrentSelector();
}
}
@Override
public void execute(Runnable command) {
if (Container.instance().getState() == ContainerState.INITIALIZED) {
WeldTaskWrapper task = new WeldTaskWrapper(command, NamespaceContextSelector.getCurrentSelector());
super.execute(task);
} else {
super.execute(command);
}
}
}
static class WeldTaskWrapper implements Runnable {
private final Runnable runnable;
private final NamespaceContextSelector currentSelector;
public WeldTaskWrapper(Runnable runnable, NamespaceContextSelector currentSelector) {
this.runnable = runnable;
this.currentSelector = currentSelector;
}
@Override
public void run() {
runnable.run();
}
}
}
| 6,585 | 36.850575 | 186 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/services/bootstrap/WeldSecurityServices.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.services.bootstrap;
import java.security.AccessController;
import java.security.Principal;
import java.security.PrivilegedAction;
import java.util.function.Consumer;
import org.jboss.as.weld.ServiceNames;
import org.jboss.as.weld.logging.WeldLogger;
import org.jboss.msc.Service;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.weld.security.spi.SecurityServices;
import org.wildfly.security.auth.server.SecurityDomain;
import org.wildfly.security.auth.server.SecurityIdentity;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public class WeldSecurityServices implements Service, SecurityServices {
public static final ServiceName SERVICE_NAME = ServiceNames.WELD_SECURITY_SERVICES_SERVICE_NAME;
private final Consumer<SecurityServices> securityServicesConsumer;
public WeldSecurityServices(final Consumer<SecurityServices> securityServicesConsumer) {
this.securityServicesConsumer = securityServicesConsumer;
}
@Override
public void start(final StartContext context) throws StartException {
securityServicesConsumer.accept(this);
}
@Override
public void stop(final StopContext context) {
securityServicesConsumer.accept(null);
}
@Override
public Principal getPrincipal() {
SecurityDomain elytronDomain = getCurrentSecurityDomain();
if(elytronDomain != null) {
return elytronDomain.getCurrentSecurityIdentity().getPrincipal();
}
throw WeldLogger.ROOT_LOGGER.securityNotEnabled();
}
@Override
public void cleanup() {
}
@Override
public Consumer<Runnable> getSecurityContextAssociator(){
SecurityDomain elytronDomain = getCurrentSecurityDomain();
if(elytronDomain != null) {
// store the identity from the original thread and use it in callback which will be invoked in a different thread
SecurityIdentity storedSecurityIdentity = elytronDomain.getCurrentSecurityIdentity();
return (action) -> storedSecurityIdentity.runAs(action);
} else {
return SecurityServices.super.getSecurityContextAssociator();
}
}
private SecurityDomain getCurrentSecurityDomain() {
if (WildFlySecurityManager.isChecking()) {
return AccessController.doPrivileged((PrivilegedAction<SecurityDomain>) () -> SecurityDomain.getCurrent());
} else {
return SecurityDomain.getCurrent();
}
}
}
| 3,721 | 36.979592 | 125 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/services/bootstrap/WeldResourceInjectionServices.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.services.bootstrap;
import static org.jboss.as.weld.util.ResourceInjectionUtilities.getResourceAnnotated;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.ServiceLoader;
import jakarta.annotation.Resource;
import jakarta.enterprise.inject.Produces;
import jakarta.enterprise.inject.spi.AnnotatedField;
import jakarta.enterprise.inject.spi.AnnotatedMember;
import jakarta.enterprise.inject.spi.AnnotatedParameter;
import jakarta.enterprise.inject.spi.InjectionPoint;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.jboss.as.ee.component.EEDefaultResourceJndiNames;
import org.jboss.as.ee.component.EEModuleDescription;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.as.naming.deployment.ContextNames.BindInfo;
import org.jboss.as.weld.logging.WeldLogger;
import org.jboss.as.weld.spi.ResourceInjectionResolver;
import org.jboss.as.weld.util.ResourceInjectionUtilities;
import org.jboss.metadata.property.PropertyReplacer;
import org.jboss.modules.Module;
import org.jboss.msc.service.ServiceRegistry;
import org.jboss.weld.injection.spi.ResourceInjectionServices;
import org.jboss.weld.injection.spi.ResourceReference;
import org.jboss.weld.injection.spi.ResourceReferenceFactory;
import org.jboss.weld.injection.spi.helpers.SimpleResourceReference;
import org.wildfly.security.manager.WildFlySecurityManager;
public class WeldResourceInjectionServices extends AbstractResourceInjectionServices implements ResourceInjectionServices {
private static final String USER_TRANSACTION_LOCATION = "java:comp/UserTransaction";
private static final String USER_TRANSACTION_CLASS_NAME = "jakarta.transaction.UserTransaction";
private static final String HANDLE_DELEGATE_CLASS_NAME = "jakarta.ejb.spi.HandleDelegate";
private static final String TIMER_SERVICE_CLASS_NAME = "jakarta.ejb.TimerService";
private static final String ORB_CLASS_NAME = "org.omg.CORBA.ORB";
private static final String TRANSACTION_SYNC_REGISTRY_LOCATION = "java:comp/TransactionSynchronizationRegistry";
private static final String TRANSACTION_SYNC_REGISTRY_CLASS_NAME = "jakarta.transaction.TransactionSynchronizationRegistry";
private static final String EE_CONTEXT_SERVICE_CLASS_NAME = "jakarta.enterprise.concurrent.ContextService";
private static final String EE_DATASOURCE_CLASS_NAME = "javax.sql.DataSource";
private static final String EE_JMS_CONNECTION_FACTORY_CLASS_NAME = "jakarta.jms.ConnectionFactory";
private static final String EE_MANAGED_EXECUTOR_SERVICE_CLASS_NAME = "jakarta.enterprise.concurrent.ManagedExecutorService";
private static final String EE_MANAGED_SCHEDULED_EXECUTOR_SERVICE_CLASS_NAME = "jakarta.enterprise.concurrent.ManagedScheduledExecutorService";
private static final String EE_MANAGED_THREAD_FACTORY_CLASS_NAME = "jakarta.enterprise.concurrent.ManagedThreadFactory";
private static final String EJB_CONTEXT_LOCATION = "java:comp/EJBContext";
private static final String EJB_CONTEXT_CLASS_NAME = "jakarta.ejb.EJBContext";
private static final String EJB_SESSION_CONTEXT_CLASS_NAME = "jakarta.ejb.SessionContext";
private static final String EJB_MESSAGE_DRIVEN_CONTEXT_CLASS_NAME = "jakarta.ejb.MessageDrivenContext";
private static final String EJB_ENTITY_CONTEXT_CLASS_NAME = "jakarta.ejb.EntityContext";
private static final String WEB_SERVICE_CONTEXT_CLASS_NAME = "jakarta.xml.ws.WebServiceContext";
private final Context context;
private final boolean warModule;
private final List<ResourceInjectionResolver> resourceResolvers;
private final PropertyReplacer propertyReplacer;
public WeldResourceInjectionServices(final ServiceRegistry serviceRegistry, final EEModuleDescription moduleDescription,
final PropertyReplacer propertyReplacer, Module module, boolean warModule) {
super(serviceRegistry, moduleDescription, module);
this.propertyReplacer = propertyReplacer;
this.warModule = warModule;
try {
this.context = new InitialContext();
} catch (NamingException e) {
throw new RuntimeException(e);
}
final Iterator<ResourceInjectionResolver> resolvers = ServiceLoader.load(ResourceInjectionResolver.class,
WildFlySecurityManager.getClassLoaderPrivileged(WeldResourceInjectionServices.class)).iterator();
if (!resolvers.hasNext()) {
this.resourceResolvers = Collections.emptyList();
} else {
this.resourceResolvers = new ArrayList<>();
while (resolvers.hasNext()) {
this.resourceResolvers.add(resolvers.next());
}
}
}
protected String getEJBResourceName(InjectionPoint injectionPoint, String proposedName) {
if (injectionPoint.getType() instanceof Class<?>) {
final Class<?> type = (Class<?>) injectionPoint.getType();
final String typeName = type.getName();
if (USER_TRANSACTION_CLASS_NAME.equals(typeName)) {
return USER_TRANSACTION_LOCATION;
} else if (HANDLE_DELEGATE_CLASS_NAME.equals(typeName)) {
WeldLogger.ROOT_LOGGER.injectionTypeNotValue(HANDLE_DELEGATE_CLASS_NAME, injectionPoint.getMember());
return proposedName;
} else if (ORB_CLASS_NAME.equals(typeName)) {
WeldLogger.ROOT_LOGGER.injectionTypeNotValue(ORB_CLASS_NAME, injectionPoint.getMember());
return proposedName;
} else if (TIMER_SERVICE_CLASS_NAME.equals(typeName)) {
WeldLogger.ROOT_LOGGER.injectionTypeNotValue(TIMER_SERVICE_CLASS_NAME, injectionPoint.getMember());
return proposedName;
} else if (EJB_CONTEXT_CLASS_NAME.equals(typeName) ||
EJB_SESSION_CONTEXT_CLASS_NAME.equals(typeName) ||
EJB_MESSAGE_DRIVEN_CONTEXT_CLASS_NAME.equals(typeName) ||
EJB_ENTITY_CONTEXT_CLASS_NAME.equals(typeName)) {
return EJB_CONTEXT_LOCATION;
} else if (WEB_SERVICE_CONTEXT_CLASS_NAME.equals(typeName)) {
//horrible hack
//there is not actually a binding we can use for this
//the whole CDI+bindings thing will likely be reviewed in EE8
return WEB_SERVICE_CONTEXT_CLASS_NAME;
} else if (TRANSACTION_SYNC_REGISTRY_CLASS_NAME.equals(typeName)) {
return TRANSACTION_SYNC_REGISTRY_LOCATION;
} else {
// EE default bindings
EEDefaultResourceJndiNames eeDefaultResourceJndiNames = moduleDescription.getDefaultResourceJndiNames();
if (eeDefaultResourceJndiNames.getContextService() != null && EE_CONTEXT_SERVICE_CLASS_NAME.equals(typeName)) {
return eeDefaultResourceJndiNames.getContextService();
} else if (eeDefaultResourceJndiNames.getDataSource() != null && EE_DATASOURCE_CLASS_NAME.equals(typeName)) {
return eeDefaultResourceJndiNames.getDataSource();
} else if (eeDefaultResourceJndiNames.getJmsConnectionFactory() != null && EE_JMS_CONNECTION_FACTORY_CLASS_NAME.equals(typeName)) {
return eeDefaultResourceJndiNames.getJmsConnectionFactory();
} else if (eeDefaultResourceJndiNames.getManagedExecutorService() != null && EE_MANAGED_EXECUTOR_SERVICE_CLASS_NAME.equals(typeName)) {
return eeDefaultResourceJndiNames.getManagedExecutorService();
} else if (eeDefaultResourceJndiNames.getManagedScheduledExecutorService() != null && EE_MANAGED_SCHEDULED_EXECUTOR_SERVICE_CLASS_NAME.equals(typeName)) {
return eeDefaultResourceJndiNames.getManagedScheduledExecutorService();
} else if (eeDefaultResourceJndiNames.getManagedThreadFactory() != null && EE_MANAGED_THREAD_FACTORY_CLASS_NAME.equals(typeName)) {
return eeDefaultResourceJndiNames.getManagedThreadFactory();
}
}
}
return proposedName;
}
protected String getResourceName(InjectionPoint injectionPoint) {
Resource resource = getResourceAnnotated(injectionPoint).getAnnotation(Resource.class);
String mappedName = resource.mappedName();
String lookup = resource.lookup();
if (!lookup.isEmpty()) {
return propertyReplacer.replaceProperties(lookup);
}
if (!mappedName.isEmpty()) {
return propertyReplacer.replaceProperties(mappedName);
}
String proposedName = ResourceInjectionUtilities.getResourceName(injectionPoint, propertyReplacer);
return getEJBResourceName(injectionPoint, proposedName);
}
@Override
public ResourceReferenceFactory<Object> registerResourceInjectionPoint(final InjectionPoint injectionPoint) {
final String result = getResourceName(injectionPoint);
if (isKnownNamespace(result) && injectionPoint.getAnnotated().isAnnotationPresent(Produces.class)) {
validateResourceInjectionPointType(getManagedReferenceFactory(getBindInfo(result)), injectionPoint);
}
return new ResourceReferenceFactory<Object>() {
@Override
public ResourceReference<Object> createResource() {
return new SimpleResourceReference<Object>(resolveResource(injectionPoint));
}
};
}
@Override
public ResourceReferenceFactory<Object> registerResourceInjectionPoint(final String jndiName, final String mappedName) {
return new ResourceReferenceFactory<Object>() {
@Override
public ResourceReference<Object> createResource() {
return new SimpleResourceReference<Object>(resolveResource(jndiName, mappedName));
}
};
}
private boolean isKnownNamespace(String name) {
return name.startsWith("java:global") || name.startsWith("java:app") || name.startsWith("java:module")
|| name.startsWith("java:comp") || name.startsWith("java:jboss");
}
@Override
public void cleanup() {
}
@Override
protected BindInfo getBindInfo(String result) {
return ContextNames.bindInfoForEnvEntry(moduleDescription.getApplicationName(), moduleDescription.getModuleName(),
moduleDescription.getModuleName(), !warModule, result);
}
public Object resolveResource(InjectionPoint injectionPoint) {
final Member member = injectionPoint.getMember();
AnnotatedMember<?> annotatedMember;
if (injectionPoint.getAnnotated() instanceof AnnotatedField) {
annotatedMember = (AnnotatedField<?>) injectionPoint.getAnnotated();
} else {
annotatedMember = ((AnnotatedParameter<?>) injectionPoint.getAnnotated()).getDeclaringCallable();
}
if (!annotatedMember.isAnnotationPresent(Resource.class)) {
throw WeldLogger.ROOT_LOGGER.annotationNotFound(Resource.class, member);
}
if (member instanceof Method && ((Method) member).getParameterCount() != 1) {
throw WeldLogger.ROOT_LOGGER.injectionPointNotAJavabean((Method) member);
}
String name = getResourceName(injectionPoint);
for (ResourceInjectionResolver resolver : resourceResolvers) {
Object result = resolver.resolve(name);
if (result != null) {
return result;
}
}
try {
return context.lookup(name);
} catch (NamingException e) {
throw WeldLogger.ROOT_LOGGER.couldNotFindResource(name, injectionPoint.getMember().toString(), e);
}
}
public Object resolveResource(String jndiName, String mappedName) {
String name = ResourceInjectionUtilities.getResourceName(jndiName, mappedName);
try {
return context.lookup(name);
} catch (NamingException e) {
throw WeldLogger.ROOT_LOGGER.couldNotFindResource(name, e);
}
}
}
| 13,335 | 51.298039 | 170 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/ejb/WeldInterceptorBindingsService.java | package org.jboss.as.weld.ejb;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.jboss.as.weld.WeldBootstrapService;
import org.jboss.as.weld.spi.ComponentInterceptorSupport;
import org.jboss.msc.Service;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.weld.annotated.enhanced.EnhancedAnnotatedType;
import org.jboss.weld.annotated.slim.SlimAnnotatedType;
import org.jboss.weld.bean.interceptor.InterceptorBindingsAdapter;
import org.jboss.weld.ejb.spi.InterceptorBindings;
import org.jboss.weld.injection.producer.InterceptionModelInitializer;
import org.jboss.weld.interceptor.spi.model.InterceptionModel;
import org.jboss.weld.manager.BeanManagerImpl;
import org.jboss.weld.resources.ClassTransformer;
import jakarta.enterprise.inject.spi.InterceptionType;
import jakarta.enterprise.inject.spi.Interceptor;
/**
* @author Stuart Douglas
* @author Jozef Hartinger
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public class WeldInterceptorBindingsService implements Service {
private final Consumer<InterceptorBindings> interceptorBindingsConsumer;
private final Supplier<WeldBootstrapService> weldContainerSupplier;
private final String beanArchiveId;
private final String ejbName;
private final Class<?> componentClass;
private final ComponentInterceptorSupport interceptorSupport;
public static final ServiceName SERVICE_NAME = ServiceName.of("WeldInterceptorBindingsService");
public WeldInterceptorBindingsService(final Consumer<InterceptorBindings> interceptorBindingsConsumer,
final Supplier<WeldBootstrapService> weldContainerSupplier,
final String beanArchiveId, final String ejbName, final Class<?> componentClass,
final ComponentInterceptorSupport componentInterceptorSupport) {
this.interceptorBindingsConsumer = interceptorBindingsConsumer;
this.weldContainerSupplier = weldContainerSupplier;
this.beanArchiveId = beanArchiveId;
this.ejbName = ejbName;
this.componentClass = componentClass;
this.interceptorSupport = componentInterceptorSupport;
}
@Override
public void start(final StartContext startContext) throws StartException {
BeanManagerImpl beanManager = weldContainerSupplier.get().getBeanManager(beanArchiveId);
//this is not always called with the deployments TCCL set
//which causes weld to blow up
interceptorBindingsConsumer.accept(getInterceptorBindings(this.ejbName, beanManager));
}
@Override
public void stop(final StopContext stopContext) {
interceptorBindingsConsumer.accept(null);
}
private InterceptorBindings getInterceptorBindings(final String ejbName, final BeanManagerImpl manager) {
InterceptorBindings retVal = null;
if (ejbName != null) {
retVal = interceptorSupport.getInterceptorBindings(ejbName, manager);
} else {
// This is a managed bean
SlimAnnotatedType<?> type = (SlimAnnotatedType<?>) manager.createAnnotatedType(componentClass);
if (!manager.getInterceptorModelRegistry().containsKey(type)) {
EnhancedAnnotatedType<?> enhancedType = manager.getServices().get(ClassTransformer.class).getEnhancedAnnotatedType(type);
InterceptionModelInitializer.of(manager, enhancedType, null).init();
}
InterceptionModel model = manager.getInterceptorModelRegistry().get(type);
if (model != null) {
retVal = new InterceptorBindingsAdapter(manager.getInterceptorModelRegistry().get(type));
}
}
return retVal != null ? retVal : NullInterceptorBindings.INSTANCE;
}
private static final class NullInterceptorBindings implements InterceptorBindings {
private static final InterceptorBindings INSTANCE = new NullInterceptorBindings();
@Override
public Collection<Interceptor<?>> getAllInterceptors() {
return Collections.emptyList();
}
@Override
public List<Interceptor<?>> getMethodInterceptors(final InterceptionType interceptionType, final Method method) {
return Collections.emptyList();
}
@Override
public List<Interceptor<?>> getLifecycleInterceptors(final InterceptionType interceptionType) {
return Collections.emptyList();
}
}
}
| 4,788 | 42.93578 | 137 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/util/Utils.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.util;
import java.util.Map;
import org.jboss.as.ee.component.Attachments;
import org.jboss.as.ee.component.EEApplicationClasses;
import org.jboss.as.ee.component.EEModuleDescription;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.module.ResourceRoot;
import org.jboss.as.web.common.WebComponentDescription;
/**
* Various utilities for working with WildFly APIs
*
* @author Jozef Hartinger
*
*/
public class Utils {
private Utils() {
}
public static boolean isClassesRoot(ResourceRoot resourceRoot) {
return "classes".equals(resourceRoot.getRootName());
}
/**
* Returns the parent of the given deployment unit if such a parent exists. If the given deployment unit is the parent
* deployment unit, it is returned.
*/
public static DeploymentUnit getRootDeploymentUnit(DeploymentUnit deploymentUnit) {
if (deploymentUnit.getParent() == null) {
return deploymentUnit;
}
return deploymentUnit.getParent();
}
public static String getDeploymentUnitId(DeploymentUnit deploymentUnit) {
String id = deploymentUnit.getName();
if (deploymentUnit.getParent() != null) {
id = deploymentUnit.getParent().getName() + "/" + id;
}
return id;
}
public static void registerAsComponent(String listener, DeploymentUnit deploymentUnit) {
final EEApplicationClasses applicationClasses = deploymentUnit.getAttachment(Attachments.EE_APPLICATION_CLASSES_DESCRIPTION);
final EEModuleDescription module = deploymentUnit.getAttachment(Attachments.EE_MODULE_DESCRIPTION);
final WebComponentDescription componentDescription = new WebComponentDescription(listener, listener, module, deploymentUnit.getServiceName(),
applicationClasses);
module.addComponent(componentDescription);
deploymentUnit.addToAttachmentList(WebComponentDescription.WEB_COMPONENTS, componentDescription.getStartServiceName());
}
public static <K, V> void putIfValueNotNull(Map<K, V> map, K key, V value) {
if (value != null) {
map.put(key, value);
}
}
}
| 3,234 | 38.45122 | 149 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/util/Indices.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.util;
import java.lang.annotation.Inherited;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationTarget;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
/**
* Utilities for working with Jandex indices.
*
* @author Jozef Hartinger
*
*/
public class Indices {
public static final DotName INHERITED_NAME = DotName.createSimple(Inherited.class.getName());
public static final Function<ClassInfo, String> CLASS_INFO_TO_FQCN = new Function<ClassInfo, String>() {
@Override
public String apply(ClassInfo input) {
return input.name().toString();
}
};
public static final Predicate<ClassInfo> ANNOTATION_PREDICATE = new Predicate<ClassInfo>() {
@Override
public boolean test(ClassInfo input) {
return isAnnotation(input);
}
};
private Indices() {
}
private static final int ANNOTATION = 0x00002000;
public static boolean isAnnotation(ClassInfo clazz) {
return (clazz.flags() & ANNOTATION) != 0;
}
/**
* Determines a list of classes the given annotation instances are defined on. If an annotation instance is not defined on a
* class (e.g. on a member) this annotation instance is not reflected anyhow in the resulting list.
*/
public static List<ClassInfo> getAnnotatedClasses(List<AnnotationInstance> instances) {
List<ClassInfo> result = new ArrayList<ClassInfo>();
for (AnnotationInstance instance : instances) {
AnnotationTarget target = instance.target();
if (target instanceof ClassInfo) {
result.add((ClassInfo) target);
}
}
return result;
}
}
| 2,900 | 33.951807 | 128 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/injection/WeldManagedReferenceFactory.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.injection;
import java.io.Serializable;
import jakarta.enterprise.context.spi.CreationalContext;
import org.jboss.as.ee.component.ComponentFactory;
import org.jboss.as.naming.ManagedReference;
import org.jboss.invocation.InterceptorContext;
import org.jboss.weld.construction.api.ConstructionHandle;
/**
* Managed reference factory that can be used to create and inject components.
*
* @author Stuart Douglas
*/
public class WeldManagedReferenceFactory implements ComponentFactory {
public static final WeldManagedReferenceFactory INSTANCE = new WeldManagedReferenceFactory();
private WeldManagedReferenceFactory() {
}
@Override
public ManagedReference create(final InterceptorContext context) {
final ConstructionHandle<?> ctx = context.getPrivateData(ConstructionHandle.class);
final WeldInjectionContext weldCtx = context.getPrivateData(WeldInjectionContext.class);
if (ctx != null) {
// @AroundConstructor interception enabled
Object instance = ctx.proceed(context.getParameters(), context.getContextData()); // let Weld create the instance now
return new WeldManagedReference(weldCtx.getContext(), instance);
} else {
// @AroundConstructor interception handled by Weld alone - no integration with Jakarta Enterprise Beans interceptors
return new WeldManagedReference(weldCtx.getContext(), weldCtx.produce());
}
}
private static final class WeldManagedReference implements ManagedReference, Serializable {
private final CreationalContext<?> context;
private final Object instance;
private WeldManagedReference(final CreationalContext<?> context, final Object instance) {
this.context = context;
this.instance = instance;
}
@Override
public void release() {
context.release();
}
@Override
public Object getInstance() {
return instance;
}
}
}
| 3,062 | 37.772152 | 129 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/injection/SecurityActions.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.injection;
import java.lang.reflect.AccessibleObject;
import java.security.PrivilegedAction;
import org.wildfly.security.manager.WildFlySecurityManager;
import static java.security.AccessController.doPrivileged;
final class SecurityActions {
private SecurityActions() {
// forbidden inheritance
}
static void setAccessible(final AccessibleObject object) {
if (! WildFlySecurityManager.isChecking()) {
object.setAccessible(true);
} else {
doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
object.setAccessible(true);
return null;
}
});
}
}
}
| 1,770 | 34.42 | 70 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/injection/WeldInjectionInterceptor.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.injection;
import org.jboss.as.ee.component.BasicComponentInstance;
import org.jboss.as.ee.component.ComponentInstance;
import org.jboss.as.naming.ManagedReference;
import org.jboss.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
/**
* Class that performs Jakarta Contexts and Dependency Injection and calls initializer methods after resource injection
* has been run
*
* @author Stuart Douglas
*/
public class WeldInjectionInterceptor implements Interceptor {
public static final InterceptorFactory FACTORY = new ImmediateInterceptorFactory(new WeldInjectionInterceptor());
private WeldInjectionInterceptor() {
}
@Override
public Object processInvocation(final InterceptorContext context) throws Exception {
WeldInjectionContext injectionContext = context.getPrivateData(WeldInjectionContext.class);
ManagedReference reference = (ManagedReference) context.getPrivateData(ComponentInstance.class).getInstanceData(BasicComponentInstance.INSTANCE_KEY);
if (reference != null) {
injectionContext.inject(reference.getInstance());
}
return context.proceed();
}
}
| 2,316 | 40.375 | 157 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/injection/ResourceLookupDependenciesProvider.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2021, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.injection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import jakarta.annotation.Resource;
import org.jboss.as.ee.structure.EJBAnnotationPropertyReplacement;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.annotation.CompositeIndex;
import org.jboss.as.weld.spi.DeploymentUnitDependenciesProvider;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationValue;
import org.jboss.jandex.DotName;
import org.jboss.metadata.property.PropertyReplacer;
import org.jboss.msc.service.ServiceName;
import org.kohsuke.MetaInfServices;
/**
* Adds binder service dependencies for any {@link Resource} lookups within java:jboss namespace that are processed by Weld.
* @author Paul Ferraro
*/
@MetaInfServices(DeploymentUnitDependenciesProvider.class)
public class ResourceLookupDependenciesProvider implements DeploymentUnitDependenciesProvider {
private static final DotName RESOURCE_ANNOTATION_NAME = DotName.createSimple(Resource.class.getName());
@Override
public Set<ServiceName> getDependencies(DeploymentUnit unit) {
CompositeIndex index = unit.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX);
PropertyReplacer replacer = EJBAnnotationPropertyReplacement.propertyReplacer(unit);
List<AnnotationInstance> annotations = index.getAnnotations(RESOURCE_ANNOTATION_NAME);
Set<ServiceName> result = !annotations.isEmpty() ? new TreeSet<>() : Collections.emptySet();
for (AnnotationInstance annotation : annotations) {
AnnotationValue lookupValue = annotation.value("lookup");
if (lookupValue != null) {
String lookup = replacer.replaceProperties(lookupValue.asString());
try {
ServiceName name = ContextNames.bindInfoFor(lookup).getBinderServiceName();
if (ContextNames.JBOSS_CONTEXT_SERVICE_NAME.isParentOf(name)) {
result.add(name);
}
} catch (RuntimeException e) {
// No associated naming store
}
}
}
return result;
}
}
| 3,377 | 42.87013 | 124 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/injection/WeldComponentService.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.injection;
import java.util.HashMap;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.function.Supplier;
import jakarta.enterprise.inject.spi.AnnotatedType;
import jakarta.enterprise.inject.spi.Bean;
import jakarta.enterprise.inject.spi.InjectionTarget;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.weld.WeldBootstrapService;
import org.jboss.as.weld.spi.ComponentSupport;
import org.jboss.msc.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.weld.bean.SessionBean;
import org.jboss.weld.ejb.spi.EjbDescriptor;
import org.jboss.weld.injection.producer.InjectionTargetService;
import org.jboss.weld.manager.BeanManagerImpl;
import org.jboss.weld.manager.api.WeldInjectionTarget;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* Interceptor that attaches all the nessesary information for weld injection to the interceptor context
*
* @author Stuart Douglas
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public class WeldComponentService implements Service {
private final Class<?> componentClass;
private final Supplier<WeldBootstrapService> weldContainerSupplier;
private final String ejbName;
private final Set<Class<?>> interceptorClasses;
private final Map<Class<?>, InjectionTarget> interceptorInjections = new HashMap<>();
private final ClassLoader classLoader;
private final String beanDeploymentArchiveId;
private final ComponentDescription componentDescription;
private final boolean isComponentWithView;
/**
* If this is true and bean is not null then weld will create the bean directly, this
* means interceptors and decorators will be applied, which is not wanted for most component
* types.
*/
private final boolean delegateProduce;
private InjectionTarget injectionTarget;
private Bean<?> bean;
private BeanManagerImpl beanManager;
public WeldComponentService(final Supplier<WeldBootstrapService> weldContainerSupplier, final Class<?> componentClass, String ejbName, final Set<Class<?>> interceptorClasses, final ClassLoader classLoader, final String beanDeploymentArchiveId, final boolean delegateProduce, ComponentDescription componentDescription, final boolean isComponentWithView) {
this.weldContainerSupplier = weldContainerSupplier;
this.componentClass = componentClass;
this.ejbName = ejbName;
this.beanDeploymentArchiveId = beanDeploymentArchiveId;
this.delegateProduce = delegateProduce;
this.interceptorClasses = interceptorClasses;
this.classLoader = classLoader;
this.componentDescription = componentDescription;
this.isComponentWithView = isComponentWithView;
}
WeldInjectionContext createInjectionContext() {
return new WeldInjectionContext(beanManager.createCreationalContext(bean), bean, delegateProduce, injectionTarget, interceptorInjections);
}
@Override
public synchronized void start(final StartContext context) throws StartException {
final ClassLoader cl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
try {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader);
beanManager = weldContainerSupplier.get().getBeanManager(beanDeploymentArchiveId);
for (final Class<?> interceptor : interceptorClasses) {
AnnotatedType<?> type = beanManager.createAnnotatedType(interceptor);
@SuppressWarnings("rawtypes")
InjectionTarget injectionTarget = beanManager.getInjectionTargetFactory(type).createInterceptorInjectionTarget();
interceptorInjections.put(interceptor, beanManager.fireProcessInjectionTarget(type, injectionTarget));
}
if (ejbName != null) {
EjbDescriptor<Object> descriptor = beanManager.getEjbDescriptor(ejbName);
//may happen if the Jakarta Enterprise Beans were vetoed
if (descriptor != null) {
bean = beanManager.getBean(descriptor);
}
}
if (bean instanceof SessionBean<?>) {
SessionBean<?> sessionBean = (SessionBean<?>) bean;
this.injectionTarget = sessionBean.getProducer();
return;
}
WeldInjectionTarget<?> injectionTarget = InjectionTargets.createInjectionTarget(componentClass, bean, beanManager, !isComponentWithView);
for (ComponentSupport support : ServiceLoader.load(ComponentSupport.class,
WildFlySecurityManager.getClassLoaderPrivileged(WeldComponentService.class))) {
if (support.isProcessing(componentDescription)) {
this.injectionTarget = support.processInjectionTarget(injectionTarget, componentDescription, beanManager);
break;
}
}
if (this.injectionTarget == null) {
this.injectionTarget = injectionTarget;
}
beanManager.getServices().get(InjectionTargetService.class).validateProducer(injectionTarget);
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(cl);
}
}
@Override
public synchronized void stop(final StopContext context) {
injectionTarget = null;
interceptorInjections.clear();
bean = null;
}
public InjectionTarget getInjectionTarget() {
return injectionTarget;
}
}
| 6,741 | 43.065359 | 358 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/injection/WeldInterceptorInjectionInterceptor.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.injection;
import java.util.Set;
import org.jboss.as.ee.component.ComponentInstance;
import org.jboss.as.naming.ManagedReference;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
/**
* Class that performs Jakarta Contexts and Dependency Injection injection and calls initializer methods on interceptor classes after resource injection
* has been run
*
* @author Stuart Douglas
*/
public class WeldInterceptorInjectionInterceptor implements Interceptor {
private final Set<Class<?>> interceptorClasses;
public WeldInterceptorInjectionInterceptor(final Set<Class<?>> interceptorClasses) {
this.interceptorClasses = interceptorClasses;
}
@Override
public Object processInvocation(final InterceptorContext context) throws Exception {
WeldInjectionContext injectionContext = context.getPrivateData(WeldInjectionContext.class);
final ComponentInstance componentInstance = context.getPrivateData(ComponentInstance.class);
//now inject the interceptors
for (final Class<?> interceptorClass : interceptorClasses) {
final ManagedReference instance = (ManagedReference) componentInstance.getInstanceData(interceptorClass);
if (instance != null) {
injectionContext.injectInterceptor(instance.getInstance());
}
}
return context.proceed();
}
}
| 2,455 | 40.627119 | 152 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/injection/DefaultComponentSupport.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.injection;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.web.common.WebComponentDescription;
import org.jboss.as.weld.spi.ComponentSupport;
/**
*
* @author Martin Kouba
*/
public class DefaultComponentSupport implements ComponentSupport {
@Override
public boolean isProcessing(ComponentDescription componentDescription) {
return componentDescription instanceof WebComponentDescription;
}
}
| 1,488 | 36.225 | 76 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/injection/WeldConstructionStartInterceptor.java | package org.jboss.as.weld.injection;
import java.util.Map;
import jakarta.enterprise.context.spi.CreationalContext;
import jakarta.enterprise.inject.spi.AnnotatedConstructor;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.weld.construction.api.AroundConstructCallback;
import org.jboss.weld.construction.api.ConstructionHandle;
import org.jboss.weld.construction.api.WeldCreationalContext;
/**
* Initiates component construction. This interceptor delegates to Weld to start component construction. When Weld resolves the values of constructor
* parameters, it invokes a callback which allows WF to perform AroundConstruct interception. The callback is registered within
* {@link #setupAroundConstructCallback(CreationalContext, InterceptorContext)}
*
* @author Jozef Hartinger
*
*/
public class WeldConstructionStartInterceptor implements Interceptor {
public static final WeldConstructionStartInterceptor INSTANCE = new WeldConstructionStartInterceptor();
private WeldConstructionStartInterceptor() {
}
@Override
public Object processInvocation(InterceptorContext context) throws Exception {
WeldInjectionContext injectionCtx = context.getPrivateData(WeldInjectionContext.class);
setupAroundConstructCallback(injectionCtx.getContext(), context);
/*
* Here we delegate to Weld to start component construction. WF will be called back on the callback registered within #setupAroundConstructCallback.
* The return value of the following call is not important as we get the component reference from ConstructionContext in WeldManagedReferenceFactory.
*/
injectionCtx.produce();
return context.getTarget();
}
private <T> void setupAroundConstructCallback(CreationalContext<T> ctx, final InterceptorContext context) {
WeldCreationalContext<T> ctxImpl = (WeldCreationalContext<T>) ctx;
ctxImpl.setConstructorInterceptionSuppressed(true); // Weld will not try to invoke around construct interceptors on this instance
ctxImpl.registerAroundConstructCallback(new AroundConstructCallback<T>() {
@SuppressWarnings("unchecked")
@Override
public T aroundConstruct(ConstructionHandle<T> ctx, AnnotatedConstructor<T> constructor, Object[] parameters, Map<String, Object> data) throws Exception {
context.putPrivateData(ConstructionHandle.class, ctx);
context.setParameters(parameters);
context.setContextData(data);
context.setConstructor(constructor.getJavaMember());
context.proceed(); // proceed with the WF interceptor chain
return (T) context.getTarget();
}
});
}
}
| 2,806 | 45.783333 | 166 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/injection/WeldInjectionContextInterceptor.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.injection;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
/**
* Interceptor that attaches all the nessesary information for weld injection to the interceptor context
*
* @author Stuart Douglas
*/
public class WeldInjectionContextInterceptor implements Interceptor {
private final WeldComponentService weldComponentService;
public WeldInjectionContextInterceptor(final WeldComponentService weldComponentService) {
this.weldComponentService = weldComponentService;
}
@Override
public Object processInvocation(final InterceptorContext context) throws Exception {
context.putPrivateData(WeldInjectionContext.class, weldComponentService.createInjectionContext());
return context.proceed();
}
}
| 1,830 | 38.804348 | 106 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/injection/InjectionTargets.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.injection;
import static java.security.AccessController.doPrivileged;
import jakarta.enterprise.inject.spi.Bean;
import org.jboss.weld.annotated.enhanced.EnhancedAnnotatedType;
import org.jboss.weld.manager.BeanManagerImpl;
import org.jboss.weld.manager.api.WeldInjectionTarget;
import org.jboss.weld.manager.api.WeldInjectionTargetBuilder;
import org.jboss.weld.resources.ClassTransformer;
import org.jboss.weld.util.Beans;
import org.wildfly.security.manager.WildFlySecurityManager;
import org.wildfly.security.manager.action.GetClassLoaderAction;
/**
* Utility class for working with Jakarta Contexts and Dependency Injection InjectionTargets
*
* @author Jozef Hartinger
*
*/
public class InjectionTargets {
private InjectionTargets() {
}
/**
* Creates a new InjectionTarget for a given class. If the interceptionSupport flag is set to true the resulting instance will support
* interception (support provided by Weld). If an InjectionTarget is created for a component where interception support is implemented
* through component's view (Jakarta Enterprise Beans, managed beans) the flag must be set to false.
*
* @param componentClass
* @param bean
* @param beanManager
* @param interceptionSupport
* @return
*/
public static <T> WeldInjectionTarget<T> createInjectionTarget(Class<?> componentClass, Bean<T> bean, BeanManagerImpl beanManager,
boolean interceptionSupport) {
final ClassTransformer transformer = beanManager.getServices().get(ClassTransformer.class);
@SuppressWarnings("unchecked")
final Class<T> clazz = (Class<T>) componentClass;
EnhancedAnnotatedType<T> type = transformer.getEnhancedAnnotatedType(clazz, beanManager.getId());
if (!type.getJavaClass().equals(componentClass)) {
/*
* Jasper loads a class with multiple classloaders which is not supported by Weld.
* If this happens, use a combination of a bean archive identifier and class' classloader hashCode as the BDA ID.
* This breaks AnnotatedType serialization but that does not matter as these are non-contextual components.
*/
final ClassLoader classLoader = WildFlySecurityManager.isChecking() ? doPrivileged(new GetClassLoaderAction(componentClass)) : componentClass.getClassLoader();
final String bdaId = beanManager.getId() + classLoader.hashCode();
type = transformer.getEnhancedAnnotatedType(clazz, bdaId);
}
if (Beans.getBeanConstructor(type) == null) {
/*
* For example, AsyncListeners may be Jakarta Contexts and Dependency Injection incompatible as long as the application never calls javax.servletAsyncContext#createListener(Class)
* and only instantiates the listener itself.
*/
return beanManager.getInjectionTargetFactory(type).createNonProducibleInjectionTarget();
}
WeldInjectionTargetBuilder<T> builder = beanManager.createInjectionTargetBuilder(type);
builder.setBean(bean);
builder.setResourceInjectionEnabled(false); // because these are all EE components where resource injection is not handled by Weld
if (interceptionSupport) {
return builder.build();
} else {
// suppress interception/decoration because this is a component for which WF provides interception support
return builder.setInterceptionEnabled(false).setTargetClassLifecycleCallbacksEnabled(false).setDecorationEnabled(false).build();
}
}
}
| 4,646 | 47.915789 | 191 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/injection/WeldInjectionContext.java | package org.jboss.as.weld.injection;
import java.io.Serializable;
import java.util.Map;
import jakarta.enterprise.context.spi.CreationalContext;
import jakarta.enterprise.inject.spi.Bean;
import jakarta.enterprise.inject.spi.InjectionTarget;
import org.jboss.as.weld.logging.WeldLogger;
import org.jboss.weld.bean.ManagedBean;
/**
* @author Stuart Douglas
*/
class WeldInjectionContext implements Serializable {
private final CreationalContext<?> context;
private final Bean<?> bean;
private final boolean delegateProduce;
//the following fields are transient, as they are only needed at creation time,
//and should not be needed after injection is complete
private final transient InjectionTarget injectionTarget;
private final transient Map<Class<?>, InjectionTarget> interceptorInjections;
WeldInjectionContext(CreationalContext<?> ctx, final Bean<?> bean, final boolean delegateProduce, final InjectionTarget injectionTarget, final Map<Class<?>, InjectionTarget> interceptorInjections) {
this.context = ctx;
this.bean = bean;
this.delegateProduce = delegateProduce;
this.injectionTarget = injectionTarget;
this.interceptorInjections = interceptorInjections;
}
/**
* Runs Jakarta Contexts and Dependency Injection on the instance. This should be called after resource injection has been performed
*/
public void inject(Object instance) {
injectionTarget.inject(instance, context);
}
public Object produce() {
if (delegateProduce && bean instanceof ManagedBean) {
return ((ManagedBean) bean).getInjectionTarget().produce(context);
} else {
return injectionTarget.produce(context);
}
}
public void injectInterceptor(Object instance) {
final InjectionTarget injection = interceptorInjections.get(instance.getClass());
if (injection != null) {
injection.inject(instance, context);
} else {
throw WeldLogger.ROOT_LOGGER.unknownInterceptorClassForCDIInjection(instance.getClass());
}
}
public CreationalContext<?> getContext() {
return context;
}
public InjectionTarget getInjectionTarget() {
return injectionTarget;
}
public void release() {
context.release();
}
}
| 2,352 | 32.140845 | 202 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/webtier/jsp/WeldJspExpressionFactoryWrapper.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2008, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.webtier.jsp;
import jakarta.el.ELContextListener;
import jakarta.el.ExpressionFactory;
import jakarta.enterprise.inject.spi.BeanManager;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import jakarta.servlet.ServletContext;
import jakarta.servlet.jsp.JspApplicationContext;
import jakarta.servlet.jsp.JspFactory;
import org.jboss.as.web.common.ExpressionFactoryWrapper;
import org.jboss.as.weld.util.Reflections;
/**
* The Web Beans Jakarta Server Pages initialization listener
*
* @author Pete Muir
* @author Stuart Douglas
*/
public class WeldJspExpressionFactoryWrapper implements ExpressionFactoryWrapper {
public static final WeldJspExpressionFactoryWrapper INSTANCE = new WeldJspExpressionFactoryWrapper();
@Override
public ExpressionFactory wrap(ExpressionFactory expressionFactory, ServletContext servletContext) {
BeanManager beanManager = getBeanManager();
if(beanManager == null) {
//this should never happen
return expressionFactory;
}
// get JspApplicationContext.
JspApplicationContext jspAppContext = JspFactory.getDefaultFactory().getJspApplicationContext( servletContext);
// register compositeELResolver with Jakarta Server Pages
jspAppContext.addELResolver(beanManager.getELResolver());
jspAppContext.addELContextListener(Reflections.<ELContextListener>newInstance("org.jboss.weld.module.web.el.WeldELContextListener", getClass().getClassLoader()));
return beanManager.wrapExpressionFactory(expressionFactory);
}
private BeanManager getBeanManager() {
try {
return (BeanManager) new InitialContext().lookup("java:comp/BeanManager");
} catch (NamingException e) {
return null;
}
}
}
| 2,850 | 38.597222 | 170 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/discovery/AnnotationType.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.discovery;
import java.lang.annotation.Annotation;
import java.lang.annotation.Inherited;
import java.util.function.Function;
import org.jboss.as.weld.util.Indices;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
public class AnnotationType {
public static final Function<AnnotationType, String> TO_FQCN = new Function<AnnotationType, String>() {
@Override
public String apply(AnnotationType input) {
return input.name.toString();
}
};
public static final Function<ClassInfo, AnnotationType> FOR_CLASSINFO = new Function<ClassInfo, AnnotationType>() {
@Override
public AnnotationType apply(ClassInfo clazz) {
return new AnnotationType(clazz.name(), clazz.annotationsMap().containsKey(Indices.INHERITED_NAME));
}
};
private final DotName name;
private final boolean inherited;
public AnnotationType(DotName name, boolean inherited) {
this.name = name;
this.inherited = inherited;
}
public AnnotationType(Class<? extends Annotation> annotation) {
this.name = DotName.createSimple(annotation.getName());
this.inherited = annotation.isAnnotationPresent(Inherited.class);
}
public DotName getName() {
return name;
}
public boolean isInherited() {
return inherited;
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof AnnotationType) {
AnnotationType that = (AnnotationType) obj;
return this.name.equals(that.name);
}
return false;
}
@Override
public String toString() {
return "AnnotationType [name=" + name + ", inherited=" + inherited + "]";
}
} | 2,930 | 31.566667 | 119 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/discovery/WeldClassFileServices.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.discovery;
import java.lang.annotation.Annotation;
import java.util.Set;
import java.util.function.Function;
import org.jboss.as.server.deployment.annotation.CompositeIndex;
import org.jboss.as.weld.logging.WeldLogger;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.weld.resources.spi.ClassFileInfo;
import org.jboss.weld.resources.spi.ClassFileServices;
import org.jboss.weld.util.cache.ComputingCache;
import org.jboss.weld.util.cache.ComputingCacheBuilder;
import org.jboss.weld.util.collections.ImmutableSet;
/**
*
* @author Martin Kouba
*/
public class WeldClassFileServices implements ClassFileServices {
private CompositeIndex index;
private ComputingCache<DotName, Set<String>> annotationClassAnnotationsCache;
private final ClassLoader moduleClassLoader;
private class AnnotationClassAnnotationLoader implements Function<DotName, Set<String>> {
@Override
public Set<String> apply(DotName name) {
ClassInfo annotationClassInfo = index.getClassByName(name);
ImmutableSet.Builder<String> builder = ImmutableSet.builder();
if (annotationClassInfo != null) {
for (DotName annotationName : annotationClassInfo.annotationsMap().keySet()) {
builder.add(annotationName.toString());
}
} else {
try {
Class<?> annotationClass = moduleClassLoader.loadClass(name.toString());
for (Annotation annotation : annotationClass.getDeclaredAnnotations()) {
builder.add(annotation.annotationType().getName());
}
} catch (ClassNotFoundException e) {
WeldLogger.DEPLOYMENT_LOGGER.unableToLoadAnnotation(name.toString());
}
}
return builder.build();
}
}
/**
*
* @param index
*/
public WeldClassFileServices(CompositeIndex index, ClassLoader moduleClassLoader) {
if (index == null) {
throw WeldLogger.ROOT_LOGGER.cannotUseAtRuntime(ClassFileServices.class.getSimpleName());
}
this.moduleClassLoader = moduleClassLoader;
this.index = index;
this.annotationClassAnnotationsCache = ComputingCacheBuilder.newBuilder().build(new AnnotationClassAnnotationLoader());
}
@Override
public ClassFileInfo getClassFileInfo(String className) {
return new WeldClassFileInfo(className, index, annotationClassAnnotationsCache, moduleClassLoader);
}
@Override
public void cleanupAfterBoot() {
if (annotationClassAnnotationsCache != null) {
annotationClassAnnotationsCache.clear();
annotationClassAnnotationsCache = null;
}
index = null;
}
@Override
public void cleanup() {
cleanupAfterBoot();
}
}
| 3,962 | 35.694444 | 127 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/discovery/WeldClassFileInfo.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.discovery;
import org.jboss.as.server.deployment.annotation.CompositeIndex;
import org.jboss.as.weld.logging.WeldLogger;
import org.jboss.as.weld.util.Reflections;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationTarget;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.MethodInfo;
import org.jboss.weld.resources.spi.ClassFileInfo;
import org.jboss.weld.util.cache.ComputingCache;
import jakarta.enterprise.inject.Vetoed;
import jakarta.inject.Inject;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.List;
import java.util.Set;
/**
*
* @author Martin Kouba
*/
public class WeldClassFileInfo implements ClassFileInfo {
private static final DotName DOT_NAME_INJECT = DotName.createSimple(Inject.class.getName());
private static final DotName DOT_NAME_VETOED = DotName.createSimple(Vetoed.class.getName());
private static final DotName OBJECT_NAME = DotName.createSimple(Object.class.getName());
private static final String CONSTRUCTOR_METHOD_NAME = "<init>";
private static final String PACKAGE_INFO_NAME = "package-info";
private final ClassInfo classInfo;
private final CompositeIndex index;
private final boolean isVetoed;
private final boolean hasCdiConstructor;
private final ComputingCache<DotName, Set<String>> annotationClassAnnotationsCache;
private final ClassLoader classLoader;
/**
*
* @param className
* @param index
* @param annotationClassAnnotationsCache
*/
public WeldClassFileInfo(String className, CompositeIndex index, ComputingCache<DotName, Set<String>> annotationClassAnnotationsCache, ClassLoader classLoader) {
this.index = index;
this.annotationClassAnnotationsCache = annotationClassAnnotationsCache;
this.classInfo = index.getClassByName(DotName.createSimple(className));
if (this.classInfo == null) {
throw WeldLogger.ROOT_LOGGER.nameNotFoundInIndex(className);
}
this.isVetoed = isVetoedTypeOrPackage();
this.hasCdiConstructor = this.classInfo.hasNoArgsConstructor() || hasInjectConstructor();
this.classLoader = classLoader;
}
@Override
public String getClassName() {
return classInfo.name().toString();
}
@Override
public boolean isAnnotationDeclared(Class<? extends Annotation> annotation) {
return isAnnotationDeclared(classInfo, annotation);
}
@Override
public boolean containsAnnotation(Class<? extends Annotation> annotation) {
return containsAnnotation(classInfo, DotName.createSimple(annotation.getName()), annotation);
}
@Override
public int getModifiers() {
return classInfo.flags();
}
@Override
public boolean hasCdiConstructor() {
return hasCdiConstructor;
}
@Override
public boolean isAssignableFrom(Class<?> fromClass) {
return isAssignableFrom(getClassName(), fromClass);
}
@Override
public boolean isAssignableTo(Class<?> toClass) {
return isAssignableTo(classInfo.name(), toClass);
}
@Override
public boolean isVetoed() {
return isVetoed;
}
@Override
public ClassFileInfo.NestingType getNestingType() {
NestingType result = null;
switch (classInfo.nestingType()) {
case ANONYMOUS:
result = NestingType.NESTED_ANONYMOUS;
break;
case TOP_LEVEL:
result = NestingType.TOP_LEVEL;
break;
case LOCAL:
result = NestingType.NESTED_LOCAL;
break;
case INNER:
if (Modifier.isStatic(classInfo.flags())) {
result = NestingType.NESTED_STATIC;
} else {
result = NestingType.NESTED_INNER;
}
break;
default:
// should never happer
break;
}
return result;
}
@Override
public String getSuperclassName() {
return classInfo.superName().toString();
}
private boolean isVetoedTypeOrPackage() {
if (isAnnotationDeclared(classInfo, DOT_NAME_VETOED)) {
return true;
}
final DotName packageInfoName = DotName.createComponentized(getPackageName(classInfo.name()), PACKAGE_INFO_NAME);
ClassInfo packageInfo = index.getClassByName(packageInfoName);
if (packageInfo != null && isAnnotationDeclared(packageInfo, DOT_NAME_VETOED)) {
return true;
}
return false;
}
private boolean isAnnotationDeclared(ClassInfo classInfo, Class<? extends Annotation> annotation) {
return isAnnotationDeclared(classInfo, DotName.createSimple(annotation.getName()));
}
private boolean isAnnotationDeclared(ClassInfo classInfo, DotName requiredAnnotationName) {
List<AnnotationInstance> annotations = classInfo.annotationsMap().get(requiredAnnotationName);
if (annotations != null) {
for (AnnotationInstance annotationInstance : annotations) {
if (annotationInstance.target().equals(classInfo)) {
return true;
}
}
}
return false;
}
private boolean hasInjectConstructor() {
List<AnnotationInstance> annotationInstances = classInfo.annotationsMap().get(DOT_NAME_INJECT);
if (annotationInstances != null) {
for (AnnotationInstance instance : annotationInstances) {
AnnotationTarget target = instance.target();
if (target instanceof MethodInfo) {
MethodInfo methodInfo = (MethodInfo) target;
if (methodInfo.name().equals(CONSTRUCTOR_METHOD_NAME)) {
return true;
}
}
}
}
return false;
}
private DotName getPackageName(DotName name) {
if (name.isComponentized()) {
while (name.isInner()) {
name = name.prefix();
if (name == null) {
throw new IllegalStateException("Could not determine package from corrupted class name");
}
}
return name.prefix();
} else {
final int lastIndex = name.local().lastIndexOf(".");
if (lastIndex == -1) {
return name;
}
return DotName.createSimple(name.local().substring(0, name.local().lastIndexOf(".")));
}
}
/**
* @param className
* @param fromClass
* @return
*/
private boolean isAssignableFrom(String className, Class<?> fromClass) {
if (className.equals(fromClass.getName())) {
return true;
}
if (Object.class.equals(fromClass)) {
return false; // there's nothing assignable from Object.class except for Object.class
}
Class<?> superClass = fromClass.getSuperclass();
if (superClass != null && isAssignableFrom(className, superClass)) {
return true;
}
for (Class<?> interfaceClass : fromClass.getInterfaces()) {
if (isAssignableFrom(className, interfaceClass)) {
return true;
}
}
return false;
}
/**
* @param to
* @param name
* @return <code>true</code> if the name is equal to the fromName, or if the name represents a superclass or superinterface of the fromName,
* <code>false</code> otherwise
*/
private boolean isAssignableTo(DotName name, Class<?> to) {
if (to.getName().equals(name.toString())) {
return true;
}
if (OBJECT_NAME.equals(name)) {
return false; // there's nothing assignable from Object.class except for Object.class
}
ClassInfo fromClassInfo = index.getClassByName(name);
if (fromClassInfo == null) {
// We reached a class that is not in the index. Let's use reflection.
final Class<?> clazz = loadClass(name.toString());
return to.isAssignableFrom(clazz);
}
DotName superName = fromClassInfo.superName();
if (superName != null && isAssignableTo(superName, to)) {
return true;
}
for (DotName interfaceName : fromClassInfo.interfaceNames()) {
if (isAssignableTo(interfaceName, to)) {
return true;
}
}
return false;
}
private boolean containsAnnotation(ClassInfo classInfo, DotName requiredAnnotationName, Class<? extends Annotation> requiredAnnotation) {
// Type and members
if (classInfo.annotationsMap().containsKey(requiredAnnotationName)) {
return true;
}
// Meta-annotations
for (DotName annotation : classInfo.annotationsMap().keySet()) {
if (annotationClassAnnotationsCache.getValue(annotation).contains(requiredAnnotationName.toString())) {
return true;
}
}
// Superclass
final DotName superName = classInfo.superName();
if (superName != null && !OBJECT_NAME.equals(superName)) {
final ClassInfo superClassInfo = index.getClassByName(superName);
if (superClassInfo == null) {
// we are accessing a class that is outside of the jandex index
// fallback to using reflection
return Reflections.containsAnnotation(loadClass(superName.toString()), requiredAnnotation);
}
if (containsAnnotation(superClassInfo, requiredAnnotationName, requiredAnnotation)) {
return true;
}
}
// Also check default methods on interfaces
for (DotName interfaceName : classInfo.interfaceNames()) {
final ClassInfo interfaceInfo = index.getClassByName(interfaceName);
if (interfaceInfo == null) {
// we are accessing a class that is outside of the jandex index
// fallback to using reflection
Class<?> interfaceClass = loadClass(interfaceName.toString());
for (Method method : interfaceClass.getDeclaredMethods()) {
if (method.isDefault() && Reflections.containsAnnotations(method.getAnnotations(), requiredAnnotation)) {
return true;
}
}
continue;
}
for (MethodInfo method : interfaceInfo.methods()) {
// Default methods are public non-abstract instance methods declared in an interface
if (isNonAbstractPublicInstanceMethod(method)) {
if (method.hasAnnotation(requiredAnnotationName)) {
return true;
}
// Meta-annotations
for (AnnotationInstance annotation : method.annotations()) {
if (annotationClassAnnotationsCache.getValue(annotation.name()).contains(requiredAnnotationName.toString())) {
return true;
}
}
}
}
}
return false;
}
private boolean isNonAbstractPublicInstanceMethod(MethodInfo method) {
return (method.flags() & (Modifier.ABSTRACT | Modifier.PUBLIC | Modifier.STATIC)) == Modifier.PUBLIC;
}
private Class<?> loadClass(String className) {
WeldLogger.DEPLOYMENT_LOGGER.tracef("Falling back to reflection for %s", className);
try {
return classLoader.loadClass(className);
} catch (ClassNotFoundException e) {
throw WeldLogger.ROOT_LOGGER.cannotLoadClass(className, e);
}
}
@Override
public String toString() {
return classInfo.toString();
}
}
| 13,125 | 35.15978 | 165 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/interceptors/Jsr299BindingsCreateInterceptor.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2009, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.interceptors;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;
import jakarta.enterprise.context.spi.CreationalContext;
import jakarta.enterprise.inject.spi.Interceptor;
import org.jboss.as.ee.component.ComponentInstance;
import org.jboss.as.weld.WeldBootstrapService;
import org.jboss.as.weld.spi.ComponentInterceptorSupport;
import org.jboss.as.weld.spi.InterceptorInstances;
import org.jboss.invocation.InterceptorContext;
import org.jboss.weld.bean.SessionBean;
import org.jboss.weld.ejb.spi.EjbDescriptor;
import org.jboss.weld.ejb.spi.InterceptorBindings;
import org.jboss.weld.manager.BeanManagerImpl;
import org.jboss.weld.serialization.spi.ContextualStore;
import org.jboss.weld.serialization.spi.helpers.SerializableContextualInstance;
/**
* Interceptor that creates the CDI interceptors and attaches them to the component
*
* @author Marius Bogoevici
* @author Stuart Douglas
* @author <a href="mailto:[email protected]>Richard Opalka</a>
*/
public class Jsr299BindingsCreateInterceptor implements org.jboss.invocation.Interceptor {
private final Supplier<WeldBootstrapService> weldContainerSupplier;
private final Supplier<InterceptorBindings> interceptorBindingsSupplier;
private final String beanArchiveId;
private final String ejbName;
private final ComponentInterceptorSupport interceptorSupport;
private volatile BeanManagerImpl beanManager;
public Jsr299BindingsCreateInterceptor(final Supplier<WeldBootstrapService> weldContainerSupplier,
final Supplier<InterceptorBindings> interceptorBindingsSupplier,
final String beanArchiveId, final String ejbName,
final ComponentInterceptorSupport interceptorSupport) {
this.weldContainerSupplier = weldContainerSupplier;
this.interceptorBindingsSupplier = interceptorBindingsSupplier;
this.beanArchiveId = beanArchiveId;
this.ejbName = ejbName;
this.interceptorSupport = interceptorSupport;
}
private void addInterceptorInstance(Interceptor<Object> interceptor, BeanManagerImpl beanManager, Map<String, SerializableContextualInstance<Interceptor<Object>, Object>> instances, final CreationalContext<Object> creationalContext) {
Object instance = beanManager.getReference(interceptor, interceptor.getBeanClass(), creationalContext, true);
SerializableContextualInstance<Interceptor<Object>, Object> serializableContextualInstance
= beanManager.getServices().get(ContextualStore.class).<Interceptor<Object>, Object>getSerializableContextualInstance(interceptor, instance, creationalContext);
instances.put(interceptor.getBeanClass().getName(), serializableContextualInstance);
}
@Override
public Object processInvocation(InterceptorContext interceptorContext) throws Exception {
BeanManagerImpl beanManager = this.beanManager;
if(beanManager == null) {
//cache the BM lookup, as it is quite slow
beanManager = this.beanManager = weldContainerSupplier.get().getBeanManager(beanArchiveId);
}
//this is not always called with the deployments TCCL set
//which causes weld to blow up
SessionBean<Object> bean = null;
if (ejbName != null) {
EjbDescriptor<Object> descriptor = beanManager.getEjbDescriptor(this.ejbName);
if (descriptor != null) {
bean = beanManager.getBean(descriptor);
}
}
InterceptorBindings interceptorBindings = interceptorBindingsSupplier.get();
final ComponentInstance componentInstance = interceptorContext.getPrivateData(ComponentInstance.class);
InterceptorInstances existing = interceptorSupport.getInterceptorInstances(componentInstance);
if (existing == null) {
CreationalContext<Object> creationalContext = beanManager.createCreationalContext(bean);
HashMap<String, SerializableContextualInstance<Interceptor<Object>, Object>> interceptorInstances = new HashMap<String, SerializableContextualInstance<Interceptor<Object>, Object>>();
if (interceptorBindings != null) {
for (Interceptor<?> interceptor : interceptorBindings.getAllInterceptors()) {
addInterceptorInstance((Interceptor<Object>) interceptor, beanManager, interceptorInstances, creationalContext);
}
}
interceptorSupport.setInterceptorInstances(componentInstance, new WeldInterceptorInstances(creationalContext, interceptorInstances));
}
return interceptorContext.proceed();
}
}
| 5,780 | 49.269565 | 238 | java |
null | wildfly-main/weld/ejb/src/main/java/org/jboss/as/weld/_private/WeldEjbLogger.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2016, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld._private;
import jakarta.ejb.NoSuchEJBException;
import org.jboss.logging.BasicLogger;
import org.jboss.logging.Logger;
import org.jboss.logging.annotations.Message;
import org.jboss.logging.annotations.MessageLogger;
@MessageLogger(projectCode = "WFLYWELDEJB", length = 4)
public interface WeldEjbLogger extends BasicLogger {
WeldEjbLogger ROOT_LOGGER = Logger.getMessageLogger(WeldEjbLogger.class, "org.jboss.as.weld.ejb");
@Message(id = 1, value = "EJB has been removed: %s")
NoSuchEJBException ejbHashBeenRemoved(Object ejbComponent);
}
| 1,609 | 38.268293 | 102 | java |
null | wildfly-main/weld/ejb/src/main/java/org/jboss/as/weld/deployment/processors/EjbImplicitBeanArchiveDetector.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment.processors;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.ejb3.component.session.SessionBeanComponentDescription;
import org.jboss.as.weld.spi.ImplicitBeanArchiveDetector;
/**
*
* @author Martin Kouba
*/
public class EjbImplicitBeanArchiveDetector implements ImplicitBeanArchiveDetector {
@Override
public boolean isImplicitBeanArchiveRequired(ComponentDescription description) {
return description instanceof SessionBeanComponentDescription;
}
}
| 1,556 | 37.925 | 84 | java |
null | wildfly-main/weld/ejb/src/main/java/org/jboss/as/weld/deployment/processors/EjbModuleServiceProvider.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment.processors;
import java.util.Collection;
import java.util.Collections;
import org.jboss.as.ee.structure.DeploymentType;
import org.jboss.as.ee.structure.DeploymentTypeMarker;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.module.ResourceRoot;
import org.jboss.as.weld.services.bootstrap.WeldEjbInjectionServices;
import org.jboss.as.weld.spi.ModuleServicesProvider;
import org.jboss.modules.Module;
import org.jboss.weld.bootstrap.api.Service;
/**
*
* @author Martin Kouba
*/
public class EjbModuleServiceProvider implements ModuleServicesProvider {
@Override
public Collection<Service> getServices(DeploymentUnit rootDeploymentUnit, DeploymentUnit deploymentUnit, Module module, ResourceRoot resourceRoot) {
if (resourceRoot == null) {
return Collections.emptySet();
}
return Collections.singleton(new WeldEjbInjectionServices(rootDeploymentUnit.getServiceRegistry(),
rootDeploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION),
rootDeploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.EE_APPLICATION_DESCRIPTION), resourceRoot.getRoot(), module,
DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit)));
}
}
| 2,369 | 42.888889 | 152 | java |
null | wildfly-main/weld/ejb/src/main/java/org/jboss/as/weld/deployment/processors/EjbComponentDescriptionProcessor.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment.processors;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.ejb3.component.EJBComponentDescription;
import org.jboss.as.server.deployment.module.ResourceRoot;
import org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex;
import org.jboss.as.weld.ejb.EjbDescriptorImpl;
import org.jboss.as.weld.spi.ComponentDescriptionProcessor;
import org.jboss.as.weld.spi.WildFlyBeanDeploymentArchive;
import org.jboss.weld.util.collections.Multimap;
import org.jboss.weld.util.collections.SetMultimap;
/**
*
* @author Martin Kouba
*/
public class EjbComponentDescriptionProcessor implements ComponentDescriptionProcessor {
private final Multimap<ResourceRoot, EJBComponentDescription> ejbComponentDescriptions = SetMultimap.newSetMultimap();
@Override
public void processComponentDescription(ResourceRoot resourceRoot, ComponentDescription component) {
if (component instanceof EJBComponentDescription) {
ejbComponentDescriptions.put(resourceRoot, (EJBComponentDescription) component);
}
}
@Override
public boolean hasBeanComponents(ResourceRoot resourceRoot) {
return !ejbComponentDescriptions.get(resourceRoot).isEmpty();
}
@Override
public void registerComponents(ResourceRoot resourceRoot, WildFlyBeanDeploymentArchive beanDeploymentArchive, DeploymentReflectionIndex reflectionIndex) {
for (EJBComponentDescription ejb : ejbComponentDescriptions.get(resourceRoot)) {
beanDeploymentArchive.addEjbDescriptor(new EjbDescriptorImpl<Object>(ejb, beanDeploymentArchive, reflectionIndex));
beanDeploymentArchive.addBeanClass(ejb.getComponentClassName());
}
}
}
| 2,763 | 42.873016 | 158 | java |
null | wildfly-main/weld/ejb/src/main/java/org/jboss/as/weld/deployment/processors/EjbComponentIntegrator.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment.processors;
import static org.jboss.as.weld.interceptors.Jsr299BindingsInterceptor.factory;
import java.util.function.Supplier;
import jakarta.enterprise.inject.spi.InterceptionType;
import org.jboss.as.ee.component.ComponentConfiguration;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.ee.component.interceptors.InterceptorOrder;
import org.jboss.as.ee.managedbean.component.ManagedBeanComponentDescription;
import org.jboss.as.ejb3.component.EJBComponentDescription;
import org.jboss.as.ejb3.component.stateful.SerializedCdiInterceptorsKey;
import org.jboss.as.ejb3.component.stateful.StatefulComponentDescription;
import org.jboss.as.weld.spi.ComponentIntegrator;
import org.jboss.as.weld.spi.ComponentInterceptorSupport;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
/**
*
* @author Martin Kouba
*/
public class EjbComponentIntegrator implements ComponentIntegrator {
@Override
public boolean isBeanNameRequired(ComponentDescription description) {
return description instanceof EJBComponentDescription;
}
@Override
public boolean isComponentWithView(ComponentDescription description) {
return (description instanceof EJBComponentDescription) || (description instanceof ManagedBeanComponentDescription);
}
@Override
public boolean integrate(ServiceName beanManagerServiceName, ComponentConfiguration configuration, ComponentDescription description,
ServiceBuilder<?> weldComponentServiceBuilder, Supplier<ServiceName> bindingServiceNameSupplier,
DefaultInterceptorIntegrationAction integrationAction, ComponentInterceptorSupport interceptorSupport) {
if (description instanceof EJBComponentDescription) {
ServiceName bindingServiceName = bindingServiceNameSupplier.get();
integrationAction.perform(bindingServiceName);
if (description.isPassivationApplicable()) {
configuration.addPrePassivateInterceptor(
factory(InterceptionType.PRE_PASSIVATE, weldComponentServiceBuilder, bindingServiceName, interceptorSupport),
InterceptorOrder.ComponentPassivation.CDI_INTERCEPTORS);
configuration.addPostActivateInterceptor(
factory(InterceptionType.POST_ACTIVATE, weldComponentServiceBuilder, bindingServiceName, interceptorSupport),
InterceptorOrder.ComponentPassivation.CDI_INTERCEPTORS);
}
if (description instanceof StatefulComponentDescription) {
// add a context key for weld interceptor replication
configuration.getInterceptorContextKeys().add(SerializedCdiInterceptorsKey.class);
}
return true;
} else if (description instanceof ManagedBeanComponentDescription) {
integrationAction.perform(bindingServiceNameSupplier.get());
return true;
}
return false;
}
}
| 4,071 | 46.348837 | 136 | java |
null | wildfly-main/weld/ejb/src/main/java/org/jboss/as/weld/services/bootstrap/WeldEjbServices.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.services.bootstrap;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.jboss.as.weld.ejb.EjbDescriptorImpl;
import org.jboss.as.weld.ejb.SessionObjectReferenceImpl;
import org.jboss.as.weld.ejb.StatefulSessionObjectReferenceImpl;
import org.jboss.weld.ejb.api.SessionObjectReference;
import org.jboss.weld.ejb.spi.EjbDescriptor;
import org.jboss.weld.ejb.spi.EjbServices;
import org.jboss.weld.ejb.spi.InterceptorBindings;
/**
* EjbServices implementation
*/
public class WeldEjbServices implements EjbServices {
private volatile Map<String, InterceptorBindings> bindings = Collections.emptyMap();
@Override
public synchronized void registerInterceptors(EjbDescriptor<?> ejbDescriptor, InterceptorBindings interceptorBindings) {
final Map<String, InterceptorBindings> bindings = new HashMap<String, InterceptorBindings>(this.bindings);
bindings.put(ejbDescriptor.getEjbName(), interceptorBindings);
this.bindings = bindings;
}
@Override
public SessionObjectReference resolveEjb(EjbDescriptor<?> ejbDescriptor) {
if (ejbDescriptor.isStateful()) {
return new StatefulSessionObjectReferenceImpl((EjbDescriptorImpl<?>) ejbDescriptor);
} else {
return new SessionObjectReferenceImpl((EjbDescriptorImpl<?>) ejbDescriptor);
}
}
@Override
public void cleanup() {
bindings.clear();
}
public InterceptorBindings getBindings(String ejbName) {
return bindings.get(ejbName);
}
}
| 2,592 | 37.132353 | 124 | java |
null | wildfly-main/weld/ejb/src/main/java/org/jboss/as/weld/services/bootstrap/WeldEjbInjectionServices.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.services.bootstrap;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Set;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import jakarta.ejb.EJB;
import jakarta.enterprise.inject.Produces;
import jakarta.enterprise.inject.spi.InjectionPoint;
import org.jboss.as.ee.component.ComponentView;
import org.jboss.as.ee.component.EEApplicationDescription;
import org.jboss.as.ee.component.EEModuleDescription;
import org.jboss.as.ee.component.ViewDescription;
import org.jboss.as.naming.ManagedReference;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.as.naming.deployment.ContextNames.BindInfo;
import org.jboss.as.weld.logging.WeldLogger;
import org.jboss.as.weld.util.ResourceInjectionUtilities;
import org.jboss.modules.Module;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceRegistry;
import org.jboss.vfs.VirtualFile;
import org.jboss.weld.injection.spi.EjbInjectionServices;
import org.jboss.weld.injection.spi.ResourceReference;
import org.jboss.weld.injection.spi.ResourceReferenceFactory;
import org.jboss.weld.injection.spi.helpers.SimpleResourceReference;
import org.jboss.weld.logging.BeanLogger;
import org.jboss.weld.util.reflection.Reflections;
/**
* Implementation of EjbInjectionServices.
*
* @author Stuart Douglas
*/
public class WeldEjbInjectionServices extends AbstractResourceInjectionServices implements EjbInjectionServices {
private final EEApplicationDescription applicationDescription;
private final VirtualFile deploymentRoot;
private final boolean warModule;
public WeldEjbInjectionServices(ServiceRegistry serviceRegistry, EEModuleDescription moduleDescription, final EEApplicationDescription applicationDescription, final VirtualFile deploymentRoot, Module module, boolean warModule) {
super(serviceRegistry, moduleDescription, module);
this.warModule = warModule;
if (serviceRegistry == null) {
throw WeldLogger.ROOT_LOGGER.parameterCannotBeNull("serviceRegistry");
}
if (moduleDescription == null) {
throw WeldLogger.ROOT_LOGGER.parameterCannotBeNull("moduleDescription");
}
if (applicationDescription == null) {
throw WeldLogger.ROOT_LOGGER.parameterCannotBeNull("applicationDescription");
}
if (deploymentRoot == null) {
throw WeldLogger.ROOT_LOGGER.parameterCannotBeNull("deploymentRoot");
}
this.applicationDescription = applicationDescription;
this.deploymentRoot = deploymentRoot;
}
@Override
public ResourceReferenceFactory<Object> registerEjbInjectionPoint(final InjectionPoint injectionPoint) {
EJB ejb = ResourceInjectionUtilities.getResourceAnnotated(injectionPoint).getAnnotation(EJB.class);
if (ejb == null) {
throw WeldLogger.ROOT_LOGGER.annotationNotFound(EJB.class, injectionPoint.getMember());
}
if (injectionPoint.getMember() instanceof Method && ((Method) injectionPoint.getMember()).getParameterCount() != 1) {
throw WeldLogger.ROOT_LOGGER.injectionPointNotAJavabean((Method) injectionPoint.getMember());
}
if (!ejb.lookup().equals("")) {
if (ejb.lookup().startsWith("ejb:")) {
return new ResourceReferenceFactory<Object>() {
@Override
public ResourceReference<Object> createResource() {
return new SimpleResourceReference<Object>(doLookup(ejb.lookup(), null));
}
};
}
return handleServiceLookup(ejb.lookup(), injectionPoint);
} else {
final ViewDescription viewDescription = getViewDescription(ejb, injectionPoint);
if (viewDescription != null) {
return handleServiceLookup(viewDescription, injectionPoint);
} else {
final String proposedName = getEjbBindLocation(injectionPoint);
return new ResourceReferenceFactory<Object>() {
@Override
public ResourceReference<Object> createResource() {
return new SimpleResourceReference<Object>(doLookup(proposedName, null));
}
};
}
}
}
private ResourceReferenceFactory<Object> handleServiceLookup(ViewDescription viewDescription, InjectionPoint injectionPoint) {
/*
* Try to obtain ComponentView eagerly and validate the resource type
*/
final ComponentView view = getComponentView(viewDescription);
if (view != null && injectionPoint.getAnnotated().isAnnotationPresent(Produces.class)) {
Class<?> clazz = view.getViewClass();
Class<?> injectionPointRawType = Reflections.getRawType(injectionPoint.getType());
//we just compare names, as for remote views the actual classes may be loaded from different class loaders
Class<?> c = clazz;
boolean found = false;
while (c != null && c != Object.class) {
if (injectionPointRawType.getName().equals(c.getName())) {
found = true;
break;
}
c = c.getSuperclass();
}
if (!found) {
throw BeanLogger.LOG.invalidResourceProducerType(injectionPoint.getAnnotated(), clazz.getName());
}
return new ComponentViewToResourceReferenceFactoryAdapter<Object>(view);
} else {
return new LazyResourceReferenceFactory(viewDescription, serviceRegistry);
}
}
private ComponentView getComponentView(ViewDescription viewDescription) {
final ServiceController<?> controller = serviceRegistry.getService(viewDescription.getServiceName());
if (controller == null) {
return null;
}
return (ComponentView) controller.getValue();
}
private ViewDescription getViewDescription(EJB ejb, InjectionPoint injectionPoint) {
final Set<ViewDescription> viewService;
if (ejb.beanName().isEmpty()) {
if (ejb.beanInterface() != Object.class) {
viewService = applicationDescription.getComponentsForViewName(ejb.beanInterface().getName(), deploymentRoot);
} else {
viewService = applicationDescription.getComponentsForViewName(getType(injectionPoint.getType()).getName(), deploymentRoot);
}
} else {
if (ejb.beanInterface() != Object.class) {
viewService = applicationDescription.getComponents(ejb.beanName(), ejb.beanInterface().getName(), deploymentRoot);
} else {
viewService = applicationDescription.getComponents(ejb.beanName(), getType(injectionPoint.getType()).getName(), deploymentRoot);
}
}
if (injectionPoint.getAnnotated().isAnnotationPresent(Produces.class)) {
if (viewService.isEmpty()) {
throw WeldLogger.ROOT_LOGGER.ejbNotResolved(ejb, injectionPoint.getMember());
} else if (viewService.size() > 1) {
throw WeldLogger.ROOT_LOGGER.moreThanOneEjbResolved(ejb, injectionPoint.getMember(), viewService);
}
} else {
if (viewService.isEmpty()) {
return null;
} else if (viewService.size() > 1) {
return null;
}
}
return viewService.iterator().next();
}
@Override
protected BindInfo getBindInfo(String result) {
return ContextNames.bindInfoForEnvEntry(moduleDescription.getApplicationName(), moduleDescription.getModuleName(), moduleDescription.getModuleName(), !warModule, result);
}
@Override
public void cleanup() {
}
private static Class<?> getType(Type type) {
if (type instanceof Class) {
return (Class<?>) type;
} else if (type instanceof ParameterizedType) {
return getType(((ParameterizedType) type).getRawType());
} else {
throw WeldLogger.ROOT_LOGGER.couldNotDetermineUnderlyingType(type);
}
}
protected ResourceReferenceFactory<Object> createLazyResourceReferenceFactory(final ViewDescription viewDescription) {
return new ResourceReferenceFactory<Object>() {
@Override
public ResourceReference<Object> createResource() {
final ManagedReference instance;
try {
final ServiceController<?> controller = serviceRegistry.getRequiredService(viewDescription.getServiceName());
final ComponentView view = (ComponentView) controller.getValue();
instance = view.createInstance();
return new ResourceReference<Object>() {
@Override
public Object getInstance() {
return instance.getInstance();
}
@Override
public void release() {
instance.release();
}
};
} catch (Exception e) {
throw new RuntimeException(e);
}
}
};
}
public Object doLookup(String jndiName, String mappedName) {
String name = ResourceInjectionUtilities.getResourceName(jndiName, mappedName);
try {
return new InitialContext().lookup(name);
} catch (NamingException e) {
throw WeldLogger.ROOT_LOGGER.couldNotFindResource(name, e);
}
}
private String getEjbBindLocation(InjectionPoint injectionPoint) {
EJB ejb = ResourceInjectionUtilities.getResourceAnnotated(injectionPoint).getAnnotation(EJB.class);
String mappedName = ejb.mappedName();
if (!mappedName.equals("")) {
return mappedName;
}
String name = ejb.name();
if (!name.equals("")) {
return ResourceInjectionUtilities.RESOURCE_LOOKUP_PREFIX + "/" + name;
}
String propertyName;
if (injectionPoint.getMember() instanceof Field) {
propertyName = injectionPoint.getMember().getName();
} else if (injectionPoint.getMember() instanceof Method) {
propertyName = ResourceInjectionUtilities.getPropertyName((Method) injectionPoint.getMember());
if (propertyName == null) {
throw WeldLogger.ROOT_LOGGER.injectionPointNotAJavabean((Method) injectionPoint.getMember());
}
} else {
throw WeldLogger.ROOT_LOGGER.cannotInject(injectionPoint);
}
String className = injectionPoint.getMember().getDeclaringClass().getName();
return ResourceInjectionUtilities.RESOURCE_LOOKUP_PREFIX + "/" + className + "/" + propertyName;
}
private static class LazyResourceReferenceFactory implements ResourceReferenceFactory<Object> {
private final ViewDescription viewDescription;
private final ServiceRegistry serviceRegistry;
LazyResourceReferenceFactory(ViewDescription viewDescription, ServiceRegistry serviceRegistry) {
this.viewDescription = viewDescription;
this.serviceRegistry = serviceRegistry;
}
@Override
public ResourceReference<Object> createResource() {
final ManagedReference instance;
try {
final ServiceController<?> controller = serviceRegistry.getRequiredService(viewDescription.getServiceName());
final ComponentView view = (ComponentView) controller.getValue();
instance = view.createInstance();
return new ResourceReference<Object>() {
@Override
public Object getInstance() {
return instance.getInstance();
}
@Override
public void release() {
instance.release();
}
};
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
| 13,459 | 42.701299 | 232 | java |
null | wildfly-main/weld/ejb/src/main/java/org/jboss/as/weld/services/bootstrap/EjbBeanDeploymentArchiveServiceProvider.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.services.bootstrap;
import java.util.Collection;
import java.util.Collections;
import org.jboss.as.weld.spi.BeanDeploymentArchiveServicesProvider;
import org.jboss.weld.bootstrap.api.Service;
import org.jboss.weld.bootstrap.spi.BeanDeploymentArchive;
/**
*
* @author Martin Kouba
*/
public class EjbBeanDeploymentArchiveServiceProvider implements BeanDeploymentArchiveServicesProvider {
@Override
public Collection<Service> getServices(BeanDeploymentArchive archive) {
return Collections.singleton(new WeldEjbServices());
}
}
| 1,596 | 36.139535 | 103 | java |
null | wildfly-main/weld/ejb/src/main/java/org/jboss/as/weld/ejb/EjbDescriptorImpl.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.ejb;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.jboss.as.ee.component.ViewDescription;
import org.jboss.as.ejb3.component.EJBComponentDescription;
import org.jboss.as.ejb3.component.EJBViewDescription;
import org.jboss.as.ejb3.component.session.SessionBeanComponentDescription;
import org.jboss.as.ejb3.component.stateful.StatefulComponentDescription;
import org.jboss.as.server.deployment.reflect.ClassReflectionIndex;
import org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex;
import org.jboss.metadata.ejb.spec.MethodInterfaceType;
import org.jboss.msc.service.ServiceName;
import org.jboss.weld.bootstrap.spi.BeanDeploymentArchive;
import org.jboss.weld.ejb.spi.BusinessInterfaceDescriptor;
import org.jboss.weld.ejb.spi.EjbDescriptor;
import org.jboss.weld.resources.spi.ResourceLoader;
/**
* Implementation of EjbDescriptor
*
* @author Stuart Douglas
*/
public class EjbDescriptorImpl<T> implements EjbDescriptor<T> {
private final ServiceName baseName;
private final Set<BusinessInterfaceDescriptor<?>> localInterfaces;
private final Set<BusinessInterfaceDescriptor<?>> remoteInterfaces;
private final Map<Class<?>, ServiceName> viewServices;
private final Set<Method> removeMethods;
private final Class<T> ejbClass;
private final String ejbName;
private final boolean stateless;
private final boolean stateful;
private final boolean singleton;
private final boolean messageDriven;
private final boolean passivationCapable;
public EjbDescriptorImpl(EJBComponentDescription componentDescription, BeanDeploymentArchive beanDeploymentArchive, final DeploymentReflectionIndex reflectionIndex) {
final SessionBeanComponentDescription description = componentDescription instanceof SessionBeanComponentDescription ? (SessionBeanComponentDescription) componentDescription : null;
final Set<BusinessInterfaceDescriptor<?>> localInterfaces = new HashSet<BusinessInterfaceDescriptor<?>>();
final Set<BusinessInterfaceDescriptor<?>> remoteInterfaces = new HashSet<BusinessInterfaceDescriptor<?>>();
final ResourceLoader loader = beanDeploymentArchive.getServices().get(ResourceLoader.class);
ejbClass = (Class<T>) loader.classForName(componentDescription.getEJBClassName());
if (componentDescription.getViews() != null) {
for (ViewDescription view : componentDescription.getViews()) {
if (description == null || getMethodIntf(view) == MethodInterfaceType.Local) {
final String viewClassName = view.getViewClassName();
localInterfaces.add(new BusinessInterfaceDescriptorImpl<Object>(beanDeploymentArchive, viewClassName));
} else if (getMethodIntf(view) == MethodInterfaceType.Remote) {
remoteInterfaces.add(new BusinessInterfaceDescriptorImpl<Object>(beanDeploymentArchive, view.getViewClassName()));
}
}
}
if(componentDescription instanceof StatefulComponentDescription) {
Set<Method> removeMethods = new HashSet<Method>();
final Collection<StatefulComponentDescription.StatefulRemoveMethod> methods = ((StatefulComponentDescription) componentDescription).getRemoveMethods();
for(final StatefulComponentDescription.StatefulRemoveMethod method : methods) {
Class<?> c = ejbClass;
while (c != null && c != Object.class) {
ClassReflectionIndex index = reflectionIndex.getClassIndex(c);
Method m = index.getMethod(method.getMethodIdentifier());
if(m != null) {
removeMethods.add(m);
}
c = c.getSuperclass();
}
}
this.removeMethods = Collections.unmodifiableSet(removeMethods);
} else {
removeMethods = Collections.emptySet();
}
this.ejbName = componentDescription.getEJBName();
this.localInterfaces = localInterfaces;
this.remoteInterfaces = remoteInterfaces;
this.baseName = componentDescription.getServiceName();
this.stateless = componentDescription.isStateless();
this.messageDriven = componentDescription.isMessageDriven();
this.stateful = componentDescription.isStateful();
this.singleton = componentDescription.isSingleton();
this.passivationCapable = componentDescription.isPassivationApplicable();
final Map<Class<?>, ServiceName> viewServices = new HashMap<Class<?>, ServiceName>();
Map<Class<?>, ServiceName> viewServicesMap = new HashMap<Class<?>, ServiceName>();
for (ViewDescription view : componentDescription.getViews()) {
viewServicesMap.put(loader.classForName(view.getViewClassName()), view.getServiceName());
}
for (Map.Entry<Class<?>, ServiceName> entry : viewServicesMap.entrySet()) {
final Class<?> viewClass = entry.getKey();
if (viewClass != null) {
//see WELD-921
//this is horrible, but until it is fixed there is not much that can be done
final Set<Class<?>> seen = new HashSet<Class<?>>();
final Set<Class<?>> toProcess = new HashSet<Class<?>>();
toProcess.add(viewClass);
while (!toProcess.isEmpty()) {
Iterator<Class<?>> it = toProcess.iterator();
final Class<?> clazz = it.next();
it.remove();
seen.add(clazz);
viewServices.put(clazz, entry.getValue());
final Class<?> superclass = clazz.getSuperclass();
if (superclass != Object.class && superclass != null && !seen.contains(superclass)) {
toProcess.add(superclass);
}
for (Class<?> iface : clazz.getInterfaces()) {
if (!seen.contains(iface)) {
toProcess.add(iface);
}
}
}
}
}
this.viewServices = viewServices;
}
private MethodInterfaceType getMethodIntf(final ViewDescription view) {
if (view instanceof EJBViewDescription) {
final EJBViewDescription ejbView = (EJBViewDescription) view;
return ejbView.getMethodIntf();
}
return null;
}
@Override
public Class<T> getBeanClass() {
return ejbClass;
}
@Override
public Collection<BusinessInterfaceDescriptor<?>> getLocalBusinessInterfaces() {
return localInterfaces;
}
@Override
public Collection<BusinessInterfaceDescriptor<?>> getRemoteBusinessInterfaces() {
return remoteInterfaces;
}
@Override
public String getEjbName() {
return ejbName;
}
@Override
public Collection<Method> getRemoveMethods() {
return removeMethods;
}
@Override
public boolean isStateless() {
return stateless;
}
@Override
public boolean isSingleton() {
return singleton;
}
@Override
public boolean isStateful() {
return stateful;
}
@Override
public boolean isMessageDriven() {
return messageDriven;
}
public ServiceName getBaseName() {
return baseName;
}
public ServiceName getCreateServiceName() {
return baseName.append("CREATE");
}
public ServiceName getStartServiceName() {
return baseName.append("START");
}
public Map<Class<?>, ServiceName> getViewServices() {
return viewServices;
}
@Override
public boolean isPassivationCapable() {
return passivationCapable;
}
}
| 9,068 | 37.75641 | 188 | java |
null | wildfly-main/weld/ejb/src/main/java/org/jboss/as/weld/ejb/DelegatingInterceptorInvocationContext.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2009, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.ejb;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import jakarta.enterprise.inject.spi.InterceptionType;
import jakarta.enterprise.inject.spi.Interceptor;
import jakarta.interceptor.InvocationContext;
import org.jboss.weld.exceptions.WeldException;
public class DelegatingInterceptorInvocationContext implements InvocationContext {
private InvocationContext delegateInvocationContext;
private final List<Interceptor> invocationQueue;
private final List<Object> interceptorInstances;
private int position;
private InterceptionType interceptionType;
public DelegatingInterceptorInvocationContext(InvocationContext delegateInvocationContext, List<Interceptor<?>> interceptors, List<Object> instances, InterceptionType interceptionType) {
this.delegateInvocationContext = delegateInvocationContext;
this.interceptionType = interceptionType;
this.invocationQueue = new ArrayList<Interceptor>(interceptors);
this.interceptorInstances = new ArrayList<Object>(instances);
position = 0;
}
public Map<String, Object> getContextData() {
return delegateInvocationContext.getContextData();
}
public Method getMethod() {
return delegateInvocationContext.getMethod();
}
@Override
public Constructor<?> getConstructor() {
return delegateInvocationContext.getConstructor();
}
public Object[] getParameters() {
return delegateInvocationContext.getParameters();
}
public Object getTarget() {
return delegateInvocationContext.getTarget();
}
public Object proceed() throws Exception {
int oldPosition = position;
try {
if (position < invocationQueue.size()) {
Object interceptorInstance = interceptorInstances.get(position);
try {
return invocationQueue.get(position++).intercept(interceptionType, interceptorInstance, this);
} catch (Exception e) {
// Unwrap WeldException
if (e instanceof WeldException && e.getCause() instanceof Exception) {
throw ((Exception) e.getCause());
} else {
throw e;
}
}
} else {
return delegateInvocationContext.proceed();
}
} finally {
position = oldPosition;
}
}
public void setParameters(Object[] params) {
delegateInvocationContext.setParameters(params);
}
public Object getTimer() {
return delegateInvocationContext.getTimer();
}
} | 3,804 | 34.896226 | 190 | java |
null | wildfly-main/weld/ejb/src/main/java/org/jboss/as/weld/ejb/SessionObjectReferenceImpl.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.ejb;
import java.security.AccessController;
import java.util.HashMap;
import java.util.Map;
import org.jboss.as.ee.component.ComponentView;
import org.jboss.as.naming.ManagedReference;
import org.jboss.as.server.CurrentServiceContainer;
import org.jboss.as.weld.logging.WeldLogger;
import org.jboss.msc.service.ServiceContainer;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.weld.ejb.api.SessionObjectReference;
/**
* Implementation for non-stateful beans.
*
* @author Stuart Douglas
*/
public class SessionObjectReferenceImpl implements SessionObjectReference {
private final Map<Class<?>, ServiceName> viewServices;
private final String ejbName;
private transient Map<String, ManagedReference> businessInterfaceToReference;
public SessionObjectReferenceImpl(EjbDescriptorImpl<?> descriptor) {
ejbName = descriptor.getEjbName();
this.viewServices = descriptor.getViewServices();
}
@Override
@SuppressWarnings({ "unchecked" })
public synchronized <S> S getBusinessObject(Class<S> businessInterfaceType) {
final String businessInterfaceName = businessInterfaceType.getName();
ManagedReference managedReference = null;
if (businessInterfaceToReference == null) {
businessInterfaceToReference = new HashMap<String, ManagedReference>();
} else {
managedReference = businessInterfaceToReference.get(businessInterfaceName);
}
if (managedReference == null) {
if (viewServices.containsKey(businessInterfaceType)) {
final ServiceController<?> serviceController = currentServiceContainer().getRequiredService(
viewServices.get(businessInterfaceType));
final ComponentView view = (ComponentView) serviceController.getValue();
try {
managedReference = view.createInstance();
businessInterfaceToReference.put(businessInterfaceType.getName(), managedReference);
} catch (Exception e) {
throw new RuntimeException(e);
}
} else {
throw WeldLogger.ROOT_LOGGER.viewNotFoundOnEJB(businessInterfaceType.getName(), ejbName);
}
}
return (S) managedReference.getInstance();
}
@Override
public void remove() {
//nop
}
@Override
public boolean isRemoved() {
return false;
}
private static ServiceContainer currentServiceContainer() {
if(System.getSecurityManager() == null) {
return CurrentServiceContainer.getServiceContainer();
}
return AccessController.doPrivileged(CurrentServiceContainer.GET_ACTION);
}
}
| 3,846 | 36.349515 | 108 | java |
null | wildfly-main/weld/ejb/src/main/java/org/jboss/as/weld/ejb/StatefulSessionObjectReferenceImpl.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.ejb;
import java.io.IOException;
import java.security.AccessController;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.jboss.as.ee.component.ComponentView;
import org.jboss.as.ejb3.component.stateful.StatefulSessionComponent;
import org.jboss.as.ejb3.component.stateful.StatefulSessionComponentInstance;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBean;
import org.jboss.as.naming.ManagedReference;
import org.jboss.as.server.CurrentServiceContainer;
import org.jboss.as.weld._private.WeldEjbLogger;
import org.jboss.as.weld.logging.WeldLogger;
import org.jboss.ejb.client.SessionID;
import org.jboss.msc.service.ServiceContainer;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.weld.ejb.api.SessionObjectReference;
/**
* Implementation for SFSB's
*
* @author Stuart Douglas
*/
public class StatefulSessionObjectReferenceImpl implements SessionObjectReference {
private final ServiceName createServiceName;
private final SessionID id;
private final StatefulSessionComponent ejbComponent;
private final Map<Class<?>, ServiceName> viewServices;
private volatile boolean removed = false;
private transient Map<String, ManagedReference> businessInterfaceToReference;
public StatefulSessionObjectReferenceImpl(final SessionID id, final ServiceName createServiceName, final Map<Class<?>, ServiceName> viewServices) {
this.id = id;
this.createServiceName = createServiceName;
this.viewServices = viewServices;
final ServiceController<?> controller = currentServiceContainer().getRequiredService(createServiceName);
ejbComponent = (StatefulSessionComponent) controller.getValue();
}
public StatefulSessionObjectReferenceImpl(EjbDescriptorImpl<?> descriptor) {
this.createServiceName = descriptor.getCreateServiceName();
final ServiceController<?> controller = currentServiceContainer().getRequiredService(createServiceName);
ejbComponent = (StatefulSessionComponent) controller.getValue();
this.id = ejbComponent.createSession();
this.viewServices = descriptor.getViewServices();
}
@Override
@SuppressWarnings({ "unchecked" })
public synchronized <S> S getBusinessObject(Class<S> businessInterfaceType) {
if (isRemoved()) {
throw WeldEjbLogger.ROOT_LOGGER.ejbHashBeenRemoved(ejbComponent);
}
final String businessInterfaceName = businessInterfaceType.getName();
ManagedReference managedReference = null;
if (businessInterfaceToReference == null) {
businessInterfaceToReference = new HashMap<String, ManagedReference>();
} else {
managedReference = businessInterfaceToReference.get(businessInterfaceName);
}
if (managedReference == null) {
if (viewServices.containsKey(businessInterfaceType)) {
final ServiceController<?> serviceController = currentServiceContainer().getRequiredService(
viewServices.get(businessInterfaceType));
final ComponentView view = (ComponentView) serviceController.getValue();
try {
managedReference = view.createInstance(Collections.<Object, Object> singletonMap(SessionID.class, id));
businessInterfaceToReference.put(businessInterfaceName, managedReference);
} catch (Exception e) {
throw new RuntimeException(e);
}
} else {
throw WeldLogger.ROOT_LOGGER
.viewNotFoundOnEJB(businessInterfaceType.getName(), ejbComponent.getComponentName());
}
}
return (S) managedReference.getInstance();
}
private static ServiceContainer currentServiceContainer() {
if(System.getSecurityManager() == null) {
return CurrentServiceContainer.getServiceContainer();
}
return AccessController.doPrivileged(CurrentServiceContainer.GET_ACTION);
}
protected Object writeReplace() throws IOException {
return new SerializedStatefulSessionObject(createServiceName, id, viewServices);
}
@Override
public void remove() {
try (StatefulSessionBean<SessionID, StatefulSessionComponentInstance> bean = this.ejbComponent.getCache().findStatefulSessionBean(this.id)) {
this.removed = true;
if (bean != null) {
bean.remove();
}
}
}
@Override
public boolean isRemoved() {
return this.removed;
}
}
| 5,717 | 40.434783 | 151 | java |
null | wildfly-main/weld/ejb/src/main/java/org/jboss/as/weld/ejb/SerializedStatefulSessionObject.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.ejb;
import org.jboss.ejb.client.SessionID;
import org.jboss.msc.service.ServiceName;
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* Serialized form of a SFSB
*
* @author Stuart Douglas
*/
public class SerializedStatefulSessionObject implements Serializable {
private final String componentServiceName;
private final SessionID sessionID;
private final Map<Class<?>, String> serviceNames;
public SerializedStatefulSessionObject(final ServiceName componentServiceName, final SessionID sessionID, final Map<Class<?>, ServiceName> serviceNames) {
this.componentServiceName = componentServiceName.getCanonicalName();
this.sessionID = sessionID;
Map<Class<?>, String> names = new HashMap<Class<?>, String>();
for (Map.Entry<Class<?>, ServiceName> e : serviceNames.entrySet()) {
names.put(e.getKey(), e.getValue().getCanonicalName());
}
this.serviceNames = names;
}
public SerializedStatefulSessionObject(final String componentServiceName, final SessionID sessionID, final Map<Class<?>, String> serviceNames) {
this.componentServiceName = componentServiceName;
this.sessionID = sessionID;
this.serviceNames = serviceNames;
}
private Object readResolve() throws ObjectStreamException {
Map<Class<?>, ServiceName> names = new HashMap<Class<?>, ServiceName>();
for (Map.Entry<Class<?>, String> e : serviceNames.entrySet()) {
names.put(e.getKey(), ServiceName.parse(e.getValue()));
}
return new StatefulSessionObjectReferenceImpl(sessionID, ServiceName.parse(componentServiceName), names);
}
public String getComponentServiceName() {
return this.componentServiceName;
}
public SessionID getSessionID() {
return this.sessionID;
}
public Map<Class<?>, String> getServiceNames() {
return serviceNames;
}
}
| 3,034 | 37.417722 | 158 | java |
null | wildfly-main/weld/ejb/src/main/java/org/jboss/as/weld/ejb/BusinessInterfaceDescriptorImpl.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.ejb;
import org.jboss.weld.bootstrap.spi.BeanDeploymentArchive;
import org.jboss.weld.ejb.spi.BusinessInterfaceDescriptor;
import org.jboss.weld.resources.spi.ResourceLoader;
/**
* Business interface descriptor
*
* @author Stuart Douglas
*/
public class BusinessInterfaceDescriptorImpl<T> implements BusinessInterfaceDescriptor<T>{
private final BeanDeploymentArchive beanDeploymentArchive;
private final String className;
public BusinessInterfaceDescriptorImpl(BeanDeploymentArchive beanDeploymentArchive, String className) {
this.beanDeploymentArchive = beanDeploymentArchive;
this.className = className;
}
@Override
public Class<T> getInterface() {
return (Class<T>) beanDeploymentArchive.getServices().get(ResourceLoader.class).classForName(className);
}
}
| 1,864 | 37.854167 | 112 | java |
null | wildfly-main/weld/ejb/src/main/java/org/jboss/as/weld/injection/EjbComponentSupport.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.injection;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.ejb3.component.EJBComponentDescription;
import org.jboss.as.ejb3.component.messagedriven.MessageDrivenComponentDescription;
import org.jboss.as.weld.spi.ComponentSupport;
/**
*
* @author Martin Kouba
*/
public class EjbComponentSupport implements ComponentSupport {
@Override
public boolean isProcessing(ComponentDescription componentDescription) {
return componentDescription instanceof MessageDrivenComponentDescription;
}
@Override
public boolean isDiscoveredExternalType(ComponentDescription componentDescription) {
return !(componentDescription instanceof EJBComponentDescription);
}
}
| 1,767 | 37.434783 | 88 | java |
null | wildfly-main/weld/ejb/src/main/java/org/jboss/as/weld/interceptors/EjbComponentInterceptorSupport.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.interceptors;
import java.util.List;
import jakarta.enterprise.inject.spi.InterceptionType;
import jakarta.enterprise.inject.spi.Interceptor;
import jakarta.interceptor.InvocationContext;
import org.jboss.as.ee.component.ComponentInstance;
import org.jboss.as.ejb3.component.stateful.SerializedCdiInterceptorsKey;
import org.jboss.as.weld.ejb.DelegatingInterceptorInvocationContext;
import org.jboss.as.weld.services.bootstrap.WeldEjbServices;
import org.jboss.as.weld.spi.InterceptorInstances;
import org.jboss.as.weld.spi.ComponentInterceptorSupport;
import org.jboss.weld.ejb.spi.EjbServices;
import org.jboss.weld.ejb.spi.InterceptorBindings;
import org.jboss.weld.ejb.spi.helpers.ForwardingEjbServices;
import org.jboss.weld.manager.api.WeldManager;
/**
*
* @author Martin Kouba
*/
public class EjbComponentInterceptorSupport implements ComponentInterceptorSupport {
@Override
public InterceptorInstances getInterceptorInstances(ComponentInstance componentInstance) {
return (WeldInterceptorInstances) componentInstance.getInstanceData(SerializedCdiInterceptorsKey.class);
}
@Override
public void setInterceptorInstances(ComponentInstance componentInstance, InterceptorInstances interceptorInstances) {
componentInstance.setInstanceData(SerializedCdiInterceptorsKey.class, interceptorInstances);
}
@Override
public Object delegateInterception(InvocationContext invocationContext, InterceptionType interceptionType, List<Interceptor<?>> currentInterceptors,
List<Object> currentInterceptorInstances) throws Exception {
return new DelegatingInterceptorInvocationContext(invocationContext, currentInterceptors, currentInterceptorInstances, interceptionType).proceed();
}
@Override
public InterceptorBindings getInterceptorBindings(String ejbName, WeldManager manager) {
EjbServices ejbServices = manager.getServices().get(EjbServices.class);
if (ejbServices instanceof ForwardingEjbServices) {
ejbServices = ((ForwardingEjbServices) ejbServices).delegate();
}
if (ejbServices instanceof WeldEjbServices) {
return ((WeldEjbServices) ejbServices).getBindings(ejbName);
}
return null;
}
}
| 3,298 | 42.407895 | 155 | java |
null | wildfly-main/weld/jpa/src/main/java/org/jboss/as/weld/deployment/processor/JpaDependenciesProvider.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2021, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment.processor;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import org.jboss.as.jpa.config.Configuration;
import org.jboss.as.jpa.config.PersistenceUnitMetadataHolder;
import org.jboss.as.jpa.service.PersistenceUnitServiceImpl;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUtils;
import org.jboss.as.server.deployment.SubDeploymentMarker;
import org.jboss.as.server.deployment.module.ResourceRoot;
import org.jboss.as.weld.spi.DeploymentUnitDependenciesProvider;
import org.jboss.metadata.ear.spec.EarMetaData;
import org.jboss.msc.service.ServiceName;
import org.jipijapa.plugin.spi.PersistenceUnitMetadata;
/**
* @author Martin Kouba
*/
public class JpaDependenciesProvider implements DeploymentUnitDependenciesProvider {
@Override
public Set<ServiceName> getDependencies(DeploymentUnit deploymentUnit) {
Set<ServiceName> dependencies = new HashSet<>();
EarMetaData earConfig = DeploymentUtils.getTopDeploymentUnit(deploymentUnit).getAttachment(org.jboss.as.ee.structure.Attachments.EAR_METADATA);
// WFLY-14923 handle initialize-in-order by only adding (top level deployment) persistence units dependencies to WeldStartService.
// with initialize-in-order enabled WeldStartService cannot depend on persistence units contained in sub-deployments as that
// may violate the initialize-in-order ordering and lead to deployment failures.
if (earConfig != null && earConfig.getInitializeInOrder() && earConfig.getModules().size() > 1) {
// Only add Jakarta EE component dependencies on all persistence units in top level deployment unit.
if (deploymentUnit.getParent() == null) {
for (ResourceRoot root : DeploymentUtils.allResourceRoots(deploymentUnit)) {
// Only process resources that aren't subdeployments
if (!SubDeploymentMarker.isSubDeployment(root)) {
addDependencyOnPersistenceUnit(dependencies, root.getAttachment(PersistenceUnitMetadataHolder.PERSISTENCE_UNITS));
}
}
}
} else {
// handle when the `initialize-in-order` feature is not enabled.
for (ResourceRoot root : DeploymentUtils.allResourceRoots(deploymentUnit)) {
addDependencyOnPersistenceUnit(dependencies, root.getAttachment(PersistenceUnitMetadataHolder.PERSISTENCE_UNITS));
}
}
return dependencies;
}
private void addDependencyOnPersistenceUnit(Set<ServiceName> dependencies, PersistenceUnitMetadataHolder persistenceUnits) {
if (persistenceUnits != null && persistenceUnits.getPersistenceUnits() != null) {
for (final PersistenceUnitMetadata pu : persistenceUnits.getPersistenceUnits()) {
final Properties properties = pu.getProperties();
final String jpaContainerManaged = properties.getProperty(Configuration.JPA_CONTAINER_MANAGED);
final boolean deployPU = (jpaContainerManaged == null || Boolean.parseBoolean(jpaContainerManaged));
if (deployPU) {
final ServiceName serviceName = PersistenceUnitServiceImpl.getPUServiceName(pu);
dependencies.add(serviceName);
}
}
}
}
}
| 4,454 | 51.411765 | 151 | java |
null | wildfly-main/weld/jpa/src/main/java/org/jboss/as/weld/services/bootstrap/JpaModuleServiceProvider.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.services.bootstrap;
import java.util.Collection;
import java.util.Collections;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.module.ResourceRoot;
import org.jboss.as.weld.spi.ModuleServicesProvider;
import org.jboss.modules.Module;
import org.jboss.weld.bootstrap.api.Service;
/**
*
* @author Martin Kouba
*/
public class JpaModuleServiceProvider implements ModuleServicesProvider {
@Override
public Collection<Service> getServices(DeploymentUnit rootDeploymentUnit, DeploymentUnit deploymentUnit, Module module, ResourceRoot resourceRoot) {
return Collections.singleton(new WeldJpaInjectionServices(deploymentUnit));
}
}
| 1,738 | 37.644444 | 152 | java |
null | wildfly-main/weld/jpa/src/main/java/org/jboss/as/weld/services/bootstrap/WeldJpaInjectionServices.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2021, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.services.bootstrap;
import static org.jboss.as.weld.util.ResourceInjectionUtilities.getResourceAnnotated;
import java.lang.reflect.Member;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.HashMap;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import jakarta.enterprise.inject.spi.InjectionPoint;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.PersistenceUnit;
import jakarta.transaction.TransactionManager;
import jakarta.transaction.TransactionSynchronizationRegistry;
import org.jboss.as.jpa.container.PersistenceUnitSearch;
import org.jboss.as.jpa.container.TransactionScopedEntityManager;
import org.jboss.as.jpa.processor.JpaAttachments;
import org.jboss.as.jpa.service.PersistenceUnitServiceImpl;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.weld.logging.WeldLogger;
import org.jboss.as.weld.util.ImmediateResourceReferenceFactory;
import org.jboss.msc.service.LifecycleEvent;
import org.jboss.msc.service.LifecycleListener;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.weld.injection.spi.JpaInjectionServices;
import org.jboss.weld.injection.spi.ResourceReference;
import org.jboss.weld.injection.spi.ResourceReferenceFactory;
import org.jboss.weld.injection.spi.helpers.SimpleResourceReference;
import org.jipijapa.plugin.spi.PersistenceUnitMetadata;
import org.wildfly.security.manager.WildFlySecurityManager;
import org.wildfly.security.manager.action.GetAccessControlContextAction;
import org.wildfly.transaction.client.ContextTransactionManager;
public class WeldJpaInjectionServices implements JpaInjectionServices {
private DeploymentUnit deploymentUnit;
public WeldJpaInjectionServices(DeploymentUnit deploymentUnit) {
this.deploymentUnit = deploymentUnit;
}
@Override
public ResourceReferenceFactory<EntityManager> registerPersistenceContextInjectionPoint(final InjectionPoint injectionPoint) {
//TODO: cache this stuff
final PersistenceContext context = getResourceAnnotated(injectionPoint).getAnnotation(PersistenceContext.class);
if (context == null) {
throw WeldLogger.ROOT_LOGGER.annotationNotFound(PersistenceContext.class, injectionPoint.getMember());
}
final String scopedPuName = getScopedPUName(deploymentUnit, context.unitName(), injectionPoint.getMember());
final ServiceName persistenceUnitServiceName = PersistenceUnitServiceImpl.getPUServiceName(scopedPuName);
final ServiceController<?> serviceController = deploymentUnit.getServiceRegistry().getRequiredService(persistenceUnitServiceName);
//now we have the service controller, as this method is only called at runtime the service should
//always be up
final PersistenceUnitServiceImpl persistenceUnitService = (PersistenceUnitServiceImpl) serviceController.getValue();
if (persistenceUnitService.getEntityManagerFactory() != null) {
return new EntityManagerResourceReferenceFactory(scopedPuName, persistenceUnitService.getEntityManagerFactory(), context, deploymentUnit.getAttachment(JpaAttachments.TRANSACTION_SYNCHRONIZATION_REGISTRY), ContextTransactionManager.getInstance());
} else {
return new LazyFactory<EntityManager>(serviceController, scopedPuName, new Callable<EntityManager>() {
@Override
public EntityManager call() throws Exception {
return new TransactionScopedEntityManager(
scopedPuName,
new HashMap<>(),
persistenceUnitService.getEntityManagerFactory(),
context.synchronization(),
deploymentUnit.getAttachment(JpaAttachments.TRANSACTION_SYNCHRONIZATION_REGISTRY),
ContextTransactionManager.getInstance());
}
});
}
}
@Override
public ResourceReferenceFactory<EntityManagerFactory> registerPersistenceUnitInjectionPoint(final InjectionPoint injectionPoint) {
//TODO: cache this stuff
final PersistenceUnit context = getResourceAnnotated(injectionPoint).getAnnotation(PersistenceUnit.class);
if (context == null) {
throw WeldLogger.ROOT_LOGGER.annotationNotFound(PersistenceUnit.class, injectionPoint.getMember());
}
final String scopedPuName = getScopedPUName(deploymentUnit, context.unitName(), injectionPoint.getMember());
final ServiceName persistenceUnitServiceName = PersistenceUnitServiceImpl.getPUServiceName(scopedPuName);
final ServiceController<?> serviceController = deploymentUnit.getServiceRegistry().getRequiredService(persistenceUnitServiceName);
//now we have the service controller, as this method is only called at runtime the service should
//always be up
final PersistenceUnitServiceImpl persistenceUnitService = (PersistenceUnitServiceImpl) serviceController.getValue();
if (persistenceUnitService.getEntityManagerFactory() != null) {
return new ImmediateResourceReferenceFactory<EntityManagerFactory>(persistenceUnitService.getEntityManagerFactory());
} else {
return new LazyFactory<EntityManagerFactory>(serviceController, scopedPuName, new Callable<EntityManagerFactory>() {
@Override
public EntityManagerFactory call() throws Exception {
return persistenceUnitService.getEntityManagerFactory();
}
});
}
}
@Override
public void cleanup() {
deploymentUnit = null;
}
private String getScopedPUName(final DeploymentUnit deploymentUnit, final String persistenceUnitName, Member injectionPoint) {
PersistenceUnitMetadata scopedPu;
scopedPu = PersistenceUnitSearch.resolvePersistenceUnitSupplier(deploymentUnit, persistenceUnitName);
if (null == scopedPu) {
throw WeldLogger.ROOT_LOGGER.couldNotFindPersistenceUnit(persistenceUnitName, deploymentUnit.getName(), injectionPoint);
}
return scopedPu.getScopedPersistenceUnitName();
}
private static class EntityManagerResourceReferenceFactory implements ResourceReferenceFactory<EntityManager> {
private final String scopedPuName;
private final EntityManagerFactory entityManagerFactory;
private final PersistenceContext context;
private final TransactionSynchronizationRegistry transactionSynchronizationRegistry;
private final TransactionManager transactionManager;
public EntityManagerResourceReferenceFactory(String scopedPuName, EntityManagerFactory entityManagerFactory, PersistenceContext context, TransactionSynchronizationRegistry transactionSynchronizationRegistry, TransactionManager transactionManager) {
this.scopedPuName = scopedPuName;
this.entityManagerFactory = entityManagerFactory;
this.context = context;
this.transactionSynchronizationRegistry = transactionSynchronizationRegistry;
this.transactionManager = transactionManager;
}
@Override
public ResourceReference<EntityManager> createResource() {
final TransactionScopedEntityManager result = new TransactionScopedEntityManager(scopedPuName, new HashMap<>(), entityManagerFactory, context.synchronization(), transactionSynchronizationRegistry, transactionManager);
return new SimpleResourceReference<EntityManager>(result);
}
}
private static class LazyFactory<T> implements ResourceReferenceFactory<T> {
public static final String MSC_SERVICE_THREAD = "MSC service thread";
public static final String INJECTION_CANNOT_BE_PERFORMED_WITHIN_MSC_SERVICE_THREAD = "injection cannot be performed from JBoss Modular Service Container (MSC) service thread";
private final Callable<T> callable;
private final ServiceController<?> serviceController;
private final String scopedPuName;
public LazyFactory(ServiceController<?> serviceController, String scopedPuName, Callable<T> callable) {
this.callable = callable;
this.serviceController = serviceController;
this.scopedPuName = scopedPuName;
}
final CountDownLatch latch = new CountDownLatch(1);
boolean failed = false, removed = false;
@Override
public ResourceReference<T> createResource() {
serviceController.addListener(
new LifecycleListener() {
@Override
public void handleEvent(final ServiceController<?> controller, final LifecycleEvent event) {
if (event == LifecycleEvent.UP) {
latch.countDown();
controller.removeListener(this);
} else if (event == LifecycleEvent.FAILED) {
failed = true;
latch.countDown();
} else if (event == LifecycleEvent.REMOVED) {
removed = true;
latch.countDown();
}
}
}
);
final AccessControlContext accessControlContext =
AccessController.doPrivileged(GetAccessControlContextAction.getInstance());
try {
// ensure that Injection of persistence unit doesn't cause MSC service thread to block.
PrivilegedAction<Void> threadNameCheck =
new PrivilegedAction<Void>() {
// run as security privileged action
@Override
public Void run() {
assert !Thread.currentThread().getName().startsWith(MSC_SERVICE_THREAD) :
INJECTION_CANNOT_BE_PERFORMED_WITHIN_MSC_SERVICE_THREAD;
return null;
}
};
WildFlySecurityManager.doChecked(threadNameCheck, accessControlContext);
latch.await();
if (failed) {
throw WeldLogger.ROOT_LOGGER.persistenceUnitFailed(scopedPuName);
} else if(removed) {
throw WeldLogger.ROOT_LOGGER.persistenceUnitRemoved(scopedPuName);
}
} catch (InterruptedException e) {
// Thread was interrupted, which we will preserve in case a higher level operation needs to see it.
Thread.currentThread().interrupt();
// rather than just returning the current EntityManagerFactory (might be null or not null),
// fail with a runtime exception.
throw new RuntimeException(e);
}
return new ResourceReference<T>() {
T persistenceUnitTarget;
@Override
public T getInstance() {
PrivilegedAction<Void> privilegedAction =
new PrivilegedAction<Void>() {
// run as security privileged action
@Override
public Void run() {
try {
persistenceUnitTarget = callable.call();
} catch (RuntimeException e) { // rethrow PersistenceException
throw e;
} catch (Exception e) { // We shouldn't get any other Exceptions but if we do, throw then as unchecked exception
throw new RuntimeException(e);
}
return null;
}
};
WildFlySecurityManager.doChecked(privilegedAction, accessControlContext);
return persistenceUnitTarget;
}
@Override
public void release() {
}
};
}
}
}
| 13,702 | 51.703846 | 258 | java |
null | wildfly-main/weld/webservices/src/main/java/org/jboss/as/weld/deployment/processors/JaxwsModuleServiceProvider.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment.processors;
import java.util.Collection;
import java.util.Collections;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.module.ResourceRoot;
import org.jboss.as.weld.services.bootstrap.WeldJaxwsInjectionServices;
import org.jboss.as.weld.spi.ModuleServicesProvider;
import org.jboss.modules.Module;
import org.jboss.weld.bootstrap.api.Service;
/**
*
* @author Martin Kouba
*/
public class JaxwsModuleServiceProvider implements ModuleServicesProvider {
@Override
public Collection<Service> getServices(DeploymentUnit rootDeploymentUnit, DeploymentUnit deploymentUnit, Module module, ResourceRoot resourceRoot) {
return Collections.singleton(new WeldJaxwsInjectionServices(deploymentUnit));
}
} | 1,815 | 40.272727 | 152 | java |
null | wildfly-main/weld/webservices/src/main/java/org/jboss/as/weld/services/bootstrap/WeldJaxwsInjectionServices.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.services.bootstrap;
import static org.jboss.as.weld.util.ResourceInjectionUtilities.getResourceAnnotated;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import jakarta.enterprise.inject.spi.InjectionPoint;
import jakarta.jws.WebService;
import jakarta.xml.ws.Service;
import jakarta.xml.ws.WebServiceRef;
import org.jboss.as.naming.ManagedReferenceFactory;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.webservices.webserviceref.WSRefAnnotationWrapper;
import org.jboss.as.webservices.webserviceref.WebServiceReferences;
import org.jboss.as.weld.logging.WeldLogger;
import org.jboss.as.weld.util.ResourceInjectionUtilities;
import org.jboss.weld.injection.spi.JaxwsInjectionServices;
import org.jboss.weld.injection.spi.ResourceReferenceFactory;
import org.jboss.weld.logging.BeanLogger;
import org.jboss.weld.util.reflection.Reflections;
/**
* @author Stuart Douglas
*/
public class WeldJaxwsInjectionServices implements JaxwsInjectionServices {
private DeploymentUnit deploymentUnit;
public WeldJaxwsInjectionServices(final DeploymentUnit unit) {
this.deploymentUnit = unit;
}
@Override
public <T> ResourceReferenceFactory<T> registerWebServiceRefInjectionPoint(final InjectionPoint injectionPoint) {
WebServiceRef annotation = getResourceAnnotated(injectionPoint).getAnnotation(WebServiceRef.class);
if (annotation == null) {
throw WeldLogger.ROOT_LOGGER.annotationNotFound(WebServiceRef.class, injectionPoint.getMember());
}
validateWebServiceRefInjectionPoint(injectionPoint, annotation);
try {
ManagedReferenceFactory factory = WebServiceReferences.createWebServiceFactory(deploymentUnit, classNameFromType(injectionPoint.getType()), new WSRefAnnotationWrapper(annotation), (AnnotatedElement) injectionPoint.getMember(), getBindingName(injectionPoint, annotation));
return new ManagedReferenceFactoryToResourceReferenceFactoryAdapter<>(factory);
} catch (DeploymentUnitProcessingException e) {
throw new RuntimeException(e);
}
}
private String getBindingName(final InjectionPoint injectionPoint, WebServiceRef annotation) {
if (!annotation.name().isEmpty()) {
return annotation.name();
}
return injectionPoint.getMember().getDeclaringClass().getName() + "/" + ResourceInjectionUtilities.getPropertyName(injectionPoint.getMember());
}
private String classNameFromType(final Type type) {
if(type instanceof Class) {
return ((Class) type).getName();
} else if(type instanceof ParameterizedType) {
return classNameFromType(((ParameterizedType) type).getRawType());
} else {
return type.toString();
}
}
private void validateWebServiceRefInjectionPoint(InjectionPoint ip, WebServiceRef annotation) {
Class<?> rawType = Reflections.getRawType(ip.getType());
if (Service.class.isAssignableFrom(rawType)) {
return;
}
if (!rawType.isAnnotationPresent(WebService.class)) {
throw BeanLogger.LOG.invalidResourceProducerType(ip.getAnnotated(), annotation.value());
}
}
@Override
public void cleanup() {
this.deploymentUnit = null;
}
}
| 4,497 | 41.433962 | 283 | java |
null | wildfly-main/weld/webservices/src/main/java/org/jboss/as/weld/services/bootstrap/JaxwsResourceInjectionResolver.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.services.bootstrap;
import jakarta.xml.ws.WebServiceContext;
import org.jboss.as.weld.spi.ResourceInjectionResolver;
import org.jboss.ws.common.injection.ThreadLocalAwareWebServiceContext;
/**
*
* @author Martin Kouba
*/
public class JaxwsResourceInjectionResolver implements ResourceInjectionResolver {
@Override
public Object resolve(String resourceName) {
if (resourceName.equals(WebServiceContext.class.getName())) {
// horrible hack
// we don't have anywhere we can look this up
// See also WFLY-4487
return ThreadLocalAwareWebServiceContext.getInstance();
}
return null;
}
}
| 1,715 | 35.510638 | 82 | java |
null | wildfly-main/weld/webservices/src/main/java/org/jboss/as/weld/injection/WSComponentSupport.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.injection;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.webservices.injection.WSComponentDescription;
import org.jboss.as.weld.spi.ComponentSupport;
/**
*
* @author Martin Kouba
*/
public class WSComponentSupport implements ComponentSupport {
@Override
public boolean isProcessing(ComponentDescription componentDescription) {
return componentDescription instanceof WSComponentDescription;
}
}
| 1,492 | 36.325 | 76 | java |
null | wildfly-main/undertow/src/test/java/org/wildfly/extension/undertow/RuntimeInitialization.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.undertow;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.function.Consumer;
import java.util.function.Supplier;
import javax.net.ssl.SSLContext;
import io.undertow.server.DefaultByteBufferPool;
import org.jboss.as.controller.ControlledProcessStateService;
import org.jboss.as.controller.RunningMode;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.as.naming.service.NamingStoreService;
import org.jboss.as.remoting.HttpListenerRegistryService;
import org.jboss.as.server.Services;
import org.jboss.as.server.moduleservice.ServiceModuleLoader;
import org.jboss.as.server.suspend.SuspendController;
import org.jboss.msc.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StopContext;
import org.wildfly.extension.io.IOServices;
import org.wildfly.extension.io.WorkerService;
import org.wildfly.security.auth.server.HttpAuthenticationFactory;
import org.xnio.OptionMap;
import org.xnio.Options;
import org.xnio.Xnio;
import org.xnio.XnioWorker;
class RuntimeInitialization extends DefaultInitialization {
private final Map<ServiceName, Supplier<Object>> values;
RuntimeInitialization(Map<ServiceName, Supplier<Object>> values) {
this.values = values;
}
private void record(ServiceTarget target, ServiceName name) {
this.record(target, name, ServiceController.Mode.PASSIVE);
}
private void start(ServiceTarget target, ServiceName name) {
this.record(target, name, ServiceController.Mode.ACTIVE);
}
private void record(ServiceTarget target, ServiceName name, ServiceController.Mode mode) {
ServiceBuilder<?> builder = target.addService(name.append("test-recorder"));
this.values.put(name, builder.requires(name));
builder.setInstance(Service.NULL).setInitialMode(mode).install();
}
@Override
protected RunningMode getRunningMode() {
return RunningMode.NORMAL;
}
@Override
protected void addExtraServices(ServiceTarget target) {
// AbstractUndertowSubsystemTestCase.testRuntime(...) methods require the recording of specific service values, and requires starting specific on-demand services
// TODO Consider removing those testRuntime(...) methods - the value of such testing is questionable
if (this.values != null) {
this.start(target, UndertowService.FILTER.append("limit-connections"));
this.start(target, UndertowService.FILTER.append("headers"));
this.start(target, UndertowService.FILTER.append("mod-cluster"));
this.record(target, UndertowRootDefinition.UNDERTOW_CAPABILITY.getCapabilityServiceName());
this.record(target, ServerDefinition.SERVER_CAPABILITY.getCapabilityServiceName("some-server"));
this.start(target, HostDefinition.HOST_CAPABILITY.getCapabilityServiceName("some-server", "default-virtual-host"));
this.start(target, HostDefinition.HOST_CAPABILITY.getCapabilityServiceName("some-server", "other-host"));
this.record(target, UndertowService.locationServiceName("some-server", "default-virtual-host", "/"));
this.start(target, ServletContainerDefinition.SERVLET_CONTAINER_CAPABILITY.getCapabilityServiceName("myContainer"));
this.start(target, UndertowService.filterRefName("some-server", "other-host", "/", "static-gzip"));
this.start(target, UndertowService.filterRefName("some-server", "other-host", "headers"));
this.record(target, UndertowService.DEFAULT_HOST);
this.record(target, UndertowService.DEFAULT_SERVER);
this.record(target, UndertowService.accessLogServiceName("some-server", "default-virtual-host"));
this.record(target, ServerDefinition.SERVER_CAPABILITY.getCapabilityServiceName("undertow-server"));
this.record(target, ServerDefinition.SERVER_CAPABILITY.getCapabilityServiceName("default-server"));
}
try {
SSLContext sslContext = SSLContext.getDefault();
target.addService(ServiceName.parse(Capabilities.REF_SUSPEND_CONTROLLER)).setInstance(new SuspendController()).install();
target.addService(Services.JBOSS_SERVICE_MODULE_LOADER).setInstance(new ServiceModuleLoader(null)).install();
target.addService(ContextNames.JAVA_CONTEXT_SERVICE_NAME).setInstance(new NamingStoreService()).install();
target.addService(ContextNames.JBOSS_CONTEXT_SERVICE_NAME).setInstance(new NamingStoreService()).install();
ServiceBuilder<?> builder1 = target.addService(IOServices.WORKER.append("default"));
Consumer<XnioWorker> workerConsumer1 = builder1.provides(IOServices.WORKER.append("default"));
builder1.setInstance(
new WorkerService(
workerConsumer1,
() -> Executors.newFixedThreadPool(1),
Xnio.getInstance().createWorkerBuilder().populateFromOptions(OptionMap.builder().set(Options.WORKER_IO_THREADS, 2).getMap())));
builder1.install();
ServiceBuilder<?> builder2 = target.addService(IOServices.WORKER.append("non-default"));
Consumer<XnioWorker> workerConsumer2 = builder2.provides(IOServices.WORKER.append("non-default"));
builder2.setInstance(
new WorkerService(
workerConsumer2,
() -> Executors.newFixedThreadPool(1),
Xnio.getInstance().createWorkerBuilder().populateFromOptions(OptionMap.builder().set(Options.WORKER_IO_THREADS, 2).getMap())));
builder2.install();
target.addService(ControlledProcessStateService.SERVICE_NAME).setInstance(new NullService()).install();
final ServiceBuilder<?> sb0 = target.addService(ServiceName.parse(Capabilities.CAPABILITY_BYTE_BUFFER_POOL + ".default"));
final Consumer<DefaultByteBufferPool> dbbpConsumer = sb0.provides(ServiceName.parse(Capabilities.CAPABILITY_BYTE_BUFFER_POOL + ".default"));
sb0.setInstance(Service.newInstance(dbbpConsumer, new DefaultByteBufferPool(true, 2048)));
sb0.install();
// ListenerRegistry.Listener listener = new ListenerRegistry.Listener("http", "default", "default",
// InetSocketAddress.createUnresolved("localhost",8080));
target.addService(ServiceName.parse(Capabilities.REF_HTTP_LISTENER_REGISTRY)).setInstance(new HttpListenerRegistryService()).install();
final ServiceName tmpDirPath = ServiceName.JBOSS.append("server", "path", "temp");
final ServiceBuilder<?> sb1 = target.addService(tmpDirPath);
final Consumer<String> c = sb1.provides(tmpDirPath);
sb1.setInstance(Service.newInstance(c, System.getProperty("java.io.tmpdir")));
sb1.install();
HttpAuthenticationFactory authenticationFactory = HttpAuthenticationFactory.builder()
.build();
final ServiceBuilder<?> sb4 = target.addService(ServiceName.parse("org.wildfly.security.http-authentication-factory.factory"));
final Consumer<HttpAuthenticationFactory> hafConsumer = sb4.provides(ServiceName.parse("org.wildfly.security.http-authentication-factory.factory"));
sb4.setInstance(Service.newInstance(hafConsumer, authenticationFactory));
sb4.install();
ServiceName sslContextServiceName = ServiceName.parse("org.wildfly.security.ssl-context.TestContext");
final ServiceBuilder<?> sb5 = target.addService(sslContextServiceName);
final Consumer<SSLContext> scConsumer = sb5.provides(sslContextServiceName);
sb5.setInstance(Service.newInstance(scConsumer, sslContext));
sb5.install();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
private static final class NullService implements org.jboss.msc.service.Service<ControlledProcessStateService> {
@Override
public void start(StartContext context) {
}
@Override
public void stop(StopContext context) {
}
@Override
public ControlledProcessStateService getValue() throws IllegalStateException, IllegalArgumentException {
return null;
}
}} | 9,679 | 52.480663 | 169 | java |
null | wildfly-main/undertow/src/test/java/org/wildfly/extension/undertow/UndertowSubsystemTestCase.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.undertow;
import java.util.EnumSet;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
/**
* Tests subsystem against configurations for all supported subsystem schema versions.
* @author Paul Ferraro
*/
@RunWith(Parameterized.class)
public class UndertowSubsystemTestCase extends AbstractUndertowSubsystemTestCase {
@Parameters
public static Iterable<UndertowSubsystemSchema> parameters() {
return EnumSet.allOf(UndertowSubsystemSchema.class);
}
public UndertowSubsystemTestCase(UndertowSubsystemSchema schema) {
super(schema);
}
}
| 1,703 | 35.255319 | 86 | java |
null | wildfly-main/undertow/src/test/java/org/wildfly/extension/undertow/UndertowServiceTestCase.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2021, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.undertow;
import org.jboss.as.subsystem.test.KernelServices;
import org.jboss.as.subsystem.test.KernelServicesBuilder;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* Test for UndertowService created from xml file.
*
* @author Flavia Rainone
*/
public class UndertowServiceTestCase extends AbstractUndertowSubsystemTestCase {
private static final String NODE_NAME = "node-name";
private static final String DEFAULT_SERVER = "default-server";
private static final String DEFAULT_SERVLET_CONTAINER = "default";
private static final String DEFAULT_VIRTUAL_HOST = "default-host";
public UndertowServiceTestCase() {
super(UndertowSubsystemSchema.VERSION_12_0);
}
@Override
public void setUp() {
super.setUp();
System.setProperty("jboss.node.name", NODE_NAME);
}
private UndertowService load(String xmlFile) throws Exception {
KernelServicesBuilder builder = createKernelServicesBuilder(new RuntimeInitialization(this.values)).setSubsystemXml(readResource(xmlFile));
KernelServices mainServices = builder.build();
if (!mainServices.isSuccessfulBoot()) {
Throwable t = mainServices.getBootError();
Assert.fail("Boot unsuccessful: " + (t != null ? t.toString() : "no boot error provided"));
}
final UndertowService undertowService = (UndertowService) this.values.get(UndertowRootDefinition.UNDERTOW_CAPABILITY.getCapabilityServiceName()).get();
assertNotNull(undertowService);
return undertowService;
}
@Test
public void testUndefinedAttributes() throws Exception {
final UndertowService undertowService = load("undertow-service-undefined-attributes.xml");
assertEquals(NODE_NAME, undertowService.getInstanceId());
assertFalse(undertowService.isObfuscateSessionRoute());
assertFalse(undertowService.isStatisticsEnabled());
assertEquals(DEFAULT_SERVER, undertowService.getDefaultServer());
assertEquals(DEFAULT_SERVLET_CONTAINER, undertowService.getDefaultContainer());
assertEquals(DEFAULT_VIRTUAL_HOST, undertowService.getDefaultVirtualHost());
}
@Test
public void testDefinedDefaultAttributes1() throws Exception {
final UndertowService undertowService = load("undertow-service-defined-default-attributes1.xml");
assertEquals(NODE_NAME, undertowService.getInstanceId());
assertFalse(undertowService.isObfuscateSessionRoute());
assertFalse(undertowService.isStatisticsEnabled());
assertEquals(DEFAULT_SERVER, undertowService.getDefaultServer());
assertEquals(DEFAULT_SERVLET_CONTAINER, undertowService.getDefaultContainer());
assertEquals(DEFAULT_VIRTUAL_HOST, undertowService.getDefaultVirtualHost());
}
@Test
public void testDefinedDefaultAttributes2() throws Exception {
final UndertowService undertowService = load("undertow-service-defined-default-attributes2.xml");
assertEquals(NODE_NAME, undertowService.getInstanceId());
assertFalse(undertowService.isObfuscateSessionRoute());
assertFalse(undertowService.isStatisticsEnabled());
assertEquals(DEFAULT_SERVER, undertowService.getDefaultServer());
assertEquals(DEFAULT_SERVLET_CONTAINER, undertowService.getDefaultContainer());
assertEquals(DEFAULT_VIRTUAL_HOST, undertowService.getDefaultVirtualHost());
}
@Test
public void testDefinedAttributes() throws Exception {
final UndertowService undertowService = load("undertow-service-defined-attributes.xml");
assertEquals(NODE_NAME + "-undertow", undertowService.getInstanceId());
assertFalse(undertowService.isObfuscateSessionRoute());
assertTrue(undertowService.isStatisticsEnabled());
assertEquals("undertow-server", undertowService.getDefaultServer());
assertEquals("servlet-container", undertowService.getDefaultContainer());
assertEquals("virtual-host", undertowService.getDefaultVirtualHost());
}
@Test
public void testObfuscateInstanceId1() throws Exception {
final UndertowService undertowService = load("undertow-service-obfuscate-instance-id-attribute1.xml");
//assertEquals(new String(Base64.getUrlEncoder().encode(NODE_NAME.getBytes())), undertowService.getInstanceId());
assertEquals(NODE_NAME, undertowService.getInstanceId());
assertTrue(undertowService.isObfuscateSessionRoute());
assertFalse(undertowService.isStatisticsEnabled());
assertEquals("undertow-server", undertowService.getDefaultServer());
assertEquals(DEFAULT_SERVLET_CONTAINER, undertowService.getDefaultContainer());
assertEquals("virtual-host3", undertowService.getDefaultVirtualHost());
}
@Test
public void testObfuscateInstanceId2() throws Exception {
final UndertowService undertowService = load("undertow-service-obfuscate-instance-id-attribute2.xml");
assertEquals("my-undertow-instance", undertowService.getInstanceId());
assertTrue(undertowService.isObfuscateSessionRoute());
assertFalse(undertowService.isStatisticsEnabled());
assertEquals("undertow-server", undertowService.getDefaultServer());
assertEquals(DEFAULT_SERVLET_CONTAINER, undertowService.getDefaultContainer());
assertEquals("virtual-host3", undertowService.getDefaultVirtualHost());
}
}
| 6,660 | 47.620438 | 159 | java |
null | wildfly-main/undertow/src/test/java/org/wildfly/extension/undertow/UndertowSubsystemTransformerTestCase.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.undertow;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.capability.RuntimeCapability;
import org.jboss.as.model.test.FailedOperationTransformationConfig;
import org.jboss.as.model.test.ModelFixer;
import org.jboss.as.model.test.ModelTestControllerVersion;
import org.jboss.as.model.test.ModelTestUtils;
import org.jboss.as.subsystem.test.AbstractSubsystemTest;
import org.jboss.as.subsystem.test.AdditionalInitialization;
import org.jboss.as.subsystem.test.KernelServices;
import org.jboss.as.subsystem.test.KernelServicesBuilder;
import org.jboss.as.subsystem.test.LegacyKernelServicesInitializer;
import org.jboss.dmr.ModelNode;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.wildfly.extension.undertow.filters.FilterDefinitions;
import org.wildfly.extension.undertow.handlers.HandlerDefinitions;
/**
* Validates Undertow subsystem transformations.
* @author Paul Ferraro
*/
@RunWith(value = Parameterized.class)
public class UndertowSubsystemTransformerTestCase extends AbstractSubsystemTest {
@Parameters
public static Collection<Object[]> parameters() {
return List.<Object[]>of(
new Object[] { ModelTestControllerVersion.EAP_7_4_0, UndertowSubsystemModel.VERSION_11_0_0 }
);
}
private void addDependencies(LegacyKernelServicesInitializer initializer) throws ClassNotFoundException, IOException {
initializer.addMavenResourceURL(String.format("%s:wildfly-undertow:%s", this.controllerVersion.getMavenGroupId(), this.controllerVersion.getMavenGavVersion()));
initializer.addMavenResourceURL(String.format("%s:wildfly-web-common:%s", this.controllerVersion.getMavenGroupId(), this.controllerVersion.getMavenGavVersion()));
initializer.addMavenResourceURL(String.format("%s:wildfly-clustering-common:%s", this.controllerVersion.getMavenGroupId(), this.controllerVersion.getMavenGavVersion()));
initializer.addMavenResourceURL(String.format("%s:wildfly-clustering-web-container:%s", this.controllerVersion.getMavenGroupId(), this.controllerVersion.getMavenGavVersion()));
initializer.addParentFirstClassPattern("org.jboss.msc.service.ServiceName");
initializer.addParentFirstClassPattern("org.jboss.as.clustering.controller.CapabilityServiceConfigurator");
switch (this.controllerVersion) {
case EAP_7_4_0:
initializer.addMavenResourceURL("io.undertow:undertow-core:2.2.5.Final");
initializer.addMavenResourceURL("io.undertow:undertow-servlet:2.2.5.Final");
initializer.addMavenResourceURL("org.jboss.spec.javax.security.jacc:jboss-jacc-api_1.5_spec:2.0.0.Final");
break;
default: {
throw new IllegalArgumentException();
}
}
}
private final ModelTestControllerVersion controllerVersion;
private final ModelVersion modelVersion;
public UndertowSubsystemTransformerTestCase(ModelTestControllerVersion controllerVersion, UndertowSubsystemModel subsystemModel) {
super(UndertowExtension.SUBSYSTEM_NAME, new UndertowExtension());
this.controllerVersion = controllerVersion;
this.modelVersion = subsystemModel.getVersion();
}
private AdditionalInitialization createAdditionalInitialization() {
return AdditionalInitialization.withCapabilities(
RuntimeCapability.buildDynamicCapabilityName(Capabilities.REF_SOCKET_BINDING, "ajp"),
RuntimeCapability.buildDynamicCapabilityName(Capabilities.REF_SOCKET_BINDING, "http"),
RuntimeCapability.buildDynamicCapabilityName(Capabilities.REF_SOCKET_BINDING, "https"),
RuntimeCapability.buildDynamicCapabilityName(Capabilities.REF_SSL_CONTEXT, "ssl")
);
}
private KernelServices build(KernelServicesBuilder builder) throws Exception {
LegacyKernelServicesInitializer initializer = builder.createLegacyKernelServicesBuilder(this.createAdditionalInitialization(), this.controllerVersion, this.modelVersion)
.skipReverseControllerCheck()
.dontPersistXml();
this.addDependencies(initializer);
KernelServices services = builder.build();
verifyBoot(ModelTestControllerVersion.MASTER, services);
verifyBoot(this.controllerVersion, services.getLegacyServices(this.modelVersion));
return services;
}
private static void verifyBoot(ModelTestControllerVersion version, KernelServices services) {
try {
Assert.assertTrue(version.getMavenGavVersion() + " boot failed: " + services.getBootErrorDescription() + (services.hasBootErrorCollectorFailures() ? ": " + services.getBootErrorCollectorFailures().toJSONString(false) : ""), services.isSuccessfulBoot());
} finally {
Throwable exception = services.getBootError();
if (exception != null) {
exception.printStackTrace(System.err);
}
}
}
@Test
public void testTransformations() throws Exception {
KernelServicesBuilder builder = this.createKernelServicesBuilder(this.createAdditionalInitialization()).setSubsystemXml(this.readResource("undertow-transform.xml"));
KernelServices services = this.build(builder);
ModelFixer fixer = model -> {
model.get(HandlerDefinitions.PATH_ELEMENT.getKeyValuePair()).set(new ModelNode());
model.get(FilterDefinitions.PATH_ELEMENT.getKeyValuePair()).set(new ModelNode());
return model;
};
this.checkSubsystemModelTransformation(services, this.modelVersion, fixer, false);
}
@Test
public void testRejections() throws Exception {
KernelServicesBuilder builder = this.createKernelServicesBuilder(this.createAdditionalInitialization());
KernelServices services = this.build(builder);
FailedOperationTransformationConfig config = new FailedOperationTransformationConfig();
PathAddress subsystemAddress = PathAddress.pathAddress(UndertowRootDefinition.PATH_ELEMENT);
PathAddress servletContainerAddress = subsystemAddress.append(PathElement.pathElement(ServletContainerDefinition.PATH_ELEMENT.getKey(), "rejected-container"));
PathAddress affinityCookiePath = subsystemAddress.append(PathElement.pathElement(ServletContainerDefinition.PATH_ELEMENT.getKey(), "affinity-cookie-container")).append(AffinityCookieDefinition.PATH_ELEMENT);
if (UndertowSubsystemModel.VERSION_13_0_0.requiresTransformation(this.modelVersion)) {
config.addFailedAttribute(servletContainerAddress, new FailedOperationTransformationConfig.NewAttributesConfig(ServletContainerDefinition.ORPHAN_SESSION_ALLOWED));
config.addFailedAttribute(affinityCookiePath, FailedOperationTransformationConfig.REJECTED_RESOURCE);
}
List<ModelNode> operations = builder.parseXmlResource("undertow-transform-reject.xml");
ModelTestUtils.checkFailedTransformedBootOperations(services, this.modelVersion, operations, config);
}
}
| 8,444 | 52.113208 | 265 | java |
null | wildfly-main/undertow/src/test/java/org/wildfly/extension/undertow/AuthMechanismParserUnitTestCase.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.undertow;
import io.undertow.servlet.api.AuthMethodConfig;
import org.junit.Assert;
import org.junit.Test;
import org.wildfly.extension.undertow.deployment.AuthMethodParser;
import java.util.Collections;
import java.util.List;
/**
* @author Stuart Douglas
*/
public class AuthMechanismParserUnitTestCase {
@Test
public void testAuthMechanismParsing() {
List<AuthMethodConfig> res = AuthMethodParser.parse("BASIC", Collections.<String, String>emptyMap());
Assert.assertEquals(1, res.size());
Assert.assertEquals(0, res.get(0).getProperties().size());
Assert.assertEquals("BASIC", res.get(0).getName());
res = AuthMethodParser.parse("BASIC?silent=true", Collections.<String, String>emptyMap());
Assert.assertEquals(1, res.size());
Assert.assertEquals(1, res.get(0).getProperties().size());
Assert.assertEquals("BASIC", res.get(0).getName());
Assert.assertEquals("true", res.get(0).getProperties().get("silent"));
res = AuthMethodParser.parse("BASIC?silent=true,FORM", Collections.<String, String>emptyMap());
Assert.assertEquals(2, res.size());
Assert.assertEquals(1, res.get(0).getProperties().size());
Assert.assertEquals("BASIC", res.get(0).getName());
Assert.assertEquals("true", res.get(0).getProperties().get("silent"));
Assert.assertEquals(0, res.get(1).getProperties().size());
Assert.assertEquals("FORM", res.get(1).getName());
res = AuthMethodParser.parse("BASIC?silent=true,FORM,", Collections.<String, String>emptyMap());
Assert.assertEquals(2, res.size());
Assert.assertEquals(1, res.get(0).getProperties().size());
Assert.assertEquals("BASIC", res.get(0).getName());
Assert.assertEquals("true", res.get(0).getProperties().get("silent"));
Assert.assertEquals(0, res.get(1).getProperties().size());
Assert.assertEquals("FORM", res.get(1).getName());
res = AuthMethodParser.parse("BASIC?silent=true,FORM?,", Collections.<String, String>emptyMap());
Assert.assertEquals(2, res.size());
Assert.assertEquals(1, res.get(0).getProperties().size());
Assert.assertEquals("BASIC", res.get(0).getName());
Assert.assertEquals("true", res.get(0).getProperties().get("silent"));
Assert.assertEquals(0, res.get(1).getProperties().size());
Assert.assertEquals("FORM", res.get(1).getName());
res = AuthMethodParser.parse("BASIC?silent=true,FORM?a=b+c&d=e%20f,", Collections.<String, String>emptyMap());
Assert.assertEquals(2, res.size());
Assert.assertEquals(1, res.get(0).getProperties().size());
Assert.assertEquals("BASIC", res.get(0).getName());
Assert.assertEquals("true", res.get(0).getProperties().get("silent"));
Assert.assertEquals(2, res.get(1).getProperties().size());
Assert.assertEquals("FORM", res.get(1).getName());
Assert.assertEquals("b c", res.get(1).getProperties().get("a"));
Assert.assertEquals("e f", res.get(1).getProperties().get("d"));
}
}
| 4,143 | 50.160494 | 118 | java |
null | wildfly-main/undertow/src/test/java/org/wildfly/extension/undertow/AbstractUndertowSubsystemTestCase.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.undertow;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
import io.undertow.server.HandlerWrapper;
import io.undertow.server.HttpHandler;
import io.undertow.server.handlers.PathHandler;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.model.test.ModelTestUtils;
import org.jboss.as.subsystem.test.AbstractSubsystemSchemaTest;
import org.jboss.as.subsystem.test.AdditionalInitialization;
import org.jboss.as.subsystem.test.KernelServices;
import org.jboss.as.subsystem.test.KernelServicesBuilder;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceName;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public abstract class AbstractUndertowSubsystemTestCase extends AbstractSubsystemSchemaTest<UndertowSubsystemSchema> {
final Map<ServiceName, Supplier<Object>> values = new ConcurrentHashMap<>();
private final UndertowSubsystemSchema schema;
AbstractUndertowSubsystemTestCase() {
this(UndertowSubsystemSchema.CURRENT);
}
AbstractUndertowSubsystemTestCase(UndertowSubsystemSchema schema) {
super(UndertowExtension.SUBSYSTEM_NAME, new UndertowExtension(), schema, UndertowSubsystemSchema.CURRENT);
this.schema = schema;
}
@Before
public void setUp() {
System.setProperty("server.data.dir", System.getProperty("java.io.tmpdir"));
System.setProperty("jboss.home.dir", System.getProperty("java.io.tmpdir"));
System.setProperty("jboss.home.dir", System.getProperty("java.io.tmpdir"));
System.setProperty("jboss.server.server.dir", System.getProperty("java.io.tmpdir"));
}
@Override
protected Properties getResolvedProperties() {
Properties properties = new Properties();
properties.put("jboss.home.dir", System.getProperty("java.io.tmpdir"));
properties.put("jboss.server.server.dir", System.getProperty("java.io.tmpdir"));
properties.put("server.data.dir", System.getProperty("java.io.tmpdir"));
return properties;
}
@Test
public void testRuntime() throws Exception {
// Skip runtime tests for old versions - since legacy SSO is only allowed in admin-only mode
if (!this.schema.since(UndertowSubsystemSchema.VERSION_14_0)) return;
KernelServicesBuilder builder = createKernelServicesBuilder(new RuntimeInitialization(this.values)).setSubsystemXml(getSubsystemXml());
KernelServices mainServices = builder.build();
if (!mainServices.isSuccessfulBoot()) {
Throwable t = mainServices.getBootError();
Assert.fail("Boot unsuccessful: " + (t != null ? t.toString() : "no boot error provided"));
}
HandlerWrapper connectionLimiterService = (HandlerWrapper) this.values.get(UndertowService.FILTER.append("limit-connections")).get();
HttpHandler connectionLimiterHandler = connectionLimiterService.wrap(new PathHandler());
Assert.assertNotNull("handler should have been created", connectionLimiterHandler);
HandlerWrapper headersService = (HandlerWrapper) this.values.get(UndertowService.FILTER.append("headers")).get();
HttpHandler headerHandler = headersService.wrap(new PathHandler());
Assert.assertNotNull("handler should have been created", headerHandler);
HandlerWrapper modClusterService = (HandlerWrapper) this.values.get(UndertowService.FILTER.append("mod-cluster")).get();
Assert.assertNotNull(modClusterService);
HttpHandler modClusterHandler = modClusterService.wrap(new PathHandler());
Assert.assertNotNull("handler should have been created", modClusterHandler);
UndertowService undertowService = (UndertowService) this.values.get(UndertowRootDefinition.UNDERTOW_CAPABILITY.getCapabilityServiceName()).get();
Assert.assertEquals("some-id", undertowService.getInstanceId());
Assert.assertTrue(undertowService.isStatisticsEnabled());
Assert.assertEquals("some-server", undertowService.getDefaultServer());
Assert.assertEquals("myContainer", undertowService.getDefaultContainer());
Assert.assertEquals("default-virtual-host", undertowService.getDefaultVirtualHost());
// Don't verify servers until we know they are registered
Assert.assertEquals(1, undertowService.getServers().size());
Server server = undertowService.getServers().iterator().next();
Assert.assertEquals("other-host", server.getDefaultHost());
Host host = (Host) this.values.get(HostDefinition.HOST_CAPABILITY.getCapabilityServiceName("some-server", "other-host")).get();
// Don't verify hosts until we know that they are all registered
Assert.assertEquals(2, server.getHosts().size());
Assert.assertEquals("some-server", server.getName());
Assert.assertEquals(3, host.getAllAliases().size());
Assert.assertTrue(host.getAllAliases().contains("default-alias"));
LocationService locationService = (LocationService) this.values.get(UndertowService.locationServiceName("some-server", "default-virtual-host", "/")).get();
Assert.assertNotNull(locationService);
JSPConfig jspConfig = ((ServletContainerService) this.values.get(ServletContainerDefinition.SERVLET_CONTAINER_CAPABILITY.getCapabilityServiceName("myContainer")).get()).getJspConfig();
Assert.assertNotNull(jspConfig);
Assert.assertNotNull(jspConfig.createJSPServletInfo());
UndertowFilter gzipFilterRef = (UndertowFilter) this.values.get(UndertowService.filterRefName("some-server", "other-host", "/", "static-gzip")).get();
HttpHandler gzipHandler = gzipFilterRef.wrap(new PathHandler());
Assert.assertNotNull("handler should have been created", gzipHandler);
Assert.assertEquals(1, host.getFilters().size());
ModelNode op = Util.createOperation("write-attribute",
PathAddress.pathAddress(UndertowRootDefinition.PATH_ELEMENT)
.append("servlet-container", "myContainer")
.append("setting", "websockets")
);
op.get("name").set("buffer-pool");
op.get("value").set("default");
ModelNode res = ModelTestUtils.checkOutcome(mainServices.executeOperation(op));
Assert.assertNotNull(res);
// WFLY-14648 Check expression in enabled attribute is resolved.
op = Util.createOperation("write-attribute",
PathAddress.pathAddress(UndertowRootDefinition.PATH_ELEMENT)
.append("server", "some-server")
.append("http-listener", "default")
);
op.get("name").set("enabled");
op.get("value").set("${env.val:true}");
res = ModelTestUtils.checkOutcome(mainServices.executeOperation(op));
Assert.assertNotNull(res);
Host defaultHost = (Host) this.values.get(UndertowService.DEFAULT_HOST).get();
Assert.assertNotNull("Default host should exist", defaultHost);
Server defaultServer = (Server) this.values.get(UndertowService.DEFAULT_SERVER).get();
Assert.assertNotNull("Default host should exist", defaultServer);
AccessLogService accessLogService = (AccessLogService) this.values.get(UndertowService.accessLogServiceName("some-server", "default-virtual-host")).get();
Assert.assertNotNull(accessLogService);
Assert.assertFalse(accessLogService.isRotate());
if (this.schema.since(UndertowSubsystemSchema.VERSION_13_0)) {
PathAddress address = PathAddress.pathAddress(UndertowRootDefinition.PATH_ELEMENT, PathElement.pathElement(Constants.APPLICATION_SECURITY_DOMAIN, "other"), SingleSignOnDefinition.PATH_ELEMENT);
ModelNode result = mainServices.executeOperation(Util.getWriteAttributeOperation(address, SingleSignOnDefinition.Attribute.PATH.getName(), new ModelNode("/modified-path")));
assertEquals(ModelDescriptionConstants.SUCCESS, result.get(ModelDescriptionConstants.OUTCOME).asString());
assertTrue("It is expected that reload is required after the operation.", result.get(ModelDescriptionConstants.RESPONSE_HEADERS).get(ModelDescriptionConstants.OPERATION_REQUIRES_RELOAD).asBoolean());
}
}
@Override
protected AdditionalInitialization createAdditionalInitialization() {
return new DefaultInitialization();
}
}
| 9,783 | 51.042553 | 211 | java |
null | wildfly-main/undertow/src/test/java/org/wildfly/extension/undertow/UndertowServerRemovalTestCase.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2023, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.undertow;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.subsystem.test.KernelServices;
import org.jboss.as.subsystem.test.KernelServicesBuilder;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceName;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* Tests server and host removal in Undertow subsystem.
*
* @author <a href="mailto:[email protected]">Lin Gao</a>
*/
public class UndertowServerRemovalTestCase extends AbstractUndertowSubsystemTestCase {
private static final String NODE_NAME = "node-name";
private static final String SERVER_ABC = "abc";
private static final String HOST_ABC = "abc-host";
public UndertowServerRemovalTestCase() {
super(UndertowSubsystemSchema.CURRENT);
}
@Override
public void setUp() {
super.setUp();
System.setProperty("jboss.node.name", NODE_NAME);
}
private KernelServices load(String subsystemXml) throws Exception {
KernelServicesBuilder builder = createKernelServicesBuilder(new RuntimeInitialization(this.values)).setSubsystemXml(subsystemXml);
KernelServices mainServices = builder.build();
if (!mainServices.isSuccessfulBoot()) {
Throwable t = mainServices.getBootError();
Assert.fail("Boot unsuccessful: " + (t != null ? t.toString() : "no boot error provided"));
}
return mainServices;
}
private PathAddress serverAddress(String server) {
return PathAddress.pathAddress("subsystem", "undertow").append("server", server);
}
private PathAddress hostAddress(String server, String host) {
return serverAddress(server).append("host", host);
}
@Test
public void removeDefaultServerShouldFail() throws Exception {
KernelServices mainServices = null;
try {
final String defaultServer = "some-server";
final String defaultHost = "default-virtual-host";
mainServices = load(getSubsystemXml());
final ServiceName undertowServerName = ServerDefinition.SERVER_CAPABILITY.getCapabilityServiceName(defaultServer);
Server server = (Server) this.values.get(undertowServerName).get();
assertNotNull(server);
Assert.assertEquals(defaultServer, server.getName());
final int times = 2;
for (int i = 0; i < times; i ++) {
ModelNode removeOp = Util.createOperation(ModelDescriptionConstants.REMOVE, serverAddress(defaultServer));
ModelNode response = mainServices.executeOperation(removeOp);
assertEquals(ModelDescriptionConstants.FAILED, response.get(ModelDescriptionConstants.OUTCOME).asString());
assertNotNull(response.get(ModelDescriptionConstants.FAILURE_DESCRIPTION));
assertTrue(response.get(ModelDescriptionConstants.FAILURE_DESCRIPTION).asString().contains("WFLYCTL0367"));
}
for (int i = 0; i < times; i ++) {
ModelNode removeOp = Util.createOperation(ModelDescriptionConstants.REMOVE, hostAddress(defaultServer, defaultHost));
ModelNode response = mainServices.executeOperation(removeOp);
assertEquals(ModelDescriptionConstants.FAILED, response.get(ModelDescriptionConstants.OUTCOME).asString());
assertNotNull(response.get(ModelDescriptionConstants.FAILURE_DESCRIPTION));
assertTrue(response.get(ModelDescriptionConstants.FAILURE_DESCRIPTION).asString().contains("WFLYCTL0367"));
}
} finally {
if (mainServices != null) {
mainServices.shutdown();
}
}
}
@Test
public void removeNonDefaultHost() throws Exception {
KernelServices mainServices = null;
try {
mainServices = load(getSubsystemXml("undertow-service-extra-server.xml"));
ModelNode removeOp = Util.createOperation(ModelDescriptionConstants.REMOVE, hostAddress(SERVER_ABC, HOST_ABC));
ModelNode response = mainServices.executeOperation(removeOp);
assertEquals(ModelDescriptionConstants.SUCCESS, response.get(ModelDescriptionConstants.OUTCOME).asString());
assertEquals(ModelDescriptionConstants.RELOAD_REQUIRED, response.get(ModelDescriptionConstants.RESPONSE_HEADERS).get(ModelDescriptionConstants.PROCESS_STATE).asString());
} finally {
if (mainServices != null) {
mainServices.shutdown();
}
}
}
@Test
public void removeNonDefaultHostAllowResourceServiceRestart() throws Exception {
KernelServices mainServices = null;
try {
mainServices = load(getSubsystemXml("undertow-service-extra-server.xml"));
ModelNode removeOp = Util.createOperation(ModelDescriptionConstants.REMOVE, hostAddress(SERVER_ABC, HOST_ABC));
removeOp.get(ModelDescriptionConstants.OPERATION_HEADERS)
.get(ModelDescriptionConstants.ALLOW_RESOURCE_SERVICE_RESTART)
.set(true);
ModelNode response = mainServices.executeOperation(removeOp);
assertEquals(ModelDescriptionConstants.SUCCESS, response.get(ModelDescriptionConstants.OUTCOME).asString());
assertFalse(response.hasDefined(ModelDescriptionConstants.RESPONSE_HEADERS));
} finally {
if (mainServices != null) {
mainServices.shutdown();
}
}
}
@Test
public void removeNonDefaultServer() throws Exception {
KernelServices mainServices = null;
try {
mainServices = load(getSubsystemXml("undertow-service-extra-server.xml"));
ModelNode removeOp = Util.createOperation(ModelDescriptionConstants.REMOVE, serverAddress(SERVER_ABC));
ModelNode response = mainServices.executeOperation(removeOp);
assertEquals(ModelDescriptionConstants.SUCCESS, response.get(ModelDescriptionConstants.OUTCOME).asString());
assertEquals(ModelDescriptionConstants.RELOAD_REQUIRED, response.get(ModelDescriptionConstants.RESPONSE_HEADERS).get(ModelDescriptionConstants.PROCESS_STATE).asString());
} finally {
if (mainServices != null) {
mainServices.shutdown();
}
}
}
@Test
public void removeNonDefaultServerAllowResourceServiceRestart() throws Exception {
KernelServices mainServices = null;
try {
mainServices = load(getSubsystemXml("undertow-service-extra-server.xml"));
ModelNode removeOp = Util.createOperation(ModelDescriptionConstants.REMOVE, serverAddress(SERVER_ABC));
removeOp.get(ModelDescriptionConstants.OPERATION_HEADERS)
.get(ModelDescriptionConstants.ALLOW_RESOURCE_SERVICE_RESTART)
.set(true);
ModelNode response = mainServices.executeOperation(removeOp);
assertEquals(ModelDescriptionConstants.SUCCESS, response.get(ModelDescriptionConstants.OUTCOME).asString());
assertEquals(ModelDescriptionConstants.RELOAD_REQUIRED, response.get(ModelDescriptionConstants.RESPONSE_HEADERS).get(ModelDescriptionConstants.PROCESS_STATE).asString());
} finally {
if (mainServices != null) {
mainServices.shutdown();
}
}
}
}
| 8,758 | 46.603261 | 182 | java |
null | wildfly-main/undertow/src/test/java/org/wildfly/extension/undertow/DefaultInitialization.java | /*
Copyright 2017 Red Hat, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.wildfly.extension.undertow;
import static org.jboss.as.controller.capability.RuntimeCapability.buildDynamicCapabilityName;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.MULTICAST_ADDRESS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.MULTICAST_PORT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PORT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SOCKET_BINDING;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SOCKET_BINDING_GROUP;
import static org.wildfly.extension.undertow.Capabilities.CAPABILITY_BYTE_BUFFER_POOL;
import static org.wildfly.extension.undertow.Capabilities.REF_IO_WORKER;
import java.security.KeyStore;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.net.ssl.SSLContext;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.RunningMode;
import org.jboss.as.controller.capability.RuntimeCapability;
import org.jboss.as.controller.capability.registry.RuntimeCapabilityRegistry;
import org.jboss.as.controller.extension.ExtensionRegistry;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.network.OutboundSocketBinding;
import org.jboss.as.subsystem.test.AdditionalInitialization;
import org.jboss.as.subsystem.test.ControllerInitializer;
import org.jboss.dmr.ModelNode;
import org.wildfly.security.auth.server.HttpAuthenticationFactory;
import org.wildfly.security.auth.server.SecurityDomain;
import org.wildfly.security.credential.store.CredentialStore;
import org.xnio.Pool;
import org.xnio.XnioWorker;
import io.undertow.connector.ByteBufferPool;
/**
* Initialization used in undertow subsystem tests.
*
* @author Brian Stansberry
*/
class DefaultInitialization extends AdditionalInitialization.ManagementAdditionalInitialization {
private static final long serialVersionUID = 1L;
@Override
protected ControllerInitializer createControllerInitializer() {
return new ControllerInitializer() {
@Override
protected void initializeSocketBindingsOperations(List<ModelNode> ops) {
super.initializeSocketBindingsOperations(ops);
ModelNode op = new ModelNode();
op.get(OP).set(ADD);
op.get(OP_ADDR).set(PathAddress.pathAddress(PathElement.pathElement(SOCKET_BINDING_GROUP, SOCKET_BINDING_GROUP_NAME),
PathElement.pathElement(SOCKET_BINDING, "advertise-socket-binding")).toModelNode());
op.get(PORT).set(8011);
op.get(MULTICAST_ADDRESS).set("224.0.1.105");
op.get(MULTICAST_PORT).set("23364");
ops.add(op);
}
};
}
@Override
protected RunningMode getRunningMode() {
return RunningMode.ADMIN_ONLY;
}
@Override
protected void setupController(ControllerInitializer controllerInitializer) {
super.setupController(controllerInitializer);
final Map<String, Integer> sockets = new HashMap<>();
{
sockets.put("ajp", 8009);
sockets.put("http", 8080);
sockets.put("http-2", 8081);
sockets.put("http-3", 8082);
sockets.put("https-non-default", 8433);
sockets.put("https-2", 8434);
sockets.put("https-3", 8435);
sockets.put("https-4", 8436);
sockets.put("ajps", 8010);
sockets.put("test3", 8012);
}
for (Map.Entry<String, Integer> entry : sockets.entrySet()) {
controllerInitializer.addSocketBinding(entry.getKey(), entry.getValue());
}
controllerInitializer.addRemoteOutboundSocketBinding("ajp-remote", "localhost", 7777);
}
@Override
protected void initializeExtraSubystemsAndModel(ExtensionRegistry extensionRegistry, Resource rootResource,
ManagementResourceRegistration rootRegistration, RuntimeCapabilityRegistry capabilityRegistry) {
super.initializeExtraSubystemsAndModel(extensionRegistry, rootResource, rootRegistration, capabilityRegistry);
Map<String, Class> capabilities = new HashMap<>();
capabilities.put(buildDynamicCapabilityName(REF_IO_WORKER,
ListenerResourceDefinition.WORKER.getDefaultValue().asString()), XnioWorker.class);
capabilities.put(buildDynamicCapabilityName(REF_IO_WORKER, "non-default"),
XnioWorker.class);
capabilities.put(buildDynamicCapabilityName(CAPABILITY_BYTE_BUFFER_POOL,
ListenerResourceDefinition.BUFFER_POOL.getDefaultValue().asString()), ByteBufferPool.class);
capabilities.put(buildDynamicCapabilityName("org.wildfly.io.buffer-pool",
ListenerResourceDefinition.BUFFER_POOL.getDefaultValue().asString()), Pool.class);
capabilities.put(buildDynamicCapabilityName(Capabilities.REF_HTTP_AUTHENTICATION_FACTORY, "elytron-factory"), HttpAuthenticationFactory.class);
capabilities.put(buildDynamicCapabilityName(Capabilities.REF_HTTP_AUTHENTICATION_FACTORY, "factory"), HttpAuthenticationFactory.class);
capabilities.put(buildDynamicCapabilityName(Capabilities.REF_SECURITY_DOMAIN, "elytron-domain"), SecurityDomain.class);
capabilities.put(buildDynamicCapabilityName("org.wildfly.security.ssl-context", "TestContext"), SSLContext.class);
capabilities.put(buildDynamicCapabilityName("org.wildfly.security.ssl-context", "my-ssl-context"), SSLContext.class);
capabilities.put(buildDynamicCapabilityName("org.wildfly.security.key-store", "my-key-store"), KeyStore.class);
capabilities.put(buildDynamicCapabilityName("org.wildfly.security.credential-store", "my-credential-store"), CredentialStore.class);
capabilities.put(buildDynamicCapabilityName("org.wildfly.security.ssl-context", "foo"), SSLContext.class);
//capabilities.put(buildDynamicCapabilityName("org.wildfly.network.outbound-socket-binding","ajp-remote"), OutboundSocketBinding.class);
registerServiceCapabilities(capabilityRegistry, capabilities);
registerCapabilities(capabilityRegistry,
RuntimeCapability.Builder.of("org.wildfly.network.outbound-socket-binding", true, OutboundSocketBinding.class).build(),
RuntimeCapability.Builder.of("org.wildfly.security.ssl-context", true, SSLContext.class).build()
);
}
}
| 7,449 | 49 | 151 | java |
null | wildfly-main/undertow/src/test/java/org/wildfly/extension/undertow/ServerServiceTestCase.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2021, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.undertow;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;
import java.util.Set;
import org.jboss.as.subsystem.test.KernelServices;
import org.jboss.as.subsystem.test.KernelServicesBuilder;
import org.jboss.msc.service.ServiceName;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
/**
* Test for Server service created from xml file.
*
* @author Flavia Rainone
*/
public class ServerServiceTestCase extends AbstractUndertowSubsystemTestCase {
private static final String NODE_NAME = "node-name";
private static final String DEFAULT_SERVER = "default-server";
private static final String DEFAULT_VIRTUAL_HOST = "default-host";
private static final String UNDERTOW_SERVER = "undertow-server";
public ServerServiceTestCase() {
super(UndertowSubsystemSchema.VERSION_12_0);
}
@Override
public void setUp() {
super.setUp();
System.setProperty("jboss.node.name", NODE_NAME);
}
private Server load(String xmlFile, String serverName) throws Exception {
KernelServicesBuilder builder = createKernelServicesBuilder(new RuntimeInitialization(this.values)).setSubsystemXml(readResource(xmlFile));
KernelServices mainServices = builder.build();
if (!mainServices.isSuccessfulBoot()) {
Throwable t = mainServices.getBootError();
Assert.fail("Boot unsuccessful: " + (t != null ? t.toString() : "no boot error provided"));
}
final ServiceName undertowServerName = ServerDefinition.SERVER_CAPABILITY.getCapabilityServiceName(serverName);
Server server = (Server) this.values.get(undertowServerName).get();
assertNotNull(server);
return server;
}
@Test
public void testUndefinedAttributes() throws Exception {
final Server server = load("undertow-service-undefined-attributes.xml", DEFAULT_SERVER);
assertEquals(DEFAULT_SERVER, server.getName());
Set<Host> hosts = server.getHosts();
assertNotNull(hosts);
assertEquals(1, hosts.size());
Host host = hosts.iterator().next();
assertNotNull(host);
assertEquals(DEFAULT_VIRTUAL_HOST, host.getName());
assertSame(server, host.getServer());
assertEquals(DEFAULT_VIRTUAL_HOST, server.getDefaultHost());
assertEquals(NODE_NAME, server.getRoute());
}
@Test
public void testDefinedDefaultAttributes1() throws Exception {
final Server server = load("undertow-service-defined-default-attributes1.xml", DEFAULT_SERVER);
assertEquals(DEFAULT_SERVER, server.getName());
Set<Host> hosts = server.getHosts();
assertNotNull(hosts);
assertEquals(1, hosts.size());
Host host = hosts.iterator().next();
assertNotNull(host);
assertEquals(DEFAULT_VIRTUAL_HOST, host.getName());
assertSame(server, host.getServer());
assertEquals(DEFAULT_VIRTUAL_HOST, server.getDefaultHost());
assertEquals(NODE_NAME, server.getRoute());
}
@Test
public void testDefinedDefaultAttributes2() throws Exception {
final Server server = load("undertow-service-defined-default-attributes2.xml", DEFAULT_SERVER);
assertEquals(DEFAULT_SERVER, server.getName());
Set<Host> hosts = server.getHosts();
assertNotNull(hosts);
assertEquals(1, hosts.size());
Host host = hosts.iterator().next();
assertNotNull(host);
assertEquals(DEFAULT_VIRTUAL_HOST, host.getName());
assertSame(server, host.getServer());
assertEquals(DEFAULT_VIRTUAL_HOST, server.getDefaultHost());
assertEquals(NODE_NAME, server.getRoute());
}
@Test
public void testDefinedAttributes() throws Exception {
final Server server = load("undertow-service-defined-attributes.xml", UNDERTOW_SERVER);
assertEquals(UNDERTOW_SERVER, server.getName());
Set<Host> hosts = server.getHosts();
assertNotNull(hosts);
assertEquals(1, hosts.size());
Host host = hosts.iterator().next();
assertNotNull(host);
assertEquals("virtual-host", host.getName());
assertSame(server, host.getServer());
assertEquals("virtual-host", server.getDefaultHost());
assertEquals(NODE_NAME + "-undertow", server.getRoute());
}
@Test
public void testObfuscateInstanceId1() throws Exception {
final Server server = load("undertow-service-obfuscate-instance-id-attribute1.xml", UNDERTOW_SERVER);
assertEquals(UNDERTOW_SERVER, server.getName());
final Set<Host> hosts = server.getHosts();
assertNotNull(hosts);
assertEquals(1, hosts.size());
final Host host = hosts.iterator().next();
assertNotNull(host);
assertEquals("virtual-host3", host.getName());
assertSame(server, host.getServer());
assertEquals("virtual-host3", server.getDefaultHost());
final MessageDigest md = MessageDigest.getInstance("MD5");
md.update(UNDERTOW_SERVER.getBytes(StandardCharsets.UTF_8));
final byte[] md5Bytes = md.digest(NODE_NAME.getBytes(StandardCharsets.UTF_8));
final Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding();
assertEquals(new String(encoder.encode(md5Bytes), StandardCharsets.UTF_8), server.getRoute());
}
@Test
public void testObfuscateInstanceId2() throws Exception {
final Server server = load("undertow-service-obfuscate-instance-id-attribute2.xml", UNDERTOW_SERVER);
assertEquals(UNDERTOW_SERVER, server.getName());
final Set<Host> hosts = server.getHosts();
assertNotNull(hosts);
assertEquals(1, hosts.size());
final Host host = hosts.iterator().next();
assertNotNull(host);
assertEquals("virtual-host3", host.getName());
assertSame(server, host.getServer());
assertEquals("virtual-host3", server.getDefaultHost());
final MessageDigest md = MessageDigest.getInstance("MD5");
md.update(UNDERTOW_SERVER.getBytes(StandardCharsets.UTF_8));
final byte[] md5Bytes = md.digest("my-undertow-instance".getBytes(StandardCharsets.UTF_8));
final Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding();
assertEquals(new String(encoder.encode(md5Bytes), StandardCharsets.UTF_8), server.getRoute());
}
}
| 7,599 | 42.181818 | 147 | java |
null | wildfly-main/undertow/src/test/java/org/wildfly/extension/undertow/security/jacc/WarJACCServiceTest.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2022, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.undertow.security.jacc;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class WarJACCServiceTest {
@Test
public void testPatternExtensionMatching() {
WarJACCService.PatternInfo htm = new WarJACCService.PatternInfo("*.htm", 2);
WarJACCService.PatternInfo html = new WarJACCService.PatternInfo("*.html", 2);
WarJACCService.PatternInfo indexHtm = new WarJACCService.PatternInfo("/index.htm", 4);
WarJACCService.PatternInfo indexHtml = new WarJACCService.PatternInfo("/index.html", 4);
WarJACCService.PatternInfo indexHtmHtml = new WarJACCService.PatternInfo("/index.htm.html", 4);
WarJACCService.PatternInfo indexHtmlHtm = new WarJACCService.PatternInfo("/index.html.htm", 4);
assertTrue(htm.isExtensionFor(indexHtm));
assertTrue(html.isExtensionFor(indexHtml));
// extension has to match completely, not partially
assertFalse(html.isExtensionFor(indexHtm));
assertFalse(htm.isExtensionFor(indexHtml));
assertTrue(htm.isExtensionFor(indexHtmlHtm));
assertTrue(html.isExtensionFor(indexHtmHtml));
// extension has to match the last segment
assertFalse(html.isExtensionFor(indexHtmlHtm));
assertFalse(htm.isExtensionFor(indexHtmHtml));
}
}
| 2,412 | 40.603448 | 104 | java |
null | wildfly-main/undertow/src/test/java/org/wildfly/extension/undertow/deployment/WarMetaDataProcessorTest.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.undertow.deployment;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.wildfly.extension.undertow.deployment.WarMetaDataProcessor.WebOrdering;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
public class WarMetaDataProcessorTest {
private final List<String> EXPECTED_ORDER = ImmutableList.of(createWebOrdering1().getJar(), createWebOrdering2().getJar(), createWebOrdering3().getJar());
@Test
public void test1() {
// sort: a.jar, b.jar, c.jar
test(ImmutableList.of(createWebOrdering1(), createWebOrdering2(), createWebOrdering3()));
}
@Test
public void test2() {
// sort: a.jar, c.jar, b.jar
test(ImmutableList.of(createWebOrdering1(), createWebOrdering3(), createWebOrdering2()));
}
@Test
public void test3() {
// sort: b.jar, a.jar, c.jar
test(ImmutableList.of(createWebOrdering2(), createWebOrdering1(), createWebOrdering3()));
}
@Test
public void test4() {
// sort: b.jar, c.jar, a.jar
test(ImmutableList.of(createWebOrdering2(), createWebOrdering3(), createWebOrdering1()));
}
@Test
public void test5() {
// sort: c.jar, a.jar, b.jar
test(ImmutableList.of(createWebOrdering3(), createWebOrdering1(), createWebOrdering2()));
}
@Test
public void test6() {
// sort: c.jar, b.jar, a.jar
test(ImmutableList.of(createWebOrdering3(), createWebOrdering2(), createWebOrdering1()));
}
private void test(List<WebOrdering> webOrderings) {
List<String> order = new ArrayList<>();
WarMetaDataProcessor.resolveOrder(webOrderings, order);
Assert.assertEquals(EXPECTED_ORDER, order);
}
private WebOrdering createWebOrdering1() {
return createWebOrdering("a", "WEB-INF/lib/a.jar", null);
}
private WebOrdering createWebOrdering2() {
return createWebOrdering("b", "WEB-INF/lib/b.jar", "a");
}
private WebOrdering createWebOrdering3() {
return createWebOrdering("c", "WEB-INF/lib/c.jar", "b");
}
private WebOrdering createWebOrdering(String name, String jarName, String after) {
WebOrdering o = new WebOrdering();
o.setName(name);
o.setJar(jarName);
if (!Strings.isNullOrEmpty(after)) {
o.addAfter(after);
}
return o;
}
}
| 3,494 | 33.60396 | 158 | java |
null | wildfly-main/undertow/src/test/java/org/wildfly/extension/undertow/deployment/AuthMethodParserTest.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.undertow.deployment;
import org.junit.Assert;
import org.junit.Test;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import io.undertow.servlet.api.AuthMethodConfig;
public class AuthMethodParserTest {
/**
*
* Test for checking that auth method parser doesn't decode twice the auth method query parameter
*/
@Test
public void testPEMEncoded() throws Exception {
String pemOrig = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQClH5+52mqHLdChbOfzuyue5FSDl2n1mOkpMlF1676NT79AScHVMi1Io"
+ "hWkuSe3W+oPLE+GAwyyr0DyolUmTkrhrMID6LamgmH8IzhOeyaxDOjwbCIUeGM1V9Qht+nTneRMhGa/oL687XioZiE1Ev52D8kMa"
+ "KMNMHprL9oOZ/QM4wIDAQAB";
String pemEnc = URLEncoder.encode(pemOrig, "UTF-8");
HashMap<String, String> props = new HashMap<>();
List<AuthMethodConfig> authMethodConfigs = AuthMethodParser.parse("CUSTOM?publicKey="+pemEnc, props);
AuthMethodConfig authMethodConfig = authMethodConfigs.get(0);
String pemDecode = authMethodConfig.getProperties().get("publicKey");
Assert.assertEquals("publicKey = pemOrig; failed probably due https://issues.jboss.org/browse/WFLY-9135",
pemOrig, pemDecode);
}
}
| 2,299 | 41.592593 | 120 | java |
null | wildfly-main/undertow/src/test/java/org/wildfly/extension/undertow/session/SharedSessionConfigXMLReaderTestCase.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2019, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.undertow.session;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.EnumSet;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.jboss.as.web.session.SharedSessionManagerConfig;
import org.jboss.metadata.property.PropertyReplacers;
import org.jboss.staxmapper.XMLMapper;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
/**
* @author Paul Ferraro
*/
@RunWith(value = Parameterized.class)
public class SharedSessionConfigXMLReaderTestCase {
@Parameters
public static Iterable<SharedSessionConfigSchema> parameters() {
return EnumSet.allOf(SharedSessionConfigSchema.class);
}
private final SharedSessionConfigSchema schema;
public SharedSessionConfigXMLReaderTestCase(SharedSessionConfigSchema schema) {
this.schema = schema;
}
@Test
public void test() throws IOException, XMLStreamException {
URL url = this.getClass().getResource(String.format("shared-session-config-%d.%d.xml", this.schema.getVersion().major(), this.schema.getVersion().minor()));
XMLMapper mapper = XMLMapper.Factory.create();
mapper.registerRootElement(this.schema.getQualifiedName(), new SharedSessionConfigXMLReader(this.schema, PropertyReplacers.noop()));
try (InputStream input = url.openStream()) {
XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(input);
SharedSessionManagerConfig config = new SharedSessionManagerConfig();
mapper.parseDocument(config, reader);
Assert.assertTrue(config.isDistributable());
Assert.assertEquals(10, config.getMaxActiveSessions().intValue());
Assert.assertEquals("/", config.getSessionConfig().getCookieConfig().getPath());
} finally {
mapper.unregisterRootAttribute(this.schema.getQualifiedName());
}
}
}
| 3,143 | 39.307692 | 164 | java |
null | wildfly-main/undertow/src/test/java/org/wildfly/extension/undertow/session/CodecSessionConfigTestCase.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.undertow.session;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import io.undertow.server.HttpServerExchange;
import io.undertow.server.session.SessionConfig;
import org.jboss.as.web.session.SessionIdentifierCodec;
import org.junit.Test;
/**
* Unit test for {@link CodecSessionConfig}
* @author Paul Ferraro
*/
public class CodecSessionConfigTestCase {
private final SessionConfig config = mock(SessionConfig.class);
private final SessionIdentifierCodec codec = mock(SessionIdentifierCodec.class);
private final SessionConfig subject = new CodecSessionConfig(this.config, this.codec);
@Test
public void findSessionId() {
HttpServerExchange exchange = new HttpServerExchange(null);
when(this.config.findSessionId(exchange)).thenReturn(null);
String result = this.subject.findSessionId(exchange);
assertNull(result);
String encodedSessionId = "session.route1";
String sessionId = "session";
when(this.config.findSessionId(exchange)).thenReturn(encodedSessionId);
when(this.codec.decode(encodedSessionId)).thenReturn(sessionId);
when(this.codec.encode(sessionId)).thenReturn(encodedSessionId);
result = this.subject.findSessionId(exchange);
assertSame(sessionId, result);
}
@Test
public void setSessionId() {
HttpServerExchange exchange = new HttpServerExchange(null);
String encodedSessionId = "session.route1";
String sessionId = "session";
when(this.config.findSessionId(exchange)).thenReturn(null);
when(this.codec.encode(sessionId)).thenReturn(encodedSessionId);
// Validate new session
this.subject.setSessionId(exchange, sessionId);
verify(this.config).setSessionId(exchange, encodedSessionId);
reset(this.config);
// Validate existing session
when(this.config.findSessionId(exchange)).thenReturn(encodedSessionId);
this.subject.setSessionId(exchange, sessionId);
verify(this.config, never()).setSessionId(exchange, encodedSessionId);
reset(this.config);
// Validate failover request for existing session
when(this.config.findSessionId(exchange)).thenReturn("session.route2");
this.subject.setSessionId(exchange, sessionId);
verify(this.config).setSessionId(exchange, encodedSessionId);
}
@Test
public void clearSession() {
HttpServerExchange exchange = new HttpServerExchange(null);
String encodedSessionId = "session.route";
String sessionId = "session";
when(this.codec.encode(sessionId)).thenReturn(encodedSessionId);
this.subject.clearSession(exchange, sessionId);
verify(this.config).clearSession(exchange, encodedSessionId);
}
@Test
public void rewriteUrl() {
String url = "http://test";
String encodedUrl = "http://test/session";
String encodedSessionId = "session.route";
String sessionId = "session";
when(this.codec.encode(sessionId)).thenReturn(encodedSessionId);
when(this.config.rewriteUrl(url, encodedSessionId)).thenReturn(encodedUrl);
String result = this.subject.rewriteUrl(url, sessionId);
assertSame(encodedUrl, result);
}
@Test
public void sessionCookieSource() {
HttpServerExchange exchange = new HttpServerExchange(null);
SessionConfig.SessionCookieSource expected = SessionConfig.SessionCookieSource.OTHER;
when(this.config.sessionCookieSource(exchange)).thenReturn(expected);
SessionConfig.SessionCookieSource result = this.subject.sessionCookieSource(exchange);
assertSame(expected, result);
}
}
| 4,801 | 33.546763 | 94 | java |
null | wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/ByteBufferPoolDefinition.java | package org.wildfly.extension.undertow;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import io.undertow.connector.ByteBufferPool;
import io.undertow.server.DefaultByteBufferPool;
import org.jboss.as.controller.AbstractAddStepHandler;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.PersistentResourceDefinition;
import org.jboss.as.controller.ReloadRequiredRemoveStepHandler;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.capability.RuntimeCapability;
import org.jboss.as.controller.operations.validation.IntRangeValidator;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
/**
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public class ByteBufferPoolDefinition extends PersistentResourceDefinition {
static final PathElement PATH_ELEMENT = PathElement.pathElement(Constants.BYTE_BUFFER_POOL);
static final RuntimeCapability<Void> UNDERTOW_BUFFER_POOL_RUNTIME_CAPABILITY =
RuntimeCapability.Builder.of(Capabilities.CAPABILITY_BYTE_BUFFER_POOL, true, ByteBufferPool.class).build();
private static final int defaultBufferSize;
private static final boolean defaultDirectBuffers;
static {
long maxMemory = Runtime.getRuntime().maxMemory();
//smaller than 64mb of ram we use 512b buffers
if (maxMemory < 64 * 1024 * 1024) {
//use 512b buffers
defaultDirectBuffers = false;
defaultBufferSize = 512;
} else if (maxMemory < 128 * 1024 * 1024) {
//use 1k buffers
defaultDirectBuffers = true;
defaultBufferSize = 1024;
} else {
//use 16k buffers for best performance
//as 16k is generally the max amount of data that can be sent in a single write() call
defaultDirectBuffers = true;
defaultBufferSize = 1024 * 16;
}
}
protected static final SimpleAttributeDefinition BUFFER_SIZE = new SimpleAttributeDefinitionBuilder(Constants.BUFFER_SIZE, ModelType.INT)
.setRequired(false)
.setRestartAllServices()
.setValidator(new IntRangeValidator(0, true, true))
.setAllowExpression(true)
.build();
protected static final SimpleAttributeDefinition MAX_POOL_SIZE = new SimpleAttributeDefinitionBuilder(Constants.MAX_POOL_SIZE, ModelType.INT)
.setRequired(false)
.setRestartAllServices()
.setValidator(new IntRangeValidator(0, true, true))
.setAllowExpression(true)
.build();
protected static final SimpleAttributeDefinition DIRECT = new SimpleAttributeDefinitionBuilder(Constants.DIRECT, ModelType.BOOLEAN)
.setRequired(false)
.setRestartAllServices()
.setAllowExpression(true)
.build();
protected static final SimpleAttributeDefinition THREAD_LOCAL_CACHE_SIZE = new SimpleAttributeDefinitionBuilder(Constants.THREAD_LOCAL_CACHE_SIZE, ModelType.INT)
.setRequired(false)
.setRestartAllServices()
.setValidator(new IntRangeValidator(0, true, true))
.setAllowExpression(true)
.setDefaultValue(new ModelNode(12))
.build();
protected static final SimpleAttributeDefinition LEAK_DETECTION_PERCENT = new SimpleAttributeDefinitionBuilder(Constants.LEAK_DETECTION_PERCENT, ModelType.INT)
.setRequired(false)
.setRestartAllServices()
.setValidator(new IntRangeValidator(0, true, true))
.setAllowExpression(true)
.setDefaultValue(ModelNode.ZERO)
.build();
static final List<AttributeDefinition> ATTRIBUTES = Arrays.asList(BUFFER_SIZE, MAX_POOL_SIZE, DIRECT, THREAD_LOCAL_CACHE_SIZE, LEAK_DETECTION_PERCENT);
ByteBufferPoolDefinition() {
super(new SimpleResourceDefinition.Parameters(PATH_ELEMENT, UndertowExtension.getResolver(PATH_ELEMENT.getKey()))
.setAddHandler(new BufferPoolAdd())
.setRemoveHandler(ReloadRequiredRemoveStepHandler.INSTANCE)
.addCapabilities(UNDERTOW_BUFFER_POOL_RUNTIME_CAPABILITY)
);
}
@Override
public Collection<AttributeDefinition> getAttributes() {
return ATTRIBUTES;
}
private static class BufferPoolAdd extends AbstractAddStepHandler {
private BufferPoolAdd() {
super(ByteBufferPoolDefinition.ATTRIBUTES);
}
@Override
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
final ModelNode bufferSizeModel = BUFFER_SIZE.resolveModelAttribute(context, model);
final ModelNode maxPoolSizeModel = MAX_POOL_SIZE.resolveModelAttribute(context, model);
final ModelNode directModel = DIRECT.resolveModelAttribute(context, model);
final int threadLocalCacheSize = THREAD_LOCAL_CACHE_SIZE.resolveModelAttribute(context, model).asInt();
final int leakDetectionPercent = LEAK_DETECTION_PERCENT.resolveModelAttribute(context, model).asInt();
final int bufferSize = bufferSizeModel.asInt(defaultBufferSize);
final int maxPoolSize = maxPoolSizeModel.asInt(-1);
final boolean direct = directModel.asBoolean(defaultDirectBuffers);
final ByteBufferPoolService service = new ByteBufferPoolService(direct, bufferSize, maxPoolSize, threadLocalCacheSize, leakDetectionPercent);
context.getCapabilityServiceTarget().addCapability(UNDERTOW_BUFFER_POOL_RUNTIME_CAPABILITY)
.setInstance(service)
.setInitialMode(ServiceController.Mode.ACTIVE)
.install();
}
}
private static final class ByteBufferPoolService implements Service<ByteBufferPool> {
private final boolean direct;
private final int size;
private final int maxSize;
private final int threadLocalCacheSize;
private final int leakDetectionPercent;
private volatile ByteBufferPool pool;
private ByteBufferPoolService(boolean direct, int size, int maxSize, int threadLocalCacheSize, int leakDetectionPercent) {
this.direct = direct;
this.size = size;
this.maxSize = maxSize;
this.threadLocalCacheSize = threadLocalCacheSize;
this.leakDetectionPercent = leakDetectionPercent;
}
@Override
public void start(StartContext startContext) throws StartException {
pool = new DefaultByteBufferPool(direct, size, maxSize, threadLocalCacheSize, leakDetectionPercent);
}
@Override
public void stop(StopContext stopContext) {
pool.close();
pool = null;
}
@Override
public ByteBufferPool getValue() throws IllegalStateException, IllegalArgumentException {
return pool;
}
}
}
| 7,553 | 41.677966 | 165 | java |
null | wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/Constants.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.undertow;
/**
* @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2012 Red Hat Inc.
*/
public interface Constants {
String ACCESS_LOG = "access-log";
String CONSOLE_ACCESS_LOG = "console-access-log";
String AJP_LISTENER = "ajp-listener";
String BUFFER_CACHE = "buffer-cache";
String BUFFER_CACHES = "buffer-caches";
String BUFFER_SIZE = "buffer-size";
String BUFFERS_PER_REGION = "buffers-per-region";
String CONFIGURATION = "configuration";
String MAX_REGIONS = "max-regions";
String BUFFER_POOL = "buffer-pool";
String SETTING = "setting";
String SECURITY_REALM = "security-realm";
String SOCKET_BINDING = "socket-binding";
String SSL_CONTEXT = "ssl-context";
String PATH = "path";
String HTTP_LISTENER = "http-listener";
String HTTPS_LISTENER = "https-listener";
String HTTP_INVOKER = "http-invoker";
String LISTENER = "listener";
String INSTANCE_ID = "instance-id";
String OBFUSCATE_SESSION_ROUTE = "obfuscate-session-route";
String NAME = "name";
String WORKER = "worker";
String SERVLET_CONTAINER = "servlet-container";
String LOCATION = "location";
String JSP = "jsp";
String JSP_CONFIG = "jsp-config";
String HANDLER = "handler";
String HANDLERS = "handlers";
String SERVER = "server";
String HOST = "host";
String PATTERN = "pattern";
String PREFIX = "prefix";
String SUFFIX = "suffix";
String ROTATE = "rotate";
//String CLASS = "class";
String DEFAULT_HOST = "default-host";
String DEFAULT_VIRTUAL_HOST = "default-virtual-host";
String DEFAULT_SERVLET_CONTAINER = "default-servlet-container";
String DEFAULT_SERVER = "default-server";
String DEFAULT_WEB_MODULE = "default-web-module";
String ALIAS = "alias";
String ERROR_PAGE = "error-page";
String ERROR_PAGES = "error-pages";
String SIMPLE_ERROR_PAGE = "simple-error-page";
String SCHEME = "scheme";
String MAX_POST_SIZE = "max-post-size";
String DEFAULT_RESPONSE_CODE = "default-response-code";
/*Jakarta Server Pages config */
String CHECK_INTERVAL = "check-interval";
String CONTAINER = "container";
String DEVELOPMENT = "development";
String DISABLED = "disabled";
String DISPLAY_SOURCE_FRAGMENT = "display-source-fragment";
String DUMP_SMAP = "dump-smap";
String ERROR_ON_USE_BEAN_INVALID_CLASS_ATTRIBUTE = "error-on-use-bean-invalid-class-attribute";
String FILE = "file";
String FILE_ENCODING = "file-encoding";
String GENERATE_STRINGS_AS_CHAR_ARRAYS = "generate-strings-as-char-arrays";
String OPTIMIZE_SCRIPTLETS = "optimize-scriptlets";
String JAVA_ENCODING = "java-encoding";
String JSP_CONFIGURATION = "jsp-configuration";
String KEEP_GENERATED = "keep-generated";
String LISTINGS = "listings";
String MAPPED_FILE = "mapped-file";
String MAX_DEPTH = "max-depth";
String MIME_MAPPING = "mime-mapping";
String MODIFICATION_TEST_INTERVAL = "modification-test-interval";
String READ_ONLY = "read-only";
String RECOMPILE_ON_FAIL = "recompile-on-fail";
String SCRATCH_DIR = "scratch-dir";
String SECRET = "secret";
String SENDFILE = "sendfile";
String SINGLE_SIGN_ON = "single-sign-on";
String SMAP = "smap";
String SOURCE_VM = "source-vm";
String SSL = "ssl";
String STATIC_RESOURCES = "static-resources";
String TAG_POOLING = "tag-pooling";
String TARGET_VM = "target-vm";
String TRIM_SPACES = "trim-spaces";
String WEBDAV = "webdav";
String WELCOME_FILE = "welcome-file";
String X_POWERED_BY = "x-powered-by";
String ENABLED = "enabled";
String DIRECTORY_LISTING = "directory-listing";
String FILTER = "filter";
String FILTERS = "filters";
String FILTER_REF = "filter-ref";
// session and affinity cookie config
String SESSION_COOKIE = "session-cookie";
String AFFINITY_COOKIE = "affinity-cookie";
String DOMAIN = "domain";
String COMMENT = "comment";
String HTTP_ONLY = "http-only";
String SECURE = "secure";
String MAX_AGE = "max-age";
String ALLOW_NON_STANDARD_WRAPPERS = "allow-non-standard-wrappers";
String PERSISTENT_SESSIONS = "persistent-sessions";
String DEFAULT_BUFFER_CACHE = "default-buffer-cache";
String RELATIVE_TO = "relative-to";
String REDIRECT_SOCKET = "redirect-socket";
String DIRECTORY = "directory";
String STACK_TRACE_ON_ERROR = "stack-trace-on-error";
String DEFAULT_ENCODING = "default-encoding";
String USE_LISTENER_ENCODING = "use-listener-encoding";
String NONE = "none";
String PROBLEM_SERVER_RETRY = "problem-server-retry";
String STICKY_SESSION_LIFETIME = "sticky-session-lifetime";
String SESSION_COOKIE_NAMES = "session-cookie-names";
String CONNECTIONS_PER_THREAD = "connections-per-thread";
String REVERSE_PROXY = "reverse-proxy";
String MAX_REQUEST_TIME = "max-request-time";
String CERTIFICATE_FORWARDING = "certificate-forwarding";
String OPTIONS = "options";
String IGNORE_FLUSH = "ignore-flush";
String WEBSOCKETS = "websockets";
//mod_cluster
String MOD_CLUSTER = "mod-cluster";
String MANAGEMENT_SOCKET_BINDING = "management-socket-binding";
String ADVERTISE_SOCKET_BINDING = "advertise-socket-binding";
String SECURITY_KEY = "security-key";
String ADVERTISE_PROTOCOL = "advertise-protocol";
String ADVERTISE_PATH = "advertise-path";
String ADVERTISE_FREQUENCY = "advertise-frequency";
String HEALTH_CHECK_INTERVAL = "health-check-interval";
String BROKEN_NODE_TIMEOUT = "broken-node-timeout";
String MANAGEMENT_ACCESS_PREDICATE = "management-access-predicate";
String REQUEST_QUEUE_SIZE = "request-queue-size";
String CACHED_CONNECTIONS_PER_THREAD = "cached-connections-per-thread";
String CONNECTION_IDLE_TIMEOUT = "connection-idle-timeout";
String FAILOVER_STRATEGY = "failover-strategy";
String USE_SERVER_LOG = "use-server-log";
String VALUE = "value";
String REWRITE = "rewrite";
String DISALLOWED_METHODS = "disallowed-methods";
String RESOLVE_PEER_ADDRESS = "resolve-peer-address";
String BALANCER = "balancer";
String CONTEXT = "context";
String NODE = "node";
String STATUS = "status";
String REQUESTS = "requests";
String ENABLE = "enable";
String DISABLE = "disable";
String LOAD = "load";
String USE_ALIAS = "use-alias";
String LOAD_BALANCING_GROUP = "load-balancing-group";
String CACHE_CONNECTIONS = "cache-connections";
String FLUSH_WAIT = "flush-wait";
String MAX_CONNECTIONS = "max-connections";
String OPEN_CONNECTIONS = "open-connections";
String PING = "ping";
String READ = "read";
String SMAX = "smax";
String TIMEOUT = "timeout";
String WRITTEN = "written";
String TTL = "ttl";
String STICKY_SESSION = "sticky-session";
String STICKY_SESSION_COOKIE = "sticky-session-cookie";
String STICKY_SESSION_PATH = "sticky-session-path";
String STICKY_SESSION_FORCE = "sticky-session-force";
String STICKY_SESSION_REMOVE= "sticky-session-remove";
String WAIT_WORKER = "wait-worker";
String MAX_ATTEMPTS = "max-attempts";
String FLUSH_PACKETS = "flush-packets";
String QUEUE_NEW_REQUESTS = "queue-new-requests";
String STOP = "stop";
String ENABLE_NODES = "enable-nodes";
String DISABLE_NODES = "disable-nodes";
String STOP_NODES = "stop-nodes";
String DEFAULT_SESSION_TIMEOUT = "default-session-timeout";
String PREDICATE = "predicate";
String SSL_SESSION_CACHE_SIZE = "ssl-session-cache-size";
String SSL_SESSION_TIMEOUT = "ssl-session-timeout";
String VERIFY_CLIENT = "verify-client";
String ENABLED_CIPHER_SUITES = "enabled-cipher-suites";
String ENABLED_PROTOCOLS = "enabled-protocols";
String ENABLE_HTTP2 = "enable-http2";
String ENABLE_SPDY = "enable-spdy";
String URI = "uri";
String ALIASES = "aliases";
String ELECTED = "elected";
String PROACTIVE_AUTHENTICATION = "proactive-authentication";
String SESSION_ID_LENGTH = "session-id-length";
String EXTENDED = "extended";
String MAX_BUFFERED_REQUEST_SIZE = "max-buffered-request-size";
String MAX_SESSIONS = "max-sessions";
String USER_AGENTS = "user-agents";
String SESSION_TIMEOUT = "session-timeout";
String CRAWLER_SESSION_MANAGEMENT = "crawler-session-management";
String MAX_AJP_PACKET_SIZE = "max-ajp-packet-size";
String STATISTICS_ENABLED = "statistics-enabled";
String DEFAULT_SECURITY_DOMAIN = "default-security-domain";
String DISABLE_FILE_WATCH_SERVICE = "disable-file-watch-service";
String DISABLE_SESSION_ID_REUSE = "disable-session-id-reuse";
String PER_MESSAGE_DEFLATE = "per-message-deflate";
String DEFLATER_LEVEL = "deflater-level";
String MAX_RETRIES = "max-retries";
// Affinity
String AFFINITY = "affinity";
String NO_AFFINITY = "no-affinity";
String SINGLE = "single";
String SINGLE_AFFINITY = "single-affinity";
String RANKED = "ranked";
String RANKED_AFFINITY = "ranked-affinity";
String DELIMITER = "delimiter";
// Elytron Integration
String APPLICATION_SECURITY_DOMAIN = "application-security-domain";
String APPLICATION_SECURITY_DOMAINS = "application-security-domains";
String HTTP_AUTHENTICATION_FACTORY = "http-authentication-factory";
String OVERRIDE_DEPLOYMENT_CONFIG = "override-deployment-config";
String REFERENCING_DEPLOYMENTS = "referencing-deployments";
String SECURITY_DOMAIN = "security-domain";
String ENABLE_JACC = "enable-jacc";
String ENABLE_JASPI = "enable-jaspi";
String INTEGRATED_JASPI = "integrated-jaspi";
String FILE_CACHE_MAX_FILE_SIZE = "file-cache-max-file-size";
String FILE_CACHE_METADATA_SIZE = "file-cache-metadata-size";
String FILE_CACHE_TIME_TO_LIVE = "file-cache-time-to-live";
String SESSION_ID = "session-id";
String ATTRIBUTE = "attribute";
String INVALIDATE_SESSION = "invalidate-session";
String LIST_SESSIONS = "list-sessions";
String LIST_SESSION_ATTRIBUTE_NAMES = "list-session-attribute-names";
String LIST_SESSION_ATTRIBUTES = "list-session-attributes";
String GET_SESSION_ATTRIBUTE = "get-session-attribute";
String GET_SESSION_LAST_ACCESSED_TIME = "get-session-last-accessed-time";
String GET_SESSION_LAST_ACCESSED_TIME_MILLIS = "get-session-last-accessed-time-millis";
String GET_SESSION_CREATION_TIME = "get-session-creation-time";
String GET_SESSION_CREATION_TIME_MILLIS = "get-session-creation-time-millis";
String DEFAULT_COOKIE_VERSION = "default-cookie-version";
String PRESERVE_PATH_ON_FORWARD = "preserve-path-on-forward";
String PROXY_PROTOCOL = "proxy-protocol";
String MAX_POOL_SIZE = "max-pool-size";
String THREAD_LOCAL_CACHE_SIZE = "thread-local-cache-size";
String DIRECT = "direct";
String LEAK_DETECTION_PERCENT = "leak-detection-percent";
String BYTE_BUFFER_POOL = "byte-buffer-pool";
}
| 12,114 | 42.113879 | 99 | java |
null | wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/HttpListenerAdd.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.extension.undertow;
import static org.wildfly.extension.undertow.Capabilities.REF_SOCKET_BINDING;
import io.undertow.server.ListenerRegistry;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.CapabilityServiceBuilder;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.network.SocketBinding;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceName;
import org.xnio.OptionMap;
import java.util.Collection;
import java.util.function.Consumer;
/**
* @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2012 Red Hat Inc.
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
class HttpListenerAdd extends ListenerAdd<HttpListenerService> {
HttpListenerAdd(Collection<AttributeDefinition> attributes) {
super(attributes);
}
@Override
HttpListenerService createService(final Consumer<ListenerService> serviceConsumer, final String name, final String serverName, final OperationContext context, ModelNode model, OptionMap listenerOptions, OptionMap socketOptions) throws OperationFailedException {
final boolean proxyProtocol = AbstractHttpListenerResourceDefinition.PROXY_PROTOCOL.resolveModelAttribute(context, model).asBoolean();
final boolean certificateForwarding = AbstractHttpListenerResourceDefinition.CERTIFICATE_FORWARDING.resolveModelAttribute(context, model).asBoolean();
final boolean proxyAddressForwarding = AbstractHttpListenerResourceDefinition.PROXY_ADDRESS_FORWARDING.resolveModelAttribute(context, model).asBoolean();
OptionMap.Builder listenerBuilder = OptionMap.builder().addAll(listenerOptions);
AbstractHttpListenerResourceDefinition.ENABLE_HTTP2.resolveOption(context, model,listenerBuilder);
AbstractHttpListenerResourceDefinition.REQUIRE_HOST_HTTP11.resolveOption(context, model,listenerBuilder);
handleHttp2Options(context, model, listenerBuilder);
return new HttpListenerService(serviceConsumer, context.getCurrentAddress(), serverName, listenerBuilder.getMap(), socketOptions, certificateForwarding, proxyAddressForwarding, proxyProtocol);
}
static void handleHttp2Options(OperationContext context, ModelNode model, OptionMap.Builder listenerBuilder) throws OperationFailedException {
AbstractHttpListenerResourceDefinition.HTTP2_ENABLE_PUSH.resolveOption(context, model,listenerBuilder);
AbstractHttpListenerResourceDefinition.HTTP2_HEADER_TABLE_SIZE.resolveOption(context, model,listenerBuilder);
AbstractHttpListenerResourceDefinition.HTTP2_INITIAL_WINDOW_SIZE.resolveOption(context, model,listenerBuilder);
AbstractHttpListenerResourceDefinition.HTTP2_MAX_CONCURRENT_STREAMS.resolveOption(context, model,listenerBuilder);
AbstractHttpListenerResourceDefinition.HTTP2_MAX_FRAME_SIZE.resolveOption(context, model,listenerBuilder);
AbstractHttpListenerResourceDefinition.HTTP2_MAX_HEADER_LIST_SIZE.resolveOption(context, model,listenerBuilder);
}
@Override
void configureAdditionalDependencies(OperationContext context, CapabilityServiceBuilder<?> serviceBuilder, ModelNode model, HttpListenerService service) throws OperationFailedException {
ModelNode redirectBindingRef = ListenerResourceDefinition.REDIRECT_SOCKET.resolveModelAttribute(context, model);
if (redirectBindingRef.isDefined()) {
ServiceName serviceName = context.getCapabilityServiceName(REF_SOCKET_BINDING, redirectBindingRef.asString(), SocketBinding.class);
service.getRedirectSocket().set(serviceBuilder.requires(serviceName));
}
service.getHttpListenerRegistry().set(serviceBuilder.requiresCapability(Capabilities.REF_HTTP_LISTENER_REGISTRY, ListenerRegistry.class));
}
}
| 4,896 | 57.297619 | 265 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.