@Override
  protected void performRuntime(
      final OperationContext context,
      final ModelNode operation,
      final ModelNode model,
      final ServiceVerificationHandler verificationHandler,
      final List<ServiceController<?>> newControllers)
      throws OperationFailedException {

    String name =
        JcaDistributedWorkManagerDefinition.DWmParameters.NAME
            .getAttribute()
            .resolveModelAttribute(context, model)
            .asString();

    String policy =
        JcaDistributedWorkManagerDefinition.DWmParameters.POLICY
            .getAttribute()
            .resolveModelAttribute(context, model)
            .asString();
    String selector =
        JcaDistributedWorkManagerDefinition.DWmParameters.SELECTOR
            .getAttribute()
            .resolveModelAttribute(context, model)
            .asString();

    ServiceTarget serviceTarget = context.getServiceTarget();
    NamedDistributedWorkManager namedDistributedWorkManager = new NamedDistributedWorkManager(name);

    if (policy != null && !policy.trim().isEmpty()) {
      switch (JcaDistributedWorkManagerDefinition.PolicyValue.valueOf(policy)) {
        case NEVER:
          {
            namedDistributedWorkManager.setPolicy(new Never());
            break;
          }
        case ALWAYS:
          {
            namedDistributedWorkManager.setPolicy(new Always());
            break;
          }
        case WATERMARK:
          {
            namedDistributedWorkManager.setPolicy(new WaterMark());
            break;
          }
        default:
          throw ROOT_LOGGER.unsupportedPolicy(policy);
      }
      Injection injector = new Injection();
      for (Map.Entry<String, String> entry :
          ((PropertiesAttributeDefinition)
                  JcaDistributedWorkManagerDefinition.DWmParameters.POLICY_OPTIONS.getAttribute())
              .unwrap(context, model)
              .entrySet()) {
        try {
          injector.inject(
              namedDistributedWorkManager.getPolicy(), entry.getKey(), entry.getValue());
        } catch (Exception e) {
          ROOT_LOGGER.unsupportedPolicyOption(entry.getKey());
        }
      }
    } else {
      namedDistributedWorkManager.setPolicy(new WaterMark());
    }

    if (selector != null && !selector.trim().isEmpty()) {
      switch (JcaDistributedWorkManagerDefinition.SelectorValue.valueOf(selector)) {
        case FIRST_AVAILABLE:
          {
            namedDistributedWorkManager.setSelector(new FirstAvailable());
            break;
          }
        case MAX_FREE_THREADS:
          {
            namedDistributedWorkManager.setSelector(new MaxFreeThreads());
            break;
          }
        case PING_TIME:
          {
            namedDistributedWorkManager.setSelector(new PingTime());
            break;
          }
        default:
          throw ROOT_LOGGER.unsupportedSelector(selector);
      }
      Injection injector = new Injection();
      for (Map.Entry<String, String> entry :
          ((PropertiesAttributeDefinition)
                  JcaDistributedWorkManagerDefinition.DWmParameters.SELECTOR_OPTIONS.getAttribute())
              .unwrap(context, model)
              .entrySet()) {
        try {
          injector.inject(
              namedDistributedWorkManager.getSelector(), entry.getKey(), entry.getValue());
        } catch (Exception e) {
          ROOT_LOGGER.unsupportedSelectorOption(entry.getKey());
        }
      }
    } else {
      namedDistributedWorkManager.setSelector(new PingTime());
    }

    String jgroupsStack =
        model.hasDefined(
                JcaDistributedWorkManagerDefinition.DWmParameters.TRANSPORT_JGROPUS_STACK
                    .getAttribute()
                    .getName())
            ? JcaDistributedWorkManagerDefinition.DWmParameters.TRANSPORT_JGROPUS_STACK
                .getAttribute()
                .resolveModelAttribute(context, model)
                .asString()
            : "udp";
    String channelName =
        JcaDistributedWorkManagerDefinition.DWmParameters.TRANSPORT_JGROPUS_CLUSTER
            .getAttribute()
            .resolveModelAttribute(context, model)
            .asString();
    Long requestTimeout =
        JcaDistributedWorkManagerDefinition.DWmParameters.TRANSPORT_REQUEST_TIMEOUT
            .getAttribute()
            .resolveModelAttribute(context, model)
            .asLong();

    DistributedWorkManagerService wmService =
        new DistributedWorkManagerService(namedDistributedWorkManager, channelName, requestTimeout);
    ServiceBuilder builder =
        serviceTarget.addService(ConnectorServices.WORKMANAGER_SERVICE.append(name), wmService);
    builder.addDependency(
        ServiceName.JBOSS.append("jgroups").append("stack").append(jgroupsStack),
        ChannelFactory.class,
        wmService.getJGroupsChannelFactoryInjector());

    builder.addDependency(
        ServiceBuilder.DependencyType.OPTIONAL,
        ThreadsServices.EXECUTOR.append(WORKMANAGER_LONG_RUNNING).append(name),
        Executor.class,
        wmService.getExecutorLongInjector());
    builder.addDependency(
        ThreadsServices.EXECUTOR.append(WORKMANAGER_SHORT_RUNNING).append(name),
        Executor.class,
        wmService.getExecutorShortInjector());

    builder
        .addDependency(
            TxnServices.JBOSS_TXN_XA_TERMINATOR,
            JBossXATerminator.class,
            wmService.getXaTerminatorInjector())
        .addListener(verificationHandler)
        .setInitialMode(ServiceController.Mode.ACTIVE)
        .install();
  }
/** @author <a href="mailto:[email protected]">Carlo de Wolf</a> */
public abstract class SessionBeanComponent extends EJBComponent
    implements org.jboss.ejb3.context.spi.SessionBeanComponent {

  private static final Logger logger = Logger.getLogger(SessionBeanComponent.class);

  static final ServiceName ASYNC_EXECUTOR_SERVICE_NAME =
      ThreadsServices.EXECUTOR.append("ejb3-async");

  protected Map<String, AccessTimeout> beanLevelAccessTimeout;
  private final Set<Method> asynchronousMethods;
  protected Executor asyncExecutor;
  private final Map<String, ServiceName> viewServices;

  /**
   * Construct a new instance.
   *
   * @param ejbComponentCreateService the component configuration
   */
  protected SessionBeanComponent(
      final SessionBeanComponentCreateService ejbComponentCreateService) {
    super(ejbComponentCreateService);
    viewServices = ejbComponentCreateService.getViewServices();

    this.beanLevelAccessTimeout = ejbComponentCreateService.getBeanAccessTimeout();
    this.asynchronousMethods = null; // ejbComponentCreateService.getAsynchronousMethods();
    //        this.asyncExecutor = (Executor)
    // ejbComponentCreateService.getInjection(ASYNC_EXECUTOR_SERVICE_NAME).getValue();
  }

  @Override
  public <T> T getBusinessObject(SessionContext ctx, Class<T> businessInterface)
      throws IllegalStateException {
    if (businessInterface == null) {
      throw new IllegalStateException("Business interface type cannot be null");
    }

    final Serializable sessionId =
        ((SessionBeanComponentInstance.SessionBeanComponentInstanceContext) ctx).getId();

    if (viewServices.containsKey(businessInterface.getName())) {
      final ServiceController<?> serviceController =
          CurrentServiceRegistry.getServiceRegistry()
              .getRequiredService(viewServices.get(businessInterface.getName()));
      final ComponentView view = (ComponentView) serviceController.getValue();
      final ComponentViewInstance instance;
      if (sessionId != null) {
        instance =
            view.createInstance(
                Collections.<Object, Object>singletonMap(
                    StatefulSessionComponent.SESSION_ATTACH_KEY, sessionId));
      } else {
        instance = view.createInstance();
      }
      return (T) instance.createProxy();
    } else {
      throw new IllegalStateException(
          "View of type " + businessInterface + " not found on bean " + this);
    }
  }

  @Override
  public EJBLocalObject getEJBLocalObject(SessionContext ctx) throws IllegalStateException {
    throw new RuntimeException(
        "NYI: org.jboss.as.ejb3.component.session.SessionBeanComponent.getEJBLocalObject");
  }

  @Override
  public EJBObject getEJBObject(SessionContext ctx) throws IllegalStateException {
    throw new RuntimeException(
        "NYI: org.jboss.as.ejb3.component.session.SessionBeanComponent.getEJBObject");
  }

  /**
   * Return the {@link Executor} used for asynchronous invocations.
   *
   * @return the async executor
   */
  public Executor getAsynchronousExecutor() {
    return asyncExecutor;
  }

  @Override
  public boolean getRollbackOnly() throws IllegalStateException {
    // NOT_SUPPORTED and NEVER will not have a transaction context, so we can ignore those
    if (getCurrentTransactionAttribute() == TransactionAttributeType.SUPPORTS) {
      throw new IllegalStateException(
          "EJB 3.1 FR 13.6.2.9 getRollbackOnly is not allowed with SUPPORTS attribute");
    }
    return super.getRollbackOnly();
  }

  protected boolean isAsynchronous(final Method method) {
    final Set<Method> asyncMethods = this.asynchronousMethods;
    if (asyncMethods == null) {
      return false;
    }

    for (Method asyncMethod : asyncMethods) {
      if (method.getName().equals(asyncMethod.getName())) {
        final Object[] methodParams = method.getParameterTypes();
        final Object[] asyncMethodParams = asyncMethod.getParameterTypes();
        if (Arrays.equals(methodParams, asyncMethodParams)) {
          return true;
        }
      }
    }
    return false;
  }

  protected Object invokeAsynchronous(final Method method, final InterceptorContext context)
      throws Exception {
    if (Void.TYPE.isAssignableFrom(method.getReturnType())) {
      return new AsyncVoidInterceptor(getAsynchronousExecutor()).processInvocation(context);
    } else {
      return new AsyncFutureInterceptor(getAsynchronousExecutor()).processInvocation(context);
    }
  }

  //    @Override
  //    public Interceptor createClientInterceptor(Class<?> view, Serializable sessionId) {
  //        // ignore the session id. Session aware components like (StatefulSessionComponent)
  // should override
  //        // this method to take into account the session id.
  //        return this.createClientInterceptor(view);
  //    }
  //
  //    @Override
  //    public Interceptor createClientInterceptor(final Class<?> view) {
  //
  //        return new Interceptor() {
  //            @Override
  //            public Object processInvocation(InterceptorContext context) throws Exception {
  //                final Method method = context.getMethod();
  //                // if no-interface view, then check whether invocation on the method is allowed
  //                // (for ex: invocation on protected methods isn't allowed)
  //                if (SessionBeanComponent.this.getComponentClass().equals(view)) {
  //                    if (!SessionBeanComponent.this.isInvocationAllowed(method)) {
  //                        throw new javax.ejb.EJBException("Cannot invoke method " + method
  //                                + " on nointerface view of bean " +
  // SessionBeanComponent.this.getComponentName());
  //
  //                    }
  //                }
  //                // TODO: FIXME: Component shouldn't be attached in a interceptor context that
  //                // runs on remote clients.
  //                context.putPrivateData(Component.class, SessionBeanComponent.this);
  //                try {
  //                    if (isAsynchronous(method)) {
  //                        return invokeAsynchronous(method, context);
  //                    }
  //                    return context.proceed();
  //                } finally {
  //                    context.putPrivateData(Component.class, null);
  //                }
  //            }
  //        };
  //    }

  /**
   * EJB 3.1 spec mandates that the view should allow invocation on only public, non-final,
   * non-static methods. This method returns true if the passed {@link Method method} is public,
   * non-static and non-final. Else returns false.
   */
  protected boolean isInvocationAllowed(Method method) {
    int m = method.getModifiers();
    // We handle only public, non-static, non-final methods
    if (!Modifier.isPublic(m)) {
      if (logger.isTraceEnabled()) {
        logger.trace("Method " + method + " is *not* public");
      }
      // it's not a public method
      return false;
    }
    if (Modifier.isFinal(m)) {
      if (logger.isTraceEnabled()) {
        logger.trace("Method " + method + " is final");
      }
      // it's a final method
      return false;
    }
    if (Modifier.isStatic(m)) {
      if (logger.isTraceEnabled()) {
        logger.trace("Method " + method + " is static");
      }
      // it's a static method
      return false;
    }
    if (Modifier.isNative(m)) {
      if (logger.isTraceEnabled()) {
        logger.trace("Method " + method + " is native");
      }
      // it's a native method
      return false;
    }
    // we handle rest of the methods
    return true;
  }

  @Override
  public void setRollbackOnly() throws IllegalStateException {
    // NOT_SUPPORTED and NEVER will not have a transaction context, so we can ignore those
    if (getCurrentTransactionAttribute() == TransactionAttributeType.SUPPORTS) {
      throw new IllegalStateException(
          "EJB 3.1 FR 13.6.2.9 getRollbackOnly is not allowed with SUPPORTS attribute");
    }
    super.setRollbackOnly();
  }
}
Example #3
0
/** User: jpai */
public interface EJB3SubsystemModel {
  String LITE = "lite";
  String NAME = "name";
  String ALIASES = "aliases";

  String ASYNC = "async";
  String IIOP = "iiop";

  String CONNECTOR_REF = "connector-ref";

  String DEFAULT_MDB_INSTANCE_POOL = "default-mdb-instance-pool";
  String DEFAULT_RESOURCE_ADAPTER_NAME = "default-resource-adapter-name";
  String DEFAULT_SFSB_CACHE = "default-sfsb-cache";
  String DEFAULT_CLUSTERED_SFSB_CACHE = "default-clustered-sfsb-cache";
  String DEFAULT_SLSB_INSTANCE_POOL = "default-slsb-instance-pool";
  String INSTANCE_ACQUISITION_TIMEOUT = "timeout";
  String INSTANCE_ACQUISITION_TIMEOUT_UNIT = "timeout-unit";
  String DEFAULT_ENTITY_BEAN_INSTANCE_POOL = "default-entity-bean-instance-pool";
  String DEFAULT_ENTITY_BEAN_OPTIMISTIC_LOCKING = "default-entity-bean-optimistic-locking";

  String MAX_POOL_SIZE = "max-pool-size";
  String STRICT_MAX_BEAN_INSTANCE_POOL = "strict-max-bean-instance-pool";

  String MAX_THREADS = "max-threads";
  String KEEPALIVE_TIME = "keepalive-time";

  String RELATIVE_TO = "relative-to";
  String PATH = "path";

  String DEFAULT_SINGLETON_BEAN_ACCESS_TIMEOUT = "default-singleton-bean-access-timeout";
  String DEFAULT_STATEFUL_BEAN_ACCESS_TIMEOUT = "default-stateful-bean-access-timeout";

  String REMOTE = "remote";
  String SERVICE = "service";
  String TIMER_SERVICE = "timer-service";
  String THREAD_POOL = "thread-pool";
  String THREAD_POOL_NAME = "thread-pool-name";
  String DEFAULT = "default";

  String USE_QUALIFIED_NAME = "use-qualified-name";
  String ENABLE_BY_DEFAULT = "enable-by-default";

  String CACHE = "cache";
  String PASSIVATION_STORE = "passivation-store";

  String FILE_PASSIVATION_STORE = "file-passivation-store";
  String IDLE_TIMEOUT = "idle-timeout";
  String IDLE_TIMEOUT_UNIT = "idle-timeout-unit";
  String MAX_SIZE = "max-size";
  String GROUPS_PATH = "groups-path";
  String SESSIONS_PATH = "sessions-path";
  String SUBDIRECTORY_COUNT = "subdirectory-count";

  String CLUSTER_PASSIVATION_STORE = "cluster-passivation-store";
  String BEAN_CACHE = "bean-cache";
  String CACHE_CONTAINER = "cache-container";
  String CLIENT_MAPPINGS_CACHE = "client-mappings-cache";
  String PASSIVATE_EVENTS_ON_REPLICATE = "passivate-events-on-replicate";

  PathElement REMOTE_SERVICE_PATH = PathElement.pathElement(SERVICE, REMOTE);
  PathElement ASYNC_SERVICE_PATH = PathElement.pathElement(SERVICE, ASYNC);
  PathElement TIMER_SERVICE_PATH = PathElement.pathElement(SERVICE, TIMER_SERVICE);
  PathElement THREAD_POOL_PATH = PathElement.pathElement(THREAD_POOL);
  PathElement IIOP_PATH = PathElement.pathElement(SERVICE, IIOP);

  ServiceName BASE_THREAD_POOL_SERVICE_NAME = ThreadsServices.EXECUTOR.append("ejb3");
}