private <T> T getProxiedInstance(Bean<T> bean) {
   WeldCreationalContext<T> creationalContext;
   boolean outer;
   if (currentCreationalContext.get() == null) {
     creationalContext = new CreationalContextImpl<T>(bean);
     currentCreationalContext.set(creationalContext);
     outer = true;
   } else {
     creationalContext = currentCreationalContext.get().getCreationalContext(bean);
     outer = false;
   }
   Context context = Container.instance().deploymentManager().getContext(bean.getScope());
   try {
     // Ensure that there is no injection point associated
     Container.instance()
         .services()
         .get(CurrentInjectionPoint.class)
         .push(SimpleInjectionPoint.EMPTY_INJECTION_POINT);
     return context.get(bean, creationalContext);
   } finally {
     Container.instance().services().get(CurrentInjectionPoint.class).pop();
     if (outer) {
       currentCreationalContext.remove();
     }
   }
 }
Пример #2
0
  public void shutdown() {
    try {
      // First, the container must destroy all contexts.
      deploymentManager.instance().select(ApplicationContext.class).get().invalidate();
      deploymentManager.instance().select(SingletonContext.class).get().invalidate();

    } finally {
      try {
        // fire @Destroyed(ApplicationScoped.class) for non-web modules
        // web modules are handled by HttpContextLifecycle
        for (BeanDeploymentModule module :
            deploymentManager.getServices().get(BeanDeploymentModules.class)) {
          if (!module.isWebModule()) {
            module.fireEvent(
                Object.class, ContextEvent.APPLICATION_DESTROYED, DestroyedLiteral.APPLICATION);
          }
        }
      } catch (Exception ignored) {
      }
      try {
        // Finally, the container must fire an event of type BeforeShutdown.
        BeforeShutdownImpl.fire(deploymentManager);
      } finally {
        Container container = Container.instance(contextId);
        container.setState(ContainerState.SHUTDOWN);
        container.cleanup();
      }
    }
  }
Пример #3
0
 public void addInjectionTargetToBeInitialized(
     InjectionTargetInitializationContext<?> initializationContext) {
   if (container.getState().equals(ContainerState.VALIDATED)
       || container.getState().equals(ContainerState.INITIALIZED)) {
     // initialize now and don't store for later initialization as this has been created at runtime
     initializationContext.initialize();
   } else {
     injectionTargetsToInitialize.add(initializationContext);
   }
 }
Пример #4
0
 public void validateProducer(Producer<?> producer) {
   if (container.getState().equals(ContainerState.VALIDATED)
       || container.getState().equals(ContainerState.INITIALIZED)) {
     // We are past the bootstrap and therefore we can validate the producer immediately
     validator.validateProducer(producer, beanManager);
   } else {
     // Validate injection points for definition errors now
     for (InjectionPoint ip : producer.getInjectionPoints()) {
       validator.validateInjectionPointForDefinitionErrors(ip, ip.getBean(), beanManager);
       validator.validateEventMetadataInjectionPoint(ip);
     }
     // Schedule validation for deployment problems to be done later
     producersToValidate.add(producer);
   }
 }
Пример #5
0
  /**
   * Starts the weld container
   *
   * @throws IllegalStateException if the container is already running
   */
  public synchronized void start(final StartContext context) {
    if (started) {
      throw WeldLogger.ROOT_LOGGER.alreadyRunning("WeldContainer");
    }
    started = true;

    WeldLogger.DEPLOYMENT_LOGGER.startingWeldService(deploymentName);
    // set up injected services
    addWeldService(SecurityServices.class, securityServices.getValue());
    addWeldService(TransactionServices.class, weldTransactionServices.getValue());

    if (!deployment.getServices().contains(ExecutorServices.class)) {
      addWeldService(ExecutorServices.class, executorServices.getValue());
    }

    ModuleGroupSingletonProvider.addClassLoaders(
        deployment.getModule().getClassLoader(), deployment.getSubDeploymentClassLoaders());

    ClassLoader oldTccl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
    try {
      WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(
          deployment.getModule().getClassLoader());
      bootstrap.startContainer(deploymentName, environment, deployment);
      WeldProvider.containerInitialized(
          Container.instance(deploymentName), getBeanManager(), deployment);
    } finally {
      WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTccl);
    }
  }
Пример #6
0
 /*
  * It may in theory happen that an app calls BeanManager.createAnnotatedType() for a previously unknown class on node1 and then
  * stores this annotated type in session. On node2, this annotated type is not know. We'll try to load it.
  */
 private SlimAnnotatedType<?> tryToLoadUnknownBackedAnnotatedType() {
   if (identifier.getSuffix() != null || identifier.isModified()) {
     return null; // this is not a backed annotated type
   }
   // first, obtain the BeanManager for a given BDA
   final BeanManagerImpl manager =
       Container.instance(identifier).getBeanManager(identifier.getBdaId());
   if (manager == null) {
     return null;
   }
   // second, try to load the class
   final ResourceLoader resourceLoader = manager.getServices().get(ResourceLoader.class);
   Class<?> clazz = null;
   try {
     clazz = resourceLoader.classForName(identifier.getClassName());
   } catch (ResourceLoadingException e) {
     MetadataLogger.LOG.catchingDebug(e);
     return null;
   }
   // finally, try to load the annotated type
   try {
     return manager
         .getServices()
         .get(ClassTransformer.class)
         .getBackedAnnotatedType(clazz, identifier.getBdaId());
   } catch (ResourceLoadingException e) {
     MetadataLogger.LOG.catchingDebug(e);
     return null;
   }
 }
 /**
  * Invokes the method on the correct version of the instance as obtained by a context lookup
  *
  * @param self the proxy instance.
  * @param proxiedMethod the overridden method declared in the super class or interface.
  * @param proceed the forwarder method for invoking the overridden method. It is null if the
  *     overridden mehtod is abstract or declared in the interface.
  * @param args an array of objects containing the values of the arguments passed in the method
  *     invocation on the proxy instance. If a parameter type is a primitive type, the type of the
  *     array element is a wrapper class.
  * @return the resulting value of the method invocation.
  * @throws Throwable if the method invocation fails.
  */
 public Object invoke(Object self, Method proxiedMethod, Method proceed, Object[] args)
     throws Throwable {
   if (bean == null) {
     bean =
         Container.instance()
             .services()
             .get(ContextualStore.class)
             .<Bean<Object>, Object>getContextual(id);
   }
   Object proxiedInstance = getProxiedInstance(bean);
   if (proxiedInstance == null) {
     // TODO not sure if this right PLM
     return null;
   }
   if (proxiedMethod.getName().equals("equals")
       && proxiedMethod.getParameterTypes().length == 1
       && proxiedMethod.getParameterTypes()[0] == Object.class
       && args[0] == self) {
     return true;
   }
   try {
     Method method = SecureReflections.lookupMethod(proxiedInstance, proxiedMethod);
     Object returnValue = SecureReflections.invoke(proxiedInstance, method, args);
     log.trace(
         CALL_PROXIED_METHOD,
         proxiedMethod,
         proxiedInstance,
         args,
         returnValue == null ? null : returnValue);
     return returnValue;
   } catch (InvocationTargetException e) {
     throw e.getCause();
   }
 }
Пример #8
0
  /**
   * When in portable mode (default) this method verifies that the container has reached the
   * specified minimal state. If it hasn't, an {@link IllegalStateException} is thrown. When in
   * non-portable mode this method is no-op.
   *
   * @param methodName
   * @param minimalState the minimal state
   * @throws IllegalStateException If the application initialization is not finished yet
   */
  private void checkContainerState(String methodName, ContainerState minimalState) {
    if (nonPortableMode) {
      return;
    }
    if (this.container == null) {
      this.container = Container.instance(manager);
    }

    ContainerState state = container.getState();
    if (SHUTDOWN.equals(state)) {
      throw BeanManagerLogger.LOG.methodNotAvailableAfterShutdown(methodName);
    }
    if (state.compareTo(minimalState) < 0) {
      throw BeanManagerLogger.LOG.methodNotAvailableDuringInitialization(methodName, state);
    }
  }
Пример #9
0
 public InjectionTargetService(BeanManagerImpl beanManager) {
   this.validator = beanManager.getServices().get(Validator.class);
   this.producersToValidate = new ConcurrentLinkedQueue<Producer<?>>();
   this.injectionTargetsToInitialize =
       new ConcurrentLinkedQueue<InjectionTargetInitializationContext<?>>();
   this.container = Container.instance(beanManager);
   this.beanManager = beanManager;
 }
Пример #10
0
 private BeanDeploymentArchiveImpl findRootBda() {
   for (Map.Entry<BeanDeploymentArchive, BeanManagerImpl> entry :
       Container.instance().beanDeploymentArchives().entrySet()) {
     if (entry.getKey() instanceof BeanDeploymentArchiveImpl) {
       BeanDeploymentArchiveImpl bda = cast(entry.getKey());
       if (bda.isRoot()) {
         return bda;
       }
     }
   }
   return null;
 }
Пример #11
0
 private Object readResolve() throws ObjectStreamException {
   SlimAnnotatedType<?> type =
       Container.instance(identifier)
           .services()
           .get(ClassTransformer.class)
           .getSlimAnnotatedTypeById(identifier);
   if (type == null) {
     type = tryToLoadUnknownBackedAnnotatedType();
   }
   if (type == null) {
     throw MetadataLogger.LOG.annotatedTypeDeserializationFailure(identifier);
   }
   return type;
 }
Пример #12
0
    /**
     * If the called of a {@link CDI} method is placed outside of BDA we have two options:
     *
     * <ol>
     *   <li>The class is placed in an archive with no beans.xml but with a CDI extension. In that
     *       case there exists an additional BDA but {@link Weld#getBeanManager()} may not find it
     *       since the {@link BeanDeploymentArchive#getBeanClasses()} of this logical BDA only
     *       contains extension classes or classes added by an extension. Therefore, we are going to
     *       iterate over the additional BDAs and try to match them with the classloader of the
     *       caller class.
     *   <li>The class comes from an archive that is not a BDA nor bundles an extension. In that
     *       case we return the root BDA which may be the BDA for WEB-INF/classes in war deployments
     *       or the root BDA of an ear.
     * </ol>
     */
    @Override
    protected BeanManagerImpl unsatisfiedBeanManager(String callerClassName) {
      BeanDeploymentArchiveImpl rootBda = findRootBda();
      if (rootBda == null) {
        return super.unsatisfiedBeanManager(callerClassName);
      }

      Class<?> callingClass = null;
      try {
        callingClass = rootBda.getModule().getClassLoader().loadClass(callerClassName);
      } catch (ClassNotFoundException e) {
        // fallback to the root bda manager
        return Container.instance().beanDeploymentArchives().get(rootBda);
      }

      BeanManagerImpl additionalBdaManager =
          findBeanManagerForAdditionalBdaWithMatchingClassloader(callingClass.getClassLoader());
      if (additionalBdaManager != null) {
        return additionalBdaManager;
      }

      // fallback to the root bda manager
      return Container.instance().beanDeploymentArchives().get(rootBda);
    }
Пример #13
0
 /**
  * Stops the container
  *
  * @throws IllegalStateException if the container is not running
  */
 public synchronized void stop(final StopContext context) {
   if (!started) {
     throw WeldLogger.ROOT_LOGGER.notStarted("WeldContainer");
   }
   WeldLogger.DEPLOYMENT_LOGGER.stoppingWeldService(deploymentName);
   ClassLoader oldTccl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
   try {
     WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(
         deployment.getModule().getClassLoader());
     WeldProvider.containerShutDown(Container.instance(deploymentName));
     bootstrap.shutdown();
   } finally {
     WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTccl);
     ModuleGroupSingletonProvider.removeClassLoader(deployment.getModule().getClassLoader());
   }
   started = false;
 }
Пример #14
0
 private BeanManagerImpl findBeanManagerForAdditionalBdaWithMatchingClassloader(
     ClassLoader classLoader) {
   for (Map.Entry<BeanDeploymentArchive, BeanManagerImpl> entry :
       Container.instance().beanDeploymentArchives().entrySet()) {
     if (entry.getKey() instanceof BeanDeploymentArchiveImpl) {
       BeanDeploymentArchiveImpl bda = cast(entry.getKey());
       if (bda.getId().endsWith(WeldDeployment.ADDITIONAL_CLASSES_BDA_SUFFIX)) {
         if (bda.getModule() != null
             && bda.getModule().getClassLoader() != null
             && bda.getModule().getClassLoader().equals(classLoader)) {
           return entry.getValue();
         }
       }
     }
   }
   return null;
 }
Пример #15
0
  @SuppressWarnings("unchecked")
  public void setup(Map<String, Object> properties) {
    try {
      final BeanManager manager =
          (BeanManager) new InitialContext().lookup(STANDARD_BEAN_MANAGER_JNDI_NAME);

      if (manager != null && Container.available()) {

        final Bean<BoundSessionContext> sessionContextBean =
            (Bean<BoundSessionContext>)
                manager.resolve(manager.getBeans(BoundSessionContext.class, BoundLiteral.INSTANCE));
        CreationalContext<?> ctx = manager.createCreationalContext(sessionContextBean);
        final BoundSessionContext sessionContext =
            (BoundSessionContext)
                manager.getReference(sessionContextBean, BoundSessionContext.class, ctx);
        sessionContext.associate(sessionContexts.get());
        sessionContext.activate();

        final Bean<BoundRequestContext> requestContextBean =
            (Bean<BoundRequestContext>)
                manager.resolve(manager.getBeans(BoundRequestContext.class, BoundLiteral.INSTANCE));
        ctx = manager.createCreationalContext(requestContextBean);
        final BoundRequestContext requestContext =
            (BoundRequestContext)
                manager.getReference(requestContextBean, BoundRequestContext.class, ctx);
        requestContext.associate(requestContexts.get());
        requestContext.activate();

        final Bean<BoundConversationContext> conversationContextBean =
            (Bean<BoundConversationContext>)
                manager.resolve(
                    manager.getBeans(BoundConversationContext.class, BoundLiteral.INSTANCE));
        ctx = manager.createCreationalContext(conversationContextBean);
        final BoundConversationContext conversationContext =
            (BoundConversationContext)
                manager.getReference(conversationContextBean, BoundConversationContext.class, ctx);
        BoundRequest request =
            new MutableBoundRequest(requestContexts.get(), sessionContexts.get());
        boundRequests.set(request);
        conversationContext.associate(request);
        conversationContext.activate();
      }
    } catch (NamingException e) {
      log.error("Failed to setup Weld contexts", e);
    }
  }
Пример #16
0
  @SuppressWarnings("unchecked")
  public void teardown(Map<String, Object> properties) {
    try {
      final BeanManager manager =
          (BeanManager) new InitialContext().lookup("java:comp/BeanManager");

      if (manager != null && Container.available()) {
        final Bean<BoundSessionContext> sessionContextBean =
            (Bean<BoundSessionContext>)
                manager.resolve(manager.getBeans(BoundSessionContext.class, BoundLiteral.INSTANCE));
        CreationalContext<?> ctx = manager.createCreationalContext(sessionContextBean);
        final BoundSessionContext sessionContext =
            (BoundSessionContext)
                manager.getReference(sessionContextBean, BoundSessionContext.class, ctx);
        sessionContext.deactivate();
        sessionContext.dissociate(sessionContexts.get());

        final Bean<BoundRequestContext> requestContextBean =
            (Bean<BoundRequestContext>)
                manager.resolve(manager.getBeans(BoundRequestContext.class, BoundLiteral.INSTANCE));
        ctx = manager.createCreationalContext(requestContextBean);
        final BoundRequestContext requestContext =
            (BoundRequestContext)
                manager.getReference(requestContextBean, BoundRequestContext.class, ctx);
        requestContext.deactivate();
        requestContext.dissociate(requestContexts.get());

        final Bean<BoundConversationContext> conversationContextBean =
            (Bean<BoundConversationContext>)
                manager.resolve(
                    manager.getBeans(BoundConversationContext.class, BoundLiteral.INSTANCE));
        ctx = manager.createCreationalContext(conversationContextBean);
        final BoundConversationContext conversationContext =
            (BoundConversationContext)
                manager.getReference(conversationContextBean, BoundConversationContext.class, ctx);
        conversationContext.deactivate();
        conversationContext.dissociate(boundRequests.get());
      }
    } catch (NamingException e) {
      log.error("Failed to tear down Weld contexts", e);
    } finally {
      sessionContexts.remove();
      requestContexts.remove();
      boundRequests.remove();
    }
  }
Пример #17
0
 private void validateEnabledAlternatives(BeanManagerImpl beanManager) {
   for (Metadata<Class<? extends Annotation>> stereotype :
       beanManager.getEnabled().getAlternativeStereotypes()) {
     if (!beanManager.isStereotype(stereotype.getValue())) {
       throw new DeploymentException(ALTERNATIVE_STEREOTYPE_NOT_STEREOTYPE, stereotype);
     }
     if (!isAlternative(beanManager, stereotype.getValue())) {
       throw new DeploymentException(ALTERNATIVE_STEREOTYPE_NOT_ANNOTATED, stereotype);
     }
   }
   for (Metadata<Class<?>> clazz : beanManager.getEnabled().getAlternativeClasses()) {
     if (clazz.getValue().isAnnotation() || clazz.getValue().isInterface()) {
       throw new DeploymentException(ALTERNATIVE_BEAN_CLASS_NOT_CLASS, clazz);
     }
     WeldClass<?> weldClass =
         Container.instance().services().get(ClassTransformer.class).loadClass(clazz.getValue());
     if (!weldClass.isAnnotationPresent(Alternative.class)) {
       throw new DeploymentException(ALTERNATIVE_BEAN_CLASS_NOT_ANNOTATED, clazz);
     }
   }
 }
  public ExtensionBeanDeployer deployBeans() {
    ClassTransformer classTransformer =
        Container.instance().deploymentServices().get(ClassTransformer.class);
    for (Extension extension : extensions) {
      @SuppressWarnings("unchecked")
      WeldClass<Extension> clazz =
          (WeldClass<Extension>) classTransformer.loadClass(extension.getClass());

      // Locate the BeanDeployment for this extension
      BeanDeployment beanDeployment =
          DeploymentStructures.getOrCreateBeanDeployment(
              deployment, beanManager, beanDeployments, clazz.getJavaClass());

      ExtensionBean bean = new ExtensionBean(beanDeployment.getBeanManager(), clazz, extension);
      Set<ObserverMethodImpl<?, ?>> observerMethods = new HashSet<ObserverMethodImpl<?, ?>>();
      createObserverMethods(bean, beanDeployment.getBeanManager(), clazz, observerMethods);
      beanDeployment.getBeanManager().addBean(bean);
      for (ObserverMethodImpl<?, ?> observerMethod : observerMethods) {
        observerMethod.initialize();
        beanDeployment.getBeanManager().addObserver(observerMethod);
      }
    }
    return this;
  }
Пример #19
0
 private static Instance<Context> instance() {
   return Container.instance().deploymentManager().instance().select(Context.class);
 }
Пример #20
0
 private Container getContainer() {
   return Container.instance(contextId);
 }
Пример #21
0
  public WeldRuntime startContainer(
      String contextId, Environment environment, Deployment deployment) {
    if (deployment == null) {
      throw BootstrapLogger.LOG.deploymentRequired();
    }

    checkApiVersion();

    final ServiceRegistry registry = deployment.getServices();

    // initiate part of registry in order to allow access to WeldConfiguration
    new AdditionalServiceLoader(deployment).loadAdditionalServices(registry);

    // Resource Loader has to be loaded prior to WeldConfiguration
    if (!registry.contains(ResourceLoader.class)) {
      registry.add(ResourceLoader.class, DefaultResourceLoader.INSTANCE);
    }

    WeldConfiguration configuration = new WeldConfiguration(registry, deployment);
    registry.add(WeldConfiguration.class, configuration);

    String finalContextId =
        BeanDeployments.getFinalId(
            contextId,
            registry.get(WeldConfiguration.class).getStringProperty(ROLLING_UPGRADES_ID_DELIMITER));
    this.contextId = finalContextId;
    this.deployment = deployment;
    this.environment = environment;

    if (this.extensions == null) {
      setExtensions(deployment.getExtensions());
    }
    // Add extension to register built-in components
    this.extensions.add(MetadataImpl.from(new WeldExtension()));

    // Add Weld extensions
    String vetoTypeRegex =
        configuration.getStringProperty(
            ConfigurationKey.VETO_TYPES_WITHOUT_BEAN_DEFINING_ANNOTATION);
    if (!vetoTypeRegex.isEmpty()) {
      this.extensions.add(MetadataImpl.from(new WeldVetoExtension(vetoTypeRegex)));
    }

    // Finish the rest of registry init, setupInitialServices() requires already changed
    // finalContextId
    setupInitialServices();
    registry.addAll(initialServices.entrySet());

    if (!registry.contains(ProxyServices.class)) {
      registry.add(ProxyServices.class, new SimpleProxyServices());
    }
    if (!registry.contains(SecurityServices.class)) {
      registry.add(SecurityServices.class, NoopSecurityServices.INSTANCE);
    }

    addImplementationServices(registry);

    verifyServices(registry, environment.getRequiredDeploymentServices(), contextId);
    if (!registry.contains(TransactionServices.class)) {
      BootstrapLogger.LOG.jtaUnavailable();
    }

    this.deploymentManager = BeanManagerImpl.newRootManager(finalContextId, "deployment", registry);

    Container.initialize(
        finalContextId,
        deploymentManager,
        ServiceRegistries.unmodifiableServiceRegistry(deployment.getServices()));
    getContainer().setState(ContainerState.STARTING);

    this.contexts = createContexts(registry);

    this.bdaMapping = new BeanDeploymentArchiveMapping();
    this.deploymentVisitor =
        new DeploymentVisitor(deploymentManager, environment, deployment, contexts, bdaMapping);

    if (deployment instanceof CDI11Deployment) {
      registry.add(
          BeanManagerLookupService.class,
          new BeanManagerLookupService(
              (CDI11Deployment) deployment, bdaMapping.getBdaToBeanManagerMap()));
    } else {
      BootstrapLogger.LOG.legacyDeploymentMetadataProvided();
    }

    // Read the deployment structure, bdaMapping will be the physical structure
    // as caused by the presence of beans.xml
    deploymentVisitor.visit();

    return new WeldRuntime(finalContextId, deploymentManager, bdaMapping.getBdaToBeanManagerMap());
  }