use of org.jboss.weld.bootstrap.spi.BeanDeploymentArchive in project core by weld.
the class WeldServletLifecycle method initialize.
/**
* @param context
* @return <code>true</code> if initialized properly, <code>false</code> otherwise
*/
boolean initialize(ServletContext context) {
isDevModeEnabled = Boolean.valueOf(context.getInitParameter(CONTEXT_PARAM_DEV_MODE));
WeldManager manager = (WeldManager) context.getAttribute(BEAN_MANAGER_ATTRIBUTE_NAME);
if (manager != null) {
isBootstrapNeeded = false;
String contextId = BeanManagerProxy.unwrap(manager).getContextId();
context.setInitParameter(org.jboss.weld.Container.CONTEXT_ID_KEY, contextId);
} else {
Object container = context.getAttribute(Listener.CONTAINER_ATTRIBUTE_NAME);
if (container instanceof ContainerInstanceFactory) {
ContainerInstanceFactory factory = (ContainerInstanceFactory) container;
// start the container
ContainerInstance containerInstance = factory.initialize();
container = containerInstance;
// we are in charge of shutdown also
this.shutdownAction = () -> containerInstance.shutdown();
}
if (container instanceof ContainerInstance) {
// the container instance was either passed to us directly or was created in the block above
ContainerInstance containerInstance = (ContainerInstance) container;
manager = BeanManagerProxy.unwrap(containerInstance.getBeanManager());
context.setInitParameter(org.jboss.weld.Container.CONTEXT_ID_KEY, containerInstance.getId());
isBootstrapNeeded = false;
}
}
final CDI11Bootstrap bootstrap = new WeldBootstrap();
if (isBootstrapNeeded) {
final CDI11Deployment deployment = createDeployment(context, bootstrap);
deployment.getServices().add(ExternalConfiguration.class, new ExternalConfigurationBuilder().add(BEAN_IDENTIFIER_INDEX_OPTIMIZATION.get(), Boolean.FALSE.toString()).build());
if (deployment.getBeanDeploymentArchives().isEmpty()) {
// Skip initialization - there is no bean archive in the deployment
CommonLogger.LOG.initSkippedNoBeanArchiveFound();
return false;
}
ResourceInjectionServices resourceInjectionServices = new ServletResourceInjectionServices() {
};
try {
for (BeanDeploymentArchive archive : deployment.getBeanDeploymentArchives()) {
archive.getServices().add(ResourceInjectionServices.class, resourceInjectionServices);
}
} catch (NoClassDefFoundError e) {
// Support GAE
WeldServletLogger.LOG.resourceInjectionNotAvailable();
}
String id = context.getInitParameter(org.jboss.weld.Container.CONTEXT_ID_KEY);
if (id != null) {
bootstrap.startContainer(id, Environments.SERVLET, deployment);
} else {
bootstrap.startContainer(Environments.SERVLET, deployment);
}
bootstrap.startInitialization();
/*
* Determine the BeanManager used for example for EL resolution - this should work fine as all bean archives share the same classloader. The only
* difference this can make is per-BDA (CDI 1.0 style) enablement of alternatives, interceptors and decorators. Nothing we can do about that.
*
* First try to find the bean archive for WEB-INF/classes. If not found, take the first one available.
*/
for (BeanDeploymentArchive bda : deployment.getBeanDeploymentArchives()) {
if (bda.getId().contains(ManagerObjectFactory.WEB_INF_CLASSES_FILE_PATH) || bda.getId().contains(ManagerObjectFactory.WEB_INF_CLASSES)) {
manager = bootstrap.getManager(bda);
break;
}
}
if (manager == null) {
manager = bootstrap.getManager(deployment.getBeanDeploymentArchives().iterator().next());
}
// Push the manager into the servlet context so we can access in JSF
context.setAttribute(BEAN_MANAGER_ATTRIBUTE_NAME, manager);
}
ContainerContext containerContext = new ContainerContext(context, manager);
StringBuilder dump = new StringBuilder();
Container container = findContainer(containerContext, dump);
if (container == null) {
WeldServletLogger.LOG.noSupportedServletContainerDetected();
WeldServletLogger.LOG.debugv("Exception dump from Container lookup: {0}", dump);
} else {
container.initialize(containerContext);
this.container = container;
}
if (Reflections.isClassLoadable(WeldClassLoaderResourceLoader.INSTANCE, JSP_FACTORY_CLASS_NAME) && JspFactory.getDefaultFactory() != null) {
JspApplicationContext jspApplicationContext = JspFactory.getDefaultFactory().getJspApplicationContext(context);
// Register the ELResolver with JSP
jspApplicationContext.addELResolver(manager.getELResolver());
// Register ELContextListener with JSP
try {
jspApplicationContext.addELContextListener(new WeldELContextListener());
} catch (Exception e) {
throw WeldServletLogger.LOG.errorLoadingWeldELContextListener(e);
}
// Push the wrapped expression factory into the servlet context so that Tomcat or Jetty can hook it in using a container code
context.setAttribute(EXPRESSION_FACTORY_NAME, manager.wrapExpressionFactory(jspApplicationContext.getExpressionFactory()));
}
if (isBootstrapNeeded) {
bootstrap.deployBeans().validateBeans().endInitialization();
if (isDevModeEnabled) {
FilterRegistration.Dynamic filterDynamic = context.addFilter("Weld Probe Filter", DevelopmentMode.PROBE_FILTER_CLASS_NAME);
filterDynamic.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE), true, "/*");
}
this.shutdownAction = () -> bootstrap.shutdown();
}
return true;
}
use of org.jboss.weld.bootstrap.spi.BeanDeploymentArchive in project core by weld.
the class AdditionalBeanDeploymentArchiveTest method testAdditionalBeanDeploymentArchiveCreated.
@Test
public void testAdditionalBeanDeploymentArchiveCreated(Outsider outsider, BeanManagerImpl beanManager) {
assertNotNull(outsider);
outsider.ping();
Map<BeanDeploymentArchive, BeanManagerImpl> beanDeploymentArchivesMap = Container.instance(beanManager).beanDeploymentArchives();
assertEquals(3, beanDeploymentArchivesMap.size());
boolean additionalBdaFound = false;
for (BeanDeploymentArchive bda : beanDeploymentArchivesMap.keySet()) {
if (bda.getId().equals(WeldDeployment.ADDITIONAL_BDA_ID)) {
additionalBdaFound = true;
break;
}
}
assertTrue(additionalBdaFound);
}
use of org.jboss.weld.bootstrap.spi.BeanDeploymentArchive in project core by weld.
the class Weld method createDeployment.
/**
* <p>
* Extensions to Weld SE can subclass and override this method to customize the deployment before weld boots up. For example, to add a custom
* ResourceLoader, you would subclass Weld like so:
* </p>
*
* <pre>
* public class MyWeld extends Weld {
* protected Deployment createDeployment(ResourceLoader resourceLoader, CDI11Bootstrap bootstrap) {
* return super.createDeployment(new MyResourceLoader(), bootstrap);
* }
* }
* </pre>
*
* <p>
* This could then be used as normal:
* </p>
*
* <pre>
* WeldContainer container = new MyWeld().initialize();
* </pre>
*
* @param resourceLoader
* @param bootstrap
*/
protected Deployment createDeployment(ResourceLoader resourceLoader, CDI11Bootstrap bootstrap) {
final Iterable<Metadata<Extension>> extensions = getExtensions();
final TypeDiscoveryConfiguration typeDiscoveryConfiguration = bootstrap.startExtensions(extensions);
final Deployment deployment;
final Set<WeldBeanDeploymentArchive> beanDeploymentArchives = new HashSet<WeldBeanDeploymentArchive>();
final Map<Class<? extends Service>, Service> additionalServices = new HashMap<>(this.additionalServices);
final Set<Class<? extends Annotation>> beanDefiningAnnotations = ImmutableSet.<Class<? extends Annotation>>builder().addAll(typeDiscoveryConfiguration.getKnownBeanDefiningAnnotations()).add(ThreadScoped.class).build();
if (discoveryEnabled) {
DiscoveryStrategy strategy = DiscoveryStrategyFactory.create(resourceLoader, bootstrap, beanDefiningAnnotations, isEnabled(Jandex.DISABLE_JANDEX_DISCOVERY_STRATEGY, false));
if (isImplicitScanEnabled()) {
strategy.setScanner(new ClassPathBeanArchiveScanner(bootstrap));
}
beanDeploymentArchives.addAll(strategy.performDiscovery());
ClassFileServices classFileServices = strategy.getClassFileServices();
if (classFileServices != null) {
additionalServices.put(ClassFileServices.class, classFileServices);
}
}
if (isSyntheticBeanArchiveRequired()) {
ImmutableSet.Builder<String> beanClassesBuilder = ImmutableSet.builder();
beanClassesBuilder.addAll(scanPackages());
Set<String> setOfAllBeanClasses = beanClassesBuilder.build();
// the creation process differs based on bean discovery mode
if (BeanDiscoveryMode.ANNOTATED.equals(beanDiscoveryMode)) {
// Annotated bean discovery mode, filter classes
ImmutableSet.Builder<String> filteredSetbuilder = ImmutableSet.builder();
for (String className : setOfAllBeanClasses) {
Class<?> clazz = Reflections.loadClass(resourceLoader, className);
if (clazz != null && Reflections.hasBeanDefiningAnnotation(clazz, beanDefiningAnnotations)) {
filteredSetbuilder.add(className);
}
}
setOfAllBeanClasses = filteredSetbuilder.build();
}
WeldBeanDeploymentArchive syntheticBeanArchive = new WeldBeanDeploymentArchive(WeldDeployment.SYNTHETIC_BDA_ID, setOfAllBeanClasses, null, buildSyntheticBeansXml(), Collections.emptySet(), ImmutableSet.copyOf(beanClasses));
beanDeploymentArchives.add(syntheticBeanArchive);
}
if (beanDeploymentArchives.isEmpty() && this.containerLifecycleObservers.isEmpty() && this.extensions.isEmpty()) {
throw WeldSELogger.LOG.weldContainerCannotBeInitializedNoBeanArchivesFound();
}
Multimap<String, BeanDeploymentArchive> problems = BeanArchives.findBeanClassesDeployedInMultipleBeanArchives(beanDeploymentArchives);
if (!problems.isEmpty()) {
// Right now, we only log a warning for each bean class deployed in multiple bean archives
for (Entry<String, Collection<BeanDeploymentArchive>> entry : problems.entrySet()) {
WeldSELogger.LOG.beanClassDeployedInMultipleBeanArchives(entry.getKey(), WeldCollections.toMultiRowString(entry.getValue()));
}
}
if (isEnabled(ARCHIVE_ISOLATION_SYSTEM_PROPERTY, true)) {
deployment = new WeldDeployment(resourceLoader, bootstrap, beanDeploymentArchives, extensions);
CommonLogger.LOG.archiveIsolationEnabled();
} else {
Set<WeldBeanDeploymentArchive> flatDeployment = new HashSet<WeldBeanDeploymentArchive>();
flatDeployment.add(WeldBeanDeploymentArchive.merge(bootstrap, beanDeploymentArchives));
deployment = new WeldDeployment(resourceLoader, bootstrap, flatDeployment, extensions);
CommonLogger.LOG.archiveIsolationDisabled();
}
// Register additional services if a service with higher priority not present
for (Entry<Class<? extends Service>, Service> entry : additionalServices.entrySet()) {
Services.put(deployment.getServices(), entry.getKey(), entry.getValue());
}
return deployment;
}
use of org.jboss.weld.bootstrap.spi.BeanDeploymentArchive in project core by weld.
the class BeanArchivesTest method testFindBeanClassesDeployedInMultipleBeanArchives.
@Test
public void testFindBeanClassesDeployedInMultipleBeanArchives() {
String beanClass = "com.foo.Bar";
BeanDeploymentArchive bda1 = new WeldBeanDeploymentArchive("foo", ImmutableList.of(beanClass), null);
BeanDeploymentArchive bda2 = new WeldBeanDeploymentArchive("bar", ImmutableList.of(beanClass), null);
Multimap<String, BeanDeploymentArchive> problems = BeanArchives.findBeanClassesDeployedInMultipleBeanArchives(Collections.singleton(bda1));
assertTrue(problems.isEmpty());
problems = BeanArchives.findBeanClassesDeployedInMultipleBeanArchives(ImmutableSet.of(bda1, bda2));
assertFalse(problems.isEmpty());
assertEquals(1, problems.size());
Entry<String, Collection<BeanDeploymentArchive>> entry = problems.entrySet().iterator().next();
assertEquals(beanClass, entry.getKey());
assertEquals(2, entry.getValue().size());
for (BeanDeploymentArchive bda : entry.getValue()) {
if (!bda.getId().equals("foo") && !bda.getId().equals("bar")) {
fail();
}
}
}
use of org.jboss.weld.bootstrap.spi.BeanDeploymentArchive in project core by weld.
the class JsonObjects method createDeploymentJson.
/**
* @param beanManager
* @return the root resource representation
*/
@SuppressFBWarnings(value = "REC_CATCH_EXCEPTION", justification = "We want to catch all exceptions, runtime included.")
static String createDeploymentJson(BeanManagerImpl beanManager, Probe probe) {
Map<BeanDeploymentArchive, BeanManagerImpl> beanDeploymentArchivesMap = Container.instance(beanManager).beanDeploymentArchives();
AnnotationApiAbstraction annotationApi = beanManager.getServices().get(AnnotationApiAbstraction.class);
JsonObjectBuilder deploymentBuilder = Json.objectBuilder();
// INIT TS
deploymentBuilder.add(INIT_TS, probe.getInitTs());
// CONTEXT ID
deploymentBuilder.add(CONTEXT_ID, beanManager.getContextId());
// WELD VERSION
deploymentBuilder.add(VERSION, Formats.getSimpleVersion());
// BEAN DEPLOYMENT ARCHIVES
JsonArrayBuilder bdasBuilder = Json.arrayBuilder();
List<BeanDeploymentArchive> bdas = new ArrayList<BeanDeploymentArchive>(beanDeploymentArchivesMap.keySet());
Collections.sort(bdas, probe.getBdaComparator());
for (BeanDeploymentArchive bda : bdas) {
JsonObjectBuilder bdaBuilder = createSimpleBdaJson(bda.getId());
// If beans.xml is not found it's likely an implicit bean archive
BeansXml beansXml = bda.getBeansXml();
bdaBuilder.add(BEAN_DISCOVERY_MODE, beansXml != null ? beansXml.getBeanDiscoveryMode().toString() : BeanDiscoveryMode.ANNOTATED.toString());
// beans.xml
if (beansXml != null) {
JsonObjectBuilder beansXmlBuilder = Json.objectBuilder();
if (beansXml.equals(BeansXml.EMPTY_BEANS_XML)) {
beansXmlBuilder.add(MARKER, Boolean.TRUE);
} else {
beansXmlBuilder.add(Strings.URL, beansXml.getUrl() != null ? beansXml.getUrl().toString() : EMPTY);
beansXmlBuilder.add(VERSION, beansXml.getVersion() != null ? beansXml.getVersion().toString() : EMPTY);
beansXmlBuilder.add(TRIMMED, beansXml.isTrimmed());
if (beansXml.getScanning() != null && (!beansXml.getScanning().getExcludes().isEmpty() || !beansXml.getScanning().getExcludes().isEmpty())) {
JsonArrayBuilder scanBuilder = Json.arrayBuilder();
createMetadataArrayJson(scanBuilder, beansXml.getScanning().getExcludes(), EXCLUDE);
createMetadataArrayJson(scanBuilder, beansXml.getScanning().getIncludes(), INCLUDE);
beansXmlBuilder.add(SCAN, scanBuilder);
}
}
bdaBuilder.add(Strings.BEANS_XML, beansXmlBuilder);
}
// Enablement - interceptors, decorators, alternatives
JsonObjectBuilder enablementBuilder = Json.objectBuilder(true);
ModuleEnablement enablement = beanDeploymentArchivesMap.get(bda).getEnabled();
JsonArrayBuilder interceptors = Json.arrayBuilder();
for (Class<?> interceptor : Components.getSortedProbeComponetCandidates(enablement.getInterceptors())) {
Bean<?> interceptorBean = findEnabledBean(interceptor, BeanKind.INTERCEPTOR, probe);
if (interceptorBean != null) {
JsonObjectBuilder builder = decorateProbeComponent(interceptor, createSimpleBeanJson(interceptorBean, probe));
if (beansXml != null) {
for (Metadata<String> meta : beansXml.getEnabledInterceptors()) {
if (meta.getValue().equals(interceptorBean.getBeanClass().getName())) {
// Locally enabled
builder.add(BEANS_XML, true);
}
}
}
Object priority = interceptorBean.getBeanClass().getAnnotation(annotationApi.PRIORITY_ANNOTATION_CLASS);
if (priority != null) {
builder.add(PRIORITY, annotationApi.getPriority(priority));
}
if (builder.has(PRIORITY) && builder.has(BEANS_XML)) {
builder.add(CONFLICTS, true);
}
interceptors.add(builder);
}
}
enablementBuilder.add(INTERCEPTORS, interceptors);
JsonArrayBuilder decorators = Json.arrayBuilder();
for (Class<?> decorator : enablement.getDecorators()) {
Bean<?> decoratorBean = findEnabledBean(decorator, BeanKind.DECORATOR, probe);
if (decoratorBean != null) {
JsonObjectBuilder builder = createSimpleBeanJson(decoratorBean, probe);
if (beansXml != null) {
for (Metadata<String> meta : beansXml.getEnabledDecorators()) {
if (meta.getValue().equals(decoratorBean.getBeanClass().getName())) {
// Locally enabled
builder.add(BEANS_XML, true);
}
}
}
Object priority = decoratorBean.getBeanClass().getAnnotation(annotationApi.PRIORITY_ANNOTATION_CLASS);
if (priority != null) {
builder.add(PRIORITY, annotationApi.getPriority(priority));
}
if (builder.has(PRIORITY) && builder.has(BEANS_XML)) {
builder.add(CONFLICTS, true);
}
decorators.add(builder);
}
}
enablementBuilder.add(DECORATORS, decorators);
JsonArrayBuilder alternatives = Json.arrayBuilder();
for (Class<?> clazz : Sets.union(enablement.getAlternativeClasses(), enablement.getGlobalAlternatives())) {
Bean<?> alternativeBean = findAlternativeBean(clazz, probe);
if (alternativeBean != null) {
JsonObjectBuilder builder = createSimpleBeanJson(alternativeBean, probe);
if (enablement.getAlternativeClasses().contains(clazz)) {
builder.add(BEANS_XML, true);
}
if (enablement.getGlobalAlternatives().contains(clazz)) {
Object priority = clazz.getAnnotation(annotationApi.PRIORITY_ANNOTATION_CLASS);
if (priority != null) {
builder.add(PRIORITY, annotationApi.getPriority(priority));
}
}
alternatives.add(builder);
}
}
for (Class<? extends Annotation> stereotype : enablement.getAlternativeStereotypes()) {
Set<Bean<?>> beans = findAlternativeStereotypeBeans(stereotype, probe);
if (!beans.isEmpty()) {
for (Bean<?> bean : beans) {
JsonObjectBuilder builder = createSimpleBeanJson(bean, probe);
builder.add(BEANS_XML, true);
alternatives.add(builder);
}
}
}
enablementBuilder.add(ALTERNATIVES, alternatives);
bdaBuilder.add(ENABLEMENT, enablementBuilder);
// Accessible BDAs
BeanManagerImpl manager = beanDeploymentArchivesMap.get(bda);
JsonArrayBuilder accesibleBdasBuilder = Json.arrayBuilder();
for (BeanManagerImpl accesible : manager.getAccessibleManagers()) {
accesibleBdasBuilder.add(Components.getId(accesible.getId()));
}
bdaBuilder.add(ACCESSIBLE_BDAS, accesibleBdasBuilder);
bdaBuilder.add(BEANS, Components.getNumberOfEnabledBeans(manager));
bdasBuilder.add(bdaBuilder);
}
deploymentBuilder.add(BDAS, bdasBuilder);
// CONFIGURATION
JsonArrayBuilder configBuilder = Json.arrayBuilder();
WeldConfiguration configuration = beanManager.getServices().get(WeldConfiguration.class);
for (ConfigurationKey key : Reports.getSortedConfigurationKeys()) {
Object defaultValue = key.getDefaultValue();
String desc = Reports.getDesc(key);
if (desc == null) {
// Don't show config options without description
continue;
}
Object value = Reports.getValue(key, configuration);
if (value == null) {
// Unsupported property type
continue;
}
configBuilder.add(Json.objectBuilder().add(NAME, key.get()).add(DEFAULT_VALUE, defaultValue.toString()).add(VALUE, value.toString()).add(DESCRIPTION, desc));
}
deploymentBuilder.add(CONFIGURATION, configBuilder);
// INSPECTABLE CONTEXTS
deploymentBuilder.add(CONTEXTS, createContextsJson(beanManager, probe));
// DASHBOARD DATA
JsonObjectBuilder dashboardBuilder = Json.objectBuilder();
// Application
JsonObjectBuilder appBuilder = Json.objectBuilder();
appBuilder.add(BEANS, probe.getApplicationBeansCount());
appBuilder.add(OBSERVERS, probe.getApplicationObserversCount());
dashboardBuilder.add(APPLICATION, appBuilder);
// Bootstrap
dashboardBuilder.add(BOOSTRAP_STATS, createBootstrapStatsJson(probe));
deploymentBuilder.add(DASHBOARD, dashboardBuilder);
return deploymentBuilder.build();
}
Aggregations