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/ejb3/src/main/java/org/jboss/as/ejb3/component/EJBViewConfiguration.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, 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.ejb3.component;
import org.jboss.as.ee.component.ComponentConfiguration;
import org.jboss.as.ee.component.ViewConfiguration;
import org.jboss.invocation.proxy.ProxyFactory;
import org.jboss.metadata.ejb.spec.MethodInterfaceType;
import org.jboss.msc.service.ServiceName;
/**
* Jakarta Enterprise Beans specific view configuration.
*
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public class EJBViewConfiguration extends ViewConfiguration {
private final MethodInterfaceType methodIntf;
public EJBViewConfiguration(final Class<?> viewClass, final ComponentConfiguration componentConfiguration, final ServiceName viewServiceName, final ProxyFactory<?> proxyFactory, final MethodInterfaceType methodIntf) {
super(viewClass, componentConfiguration, viewServiceName, proxyFactory);
this.methodIntf = methodIntf;
}
public MethodInterfaceType getMethodIntf() {
return methodIntf;
}
}
| 1,999 | 39 | 221 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/InvokeMethodOnTargetInterceptor.java | /*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, 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.ejb3.component;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.jboss.as.ee.component.ComponentInstance;
import org.jboss.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
import org.jboss.invocation.Interceptors;
/**
*
* Interceptor that directly invokes the target from the interceptor context and returns the result
*
* @author <a href="mailto:[email protected]">Carlo de Wolf</a>
*/
public class InvokeMethodOnTargetInterceptor implements Interceptor {
public static final Class<Object[]> PARAMETERS_KEY = Object[].class;
private final Method method;
InvokeMethodOnTargetInterceptor(Method method) {
this.method = method;
}
public static InterceptorFactory factory(final Method method) {
return new ImmediateInterceptorFactory(new InvokeMethodOnTargetInterceptor(method));
}
@Override
public Object processInvocation(final InterceptorContext context) throws Exception {
final Object instance = context.getPrivateData(ComponentInstance.class).getInstance();
try {
return method.invoke(instance, context.getPrivateData(PARAMETERS_KEY));
} catch (InvocationTargetException e) {
throw Interceptors.rethrow(e.getCause());
}
}
}
| 2,471 | 38.238095 | 99 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/ServerInterceptorsViewConfigurator.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.ejb3.component;
import org.jboss.as.ee.component.ComponentConfiguration;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.ee.component.ViewConfiguration;
import org.jboss.as.ee.component.ViewConfigurator;
import org.jboss.as.ee.component.ViewDescription;
import org.jboss.as.ee.component.interceptors.InterceptorOrder;
import org.jboss.as.ee.component.interceptors.UserInterceptorFactory;
import org.jboss.as.ejb3.interceptor.server.ServerInterceptorCache;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorFactory;
import org.jboss.invocation.InterceptorFactoryContext;
import org.jboss.invocation.Interceptors;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
/**
* @author <a href="mailto:[email protected]">Tomasz Adamski</a>
*/
public class ServerInterceptorsViewConfigurator implements ViewConfigurator {
private static final Class<?>[] EMPTY_CLASS_ARRAY = new Class[0];
public static final ServerInterceptorsViewConfigurator INSTANCE = new ServerInterceptorsViewConfigurator();
private ServerInterceptorsViewConfigurator() {
}
@Override
public void configure(final DeploymentPhaseContext deploymentPhaseContext, final ComponentConfiguration componentConfiguration, final ViewDescription viewDescription, final ViewConfiguration viewConfiguration) throws DeploymentUnitProcessingException {
final ComponentDescription componentDescription = componentConfiguration.getComponentDescription();
if (!(componentDescription instanceof EJBComponentDescription)) {
return;
}
final EJBComponentDescription ejbComponentDescription = (EJBComponentDescription) componentDescription;
final ServerInterceptorCache serverInterceptorCache = ejbComponentDescription.getServerInterceptorCache();
if(serverInterceptorCache == null){
return;
}
final List<InterceptorFactory> serverInterceptorsAroundInvoke = serverInterceptorCache.getServerInterceptorsAroundInvoke();
final List<InterceptorFactory> serverInterceptorsAroundTimeout;
if (ejbComponentDescription.isTimerServiceRequired()) {
serverInterceptorsAroundTimeout = serverInterceptorCache.getServerInterceptorsAroundTimeout();
} else {
serverInterceptorsAroundTimeout = new ArrayList<>();
}
final List<Method> viewMethods = viewConfiguration.getProxyFactory().getCachedMethods();
for (final Method method : viewMethods) {
viewConfiguration.addViewInterceptor(method, new UserInterceptorFactory(weaved(serverInterceptorsAroundInvoke), weaved(serverInterceptorsAroundTimeout)), InterceptorOrder.View.USER_APP_SPECIFIC_CONTAINER_INTERCEPTORS);
}
}
private InterceptorFactory weaved(final Collection<InterceptorFactory> interceptorFactories) {
return new InterceptorFactory() {
@Override
public Interceptor create(InterceptorFactoryContext context) {
final Interceptor[] interceptors = new Interceptor[interceptorFactories.size()];
final Iterator<InterceptorFactory> factories = interceptorFactories.iterator();
for (int i = 0; i < interceptors.length; i++) {
interceptors[i] = factories.next().create(context);
}
return Interceptors.getWeavedInterceptor(interceptors);
}
};
}
}
| 4,724 | 48.21875 | 256 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/MethodIntfHelper.java | /*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, 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.ejb3.component;
import org.jboss.as.ee.component.ComponentView;
import org.jboss.invocation.InterceptorContext;
import org.jboss.metadata.ejb.spec.MethodInterfaceType;
/**
* @author <a href="mailto:[email protected]">Carlo de Wolf</a>
*/
public class MethodIntfHelper {
// centralize this hack
public static MethodInterfaceType of(final InterceptorContext invocation) {
//for timer invocations there is no view, so the methodInf is attached directly
//to the context. Otherwise we retrieve it from the invoked view
MethodInterfaceType methodIntf = invocation.getPrivateData(MethodInterfaceType.class);
if (methodIntf == null) {
final ComponentView componentView = invocation.getPrivateData(ComponentView.class);
if (componentView != null) {
methodIntf = componentView.getPrivateData(MethodInterfaceType.class);
} else {
methodIntf = MethodInterfaceType.Bean;
}
}
return methodIntf;
}
}
| 2,079 | 42.333333 | 95 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/EJBComponentUnavailableException.java | package org.jboss.as.ejb3.component;
import jakarta.ejb.EJBException;
/**
* An exception which can be used to indicate that a particular Jakarta Enterprise Beans component is (no longer) available for handling invocations.
* This typically is thrown when an Jakarta Enterprise Beans are invoked
* after the Jakarta Enterprise Beans component has been marked for shutdown.
*
* @author: Jaikiran Pai
*/
public class EJBComponentUnavailableException extends EJBException {
public EJBComponentUnavailableException() {
}
public EJBComponentUnavailableException(final String msg) {
super(msg);
}
public EJBComponentUnavailableException(final String msg, final Exception e) {
super(msg, e);
}
public EJBComponentUnavailableException(final Exception e) {
super(e);
}
}
| 830 | 26.7 | 149 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/EJBComponentDescription.java | /*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, 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.ejb3.component;
import static org.jboss.as.ejb3.logging.EjbLogger.ROOT_LOGGER;
import static org.jboss.as.ejb3.subsystem.IdentityResourceDefinition.IDENTITY_CAPABILITY_NAME;
import java.lang.reflect.Method;
import java.rmi.Remote;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BooleanSupplier;
import java.util.function.Function;
import jakarta.ejb.EJBLocalObject;
import jakarta.ejb.TransactionAttributeType;
import jakarta.ejb.TransactionManagementType;
import jakarta.transaction.TransactionSynchronizationRegistry;
import org.jboss.as.controller.capability.CapabilityServiceSupport;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.ee.component.Attachments;
import org.jboss.as.ee.component.BindingConfiguration;
import org.jboss.as.ee.component.Component;
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.ComponentNamingMode;
import org.jboss.as.ee.component.ComponentStartService;
import org.jboss.as.ee.component.ComponentView;
import org.jboss.as.ee.component.DependencyConfigurator;
import org.jboss.as.ee.component.InterceptorDescription;
import org.jboss.as.ee.component.NamespaceConfigurator;
import org.jboss.as.ee.component.NamespaceViewConfigurator;
import org.jboss.as.ee.component.ViewConfiguration;
import org.jboss.as.ee.component.ViewConfigurator;
import org.jboss.as.ee.component.ViewDescription;
import org.jboss.as.ee.component.ViewService;
import org.jboss.as.ee.component.interceptors.ComponentDispatcherInterceptor;
import org.jboss.as.ee.component.interceptors.InterceptorOrder;
import org.jboss.as.ee.naming.ContextInjectionSource;
import org.jboss.as.ejb3.component.interceptors.AdditionalSetupInterceptor;
import org.jboss.as.ejb3.component.interceptors.CurrentInvocationContextInterceptor;
import org.jboss.as.ejb3.component.interceptors.EjbExceptionTransformingInterceptorFactories;
import org.jboss.as.ejb3.component.interceptors.LoggingInterceptor;
import org.jboss.as.ejb3.component.interceptors.ShutDownInterceptorFactory;
import org.jboss.as.ejb3.component.invocationmetrics.ExecutionTimeInterceptor;
import org.jboss.as.ejb3.component.invocationmetrics.WaitTimeInterceptor;
import org.jboss.as.ejb3.deployment.ApplicableMethodInformation;
import org.jboss.as.ejb3.deployment.ApplicationExceptions;
import org.jboss.as.ejb3.deployment.EjbDeploymentAttachmentKeys;
import org.jboss.as.ejb3.deployment.EjbJarDescription;
import org.jboss.as.ejb3.deployment.ModuleDeployment;
import org.jboss.as.ejb3.interceptor.server.ServerInterceptorCache;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.ejb3.security.EJBMethodSecurityAttribute;
import org.jboss.as.ejb3.security.EJBSecurityViewConfigurator;
import org.jboss.as.ejb3.security.IdentityOutflowInterceptorFactory;
import org.jboss.as.ejb3.security.PolicyContextIdInterceptor;
import org.jboss.as.ejb3.security.RoleAddingInterceptor;
import org.jboss.as.ejb3.security.RunAsPrincipalInterceptor;
import org.jboss.as.ejb3.security.SecurityDomainInterceptorFactory;
import org.jboss.as.ejb3.security.SecurityRolesAddingInterceptor;
import org.jboss.as.ejb3.subsystem.EJB3RemoteResourceDefinition;
import org.jboss.as.ejb3.suspend.EJBSuspendHandlerService;
import org.jboss.as.ejb3.timerservice.spi.AutoTimer;
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.SetupAction;
import org.jboss.invocation.AccessCheckingInterceptor;
import org.jboss.invocation.ContextClassLoaderInterceptor;
import org.jboss.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
import org.jboss.invocation.InterceptorFactoryContext;
import org.jboss.invocation.Interceptors;
import org.jboss.invocation.proxy.MethodIdentifier;
import org.jboss.metadata.ejb.spec.EnterpriseBeanMetaData;
import org.jboss.metadata.ejb.spec.MethodInterfaceType;
import org.jboss.metadata.javaee.spec.SecurityRolesMetaData;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import org.wildfly.security.auth.server.SecurityDomain;
import org.wildfly.security.authz.RoleMapper;
import org.wildfly.security.authz.Roles;
/**
* @author <a href="mailto:[email protected]">Carlo de Wolf</a>
*
* NOTE: References in this document to Enterprise JavaBeans (EJB) refer to the Jakarta Enterprise Beans unless otherwise noted.
*
*/
public abstract class EJBComponentDescription extends ComponentDescription {
// references to external capabilities
private static final String REMOTE_TRANSACTION_SERVICE_CAPABILITY_NAME = "org.wildfly.transactions.remote-transaction-service";
private static final String TRANSACTION_GLOBAL_DEFAULT_LOCAL_PROVIDER_CAPABILITY_NAME = "org.wildfly.transactions.global-default-local-provider";
private static final String TRANSACTION_SYNCHRONIZATION_REGISTRY_CAPABILITY_NAME = "org.wildfly.transactions.transaction-synchronization-registry";
/**
* EJB 3.1 FR 13.3.1, the default transaction management type is container-managed transaction demarcation.
*/
private TransactionManagementType transactionManagementType = TransactionManagementType.CONTAINER;
/**
* The deployment descriptor information for this bean, if any
*/
private EnterpriseBeanMetaData descriptorData;
/**
* The default security domain to use if no explicit security domain is configured for this bean
*/
private String defaultSecurityDomain;
/**
* The @DeclareRoles (a.k.a security-role-ref) for the bean
*/
private final Set<String> declaredRoles = new HashSet<String>();
/**
* The @RunAs role associated with this bean, if any
*/
private String runAsRole;
/**
* The @RunAsPrincipal associated with this bean, if any
*/
private String runAsPrincipal;
/**
* Roles mapped with security-role
*/
private SecurityRolesMetaData securityRoles;
/**
* Security role links. The key is the "from" role name and the value is a collection of "to" role names of the link.
*/
private final Map<String, Collection<String>> securityRoleLinks = new HashMap<String, Collection<String>>();
private final ApplicableMethodInformation<EJBMethodSecurityAttribute> descriptorMethodPermissions;
private final ApplicableMethodInformation<EJBMethodSecurityAttribute> annotationMethodPermissions;
/**
* @Schedule methods
*/
private final Map<Method, List<AutoTimer>> scheduleMethods = new IdentityHashMap<Method, List<AutoTimer>>();
/**
* The actual timeout method
*/
private Method timeoutMethod;
/**
* The EJB 2.x local view
*/
private EJBViewDescription ejbLocalView;
/**
* The ejb local home view
*/
private EjbHomeViewDescription ejbLocalHomeView;
/**
* The EJB 2.x remote view
*/
private EJBViewDescription ejbRemoteView;
/**
* The ejb local home view
*/
private EjbHomeViewDescription ejbHomeView;
/**
* The management resource for the associated timer service, if present
*/
private Resource timerServiceResource;
/**
* If true this component is accessible via CORBA
*/
private boolean exposedViaIiop = false;
/**
* The transaction attributes
*/
private final ApplicableMethodInformation<TransactionAttributeType> transactionAttributes;
/**
* The transaction timeouts
*/
private final ApplicableMethodInformation<Integer> transactionTimeouts;
/**
* The default container interceptors
*/
private List<InterceptorDescription> defaultContainerInterceptors = new ArrayList<InterceptorDescription>();
/**
* Whether or not to exclude the default container interceptors for the EJB
*/
private boolean excludeDefaultContainerInterceptors;
/**
* Container interceptors applicable for all methods of the EJB
*/
private List<InterceptorDescription> classLevelContainerInterceptors = new ArrayList<InterceptorDescription>();
/**
* Container interceptors applicable per method of the EJB
*/
private Map<MethodIdentifier, List<InterceptorDescription>> methodLevelContainerInterceptors = new HashMap<MethodIdentifier, List<InterceptorDescription>>();
/**
* Whether or not to exclude the default container interceptors applicable for the method of the EJB
*/
private Map<MethodIdentifier, Boolean> excludeDefaultContainerInterceptorsForMethod = new HashMap<MethodIdentifier, Boolean>();
/**
* Whether or not to exclude the class level container interceptors applicable for the method of the EJB
*/
private Map<MethodIdentifier, Boolean> excludeClassLevelContainerInterceptorsForMethod = new HashMap<MethodIdentifier, Boolean>();
/**
* Combination of class and method level container interceptors
*/
private Set<InterceptorDescription> allContainerInterceptors;
private ServerInterceptorCache serverInterceptorCache = null;
/**
* missing-method-permissions-deny-access that's used for secured EJBs
*/
private Boolean missingMethodPermissionsDenyAccess = null;
private final ShutDownInterceptorFactory shutDownInterceptorFactory = new ShutDownInterceptorFactory();
private BooleanSupplier outflowSecurityDomainsConfigured;
private boolean securityRequired;
/**
* The {@code ServiceName} of the WildFly Elytron security domain.
*/
private ServiceName securityDomainServiceName;
/**
* The name of the security domain defined within the deployment for this component.
*/
private String definedSecurityDomain;
/**
* Should JACC be enabled when using an Elytron security domain.
*/
private boolean requiresJacc;
private boolean legacyCompliantPrincipalPropagation;
/**
* Construct a new instance.
*
* @param componentName the component name
* @param componentClassName the component instance class name
* @param ejbJarDescription the module
* @param deploymentUnitServiceName
* @param descriptorData the optional descriptor metadata
*/
public EJBComponentDescription(final String componentName, final String componentClassName, final EjbJarDescription ejbJarDescription, final DeploymentUnit deploymentUnit, final EnterpriseBeanMetaData descriptorData) {
super(componentName, componentClassName, ejbJarDescription.getEEModuleDescription(), deploymentUnit.getServiceName());
this.descriptorData = descriptorData;
if (ejbJarDescription.isWar()) {
setNamingMode(ComponentNamingMode.USE_MODULE);
} else {
setNamingMode(ComponentNamingMode.CREATE);
}
getConfigurators().addFirst(new NamespaceConfigurator());
getConfigurators().add(new EjbJarConfigurationConfigurator());
getConfigurators().add(new SecurityDomainDependencyConfigurator(this));
// setup a current invocation interceptor
this.addCurrentInvocationContextFactory();
// setup a dependency on EJB remote tx repository service, if this EJB exposes at least one remote view
this.addRemoteTransactionsDependency();
this.transactionAttributes = new ApplicableMethodInformation<TransactionAttributeType>(componentName, TransactionAttributeType.REQUIRED);
this.transactionTimeouts = new ApplicableMethodInformation<Integer>(componentName, null);
this.descriptorMethodPermissions = new ApplicableMethodInformation<EJBMethodSecurityAttribute>(componentName, null);
this.annotationMethodPermissions = new ApplicableMethodInformation<EJBMethodSecurityAttribute>(componentName, null);
//add a dependency on the module deployment service
//we need to make sure this is up before the EJB starts, so that remote invocations are available
addDependency(deploymentUnit.getServiceName().append(ModuleDeployment.SERVICE_NAME));
getConfigurators().addFirst(EJBValidationConfigurator.INSTANCE);
getConfigurators().add(new ComponentConfigurator() {
@Override
public void configure(final DeploymentPhaseContext context, final ComponentDescription description, final ComponentConfiguration configuration) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = context.getDeploymentUnit();
String contextID = deploymentUnit.getName();
if (deploymentUnit.getParent() != null) {
contextID = deploymentUnit.getParent().getName() + "!" + contextID;
}
//make sure java:comp/env is always available, even if nothing is bound there
if (description.getNamingMode() == ComponentNamingMode.CREATE) {
description.getBindingConfigurations().add(new BindingConfiguration("java:comp/env", new ContextInjectionSource("env", "java:comp/env")));
}
final List<SetupAction> ejbSetupActions = deploymentUnit.getAttachmentList(Attachments.OTHER_EE_SETUP_ACTIONS);
if (description.isTimerServiceRequired()) {
if (!ejbSetupActions.isEmpty()) {
configuration.addTimeoutViewInterceptor(AdditionalSetupInterceptor.factory(ejbSetupActions), InterceptorOrder.View.EE_SETUP);
}
configuration.addTimeoutViewInterceptor(shutDownInterceptorFactory, InterceptorOrder.View.SHUTDOWN_INTERCEPTOR);
final ClassLoader classLoader = configuration.getModuleClassLoader();
configuration.addTimeoutViewInterceptor(AccessCheckingInterceptor.getFactory(), InterceptorOrder.View.CHECKING_INTERCEPTOR);
configuration.addTimeoutViewInterceptor(new ImmediateInterceptorFactory(new ContextClassLoaderInterceptor(classLoader)), InterceptorOrder.View.TCCL_INTERCEPTOR);
configuration.addTimeoutViewInterceptor(configuration.getNamespaceContextInterceptorFactory(), InterceptorOrder.View.JNDI_NAMESPACE_INTERCEPTOR);
configuration.addTimeoutViewInterceptor(CurrentInvocationContextInterceptor.FACTORY, InterceptorOrder.View.INVOCATION_CONTEXT_INTERCEPTOR);
EJBComponentDescription ejbComponentDescription = (EJBComponentDescription) description;
final boolean securityRequired = hasBeanLevelSecurityMetadata();
ejbComponentDescription.setSecurityRequired(securityRequired);
if (ejbComponentDescription.getSecurityDomainServiceName() != null) {
final HashMap<Integer, InterceptorFactory> elytronInterceptorFactories = getElytronInterceptorFactories(contextID, ejbComponentDescription.requiresJacc(), true);
elytronInterceptorFactories.forEach((priority, elytronInterceptorFactory) -> configuration.addTimeoutViewInterceptor(elytronInterceptorFactory, priority));
}
final Set<Method> classMethods = configuration.getClassIndex().getClassMethods();
for (final Method method : classMethods) {
configuration.addTimeoutViewInterceptor(method, new ImmediateInterceptorFactory(new ComponentDispatcherInterceptor(method)), InterceptorOrder.View.COMPONENT_DISPATCHER);
}
//server side interceptors
if(serverInterceptorCache != null) {
configuration.addTimeoutViewInterceptor(weaved(serverInterceptorCache.getServerInterceptorsAroundTimeout()), InterceptorOrder.View.USER_APP_SPECIFIC_CONTAINER_INTERCEPTORS);
}
}
if (!ejbSetupActions.isEmpty()) {
configuration.getStartDependencies().add(new DependencyConfigurator<ComponentStartService>() {
@Override
public void configureDependency(final ServiceBuilder<?> serviceBuilder, final ComponentStartService service) throws DeploymentUnitProcessingException {
for (final SetupAction setupAction : ejbSetupActions) {
for (final ServiceName setupActionDependency : setupAction.dependencies()) {
serviceBuilder.requires(setupActionDependency);
}
}
}
});
}
configuration.addComponentInterceptor(ExecutionTimeInterceptor.FACTORY, InterceptorOrder.Component.EJB_EXECUTION_TIME_INTERCEPTOR, true);
configuration.getCreateDependencies().add(new DependencyConfigurator<EJBComponentCreateService>() {
@Override
public void configureDependency(ServiceBuilder<?> serviceBuilder, EJBComponentCreateService service) throws DeploymentUnitProcessingException {
serviceBuilder.addDependency(LoggingInterceptor.LOGGING_ENABLED_SERVICE_NAME, AtomicBoolean.class, service.getExceptionLoggingEnabledInjector());
}
});
}
});
// setup dependencies on the transaction manager services
addTransactionManagerDependencies();
// setup ejb suspend handler dependency
addEJBSuspendHandlerDependency();
}
private static InterceptorFactory weaved(final Collection<InterceptorFactory> interceptorFactories) {
return new InterceptorFactory() {
@Override
public Interceptor create(InterceptorFactoryContext context) {
final Interceptor[] interceptors = new Interceptor[interceptorFactories.size()];
final Iterator<InterceptorFactory> factories = interceptorFactories.iterator();
for (int i = 0; i < interceptors.length; i++) {
interceptors[i] = factories.next().create(context);
}
return Interceptors.getWeavedInterceptor(interceptors);
}
};
}
public void addLocalHome(final String localHome) {
final EjbHomeViewDescription view = new EjbHomeViewDescription(this, localHome, MethodInterfaceType.LocalHome);
view.getConfigurators().add(new Ejb2ViewTypeConfigurator(Ejb2xViewType.LOCAL_HOME));
getViews().add(view);
// setup server side view interceptors
setupViewInterceptors(view);
// setup client side view interceptors
setupClientViewInterceptors(view);
// return created view
this.ejbLocalHomeView = view;
}
public void addRemoteHome(final String remoteHome) {
final EjbHomeViewDescription view = new EjbHomeViewDescription(this, remoteHome, MethodInterfaceType.Home);
view.getConfigurators().add(new Ejb2ViewTypeConfigurator(Ejb2xViewType.HOME));
getViews().add(view);
// setup server side view interceptors
setupViewInterceptors(view);
// setup client side view interceptors
setupClientViewInterceptors(view);
// return created view
this.ejbHomeView = view;
}
public void addEjbLocalObjectView(final String viewClassName) {
final EJBViewDescription view = registerView(viewClassName, MethodInterfaceType.Local, true);
view.getConfigurators().add(new Ejb2ViewTypeConfigurator(Ejb2xViewType.LOCAL));
this.ejbLocalView = view;
}
public void addEjbObjectView(final String viewClassName) {
final EJBViewDescription view = registerView(viewClassName, MethodInterfaceType.Remote, true);
view.getConfigurators().add(new Ejb2ViewTypeConfigurator(Ejb2xViewType.REMOTE));
this.ejbRemoteView = view;
}
public TransactionManagementType getTransactionManagementType() {
return transactionManagementType;
}
public void setTransactionManagementType(TransactionManagementType transactionManagementType) {
this.transactionManagementType = transactionManagementType;
}
public String getEJBName() {
return this.getComponentName();
}
public String getEJBClassName() {
return this.getComponentClassName();
}
protected void setupViewInterceptors(final EJBViewDescription view) {
// add a logging interceptor (to take care of EJB3 spec, section 14.3 logging requirements)
view.getConfigurators().add(new ViewConfigurator() {
@Override
public void configure(DeploymentPhaseContext context, ComponentConfiguration componentConfiguration, ViewDescription description, ViewConfiguration viewConfiguration) throws DeploymentUnitProcessingException {
viewConfiguration.addViewInterceptor(LoggingInterceptor.FACTORY, InterceptorOrder.View.EJB_EXCEPTION_LOGGING_INTERCEPTOR);
final ClassLoader classLoader = componentConfiguration.getModuleClassLoader();
viewConfiguration.addViewInterceptor(AccessCheckingInterceptor.getFactory(), InterceptorOrder.View.CHECKING_INTERCEPTOR);
viewConfiguration.addViewInterceptor(new ImmediateInterceptorFactory(new ContextClassLoaderInterceptor(classLoader)), InterceptorOrder.View.TCCL_INTERCEPTOR);
//If this is the EJB 2.x local or home view add the exception transformer interceptor
if (view.getMethodIntf() == MethodInterfaceType.Local && EJBLocalObject.class.isAssignableFrom(viewConfiguration.getViewClass())) {
viewConfiguration.addViewInterceptor(EjbExceptionTransformingInterceptorFactories.LOCAL_INSTANCE, InterceptorOrder.View.REMOTE_EXCEPTION_TRANSFORMER);
} else if (view.getMethodIntf() == MethodInterfaceType.LocalHome) {
viewConfiguration.addViewInterceptor(EjbExceptionTransformingInterceptorFactories.LOCAL_INSTANCE, InterceptorOrder.View.REMOTE_EXCEPTION_TRANSFORMER);
}
final List<SetupAction> ejbSetupActions = context.getDeploymentUnit().getAttachmentList(Attachments.OTHER_EE_SETUP_ACTIONS);
if (!ejbSetupActions.isEmpty()) {
viewConfiguration.addViewInterceptor(AdditionalSetupInterceptor.factory(ejbSetupActions), InterceptorOrder.View.EE_SETUP);
}
viewConfiguration.addViewInterceptor(WaitTimeInterceptor.FACTORY, InterceptorOrder.View.EJB_WAIT_TIME_INTERCEPTOR);
viewConfiguration.addViewInterceptor(shutDownInterceptorFactory, InterceptorOrder.View.SHUTDOWN_INTERCEPTOR);
}
});
this.addCurrentInvocationContextFactory(view);
this.setupSecurityInterceptors(view);
this.setupRemoteViewInterceptors(view);
view.getConfigurators().addFirst(new NamespaceViewConfigurator());
}
private void setupRemoteViewInterceptors(final EJBViewDescription view) {
if (view.getMethodIntf() == MethodInterfaceType.Remote || view.getMethodIntf() == MethodInterfaceType.Home) {
view.getConfigurators().add(new ViewConfigurator() {
@Override
public void configure(final DeploymentPhaseContext context, final ComponentConfiguration componentConfiguration, final ViewDescription description, final ViewConfiguration configuration) throws DeploymentUnitProcessingException {
if (Remote.class.isAssignableFrom(configuration.getViewClass())) {
configuration.addViewInterceptor(EjbExceptionTransformingInterceptorFactories.REMOTE_INSTANCE, InterceptorOrder.View.REMOTE_EXCEPTION_TRANSFORMER);
}
}
});
if (view.getMethodIntf() == MethodInterfaceType.Home) {
view.getConfigurators().add(new ViewConfigurator() {
@Override
public void configure(final DeploymentPhaseContext context, final ComponentConfiguration componentConfiguration, final ViewDescription description, final ViewConfiguration configuration) throws DeploymentUnitProcessingException {
if (Remote.class.isAssignableFrom(configuration.getViewClass())) {
final String earApplicationName = componentConfiguration.getComponentDescription().getModuleDescription().getEarApplicationName();
configuration.setViewInstanceFactory(new RemoteHomeViewInstanceFactory(earApplicationName, componentConfiguration.getModuleName(), componentConfiguration.getComponentDescription().getModuleDescription().getDistinctName(), componentConfiguration.getComponentName()));
}
}
});
}
}
}
protected void setupClientViewInterceptors(ViewDescription view) {
// add a client side interceptor which handles the toString() method invocation on the bean's views
this.addToStringMethodInterceptor(view);
}
/**
* Setup the current invocation context interceptor, which will be used during the post-construct
* lifecycle of the component instance
*/
protected abstract void addCurrentInvocationContextFactory();
/**
* Setup the current invocation context interceptor, which will be used during the invocation on the view (methods)
*
* @param view The view for which the interceptor has to be setup
*/
protected abstract void addCurrentInvocationContextFactory(ViewDescription view);
/**
* Adds a dependency for the ComponentConfiguration on the remote transaction service if the EJB exposes at least one remote view
*/
protected void addRemoteTransactionsDependency() {
this.getConfigurators().add(new ComponentConfigurator() {
@Override
public void configure(DeploymentPhaseContext context, ComponentDescription description, ComponentConfiguration componentConfiguration) throws DeploymentUnitProcessingException {
if (this.hasRemoteView((EJBComponentDescription) description)) {
// add a dependency on local transaction service
componentConfiguration.getCreateDependencies().add(new DependencyConfigurator<EJBComponentCreateService>() {
@Override
public void configureDependency(ServiceBuilder<?> serviceBuilder, EJBComponentCreateService ejbComponentCreateService) throws DeploymentUnitProcessingException {
CapabilityServiceSupport support = context.getDeploymentUnit().getAttachment(org.jboss.as.server.deployment.Attachments.CAPABILITY_SERVICE_SUPPORT);
// add dependency on the remote transaction service
serviceBuilder.requires(support.getCapabilityServiceName(REMOTE_TRANSACTION_SERVICE_CAPABILITY_NAME));
}
});
}
}
/**
* Returns true if the passed EJB component description has at least one remote view
* @param ejbComponentDescription
* @return
*/
private boolean hasRemoteView(final EJBComponentDescription ejbComponentDescription) {
final Set<ViewDescription> views = ejbComponentDescription.getViews();
for (final ViewDescription view : views) {
if (!(view instanceof EJBViewDescription)) {
continue;
}
final MethodInterfaceType viewType = ((EJBViewDescription) view).getMethodIntf();
if (viewType == MethodInterfaceType.Remote || viewType == MethodInterfaceType.Home) {
return true;
}
}
return false;
}
});
}
/**
* Sets up a {@link ComponentConfigurator} which then sets up the relevant dependencies on the transaction manager services for the {@link EJBComponentCreateService}
*/
protected void addTransactionManagerDependencies() {
this.getConfigurators().add(new ComponentConfigurator() {
@Override
public void configure(final DeploymentPhaseContext context, final ComponentDescription description, final ComponentConfiguration componentConfiguration) throws DeploymentUnitProcessingException {
componentConfiguration.getCreateDependencies().add(new DependencyConfigurator<EJBComponentCreateService>() {
@Override
public void configureDependency(final ServiceBuilder<?> serviceBuilder, final EJBComponentCreateService ejbComponentCreateService) throws DeploymentUnitProcessingException {
CapabilityServiceSupport support = context.getDeploymentUnit().getAttachment(org.jboss.as.server.deployment.Attachments.CAPABILITY_SERVICE_SUPPORT);
// add dependency on the local transaction provider
serviceBuilder.requires(support.getCapabilityServiceName(TRANSACTION_GLOBAL_DEFAULT_LOCAL_PROVIDER_CAPABILITY_NAME));
// add dependency on TransactionSynchronizationRegistry
serviceBuilder.addDependency(support.getCapabilityServiceName(TRANSACTION_SYNCHRONIZATION_REGISTRY_CAPABILITY_NAME), TransactionSynchronizationRegistry.class, ejbComponentCreateService.getTransactionSynchronizationRegistryInjector());
}
});
}
});
}
/**
* Sets up a {@link ComponentConfigurator} which then sets up the dependency on the EJBSuspendHandlerService service for the {@link EJBComponentCreateService}
*/
protected void addEJBSuspendHandlerDependency() {
getConfigurators().add(new ComponentConfigurator() {
@Override
public void configure(final DeploymentPhaseContext context, final ComponentDescription description, final ComponentConfiguration componentConfiguration) throws DeploymentUnitProcessingException {
componentConfiguration.getCreateDependencies().add(new DependencyConfigurator<EJBComponentCreateService>() {
@Override public void configureDependency(final ServiceBuilder<?> serviceBuilder, final EJBComponentCreateService ejbComponentCreateService)
throws DeploymentUnitProcessingException {
serviceBuilder.addDependency(EJBSuspendHandlerService.SERVICE_NAME, EJBSuspendHandlerService.class,
ejbComponentCreateService.getEJBSuspendHandlerInjector());
}
});
}
});
}
protected void setupSecurityInterceptors(final ViewDescription view) {
// setup security interceptor for the component
view.getConfigurators().add(new EJBSecurityViewConfigurator());
}
private void addToStringMethodInterceptor(final ViewDescription view) {
view.getConfigurators().add(new ViewConfigurator() {
@Override
public void configure(DeploymentPhaseContext context, ComponentConfiguration componentConfiguration, ViewDescription description, ViewConfiguration configuration) throws DeploymentUnitProcessingException {
final Method TO_STRING_METHOD;
try {
TO_STRING_METHOD = Object.class.getMethod("toString");
} catch (NoSuchMethodException nsme) {
throw new DeploymentUnitProcessingException(nsme);
}
List<Method> methods = configuration.getProxyFactory().getCachedMethods();
for (Method method : methods) {
if (TO_STRING_METHOD.equals(method)) {
configuration.addClientInterceptor(method, new ImmediateInterceptorFactory(new ToStringMethodInterceptor(EJBComponentDescription.this.getComponentName())), InterceptorOrder.Client.TO_STRING);
return;
}
}
}
});
}
public boolean isEntity() {
return false;
}
public boolean isMessageDriven() {
return false;
}
public boolean isSession() {
return false;
}
public boolean isSingleton() {
return false;
}
public boolean isStateful() {
return false;
}
public boolean isStateless() {
return false;
}
public void addDeclaredRoles(String... roles) {
this.declaredRoles.addAll(Arrays.asList(roles));
}
public void setDeclaredRoles(Collection<String> roles) {
if (roles == null) {
throw EjbLogger.ROOT_LOGGER.SecurityRolesIsNull();
}
this.declaredRoles.clear();
this.declaredRoles.addAll(roles);
}
public Set<String> getDeclaredRoles() {
return Collections.unmodifiableSet(this.declaredRoles);
}
public void setRunAs(String role) {
this.runAsRole = role;
}
public String getRunAs() {
return this.runAsRole;
}
public void setRunAsPrincipal(String principal) {
this.runAsPrincipal = principal;
}
public String getRunAsPrincipal() {
return runAsPrincipal;
}
public void setDefaultSecurityDomain(final String defaultSecurityDomain) {
this.defaultSecurityDomain = defaultSecurityDomain;
}
public void setOutflowSecurityDomainsConfigured(final BooleanSupplier outflowSecurityDomainsConfigured) {
this.outflowSecurityDomainsConfigured = outflowSecurityDomainsConfigured;
}
public boolean isOutflowSecurityDomainsConfigured() {
return outflowSecurityDomainsConfigured.getAsBoolean();
}
/**
* Returns the security domain that is applicable for this bean. In the absence of any explicit
* configuration of a security domain for this bean, this method returns the default security domain
* (if any) that's configured for all beans in the EJB3 subsystem
*
* @return
*/
public String getResolvedSecurityDomain() {
if (this.definedSecurityDomain == null) {
return this.defaultSecurityDomain;
}
return this.definedSecurityDomain;
}
public void setMissingMethodPermissionsDenyAccess(Boolean missingMethodPermissionsDenyAccess) {
this.missingMethodPermissionsDenyAccess = missingMethodPermissionsDenyAccess;
}
public Boolean isMissingMethodPermissionsDeniedAccess() {
return this.missingMethodPermissionsDenyAccess;
}
public SecurityRolesMetaData getSecurityRoles() {
return securityRoles;
}
public void setSecurityRoles(SecurityRolesMetaData securityRoles) {
this.securityRoles = securityRoles;
}
public void setSecurityDomainServiceName(final ServiceName securityDomainServiceName) {
this.securityDomainServiceName = securityDomainServiceName;
}
public ServiceName getSecurityDomainServiceName() {
return this.securityDomainServiceName;
}
public void setDefinedSecurityDomain(final String definedSecurityDomain) {
this.definedSecurityDomain = definedSecurityDomain;
}
public String getDefinedSecurityDomain() {
return this.definedSecurityDomain;
}
public boolean requiresJacc() {
return requiresJacc;
}
public void setRequiresJacc(final boolean requiresJacc) {
this.requiresJacc = requiresJacc;
}
public void setLegacyCompliantPrincipalPropagation(final boolean legacyCompliantPrincipalPropagation) {
this.legacyCompliantPrincipalPropagation = legacyCompliantPrincipalPropagation;
}
public boolean requiresLegacyCompliantPrincipalPropagation() {
return legacyCompliantPrincipalPropagation;
}
public void linkSecurityRoles(final String fromRole, final String toRole) {
if (fromRole == null || fromRole.trim().isEmpty()) {
throw EjbLogger.ROOT_LOGGER.failToLinkFromEmptySecurityRole(fromRole);
}
if (toRole == null || toRole.trim().isEmpty()) {
throw EjbLogger.ROOT_LOGGER.failToLinkToEmptySecurityRole(toRole);
}
Collection<String> roleLinks = this.securityRoleLinks.get(fromRole);
if (roleLinks == null) {
roleLinks = new HashSet<String>();
this.securityRoleLinks.put(fromRole, roleLinks);
}
roleLinks.add(toRole);
}
protected EJBViewDescription registerView(final String viewClassName, final MethodInterfaceType viewType) {
return registerView(viewClassName, viewType, false);
}
protected EJBViewDescription registerView(final String viewClassName, final MethodInterfaceType viewType, final boolean ejb2xView) {
// setup the ViewDescription
final EJBViewDescription viewDescription = new EJBViewDescription(this, viewClassName, viewType, ejb2xView);
getViews().add(viewDescription);
// setup server side view interceptors
setupViewInterceptors(viewDescription);
// setup client side view interceptors
setupClientViewInterceptors(viewDescription);
// return created view
if (viewType == MethodInterfaceType.Remote ||
viewType == MethodInterfaceType.Home) {
setupRemoteView(viewDescription);
}
return viewDescription;
}
protected void setupRemoteView(final EJBViewDescription viewDescription) {
viewDescription.getConfigurators().add(new ViewConfigurator() {
@Override
public void configure(final DeploymentPhaseContext context, final ComponentConfiguration componentConfiguration, final ViewDescription description, final ViewConfiguration configuration) throws DeploymentUnitProcessingException {
configuration.getDependencies().add(new DependencyConfigurator<ViewService>() {
@Override
public void configureDependency(final ServiceBuilder<?> serviceBuilder, final ViewService service) throws DeploymentUnitProcessingException {
CapabilityServiceSupport support = context.getDeploymentUnit().getAttachment(org.jboss.as.server.deployment.Attachments.CAPABILITY_SERVICE_SUPPORT);
serviceBuilder.requires(support.getCapabilityServiceName(EJB3RemoteResourceDefinition.EJB_REMOTE_CAPABILITY_NAME));
}
});
}
});
}
public Map<String, Collection<String>> getSecurityRoleLinks() {
return Collections.unmodifiableMap(this.securityRoleLinks);
}
/**
* Returns true if this component description has any security metadata configured at the EJB level.
* Else returns false. Note that this method does *not* consider method level security metadata.
*
* @return
*/
public boolean hasBeanLevelSecurityMetadata() {
// if an explicit security-domain is present, then we consider it the bean to be processed by security interceptors
if (definedSecurityDomain != null) {
return true;
}
// if a run-as is present, then we consider it the bean to be processed by security interceptors
if (runAsRole != null) {
return true;
}
// if a run-as-principal is present, then we consider it the bean to be processed by security interceptors
if (runAsPrincipal != null) {
return true;
}
// if security roles are configured then we consider the bean to be processed by security interceptors
if (securityRoles != null && !securityRoles.isEmpty()) {
return true;
}
// if security role links are configured then we consider the bean to be processed by security interceptors
if (securityRoleLinks != null && !securityRoleLinks.isEmpty()) {
return true;
}
// if declared roles are configured then we consider the bean to be processed by security interceptors
if (declaredRoles != null && !declaredRoles.isEmpty()) {
return true;
}
// no security metadata at bean level
return false;
}
private static class Ejb2ViewTypeConfigurator implements ViewConfigurator {
private final Ejb2xViewType local;
public Ejb2ViewTypeConfigurator(final Ejb2xViewType local) {
this.local = local;
}
@Override
public void configure(final DeploymentPhaseContext context, final ComponentConfiguration componentConfiguration, final ViewDescription description, final ViewConfiguration configuration) throws DeploymentUnitProcessingException {
configuration.putPrivateData(Ejb2xViewType.class, local);
}
}
/**
* A {@link ComponentConfigurator} which picks up {@link org.jboss.as.ejb3.deployment.ApplicationExceptions} from the attachment of the deployment
* unit and sets it to the {@link EJBComponentCreateServiceFactory component create service factory} of the component
* configuration.
* <p/>
* The component configuration is expected to be set with {@link EJBComponentCreateServiceFactory}, as its create
* service factory, before this {@link EjbJarConfigurationConfigurator} is run.
*/
private static final class EjbJarConfigurationConfigurator implements ComponentConfigurator {
@Override
public void configure(DeploymentPhaseContext context, ComponentDescription description, ComponentConfiguration configuration) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = context.getDeploymentUnit();
final ApplicationExceptions appExceptions = deploymentUnit.getAttachment(EjbDeploymentAttachmentKeys.APPLICATION_EXCEPTION_DETAILS);
if (appExceptions == null) {
throw EjbLogger.ROOT_LOGGER.ejbJarConfigNotFound(deploymentUnit);
}
final EJBComponentCreateServiceFactory ejbComponentCreateServiceFactory = (EJBComponentCreateServiceFactory) configuration.getComponentCreateServiceFactory();
ejbComponentCreateServiceFactory.setEjbJarConfiguration(appExceptions);
}
}
/**
* Responsible for adding a dependency on the security domain service for the EJB component, if a security domain
* is applicable for the bean
*/
private static final class SecurityDomainDependencyConfigurator implements ComponentConfigurator {
private final EJBComponentDescription ejbComponentDescription;
SecurityDomainDependencyConfigurator(final EJBComponentDescription ejbComponentDescription) {
this.ejbComponentDescription = ejbComponentDescription;
}
@Override
public void configure(DeploymentPhaseContext context, ComponentDescription description, ComponentConfiguration configuration) throws DeploymentUnitProcessingException {
configuration.getCreateDependencies().add(new DependencyConfigurator<Service<Component>>() {
@Override
public void configureDependency(ServiceBuilder<?> serviceBuilder, Service<Component> service) throws DeploymentUnitProcessingException {
final EJBComponentCreateService ejbComponentCreateService = (EJBComponentCreateService) service;
if (SecurityDomainDependencyConfigurator.this.ejbComponentDescription.getSecurityDomainServiceName() != null) {
final DeploymentUnit deploymentUnit = context.getDeploymentUnit();
final CapabilityServiceSupport support = deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.CAPABILITY_SERVICE_SUPPORT);
serviceBuilder.addDependency(SecurityDomainDependencyConfigurator.this.ejbComponentDescription.getSecurityDomainServiceName(),
SecurityDomain.class, ejbComponentCreateService.getSecurityDomainInjector());
if (SecurityDomainDependencyConfigurator.this.ejbComponentDescription.isOutflowSecurityDomainsConfigured()) {
serviceBuilder.addDependency(support.getCapabilityServiceName(IDENTITY_CAPABILITY_NAME), Function.class, ejbComponentCreateService.getIdentityOutflowFunctionInjector());
}
} else {
final String securityDomainName = SecurityDomainDependencyConfigurator.this.ejbComponentDescription.getResolvedSecurityDomain();
if (securityDomainName != null && !securityDomainName.isEmpty()) {
throw ROOT_LOGGER.legacySecurityUnsupported(securityDomainName);
}
}
}
});
}
}
/**
* {@link Interceptor} which returns the string representation for the view instance on which the {@link Object#toString()}
* invocation happened. This interceptor (for performance reasons) does *not* check whether the invoked method is <code>toString()</code>
* method, so it's the responsibility of the component to setup this interceptor *only* on <code>toString()</code> method on the component
* views.
*/
private static class ToStringMethodInterceptor implements Interceptor {
private final String name;
public ToStringMethodInterceptor(final String name) {
this.name = name;
}
@Override
public Object processInvocation(InterceptorContext context) throws Exception {
final ComponentView componentView = context.getPrivateData(ComponentView.class);
if (componentView == null) {
throw EjbLogger.ROOT_LOGGER.componentViewNotAvailableInContext(context);
}
return "Proxy for view class: " + componentView.getViewClass().getName() + " of EJB: " + name;
}
}
public Resource getTimerServiceResource() {
return this.timerServiceResource;
}
public void setTimerServiceResource(Resource timerServiceResource) {
this.timerServiceResource = timerServiceResource;
}
public EnterpriseBeanMetaData getDescriptorData() {
return descriptorData;
}
public Method getTimeoutMethod() {
return timeoutMethod;
}
public void setTimeoutMethod(final Method timeoutMethod) {
this.timeoutMethod = timeoutMethod;
}
public Map<Method, List<AutoTimer>> getScheduleMethods() {
return Collections.unmodifiableMap(scheduleMethods);
}
public void addScheduleMethod(final Method method, final AutoTimer timer) {
List<AutoTimer> schedules = scheduleMethods.get(method);
if (schedules == null) {
scheduleMethods.put(method, schedules = new ArrayList<AutoTimer>(1));
}
schedules.add(timer);
}
public EJBViewDescription getEjbLocalView() {
return ejbLocalView;
}
public EjbHomeViewDescription getEjbLocalHomeView() {
return ejbLocalHomeView;
}
public EjbHomeViewDescription getEjbHomeView() {
return ejbHomeView;
}
public EJBViewDescription getEjbRemoteView() {
return ejbRemoteView;
}
public boolean isExposedViaIiop() {
return exposedViaIiop;
}
public void setExposedViaIiop(final boolean exposedViaIiop) {
this.exposedViaIiop = exposedViaIiop;
}
public ApplicableMethodInformation<TransactionAttributeType> getTransactionAttributes() {
return transactionAttributes;
}
public ApplicableMethodInformation<Integer> getTransactionTimeouts() {
return transactionTimeouts;
}
public ApplicableMethodInformation<EJBMethodSecurityAttribute> getDescriptorMethodPermissions() {
return descriptorMethodPermissions;
}
public ApplicableMethodInformation<EJBMethodSecurityAttribute> getAnnotationMethodPermissions() {
return annotationMethodPermissions;
}
public void setDefaultContainerInterceptors(final List<InterceptorDescription> defaultInterceptors) {
this.defaultContainerInterceptors = defaultInterceptors;
}
public List<InterceptorDescription> getDefaultContainerInterceptors() {
return this.defaultContainerInterceptors;
}
public void setClassLevelContainerInterceptors(final List<InterceptorDescription> containerInterceptors) {
this.classLevelContainerInterceptors = containerInterceptors;
}
public List<InterceptorDescription> getClassLevelContainerInterceptors() {
return this.classLevelContainerInterceptors;
}
public void setExcludeDefaultContainerInterceptors(boolean excludeDefaultContainerInterceptors) {
this.excludeDefaultContainerInterceptors = excludeDefaultContainerInterceptors;
}
public boolean isExcludeDefaultContainerInterceptors() {
return this.excludeDefaultContainerInterceptors;
}
public void excludeDefaultContainerInterceptors(final MethodIdentifier methodIdentifier) {
this.excludeDefaultContainerInterceptorsForMethod.put(methodIdentifier, true);
}
public boolean isExcludeDefaultContainerInterceptors(final MethodIdentifier methodIdentifier) {
return this.excludeDefaultContainerInterceptorsForMethod.get(methodIdentifier) != null;
}
public void excludeClassLevelContainerInterceptors(final MethodIdentifier methodIdentifier) {
this.excludeClassLevelContainerInterceptorsForMethod.put(methodIdentifier, true);
}
public boolean isExcludeClassLevelContainerInterceptors(final MethodIdentifier methodIdentifier) {
return this.excludeClassLevelContainerInterceptorsForMethod.get(methodIdentifier) != null;
}
public Map<MethodIdentifier, List<InterceptorDescription>> getMethodLevelContainerInterceptors() {
return this.methodLevelContainerInterceptors;
}
public void setMethodContainerInterceptors(final MethodIdentifier methodIdentifier, final List<InterceptorDescription> containerInterceptors) {
this.methodLevelContainerInterceptors.put(methodIdentifier, containerInterceptors);
}
public Set<MethodIdentifier> getTimerMethods() {
final Set<MethodIdentifier> methods = new HashSet<MethodIdentifier>();
if (timeoutMethod != null) {
methods.add(MethodIdentifier.getIdentifierForMethod(timeoutMethod));
}
for (Method method : scheduleMethods.keySet()) {
methods.add(MethodIdentifier.getIdentifierForMethod(method));
}
return methods;
}
/**
* Returns a combined map of class and method level container interceptors
*/
public Set<InterceptorDescription> getAllContainerInterceptors() {
if (this.allContainerInterceptors == null) {
this.allContainerInterceptors = new HashSet<InterceptorDescription>();
this.allContainerInterceptors.addAll(this.classLevelContainerInterceptors);
if (!this.excludeDefaultContainerInterceptors) {
this.allContainerInterceptors.addAll(this.defaultContainerInterceptors);
}
for (List<InterceptorDescription> interceptors : this.methodLevelContainerInterceptors.values()) {
this.allContainerInterceptors.addAll(interceptors);
}
}
return this.allContainerInterceptors;
}
public ServerInterceptorCache getServerInterceptorCache() {
return serverInterceptorCache;
}
public void setServerInterceptorCache(ServerInterceptorCache serverInterceptorCache) {
this.serverInterceptorCache = serverInterceptorCache;
}
public ShutDownInterceptorFactory getShutDownInterceptorFactory() {
return shutDownInterceptorFactory;
}
@Override
public String toString() {
return getClass().getName() + "{" +
"serviceName=" + getServiceName() +
'}' + "@" + Integer.toHexString(hashCode());
}
public HashMap<Integer, InterceptorFactory> getElytronInterceptorFactories(String policyContextID, boolean enableJacc, boolean propagateSecurity) {
final HashMap<Integer, InterceptorFactory> interceptorFactories = new HashMap<>(2);
final Set<String> roles = new HashSet<>();
// First interceptor: security domain association
interceptorFactories.put(InterceptorOrder.View.SECURITY_CONTEXT, SecurityDomainInterceptorFactory.INSTANCE);
if (enableJacc) {
// Next interceptor: policy context ID
interceptorFactories.put(InterceptorOrder.View.POLICY_CONTEXT, new ImmediateInterceptorFactory(new PolicyContextIdInterceptor(policyContextID)));
}
if (securityRoles != null) {
final Map<String, Set<String>> principalVsRolesMap = securityRoles.getPrincipalVersusRolesMap();
if (! principalVsRolesMap.isEmpty()) {
interceptorFactories.put(InterceptorOrder.View.SECURITY_ROLES, new ImmediateInterceptorFactory(new SecurityRolesAddingInterceptor("ejb", principalVsRolesMap)));
}
}
// Next interceptor: run-as-principal
// Switch users if there's a run-as principal
if (runAsPrincipal != null) {
interceptorFactories.put(InterceptorOrder.View.RUN_AS_PRINCIPAL, new ImmediateInterceptorFactory(new RunAsPrincipalInterceptor(runAsPrincipal)));
// Next interceptor: extra principal roles
if (securityRoles != null) {
final Set<String> extraRoles = securityRoles.getSecurityRoleNamesByPrincipal(runAsPrincipal);
if (! extraRoles.isEmpty()) {
interceptorFactories.put(InterceptorOrder.View.EXTRA_PRINCIPAL_ROLES, new ImmediateInterceptorFactory(new RoleAddingInterceptor("ejb", RoleMapper.constant(Roles.fromSet(extraRoles)))));
roles.addAll(extraRoles);
}
}
// Next interceptor: prevent identity propagation
} else if (! propagateSecurity) {
interceptorFactories.put(InterceptorOrder.View.RUN_AS_PRINCIPAL, new ImmediateInterceptorFactory(new RunAsPrincipalInterceptor(RunAsPrincipalInterceptor.ANONYMOUS_PRINCIPAL)));
}
// Next interceptor: run-as-role
if (runAsRole != null) {
interceptorFactories.put(InterceptorOrder.View.RUN_AS_ROLE, new ImmediateInterceptorFactory(new RoleAddingInterceptor("ejb", RoleMapper.constant(Roles.fromSet(Collections.singleton(runAsRole))))));
roles.add(runAsRole);
}
// Next interceptor: security identity outflow
if (! roles.isEmpty()) {
interceptorFactories.put(InterceptorOrder.View.SECURITY_IDENTITY_OUTFLOW, new IdentityOutflowInterceptorFactory("ejb", RoleMapper.constant(Roles.fromSet(roles))));
} else {
interceptorFactories.put(InterceptorOrder.View.SECURITY_IDENTITY_OUTFLOW, IdentityOutflowInterceptorFactory.INSTANCE);
}
// Ignoring declared roles
RoleMapper.constant(Roles.fromSet(getDeclaredRoles()));
return interceptorFactories;
}
public void setSecurityRequired(final boolean securityRequired) {
this.securityRequired = securityRequired;
}
public boolean isSecurityRequired() {
return securityRequired;
}
}
| 57,331 | 46.421009 | 294 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/EJBComponent.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.ejb3.component;
import static java.security.AccessController.doPrivileged;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.Policy;
import java.security.Principal;
import java.security.PrivilegedAction;
import java.security.PrivilegedExceptionAction;
import java.security.ProtectionDomain;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import jakarta.ejb.EJBHome;
import jakarta.ejb.EJBLocalHome;
import jakarta.ejb.TransactionAttributeType;
import jakarta.ejb.TransactionManagementType;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import jakarta.security.jacc.EJBRoleRefPermission;
import jakarta.transaction.Status;
import jakarta.transaction.SystemException;
import jakarta.transaction.TransactionManager;
import jakarta.transaction.TransactionSynchronizationRegistry;
import jakarta.transaction.UserTransaction;
import org.jboss.as.ee.component.BasicComponent;
import org.jboss.as.ee.component.ComponentView;
import org.jboss.as.ee.component.interceptors.InvocationType;
import org.jboss.as.ejb3.component.allowedmethods.AllowedMethodsInformation;
import org.jboss.as.ejb3.component.interceptors.ShutDownInterceptorFactory;
import org.jboss.as.ejb3.component.invocationmetrics.InvocationMetrics;
import org.jboss.as.ejb3.context.CurrentInvocationContext;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.ejb3.security.EJBSecurityMetaData;
import org.jboss.as.ejb3.security.JaccInterceptor;
import org.jboss.as.ejb3.subsystem.EJBStatistics;
import org.jboss.as.ejb3.suspend.EJBSuspendHandlerService;
import org.jboss.as.ejb3.timerservice.spi.ManagedTimerService;
import org.jboss.as.ejb3.timerservice.spi.ManagedTimerServiceFactory;
import org.jboss.as.ejb3.tx.ApplicationExceptionDetails;
import org.jboss.as.naming.ManagedReference;
import org.jboss.as.naming.context.NamespaceContextSelector;
import org.jboss.as.server.CurrentServiceContainer;
import org.jboss.as.server.suspend.ServerActivityCallback;
import org.jboss.ejb.client.Affinity;
import org.jboss.ejb.client.EJBClient;
import org.jboss.ejb.client.EJBHomeLocator;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
import org.jboss.invocation.proxy.MethodIdentifier;
import org.jboss.metadata.ejb.spec.MethodInterfaceType;
import org.jboss.msc.service.ServiceContainer;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.wildfly.extension.requestcontroller.ControlPoint;
import org.wildfly.security.auth.principal.AnonymousPrincipal;
import org.wildfly.security.auth.server.SecurityDomain;
import org.wildfly.security.auth.server.SecurityIdentity;
import org.wildfly.security.authz.Roles;
import org.wildfly.security.manager.WildFlySecurityManager;
import org.wildfly.transaction.client.ContextTransactionManager;
/**
* @author <a href="mailto:[email protected]">Carlo de Wolf</a>
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public abstract class EJBComponent extends BasicComponent implements ServerActivityCallback {
private static final ApplicationExceptionDetails APPLICATION_EXCEPTION = new ApplicationExceptionDetails("java.lang.Exception", true, false);
private final Map<MethodTransactionAttributeKey, TransactionAttributeType> txAttrs;
private final Map<MethodTransactionAttributeKey, Integer> txTimeouts;
private final Map<MethodTransactionAttributeKey, Boolean> txExplicitAttrs;
private final boolean isBeanManagedTransaction;
private final Map<Class<?>, ApplicationExceptionDetails> applicationExceptions;
private final EJBSecurityMetaData securityMetaData;
private final Map<String, ServiceName> viewServices;
private final ServiceName ejbLocalHomeViewServiceName;
private final ServiceName ejbHomeViewServiceName;
private final ServiceName ejbObjectViewServiceName;
private final ServiceName ejbLocalObjectViewServiceName;
private final ManagedTimerServiceFactory timerServiceFactory;
private final Map<Method, InterceptorFactory> timeoutInterceptors;
private final Method timeoutMethod;
private final String applicationName;
private final String earApplicationName;
private final String moduleName;
private final String distinctName;
private final InvocationMetrics invocationMetrics = new InvocationMetrics();
private final EJBSuspendHandlerService ejbSuspendHandlerService;
private final ShutDownInterceptorFactory shutDownInterceptorFactory;
private final TransactionSynchronizationRegistry transactionSynchronizationRegistry;
private final UserTransaction userTransaction;
private final ControlPoint controlPoint;
private final AtomicBoolean exceptionLoggingEnabled;
private final SecurityDomain securityDomain;
private final boolean enableJacc;
private ThreadLocal<SecurityIdentity> incomingRunAsIdentity;
private final Function<SecurityIdentity, Set<SecurityIdentity>> identityOutflowFunction;
private final boolean securityRequired;
private final EJBComponentDescription componentDescription;
private final boolean legacyCompliantPrincipalPropagation;
private volatile ManagedTimerService timerService;
/**
* Construct a new instance.
*
* @param ejbComponentCreateService the component configuration
*/
protected EJBComponent(final EJBComponentCreateService ejbComponentCreateService) {
super(ejbComponentCreateService);
this.applicationExceptions = Collections.unmodifiableMap(ejbComponentCreateService.getApplicationExceptions().getApplicationExceptions());
final Map<MethodTransactionAttributeKey, TransactionAttributeType> txAttrs = ejbComponentCreateService.getTxAttrs();
if (txAttrs == null || txAttrs.isEmpty()) {
this.txAttrs = Collections.emptyMap();
this.txExplicitAttrs = Collections.emptyMap();
} else {
this.txAttrs = txAttrs;
this.txExplicitAttrs = ejbComponentCreateService.getExplicitTxAttrs();
}
final Map<MethodTransactionAttributeKey, Integer> txTimeouts = ejbComponentCreateService.getTxTimeouts();
if (txTimeouts == null || txTimeouts.isEmpty()) {
this.txTimeouts = Collections.emptyMap();
} else {
this.txTimeouts = txTimeouts;
}
isBeanManagedTransaction = TransactionManagementType.BEAN.equals(ejbComponentCreateService.getTransactionManagementType());
// security metadata
this.securityMetaData = ejbComponentCreateService.getSecurityMetaData();
this.viewServices = ejbComponentCreateService.getViewServices();
this.timerServiceFactory = ejbComponentCreateService.getTimerServiceFactory();
this.timeoutMethod = ejbComponentCreateService.getTimeoutMethod();
this.ejbLocalHomeViewServiceName = ejbComponentCreateService.getEjbLocalHome();
this.ejbHomeViewServiceName = ejbComponentCreateService.getEjbHome();
this.applicationName = ejbComponentCreateService.getApplicationName();
this.earApplicationName = ejbComponentCreateService.getEarApplicationName();
this.distinctName = ejbComponentCreateService.getDistinctName();
this.moduleName = ejbComponentCreateService.getModuleName();
this.ejbObjectViewServiceName = ejbComponentCreateService.getEjbObject();
this.ejbLocalObjectViewServiceName = ejbComponentCreateService.getEjbLocalObject();
this.timeoutInterceptors = Collections.unmodifiableMap(ejbComponentCreateService.getTimeoutInterceptors());
this.shutDownInterceptorFactory = ejbComponentCreateService.getShutDownInterceptorFactory();
this.ejbSuspendHandlerService = ejbComponentCreateService.getEJBSuspendHandler();
this.transactionSynchronizationRegistry = ejbComponentCreateService.getTransactionSynchronizationRegistry();
this.userTransaction = ejbComponentCreateService.getUserTransaction();
this.controlPoint = ejbComponentCreateService.getControlPoint();
this.exceptionLoggingEnabled = ejbComponentCreateService.getExceptionLoggingEnabled();
this.securityDomain = ejbComponentCreateService.getSecurityDomain();
this.enableJacc = ejbComponentCreateService.isEnableJacc();
this.legacyCompliantPrincipalPropagation = ejbComponentCreateService.isLegacyCompliantPrincipalPropagation();
this.incomingRunAsIdentity = new ThreadLocal<>();
this.identityOutflowFunction = ejbComponentCreateService.getIdentityOutflowFunction();
this.securityRequired = ejbComponentCreateService.isSecurityRequired();
this.componentDescription = ejbComponentCreateService.getComponentDescription();
}
protected <T> T createViewInstanceProxy(final Class<T> viewInterface, final Map<Object, Object> contextData) {
if (viewInterface == null)
throw EjbLogger.ROOT_LOGGER.viewInterfaceCannotBeNull();
if (viewServices.containsKey(viewInterface.getName())) {
final ServiceName serviceName = viewServices.get(viewInterface.getName());
return createViewInstanceProxy(viewInterface, contextData, serviceName);
} else {
throw EjbLogger.ROOT_LOGGER.viewNotFound(viewInterface.getName(), this.getComponentName());
}
}
protected <T> T createViewInstanceProxy(final Class<T> viewInterface, final Map<Object, Object> contextData, final ServiceName serviceName) {
final ServiceController<?> serviceController = currentServiceContainer().getRequiredService(serviceName);
final ComponentView view = (ComponentView) serviceController.getValue();
final ManagedReference instance;
try {
if(WildFlySecurityManager.isChecking()) {
instance = WildFlySecurityManager.doUnchecked(new PrivilegedExceptionAction<ManagedReference>() {
@Override
public ManagedReference run() throws Exception {
return view.createInstance(contextData);
}
});
} else {
instance = view.createInstance(contextData);
}
} catch (Exception e) {
//TODO: do we need to let the exception propagate here?
throw new RuntimeException(e);
}
return viewInterface.cast(instance.getInstance());
}
private static ServiceContainer currentServiceContainer() {
if(System.getSecurityManager() == null) {
return CurrentServiceContainer.getServiceContainer();
}
return AccessController.doPrivileged(CurrentServiceContainer.GET_ACTION);
}
public ApplicationExceptionDetails getApplicationException(Class<?> exceptionClass, Method invokedMethod) {
ApplicationExceptionDetails applicationException = this.applicationExceptions.get(exceptionClass);
if (applicationException != null) {
return applicationException;
}
// Check if the super class of the passed exception class, is an application exception.
Class<?> superClass = exceptionClass.getSuperclass();
while (superClass != null && !(superClass.equals(Exception.class) || superClass.equals(Object.class))) {
applicationException = this.applicationExceptions.get(superClass);
// check whether the "inherited" attribute is set. A subclass of an application exception
// is an application exception only if the inherited attribute on the parent application exception
// is set to true.
if (applicationException != null) {
if (applicationException.isInherited()) {
return applicationException;
}
// Once we find a super class which is an application exception,
// we just stop there (no need to check the grand super class), irrespective of whether the "inherited"
// is true or false
return null; // not an application exception, so return null
}
// move to next super class
superClass = superClass.getSuperclass();
}
// AS7-1317: examine the throws clause of the method
// An unchecked-exception is only an application exception if annotated (or described) as such.
// (see Enterprise Beans 3.1 FR 14.2.1)
if (RuntimeException.class.isAssignableFrom(exceptionClass) || Error.class.isAssignableFrom(exceptionClass))
return null;
if (invokedMethod != null) {
final Class<?>[] exceptionTypes = invokedMethod.getExceptionTypes();
for (Class<?> type : exceptionTypes) {
if (type.isAssignableFrom(exceptionClass))
return APPLICATION_EXCEPTION;
}
}
// not an application exception, so return null.
return null;
}
public Principal getCallerPrincipal() {
if (isSecurityDomainKnown()) {
return getCallerSecurityIdentity().getPrincipal();
}
return new AnonymousPrincipal();
}
public SecurityIdentity getIncomingRunAsIdentity() {
return incomingRunAsIdentity.get();
}
public void setIncomingRunAsIdentity(SecurityIdentity identity) {
if (identity == null) {
incomingRunAsIdentity.remove();
} else {
incomingRunAsIdentity.set(identity);
}
}
protected TransactionAttributeType getCurrentTransactionAttribute() {
final InterceptorContext invocation = CurrentInvocationContext.get();
final MethodInterfaceType methodIntf = MethodIntfHelper.of(invocation);
return getTransactionAttributeType(methodIntf, invocation.getMethod());
}
public EJBHome getEJBHome() throws IllegalStateException {
if (ejbHomeViewServiceName == null) {
throw EjbLogger.ROOT_LOGGER.beanHomeInterfaceIsNull(getComponentName());
}
final ServiceController<?> serviceController = currentServiceContainer().getRequiredService(ejbHomeViewServiceName);
final ComponentView view = (ComponentView) serviceController.getValue();
final String locatorAppName = earApplicationName == null ? "" : earApplicationName;
return EJBClient.createProxy(createHomeLocator(view.getViewClass().asSubclass(EJBHome.class), locatorAppName, moduleName, getComponentName(), distinctName));
}
private static <T extends EJBHome> EJBHomeLocator<T> createHomeLocator(Class<T> viewClass, String appName, String moduleName, String beanName, String distinctName) {
return new EJBHomeLocator<T>(viewClass, appName, moduleName, beanName, distinctName, Affinity.LOCAL);
}
public Class<?> getEjbObjectType() {
if (ejbObjectViewServiceName == null) {
return null;
}
final ServiceController<?> serviceController = currentServiceContainer().getRequiredService(ejbObjectViewServiceName);
final ComponentView view = (ComponentView) serviceController.getValue();
return view.getViewClass();
}
public Class<?> getEjbLocalObjectType() {
if (ejbLocalObjectViewServiceName == null) {
return null;
}
final ServiceController<?> serviceController = currentServiceContainer().getRequiredService(ejbLocalObjectViewServiceName);
final ComponentView view = (ComponentView) serviceController.getValue();
return view.getViewClass();
}
public EJBLocalHome getEJBLocalHome() throws IllegalStateException {
if (ejbLocalHomeViewServiceName == null) {
throw EjbLogger.ROOT_LOGGER.beanLocalHomeInterfaceIsNull(getComponentName());
}
return createViewInstanceProxy(EJBLocalHome.class, Collections.emptyMap(), ejbLocalHomeViewServiceName);
}
public boolean getRollbackOnly() throws IllegalStateException {
if (isBeanManagedTransaction()) {
throw EjbLogger.ROOT_LOGGER.failToCallgetRollbackOnly();
}
try {
TransactionManager tm = this.getTransactionManager();
// The getRollbackOnly method should be used only in the context of a transaction.
if (tm.getTransaction() == null) {
throw EjbLogger.ROOT_LOGGER.failToCallgetRollbackOnlyOnNoneTransaction();
}
// EJBTHREE-805, consider an asynchronous rollback due to timeout
// This is counter to Enterprise Beans 3.1 where an asynchronous call does not inherit the transaction context!
int status = tm.getStatus();
EjbLogger.ROOT_LOGGER.tracef("Current transaction status is %d", status);
switch (status) {
case Status.STATUS_COMMITTED:
case Status.STATUS_ROLLEDBACK:
throw EjbLogger.ROOT_LOGGER.failToCallgetRollbackOnlyAfterTxcompleted();
case Status.STATUS_MARKED_ROLLBACK:
case Status.STATUS_ROLLING_BACK:
return true;
}
return false;
} catch (SystemException se) {
EjbLogger.ROOT_LOGGER.getTxManagerStatusFailed(se);
return true;
}
}
public ManagedTimerService getTimerService() {
return this.timerService;
}
public TransactionAttributeType getTransactionAttributeType(final MethodInterfaceType methodIntf, final Method method) {
return getTransactionAttributeType(methodIntf, MethodIdentifier.getIdentifierForMethod(method));
}
public TransactionAttributeType getTransactionAttributeType(final MethodInterfaceType methodIntf, final MethodIdentifier method) {
return getTransactionAttributeType(methodIntf, method, TransactionAttributeType.REQUIRED);
}
public TransactionAttributeType getTransactionAttributeType(final MethodInterfaceType methodIntf, final MethodIdentifier method, TransactionAttributeType defaultType) {
TransactionAttributeType txAttr = txAttrs.get(new MethodTransactionAttributeKey(methodIntf, method));
//fall back to type bean if not found
if (txAttr == null && methodIntf != MethodInterfaceType.Bean) {
txAttr = txAttrs.get(new MethodTransactionAttributeKey(MethodInterfaceType.Bean, method));
}
if (txAttr == null)
return defaultType;
return txAttr;
}
public boolean isTransactionAttributeTypeExplicit(final MethodInterfaceType methodIntf, final MethodIdentifier method) {
Boolean txAttr = txExplicitAttrs.get(new MethodTransactionAttributeKey(methodIntf, method));
//fall back to type bean if not found
if (txAttr == null && methodIntf != MethodInterfaceType.Bean) {
txAttr = txExplicitAttrs.get(new MethodTransactionAttributeKey(MethodInterfaceType.Bean, method));
}
if (txAttr == null)
return false;
return txAttr;
}
/**
* @deprecated Use {@link ContextTransactionManager#getInstance()} instead.
* @return the value of {@link ContextTransactionManager#getInstance()}
*/
@Deprecated
public TransactionManager getTransactionManager() {
return ContextTransactionManager.getInstance();
}
public TransactionSynchronizationRegistry getTransactionSynchronizationRegistry() {
return transactionSynchronizationRegistry;
}
public int getTransactionTimeout(final MethodInterfaceType methodIntf, final Method method) {
return getTransactionTimeout(methodIntf, MethodIdentifier.getIdentifierForMethod(method));
}
public int getTransactionTimeout(final MethodInterfaceType methodIntf, final MethodIdentifier method) {
Integer txTimeout = txTimeouts.get(new MethodTransactionAttributeKey(methodIntf, method));
if (txTimeout == null && methodIntf != MethodInterfaceType.Bean) {
txTimeout = txTimeouts.get(new MethodTransactionAttributeKey(MethodInterfaceType.Bean, method));
}
if (txTimeout == null)
return -1;
return txTimeout;
}
public UserTransaction getUserTransaction() throws IllegalStateException {
return this.userTransaction;
}
public boolean isBeanManagedTransaction() {
return isBeanManagedTransaction;
}
public boolean isCallerInRole(final String roleName) throws IllegalStateException {
if (isSecurityDomainKnown()) {
if (enableJacc) {
Policy policy = WildFlySecurityManager.isChecking() ? doPrivileged((PrivilegedAction<Policy>) Policy::getPolicy) : Policy.getPolicy();
ProtectionDomain domain = new ProtectionDomain(null, null, null, JaccInterceptor.getGrantedRoles(getCallerSecurityIdentity()));
return policy.implies(domain, new EJBRoleRefPermission(getComponentName(), roleName));
} else {
return checkCallerSecurityIdentityRole(roleName);
}
}
// No security, no role membership.
return false;
}
public boolean isStatisticsEnabled() {
return EJBStatistics.getInstance().isEnabled();
}
public Object lookup(String name) throws IllegalArgumentException {
if (name == null) {
throw EjbLogger.ROOT_LOGGER.jndiNameCannotBeNull();
}
final NamespaceContextSelector namespaceContextSelector = NamespaceContextSelector.getCurrentSelector();
if (namespaceContextSelector == null) {
throw EjbLogger.ROOT_LOGGER.noNamespaceContextSelectorAvailable(name);
}
Context jndiContext = null;
String namespaceStrippedJndiName = name;
// get the appropriate JNDI context and strip the lookup jndi name of the component namespace prefix
if (name.startsWith("java:app/")) {
jndiContext = namespaceContextSelector.getContext("app");
namespaceStrippedJndiName = name.substring("java:app/".length());
} else if (name.startsWith("java:module/")) {
jndiContext = namespaceContextSelector.getContext("module");
namespaceStrippedJndiName = name.substring("java:module/".length());
} else if (name.startsWith("java:comp/")) {
jndiContext = namespaceContextSelector.getContext("comp");
namespaceStrippedJndiName = name.substring("java:comp/".length());
} else if (!name.startsWith("java:")) { // if it *doesn't* start with java: prefix, then default it to java:comp
jndiContext = namespaceContextSelector.getContext("comp");
// no need to strip the name since it doesn't start with java: prefix.
// Also prefix the "env/" to the jndi name, since a lookup without a java: namespace prefix is effectively
// a lookup under java:comp/env/<jndi-name>
namespaceStrippedJndiName = "env/" + name;
} else if (name.startsWith("java:global/")) {
// Do *not* strip the jndi name of the prefix because java:global is a global context and doesn't specifically
// belong to the component's ENC, and hence *isn't* a component ENC relative name and has to be looked up
// with the absolute name (including the java:global prefix)
try {
jndiContext = new InitialContext();
} catch (NamingException ne) {
throw EjbLogger.ROOT_LOGGER.failToLookupJNDI(name, ne);
}
} else {
throw EjbLogger.ROOT_LOGGER.failToLookupJNDINameSpace(name);
}
EjbLogger.ROOT_LOGGER.debugf("Looking up %s in jndi context: %s", namespaceStrippedJndiName, jndiContext);
try {
return jndiContext.lookup(namespaceStrippedJndiName);
} catch (NamingException ne) {
throw EjbLogger.ROOT_LOGGER.failToLookupStrippedJNDI(namespaceContextSelector, jndiContext, ne);
}
}
public void setRollbackOnly() throws IllegalStateException {
if (isBeanManagedTransaction()) {
throw EjbLogger.ROOT_LOGGER.failToCallSetRollbackOnlyOnNoneCMB();
}
try {
// get the transaction manager
TransactionManager tm = getTransactionManager();
// check if there's a tx in progress. If not, then it's an error to call setRollbackOnly()
if (tm.getTransaction() == null) {
throw EjbLogger.ROOT_LOGGER.failToCallSetRollbackOnlyWithNoTx();
}
// set rollback
tm.setRollbackOnly();
} catch (SystemException se) {
EjbLogger.ROOT_LOGGER.setRollbackOnlyFailed(se);
}
}
public EJBSecurityMetaData getSecurityMetaData() {
return this.securityMetaData;
}
public Method getTimeoutMethod() {
return timeoutMethod;
}
public String getApplicationName() {
return applicationName;
}
public String getEarApplicationName() {
return this.earApplicationName;
}
public String getDistinctName() {
return distinctName;
}
public String getModuleName() {
return moduleName;
}
public ServiceName getEjbLocalObjectViewServiceName() {
return ejbLocalObjectViewServiceName;
}
public ServiceName getEjbObjectViewServiceName() {
return ejbObjectViewServiceName;
}
public Map<Method, InterceptorFactory> getTimeoutInterceptors() {
return timeoutInterceptors;
}
public AllowedMethodsInformation getAllowedMethodsInformation() {
return isBeanManagedTransaction() ? AllowedMethodsInformation.INSTANCE_BMT : AllowedMethodsInformation.INSTANCE_CMT;
}
public InvocationMetrics getInvocationMetrics() {
return invocationMetrics;
}
public ControlPoint getControlPoint() {
return this.controlPoint;
}
public SecurityDomain getSecurityDomain() {
return securityDomain;
}
public boolean isSecurityDomainKnown() {
return securityDomain != null;
}
public Function<SecurityIdentity, Set<SecurityIdentity>> getIdentityOutflowFunction() {
return identityOutflowFunction;
}
@Override
public synchronized void init() {
getShutDownInterceptorFactory().start();
super.init();
this.timerService = this.timerServiceFactory.createTimerService(this);
this.timerService.start();
}
@Override
public final void stop() {
getShutDownInterceptorFactory().shutdown();
this.timerService.stop();
this.done();
}
@Override
public void done() {
super.stop();
}
public boolean isExceptionLoggingEnabled() {
return exceptionLoggingEnabled.get();
}
protected ShutDownInterceptorFactory getShutDownInterceptorFactory() {
return shutDownInterceptorFactory;
}
private boolean checkCallerSecurityIdentityRole(String roleName) {
final SecurityIdentity identity = getCallerSecurityIdentity();
if("**".equals(roleName)) {
return !identity.isAnonymous();
}
Roles roles = identity.getRoles("ejb", true);
if(roles != null) {
if(roles.contains(roleName)) {
return true;
}
if(securityMetaData.getSecurityRoleLinks() != null) {
Collection<String> linked = securityMetaData.getSecurityRoleLinks().get(roleName);
if(linked != null) {
for (String role : roles) {
if (linked.contains(role)) {
return true;
}
}
}
}
}
return false;
}
private SecurityIdentity getCallerSecurityIdentity() {
InvocationType invocationType = CurrentInvocationContext.get().getPrivateData(InvocationType.class);
boolean isRemote = invocationType != null && invocationType.equals(InvocationType.REMOTE);
if (legacyCompliantPrincipalPropagation && !isRemote) {
return (getIncomingRunAsIdentity() == null) ? securityDomain.getCurrentSecurityIdentity() : getIncomingRunAsIdentity();
} else {
if (getIncomingRunAsIdentity() != null) {
return getIncomingRunAsIdentity();
} else if (securityRequired) {
return securityDomain.getCurrentSecurityIdentity();
} else {
// unsecured Jakarta Enterprise Beans
return securityDomain.getAnonymousSecurityIdentity();
}
}
}
public EJBSuspendHandlerService getEjbSuspendHandlerService() {
return this.ejbSuspendHandlerService;
}
public EJBComponentDescription getComponentDescription() {
return componentDescription;
}
}
| 30,121 | 44.501511 | 172 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/EJBBusinessMethod.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.ejb3.component;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Arrays;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.metadata.ejb.spec.MethodInterfaceType;
/**
* @author Jaikiran Pai
*/
public class EJBBusinessMethod implements Serializable {
private final String methodName;
private final Class<?>[] methodParamTypes;
private final MethodInterfaceType viewType;
private final int hashCode;
public EJBBusinessMethod(Method method) {
this(method.getName(), method.getParameterTypes());
}
public EJBBusinessMethod(String methodName, Class<?>... methodParamTypes) {
this(MethodInterfaceType.Bean, methodName, methodParamTypes);
}
public EJBBusinessMethod(MethodInterfaceType view, String methodName, Class<?>... paramTypes) {
if (methodName == null) {
throw EjbLogger.ROOT_LOGGER.methodNameIsNull();
}
this.methodName = methodName;
this.methodParamTypes = paramTypes == null ? new Class<?>[0] : paramTypes;
this.viewType = view == null ? MethodInterfaceType.Bean : view;
this.hashCode = this.generateHashCode();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EJBBusinessMethod that = (EJBBusinessMethod) o;
if (!methodName.equals(that.methodName)) {
return false;
}
if (!Arrays.equals(methodParamTypes, that.methodParamTypes)) {
return false;
}
if (viewType != that.viewType) {
return false;
}
return true;
}
@Override
public int hashCode() {
return this.hashCode;
}
private int generateHashCode() {
int result = methodName.hashCode();
result = 31 * result + Arrays.hashCode(methodParamTypes);
result = 31 * result + viewType.hashCode();
return result;
}
}
| 3,106 | 29.165049 | 99 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/EJBViewDescription.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, 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.ejb3.component;
import java.util.function.Supplier;
import org.jboss.as.ee.component.ComponentConfiguration;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.ee.component.EEModuleDescription;
import org.jboss.as.ee.component.InjectionSource;
import org.jboss.as.ee.component.ViewConfiguration;
import org.jboss.as.ee.component.ViewConfigurator;
import org.jboss.as.ee.component.ViewDescription;
import org.jboss.as.ejb3.remote.RemoteViewInjectionSource;
import org.jboss.as.ejb3.validator.EjbProxy;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.invocation.proxy.ProxyFactory;
import org.jboss.metadata.ejb.spec.MethodInterfaceType;
import org.jboss.msc.service.ServiceName;
/**
* Jakarta Enterprise Beans specific view description.
*
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public class EJBViewDescription extends ViewDescription {
private final MethodInterfaceType methodIntf;
private final boolean hasJNDIBindings;
/**
* Should be set to true if this view corresponds to an EJB 2.x
* local or remote view
*/
private final boolean ejb2xView;
public EJBViewDescription(final ComponentDescription componentDescription, final String viewClassName, final MethodInterfaceType methodIntf, final boolean ejb2xView) {
//only add the default configurator if an ejb 3.x business view
super(componentDescription, viewClassName, !ejb2xView && methodIntf != MethodInterfaceType.Home && methodIntf != MethodInterfaceType.LocalHome, EjbProxy.class.getName());
this.methodIntf = methodIntf;
this.ejb2xView = ejb2xView;
hasJNDIBindings = initHasJNDIBindings(methodIntf);
//add a configurator to attach the MethodInterfaceType for this view
getConfigurators().add(new ViewConfigurator() {
@Override
public void configure(final DeploymentPhaseContext context, final ComponentConfiguration componentConfiguration, final ViewDescription description, final ViewConfiguration configuration) throws DeploymentUnitProcessingException {
configuration.putPrivateData(MethodInterfaceType.class, getMethodIntf());
}
});
// add a view configurator for setting up application specific container interceptors for the EJB view
getConfigurators().add(EJBContainerInterceptorsViewConfigurator.INSTANCE);
// add server interceptors configurator
getConfigurators().add(ServerInterceptorsViewConfigurator.INSTANCE);
}
public MethodInterfaceType getMethodIntf() {
return methodIntf;
}
@Override
public ViewConfiguration createViewConfiguration(final Class<?> viewClass, final ComponentConfiguration componentConfiguration, final ProxyFactory<?> proxyFactory) {
return new EJBViewConfiguration(viewClass, componentConfiguration, getServiceName(), proxyFactory, getMethodIntf());
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
EJBViewDescription that = (EJBViewDescription) o;
// since the views are added to the component description, that should already be equal
if (hasJNDIBindings != that.hasJNDIBindings) return false;
if (methodIntf != that.methodIntf) return false;
if (!getViewClassName().equals(that.getViewClassName())) return false;
//we compare the components based on ==
//as you can have two components with the same name
if (getComponentDescription() != that.getComponentDescription()) return false;
return super.equals(o);
}
@Override
protected InjectionSource createInjectionSource(final ServiceName serviceName, Supplier<ClassLoader> viewClassLoader, boolean appclient) {
if(methodIntf != MethodInterfaceType.Remote && methodIntf != MethodInterfaceType.Home) {
return super.createInjectionSource(serviceName, viewClassLoader, appclient);
} else {
final EJBComponentDescription componentDescription = getComponentDescription();
final EEModuleDescription desc = componentDescription.getModuleDescription();
final String earApplicationName = desc.getEarApplicationName();
return new RemoteViewInjectionSource(serviceName, earApplicationName, desc.getModuleName(), desc.getDistinctName(), componentDescription.getComponentName(), getViewClassName() , componentDescription.isStateful(),viewClassLoader, appclient);
}
}
@Override
public EJBComponentDescription getComponentDescription() {
return (EJBComponentDescription)super.getComponentDescription();
}
@Override // TODO: what to do in JNDI if multiple views are available for no interface view ?
public ServiceName getServiceName() {
return super.getServiceName().append(methodIntf.toString());
}
@Override
public int hashCode() {
int result = methodIntf.hashCode();
result = 31 * result + (hasJNDIBindings ? 1 : 0);
result = 31 * result + getViewClassName().hashCode();
result = 31 * result + getComponentDescription().getComponentName().hashCode();
return result;
}
public boolean hasJNDIBindings() {
return hasJNDIBindings;
}
private boolean initHasJNDIBindings(final MethodInterfaceType methodIntf) {
if (methodIntf == MethodInterfaceType.MessageEndpoint) {
return false;
}
if (methodIntf == MethodInterfaceType.ServiceEndpoint) {
return false;
}
if (methodIntf == MethodInterfaceType.Timer) {
return false;
}
return true;
}
public boolean isEjb2xView() {
return ejb2xView;
}
@Override
public boolean requiresSuperclassInProxy() {
return !(isEjb2xView() || methodIntf == MethodInterfaceType.LocalHome || methodIntf == MethodInterfaceType.Home);
}
}
| 7,159 | 42.92638 | 252 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/ContainerInterceptorMethodInterceptorFactory.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.ejb3.component;
import org.jboss.as.naming.ManagedReference;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
import org.jboss.invocation.InterceptorFactoryContext;
import org.jboss.invocation.Interceptors;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* An {@link InterceptorFactory} responsible for creating {@link Interceptor} instance corresponding to a <code>container-interceptor</code>
* applicable for an Jakarta Enterprise Beans
*
* @author Jaikiran Pai
*/
public final class ContainerInterceptorMethodInterceptorFactory implements InterceptorFactory {
private final ManagedReference interceptorInstanceRef;
private final Method method;
/**
* @param interceptorInstanceRef The managed reference to the container-interceptor instance
* @param method The method for which the interceptor has to be created
*/
public ContainerInterceptorMethodInterceptorFactory(final ManagedReference interceptorInstanceRef, final Method method) {
this.interceptorInstanceRef = interceptorInstanceRef;
this.method = method;
}
/**
* Creates and returns a {@link Interceptor} which invokes the underlying container-interceptor during a method invocation
*
* @param context The interceptor factory context
* @return
*/
public Interceptor create(final InterceptorFactoryContext context) {
return new ContainerInterceptorMethodInterceptor(this.interceptorInstanceRef, method);
}
/**
* {@link Interceptor} responsible for invoking the underlying container-interceptor in its {@link #processInvocation(org.jboss.invocation.InterceptorContext)}
* method
*/
private static final class ContainerInterceptorMethodInterceptor implements Interceptor {
private final ManagedReference interceptorInstanceRef;
private final Method method;
/**
* @param interceptorInstanceRef The managed reference to the container-interceptor instance
* @param method The method on which the interceptor applies
*/
ContainerInterceptorMethodInterceptor(final ManagedReference interceptorInstanceRef, final Method method) {
this.method = method;
this.interceptorInstanceRef = interceptorInstanceRef;
}
/**
* {@inheritDoc}
*/
public Object processInvocation(final InterceptorContext context) throws Exception {
// get the container-interceptor instance
final Object interceptorInstance = interceptorInstanceRef.getInstance();
try {
final Method method = this.method;
return method.invoke(interceptorInstance, context.getInvocationContext());
} catch (IllegalAccessException e) {
final IllegalAccessError n = new IllegalAccessError(e.getMessage());
n.setStackTrace(e.getStackTrace());
throw n;
} catch (InvocationTargetException e) {
throw Interceptors.rethrow(e.getCause());
}
}
}
}
| 4,285 | 41.019608 | 163 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/MethodTransactionAttributeKey.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.ejb3.component;
import org.jboss.invocation.proxy.MethodIdentifier;
import org.jboss.metadata.ejb.spec.MethodInterfaceType;
/**
* @author Stuart Douglas
*/
public class MethodTransactionAttributeKey {
private final MethodInterfaceType methodIntf;
private final MethodIdentifier methodIdentifier;
public MethodTransactionAttributeKey(final MethodInterfaceType methodIntf, final MethodIdentifier methodIdentifier) {
this.methodIntf = methodIntf;
this.methodIdentifier = methodIdentifier;
}
public MethodIdentifier getMethodIdentifier() {
return methodIdentifier;
}
public MethodInterfaceType getMethodIntf() {
return methodIntf;
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final MethodTransactionAttributeKey that = (MethodTransactionAttributeKey) o;
if (!methodIdentifier.equals(that.methodIdentifier)) return false;
if (methodIntf != that.methodIntf) return false;
return true;
}
@Override
public int hashCode() {
int result = methodIntf.hashCode();
result = 31 * result + methodIdentifier.hashCode();
return result;
}
}
| 2,325 | 33.716418 | 121 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/EJBValidationConfigurator.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.ejb3.component;
import static org.jboss.as.ejb3.util.MethodInfoHelper.EMPTY_STRING_ARRAY;
import java.lang.reflect.Constructor;
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.ViewDescription;
import org.jboss.as.ejb3.util.EjbValidationsUtil;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.reflect.ClassReflectionIndex;
/**
*
* Configurator that validates than an Jakarta Enterprise Beans class does not validate the Jakarta Enterprise Beans specification
*
* @author Stuart Douglas
*/
public class EJBValidationConfigurator implements ComponentConfigurator {
public static final EJBValidationConfigurator INSTANCE = new EJBValidationConfigurator();
private EJBValidationConfigurator() {
}
@Override
public void configure(final DeploymentPhaseContext context, final ComponentDescription description, final ComponentConfiguration configuration) throws DeploymentUnitProcessingException {
final ClassReflectionIndex classIndex = context.getDeploymentUnit().getAttachment(Attachments.REFLECTION_INDEX).getClassIndex(configuration.getComponentClass());
final Constructor<?> ctor = classIndex.getConstructor(EMPTY_STRING_ARRAY);
boolean noInterface = false;
for(ViewDescription view : description.getViews()) {
if(view.getViewClassName().equals(description.getComponentClassName())) {
noInterface = true;
break;
}
}
EjbValidationsUtil.verifyEjbClassAndDefaultConstructor(ctor, configuration.getComponentClass().getEnclosingClass(), noInterface, description.getComponentName(), description.getComponentClassName(), configuration.getComponentClass().getModifiers());
EjbValidationsUtil.verifyEjbPublicMethodAreNotFinalNorStatic(configuration.getComponentClass().getMethods(),description.getComponentClassName());
for ( Class<?> interfaceClass : configuration.getComponentClass().getInterfaces())
EjbValidationsUtil.verifyEjbPublicMethodAreNotFinalNorStatic(interfaceClass.getMethods(), interfaceClass.getCanonicalName());
}
}
| 3,464 | 47.802817 | 256 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/EJBComponentCreateService.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, 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.ejb3.component;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import jakarta.ejb.TransactionAttributeType;
import jakarta.ejb.TransactionManagementType;
import jakarta.transaction.TransactionSynchronizationRegistry;
import jakarta.transaction.UserTransaction;
import org.jboss.as.ee.component.BasicComponentCreateService;
import org.jboss.as.ee.component.ComponentConfiguration;
import org.jboss.as.ee.component.ViewConfiguration;
import org.jboss.as.ee.component.ViewDescription;
import org.jboss.as.ejb3.component.interceptors.ShutDownInterceptorFactory;
import org.jboss.as.ejb3.component.messagedriven.MessageDrivenComponentDescription;
import org.jboss.as.ejb3.deployment.ApplicationExceptions;
import org.jboss.as.ejb3.security.EJBSecurityMetaData;
import org.jboss.as.ejb3.suspend.EJBSuspendHandlerService;
import org.jboss.as.ejb3.timerservice.spi.ManagedTimerServiceFactory;
import org.jboss.invocation.InterceptorFactory;
import org.jboss.invocation.Interceptors;
import org.jboss.invocation.proxy.MethodIdentifier;
import org.jboss.metadata.ejb.spec.MethodInterfaceType;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.value.InjectedValue;
import org.wildfly.extension.requestcontroller.ControlPoint;
import org.wildfly.security.auth.server.SecurityDomain;
import org.wildfly.transaction.client.LocalUserTransaction;
/**
* @author Jaikiran Pai
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public class EJBComponentCreateService extends BasicComponentCreateService {
private final Map<MethodTransactionAttributeKey, TransactionAttributeType> txAttrs;
private final Map<MethodTransactionAttributeKey, Boolean> txExplicitAttrs;
private final Map<MethodTransactionAttributeKey, Integer> txTimeouts;
private final TransactionManagementType transactionManagementType;
private final ApplicationExceptions applicationExceptions;
private final Map<String, ServiceName> viewServices;
private final EJBSecurityMetaData securityMetaData;
private final Map<Method, InterceptorFactory> timeoutInterceptors;
private final Method timeoutMethod;
private final ServiceName ejbLocalHome;
private final ServiceName ejbHome;
private final ServiceName ejbObject;
private final ServiceName ejbLocalObject;
private final String applicationName;
private final String earApplicationName;
private final String moduleName;
private final String distinctName;
private final InjectedValue<TransactionSynchronizationRegistry> transactionSynchronizationRegistryValue = new InjectedValue<TransactionSynchronizationRegistry>();
private final InjectedValue<ControlPoint> controlPoint = new InjectedValue<>();
private final InjectedValue<AtomicBoolean> exceptionLoggingEnabled = new InjectedValue<>();
private final InjectedValue<SecurityDomain> securityDomain = new InjectedValue<>();
private final InjectedValue<Function> identityOutflowFunction = new InjectedValue<>();
private final InjectedValue<EJBSuspendHandlerService> ejbSuspendHandler = new InjectedValue<>();
private final InjectedValue<ManagedTimerServiceFactory> timerServiceFactory = new InjectedValue<>();
private final ShutDownInterceptorFactory shutDownInterceptorFactory;
private final boolean jaccRequired;
private final boolean legacyCompliantPrincipalPropagation;
private final boolean securityRequired;
private final EJBComponentDescription componentDescription;
/**
* Construct a new instance.
*
* @param componentConfiguration the component configuration
*/
public EJBComponentCreateService(final ComponentConfiguration componentConfiguration, final ApplicationExceptions applicationExceptions) {
super(componentConfiguration);
this.applicationExceptions = applicationExceptions;
final EJBComponentDescription ejbComponentDescription = (EJBComponentDescription) componentConfiguration.getComponentDescription();
this.transactionManagementType = ejbComponentDescription.getTransactionManagementType();
// CMTTx
if (transactionManagementType.equals(TransactionManagementType.CONTAINER)) {
this.txAttrs = new HashMap<MethodTransactionAttributeKey, TransactionAttributeType>();
this.txTimeouts = new HashMap<MethodTransactionAttributeKey, Integer>();
this.txExplicitAttrs = new HashMap<>();
} else {
this.txAttrs = null;
this.txTimeouts = null;
this.txExplicitAttrs = null;
}
// Setup the security metadata for the bean
this.securityMetaData = new EJBSecurityMetaData(componentConfiguration);
if (ejbComponentDescription.isTimerServiceRequired()) {
Map<Method, InterceptorFactory> timeoutInterceptors = new IdentityHashMap<Method, InterceptorFactory>();
for (Method method : componentConfiguration.getDefinedComponentMethods()) {
if ((ejbComponentDescription.getTimeoutMethod() != null && ejbComponentDescription.getTimeoutMethod().equals(method)) ||
ejbComponentDescription.getScheduleMethods().containsKey(method)) {
final InterceptorFactory interceptorFactory = Interceptors.getChainedInterceptorFactory(componentConfiguration.getAroundTimeoutInterceptors(method));
timeoutInterceptors.put(method, interceptorFactory);
}
}
this.timeoutInterceptors = timeoutInterceptors;
} else {
timeoutInterceptors = Collections.emptyMap();
}
List<ViewConfiguration> views = componentConfiguration.getViews();
if (views != null) {
for (ViewConfiguration view : views) {
//TODO: Move this into a configurator
final EJBViewConfiguration ejbView = (EJBViewConfiguration) view;
final MethodInterfaceType viewType = ejbView.getMethodIntf();
for (Method method : view.getProxyFactory().getCachedMethods()) {
// TODO: proxy factory exposes non-public methods, is this a bug in the no-interface view?
if (!Modifier.isPublic(method.getModifiers()))
continue;
final Method componentMethod = getComponentMethod(componentConfiguration, method.getName(), method.getParameterTypes());
if (componentMethod != null) {
this.processTxAttr(ejbComponentDescription, viewType, componentMethod);
} else {
this.processTxAttr(ejbComponentDescription, viewType, method);
}
}
}
}
this.timeoutMethod = ejbComponentDescription.getTimeoutMethod();
// FIXME: TODO: a temporary measure until EJBTHREE-2120 is fully resolved, let's create tx attribute map
// for the component methods. Once the issue is resolved, we should get rid of this block and just rely on setting
// up the tx attributes only for the views exposed by this component
// AS7-899: We only want to process public methods of the proper sub-class. (getDefinedComponentMethods returns all in random order)
// TODO: use ClassReflectionIndex (low prio, because we store the result without class name) (which is a bug: AS7-905)
Set<Method> lifeCycle = new HashSet<>(componentConfiguration.getLifecycleMethods());
for (Method method : componentConfiguration.getComponentClass().getMethods()) {
this.processTxAttr(ejbComponentDescription, MethodInterfaceType.Bean, method);
lifeCycle.remove(method);
}
//now handle non-public lifecycle methods declared on the bean class itself
//see WFLY-4127
for(Method method : lifeCycle) {
if(method.getDeclaringClass().equals(componentConfiguration.getComponentClass())) {
this.processTxAttr(ejbComponentDescription, MethodInterfaceType.Bean, method);
}
}
final HashMap<String, ServiceName> viewServices = new HashMap<String, ServiceName>();
for (ViewDescription view : componentConfiguration.getComponentDescription().getViews()) {
viewServices.put(view.getViewClassName(), view.getServiceName());
}
this.viewServices = viewServices;
final EjbHomeViewDescription localHome = ejbComponentDescription.getEjbLocalHomeView();
this.ejbLocalHome = localHome == null ? null : ejbComponentDescription.getEjbLocalHomeView().getServiceName();
final EjbHomeViewDescription home = ejbComponentDescription.getEjbHomeView();
this.ejbHome = home == null ? null : home.getServiceName();
final EJBViewDescription ejbObject = ejbComponentDescription.getEjbRemoteView();
this.ejbObject = ejbObject == null ? null : ejbObject.getServiceName();
final EJBViewDescription ejbLocalObject = ejbComponentDescription.getEjbLocalView();
this.ejbLocalObject = ejbLocalObject == null ? null : ejbLocalObject.getServiceName();
this.applicationName = componentConfiguration.getApplicationName();
this.earApplicationName = componentConfiguration.getComponentDescription().getModuleDescription().getEarApplicationName();
this.moduleName = componentConfiguration.getModuleName();
this.distinctName = componentConfiguration.getComponentDescription().getModuleDescription().getDistinctName();
this.shutDownInterceptorFactory = ejbComponentDescription.getShutDownInterceptorFactory();
this.securityRequired = ejbComponentDescription.isSecurityRequired();
this.jaccRequired = ejbComponentDescription.requiresJacc();
this.legacyCompliantPrincipalPropagation = ejbComponentDescription.requiresLegacyCompliantPrincipalPropagation();
this.componentDescription = ejbComponentDescription;
}
@Override
protected boolean requiresInterceptors(final Method method, final ComponentConfiguration componentConfiguration) {
if (super.requiresInterceptors(method, componentConfiguration)) {
return true;
}
final EJBComponentDescription ejbComponentDescription = (EJBComponentDescription) componentConfiguration.getComponentDescription();
if ((ejbComponentDescription.getTimeoutMethod() != null && ejbComponentDescription.getTimeoutMethod().equals(method)) ||
ejbComponentDescription.getScheduleMethods().containsKey(method)) {
return true;
}
return false;
}
private static Method getComponentMethod(final ComponentConfiguration componentConfiguration, final String name, final Class<?>[] parameterTypes) {
try {
return componentConfiguration.getComponentClass().getMethod(name, parameterTypes);
} catch (NoSuchMethodException e) {
return null;
}
}
Map<MethodTransactionAttributeKey, TransactionAttributeType> getTxAttrs() {
return txAttrs;
}
Map<MethodTransactionAttributeKey, Boolean> getExplicitTxAttrs() {
return txExplicitAttrs;
}
Map<MethodTransactionAttributeKey, Integer> getTxTimeouts() {
return txTimeouts;
}
TransactionManagementType getTransactionManagementType() {
return transactionManagementType;
}
ApplicationExceptions getApplicationExceptions() {
return this.applicationExceptions;
}
EJBComponentDescription getComponentDescription() {
return componentDescription;
}
protected void processTxAttr(final EJBComponentDescription ejbComponentDescription, final MethodInterfaceType methodIntf, final Method method) {
if (this.getTransactionManagementType().equals(TransactionManagementType.BEAN)) {
// it's a BMT bean
return;
}
MethodInterfaceType defaultMethodIntf = (ejbComponentDescription instanceof MessageDrivenComponentDescription) ? MethodInterfaceType.MessageEndpoint : MethodInterfaceType.Bean;
TransactionAttributeType txAttr = ejbComponentDescription.getTransactionAttributes().getAttribute(methodIntf, method, defaultMethodIntf);
MethodTransactionAttributeKey key = new MethodTransactionAttributeKey(methodIntf, MethodIdentifier.getIdentifierForMethod(method));
if(txAttr != null) {
txAttrs.put(key, txAttr);
txExplicitAttrs.put(key, ejbComponentDescription.getTransactionAttributes().isMethodLevel(methodIntf, method, defaultMethodIntf));
}
Integer txTimeout = ejbComponentDescription.getTransactionTimeouts().getAttribute(methodIntf, method, defaultMethodIntf);
if (txTimeout != null) {
txTimeouts.put(key, txTimeout);
}
}
public Map<String, ServiceName> getViewServices() {
return viewServices;
}
public EJBSecurityMetaData getSecurityMetaData() {
return this.securityMetaData;
}
public Map<Method, InterceptorFactory> getTimeoutInterceptors() {
return timeoutInterceptors;
}
public Method getTimeoutMethod() {
return timeoutMethod;
}
public ServiceName getEjbHome() {
return ejbHome;
}
public ServiceName getEjbLocalHome() {
return ejbLocalHome;
}
public ServiceName getEjbObject() {
return ejbObject;
}
public ServiceName getEjbLocalObject() {
return ejbLocalObject;
}
public String getApplicationName() {
return applicationName;
}
public String getEarApplicationName() {
return this.earApplicationName;
}
public String getDistinctName() {
return distinctName;
}
public String getModuleName() {
return moduleName;
}
UserTransaction getUserTransaction() {
return LocalUserTransaction.getInstance();
}
Injector<TransactionSynchronizationRegistry> getTransactionSynchronizationRegistryInjector() {
return transactionSynchronizationRegistryValue;
}
TransactionSynchronizationRegistry getTransactionSynchronizationRegistry() {
return transactionSynchronizationRegistryValue.getValue();
}
public Injector<EJBSuspendHandlerService> getEJBSuspendHandlerInjector() {
return this.ejbSuspendHandler;
}
EJBSuspendHandlerService getEJBSuspendHandler() {
return this.ejbSuspendHandler.getValue();
}
public ControlPoint getControlPoint() {
return this.controlPoint.getOptionalValue();
}
public Injector<ControlPoint> getControlPointInjector() {
return this.controlPoint;
}
InjectedValue<AtomicBoolean> getExceptionLoggingEnabledInjector() {
return exceptionLoggingEnabled;
}
public AtomicBoolean getExceptionLoggingEnabled() {
return exceptionLoggingEnabled.getValue();
}
Injector<SecurityDomain> getSecurityDomainInjector() {
return securityDomain;
}
public SecurityDomain getSecurityDomain() {
return securityDomain.getOptionalValue();
}
public boolean isEnableJacc() {
return jaccRequired;
}
public boolean isLegacyCompliantPrincipalPropagation() {
return legacyCompliantPrincipalPropagation;
}
Injector<Function> getIdentityOutflowFunctionInjector() {
return identityOutflowFunction;
}
public Function getIdentityOutflowFunction() {
return identityOutflowFunction.getOptionalValue();
}
public ShutDownInterceptorFactory getShutDownInterceptorFactory() {
return shutDownInterceptorFactory;
}
public boolean isSecurityRequired() {
return securityRequired;
}
public ManagedTimerServiceFactory getTimerServiceFactory() {
return this.timerServiceFactory.getValue();
}
public Injector<ManagedTimerServiceFactory> getTimerServiceFactoryInjector() {
return this.timerServiceFactory;
}
}
| 17,373 | 42.00495 | 184 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/DefaultAccessTimeoutService.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.ejb3.component;
import org.jboss.as.ejb3.concurrency.AccessTimeoutDetails;
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 java.util.concurrent.TimeUnit;
/**
* Service that manages the default access timeout for session beans
*
* @author Stuart Douglas
*/
public class DefaultAccessTimeoutService implements Service<DefaultAccessTimeoutService> {
public static final ServiceName STATEFUL_SERVICE_NAME = ServiceName.JBOSS.append("ejb3", "statefulDefaultTimeout");
public static final ServiceName SINGLETON_SERVICE_NAME = ServiceName.JBOSS.append("ejb3", "singletonDefaultTimeout");
private volatile AccessTimeoutDetails value;
public DefaultAccessTimeoutService(final long value) {
this.value = new AccessTimeoutDetails(value, TimeUnit.MILLISECONDS);
}
public final AccessTimeoutDetails getDefaultAccessTimeout() {
return value;
}
public void setDefaultAccessTimeout(final long value) {
this.value = new AccessTimeoutDetails(value, TimeUnit.MILLISECONDS);
}
@Override
public void start(final StartContext context) throws StartException {
}
@Override
public void stop(final StopContext context) {
}
@Override
public DefaultAccessTimeoutService getValue() throws IllegalStateException, IllegalArgumentException {
return this;
}
}
| 2,556 | 33.554054 | 121 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/StatefulComponentCreateServiceFactory.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, 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.ejb3.component.stateful;
import java.util.concurrent.atomic.AtomicLong;
import org.jboss.as.clustering.msc.InjectedValueDependency;
import org.jboss.as.ee.component.BasicComponentCreateService;
import org.jboss.as.ee.component.ComponentConfiguration;
import org.jboss.as.ee.component.ComponentStartService;
import org.jboss.as.ee.component.DependencyConfigurator;
import org.jboss.as.ejb3.component.DefaultAccessTimeoutService;
import org.jboss.as.ejb3.component.EJBComponentCreateServiceFactory;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanCacheFactory;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.ejb3.subsystem.DefaultStatefulBeanSessionTimeoutWriteHandler;
import org.jboss.ejb.client.SessionID;
import org.jboss.msc.service.ServiceBuilder;
import org.wildfly.clustering.service.SupplierDependency;
/**
* User: jpai
*/
public class StatefulComponentCreateServiceFactory extends EJBComponentCreateServiceFactory {
@Override
public BasicComponentCreateService constructService(final ComponentConfiguration configuration) {
if (this.ejbJarConfiguration == null) {
throw EjbLogger.ROOT_LOGGER.ejbJarConfigNotBeenSet(this, configuration.getComponentName());
}
// setup an injection dependency to inject the DefaultAccessTimeoutService and DefaultStatefulSessionTimeoutService
// in the stateful bean component create service
configuration.getCreateDependencies().add(new DependencyConfigurator<StatefulSessionComponentCreateService>() {
@Override
public void configureDependency(ServiceBuilder<?> serviceBuilder, StatefulSessionComponentCreateService componentCreateService) {
serviceBuilder.addDependency(DefaultAccessTimeoutService.STATEFUL_SERVICE_NAME, DefaultAccessTimeoutService.class, componentCreateService.getDefaultAccessTimeoutInjector());
serviceBuilder.addDependency(DefaultStatefulBeanSessionTimeoutWriteHandler.SERVICE_NAME, AtomicLong.class, componentCreateService.getDefaultStatefulSessionTimeoutInjector());
}
});
StatefulComponentDescription description = (StatefulComponentDescription) configuration.getComponentDescription();
SupplierDependency<StatefulSessionBeanCacheFactory<SessionID, StatefulSessionComponentInstance>> cacheFactory = new InjectedValueDependency<>(description.getCacheFactoryServiceName(), (Class<StatefulSessionBeanCacheFactory<SessionID, StatefulSessionComponentInstance>>) (Class<?>) StatefulSessionBeanCacheFactory.class);
configuration.getStartDependencies().add(new DependencyConfigurator<ComponentStartService>() {
@Override
public void configureDependency(ServiceBuilder<?> builder, ComponentStartService service) {
cacheFactory.register(builder);
}
});
return new StatefulSessionComponentCreateService(configuration, this.ejbJarConfiguration, cacheFactory);
}
}
| 4,038 | 56.7 | 328 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/StatefulTransactionMarker.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.ejb3.component.stateful;
/**
* Marker class that is added to the invocation context to indicate to inner interceptors if this
* SFSB is participating in a transaction or not.
*
* @author Stuart Douglas
*/
public class StatefulTransactionMarker {
private static final StatefulTransactionMarker FIRST = new StatefulTransactionMarker(true);
private static final StatefulTransactionMarker SECOND = new StatefulTransactionMarker(false);
public static StatefulTransactionMarker of(boolean firstInvocation) {
return firstInvocation ? FIRST : SECOND;
}
private final boolean firstInvocation;
private StatefulTransactionMarker(final boolean firstInvocation) {
this.firstInvocation = firstInvocation;
}
public boolean isFirstInvocation() {
return firstInvocation;
}
}
| 1,874 | 36.5 | 97 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/StatefulRemoveDelegationInterceptor.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.ejb3.component.stateful;
import org.jboss.as.ee.component.ComponentInstance;
import org.jboss.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
/**
* Interceptor that delegates calls to Enterprise Beans 2.x remove methods to the component remove method interceptor chain
*
* @author Stuart Douglas
*/
public class StatefulRemoveDelegationInterceptor implements Interceptor{
public static final InterceptorFactory FACTORY = new ImmediateInterceptorFactory(new StatefulRemoveDelegationInterceptor());
private StatefulRemoveDelegationInterceptor() {
}
@Override
public Object processInvocation(final InterceptorContext context) throws Exception {
StatefulSessionComponentInstance instance = (StatefulSessionComponentInstance) context.getPrivateData(ComponentInstance.class);
return instance.getEjb2XRemoveInterceptor().processInvocation(context);
}
}
| 2,071 | 40.44 | 135 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/StatefulSessionBeanImmutability.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.ejb3.component.stateful;
import java.lang.reflect.InvocationHandler;
import org.jboss.as.ee.component.ProxyInvocationHandler;
import org.jboss.invocation.proxy.ProxyFactory;
import org.kohsuke.MetaInfServices;
import org.wildfly.clustering.ee.Immutability;
/**
* Immutability test for EJB proxies, whose serializable placeholders are immutable.
* @author Paul Ferraro
*/
@MetaInfServices(Immutability.class)
public class StatefulSessionBeanImmutability implements Immutability {
@Override
public boolean test(Object object) {
try {
InvocationHandler handler = ProxyFactory.getInvocationHandlerStatic(object);
return handler instanceof ProxyInvocationHandler;
} catch (RuntimeException e) {
return false;
}
}
}
| 1,834 | 36.44898 | 88 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/StatefulTimeoutInfo.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.ejb3.component.stateful;
import jakarta.ejb.StatefulTimeout;
import java.util.concurrent.TimeUnit;
/**
* @author Stuart Douglas
*/
public class StatefulTimeoutInfo {
private final long value;
private final TimeUnit timeUnit;
public StatefulTimeoutInfo(final long value, final TimeUnit timeUnit) {
this.value = value;
this.timeUnit = timeUnit;
}
public StatefulTimeoutInfo(final StatefulTimeout statefulTimeout) {
this.value = statefulTimeout.value();
this.timeUnit = statefulTimeout.unit();
}
public TimeUnit getTimeUnit() {
return timeUnit;
}
public long getValue() {
return value;
}
}
| 1,721 | 31.490566 | 75 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/StatefulSessionSynchronizationInterceptor.java | /*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, 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.ejb3.component.stateful;
import static org.jboss.as.ejb3.component.stateful.StatefulSessionComponentInstance.SYNC_STATE_AFTER_COMPLETE_DELAYED_COMMITTED;
import static org.jboss.as.ejb3.component.stateful.StatefulSessionComponentInstance.SYNC_STATE_AFTER_COMPLETE_DELAYED_NO_COMMIT;
import static org.jboss.as.ejb3.component.stateful.StatefulSessionComponentInstance.SYNC_STATE_INVOCATION_IN_PROGRESS;
import static org.jboss.as.ejb3.component.stateful.StatefulSessionComponentInstance.SYNC_STATE_NO_INVOCATION;
import static org.jboss.as.ejb3.logging.EjbLogger.ROOT_LOGGER;
import java.util.concurrent.atomic.AtomicInteger;
import jakarta.ejb.EJBException;
import jakarta.ejb.TransactionManagementType;
import jakarta.transaction.Status;
import jakarta.transaction.Synchronization;
import jakarta.transaction.TransactionSynchronizationRegistry;
import org.jboss.as.ee.component.Component;
import org.jboss.as.ee.component.ComponentInstanceInterceptorFactory;
import org.jboss.as.ejb3.component.interceptors.AbstractEJBInterceptor;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBean;
import org.jboss.as.ejb3.concurrency.AccessTimeoutDetails;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.ejb3.tx.OwnableReentrantLock;
import org.jboss.ejb.client.SessionID;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
import org.jboss.invocation.InterceptorFactoryContext;
/**
* {@link org.jboss.invocation.Interceptor} which manages {@link Synchronization} semantics on a stateful session bean.
*
* @author <a href="mailto:[email protected]">Carlo de Wolf</a>
* @author Jaikiran Pai
*/
public class StatefulSessionSynchronizationInterceptor extends AbstractEJBInterceptor {
private final boolean containerManagedTransactions;
private static final Factory CONTAINER_MANAGED = new Factory(TransactionManagementType.CONTAINER);
private static final Factory BEAN_MANAGED = new Factory(TransactionManagementType.BEAN);
public static InterceptorFactory factory(final TransactionManagementType type) {
//we need to always return the same factory instance
//otherwise multiple synchronization interceptors may be created
return type == TransactionManagementType.CONTAINER ? CONTAINER_MANAGED : BEAN_MANAGED;
}
public StatefulSessionSynchronizationInterceptor(final boolean containerManagedTransactions) {
this.containerManagedTransactions = containerManagedTransactions;
}
@Override
public Object processInvocation(final InterceptorContext context) throws Exception {
final StatefulSessionComponent component = getComponent(context, StatefulSessionComponent.class);
final StatefulSessionBean<SessionID, StatefulSessionComponentInstance> bean = StatefulComponentInstanceInterceptor.getBean(context);
final StatefulSessionComponentInstance instance = bean.getInstance();
final OwnableReentrantLock lock = instance.getLock();
final Object threadLock = instance.getThreadLock();
final AtomicInteger invocationSyncState = instance.getInvocationSyncState();
final TransactionSynchronizationRegistry tsr = component.getTransactionSynchronizationRegistry();
final Object lockOwner = getLockOwner(tsr);
final AccessTimeoutDetails timeout = component.getAccessTimeout(context.getMethod());
if (ROOT_LOGGER.isTraceEnabled()) {
ROOT_LOGGER.trace("Trying to acquire lock: " + lock + " for stateful component instance: " + instance + " during invocation: " + context);
}
// we obtain a lock in this synchronization interceptor because the lock needs to be tied to the synchronization
// so that it can released on the tx synchronization callbacks
boolean acquired = lock.tryLock(timeout.getValue(), timeout.getTimeUnit(), lockOwner);
if (!acquired) {
throw EjbLogger.ROOT_LOGGER.failToObtainLock(component.getComponentName(), timeout.getValue(), timeout.getTimeUnit());
}
synchronized (threadLock) {
invocationSyncState.set(SYNC_STATE_INVOCATION_IN_PROGRESS); //invocation in progress
if (ROOT_LOGGER.isTraceEnabled()) {
ROOT_LOGGER.trace("Acquired lock: " + lock + " for stateful component instance: " + instance + " during invocation: " + context);
}
// If using CMT, get the key to current transaction associated with this thread
// we never register a sync for bean managed transactions
// the inner BMT interceptor is going to setup the correct transaction anyway
// so enrolling in an existing transaction is not correct
Object currentTransactionKey = this.containerManagedTransactions ? tsr.getTransactionKey() : null;
boolean wasTxSyncRegistered = false;
try {
if ((currentTransactionKey != null) && tsr.getResource(bean.getId()) == null) {
final int status = tsr.getTransactionStatus();
// if this SFSB instance is already associated with a different transaction, then it's an error
// if the thread is currently associated with a tx, then register a tx synchronization
if (status != Status.STATUS_COMMITTED && status != Status.STATUS_ROLLEDBACK) {
// register a tx synchronization for this SFSB instance
final Synchronization statefulSessionSync = new StatefulSessionSynchronization(bean);
tsr.registerInterposedSynchronization(statefulSessionSync);
wasTxSyncRegistered = true;
if (ROOT_LOGGER.isTraceEnabled()) {
ROOT_LOGGER.trace("Registered tx synchronization: " + statefulSessionSync + " for tx: " + currentTransactionKey +
" associated with stateful component instance: " + instance);
}
// invoke the afterBegin callback on the SFSB
instance.afterBegin();
// Retain reference to bean for all invocations within tx
tsr.putResource(bean.getId(), bean);
context.putPrivateData(StatefulTransactionMarker.class, StatefulTransactionMarker.of(true));
}
} else {
context.putPrivateData(StatefulTransactionMarker.class, StatefulTransactionMarker.of(false));
}
// proceed with the invocation
// handle exceptions to coincide with exception handling in StatefulComponentInstanceInterceptor
try {
return context.proceed();
} catch (Exception ex) {
if (component.shouldDiscard(ex, context.getMethod())) {
bean.discard();
}
throw ex;
} catch (Throwable t) {
// discard bean cache state on error
bean.discard();
throw t;
}
} finally {
// if the current call did *not* register a tx SessionSynchronization, then we have to explicitly mark the
// SFSB instance as "no longer in use". If it registered a tx SessionSynchronization, then releasing the lock is
// taken care off by a tx synchronization callbacks.
// case: sync was not registered in this invocation nor in a previous one
if (!wasTxSyncRegistered) {
if ((currentTransactionKey == null) || (tsr.getResource(bean.getId()) == null)) {
ROOT_LOGGER.tracef("Calling release from synchronization interceptor (#1), instance id K = %s", instance.getId());
close(bean);
} else {
// case: sync was not registered in this invocation but in a previous one
// if we don't release the lock here then it will be acquired multiple times and only released once
// The StatefulSessionBean will be closed by its synchronization
releaseLock(instance);
}
}
for(;;) {
int state = invocationSyncState.get();
if(state == SYNC_STATE_INVOCATION_IN_PROGRESS && invocationSyncState.compareAndSet(SYNC_STATE_INVOCATION_IN_PROGRESS, SYNC_STATE_NO_INVOCATION)) {
break;
} else if (state == SYNC_STATE_AFTER_COMPLETE_DELAYED_COMMITTED || state == SYNC_STATE_AFTER_COMPLETE_DELAYED_NO_COMMIT) {
try {
//invoke the after completion method, other after completion syncs may have already run
handleAfterCompletion(state == SYNC_STATE_AFTER_COMPLETE_DELAYED_COMMITTED, bean);
} finally {
invocationSyncState.set(SYNC_STATE_NO_INVOCATION);
}
} else {
EjbLogger.ROOT_LOGGER.unexpectedInvocationState(state);
break;
}
}
}
}
}
/**
* Use either the active transaction or the current thread as the lock owner
*
* @return The lock owner
*/
private static Object getLockOwner(final TransactionSynchronizationRegistry transactionSynchronizationRegistry) {
Object owner = transactionSynchronizationRegistry.getTransactionKey();
return owner != null ? owner : Thread.currentThread();
}
/**
* Closes the specified {@link StatefulSessionBean} and releases the lock, held by this thread, on the stateful component instance.
*
* @param instance The stateful component instance
*/
static void close(StatefulSessionBean<SessionID, StatefulSessionComponentInstance> bean) {
StatefulSessionComponentInstance instance = bean.getInstance();
try {
bean.close();
} finally {
// release the lock on the SFSB instance
releaseLock(instance);
}
}
/**
* Releases the lock, held by this thread, on the stateful component instance.
*/
static void releaseLock(final StatefulSessionComponentInstance instance) {
instance.getLock().unlock(getLockOwner(instance.getComponent().getTransactionSynchronizationRegistry()));
ROOT_LOGGER.tracef("Released lock: %s", instance.getLock());
}
private static class Factory extends ComponentInstanceInterceptorFactory {
private final TransactionManagementType type;
public Factory(final TransactionManagementType type) {
this.type = type;
}
@Override
protected Interceptor create(final Component component, final InterceptorFactoryContext context) {
return new StatefulSessionSynchronizationInterceptor(type == TransactionManagementType.CONTAINER );
}
}
private static final class StatefulSessionSynchronization implements Synchronization {
private final StatefulSessionBean<SessionID, StatefulSessionComponentInstance> bean;
StatefulSessionSynchronization(StatefulSessionBean<SessionID, StatefulSessionComponentInstance> bean) {
this.bean = bean;
}
@Override
public void beforeCompletion() {
StatefulSessionComponentInstance instance = this.bean.getInstance();
try {
ROOT_LOGGER.tracef("Before completion callback invoked on Transaction synchronization: %s of stateful component instance: %s" , this, instance);
if (!this.bean.isDiscarded()) {
instance.beforeCompletion();
}
} catch (Throwable t) {
handleThrowable(t, this.bean);
}
}
@Override
public void afterCompletion(int status) {
StatefulSessionComponentInstance instance = this.bean.getInstance();
AtomicInteger state = instance.getInvocationSyncState();
final boolean committed = status == Status.STATUS_COMMITTED;
for(;;) {
int s = state.get();
if (s == SYNC_STATE_NO_INVOCATION) {
handleAfterCompletion(committed, this.bean);
break;
} else if (s == SYNC_STATE_INVOCATION_IN_PROGRESS && state.compareAndSet(SYNC_STATE_INVOCATION_IN_PROGRESS, committed ? SYNC_STATE_AFTER_COMPLETE_DELAYED_COMMITTED : SYNC_STATE_AFTER_COMPLETE_DELAYED_NO_COMMIT)) {
break;
}
}
}
}
static void handleAfterCompletion(boolean committed, StatefulSessionBean<SessionID, StatefulSessionComponentInstance> bean) {
StatefulSessionComponentInstance instance = bean.getInstance();
try {
ROOT_LOGGER.tracef("After completion callback invoked on Transaction synchronization: %s", instance);
if (!bean.isDiscarded()) {
instance.afterCompletion(committed);
}
} catch (Throwable t) {
handleThrowable(t, bean);
}
// Bean removal within a tx deferred destroy to its Synchronization
if (bean.isRemoved()) {
try {
instance.destroy();
} catch (Throwable t) {
handleThrowable(t, bean);
}
}
// tx has completed, so close the StatefulSessionBean and unlock the instance lock
instance.getComponent().getTransactionSynchronizationRegistry().putResource(bean.getId(), null);
close(bean);
}
private static void handleThrowable(Throwable t, StatefulSessionBean<SessionID, StatefulSessionComponentInstance> bean) {
StatefulSessionComponentInstance instance = bean.getInstance();
ROOT_LOGGER.discardingStatefulComponent(instance, t);
try {
// discard the SFSB instance
bean.discard();
} finally {
// release the lock associated with the SFSB instance
releaseLock(instance);
}
// throw back an appropriate exception
if (t instanceof RuntimeException)
throw (RuntimeException) t;
if (t instanceof Error)
throw (Error) t;
throw (EJBException) new EJBException().initCause(t);
}
}
| 15,759 | 49.351438 | 230 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/SerializedStatefulSessionComponent.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.ejb3.component.stateful;
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.security.AccessController;
import java.util.HashMap;
import java.util.Map;
import org.jboss.as.ee.component.BasicComponentInstance;
import org.jboss.as.naming.ManagedReference;
import org.jboss.as.server.CurrentServiceContainer;
import org.jboss.ejb.client.SessionID;
import org.jboss.msc.service.ServiceContainer;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
/**
*
* Serialized form of a SFSB
*
* @author Stuart Douglas
*/
public class SerializedStatefulSessionComponent implements Serializable {
private static final long serialVersionUID = 1L;
private final String serviceName;
private final SessionID sessionID;
private final Map<Object, Object> serializableInterceptors;
private final ManagedReference instance;
public SerializedStatefulSessionComponent(final ManagedReference instance, final SessionID sessionID, final String serviceName, final Map<Object, Object> serializableInterceptors) {
this.instance = instance;
this.sessionID = sessionID;
this.serviceName = serviceName;
this.serializableInterceptors = serializableInterceptors;
}
private Object readResolve() throws ObjectStreamException {
ServiceName name = ServiceName.parse(serviceName);
ServiceController<?> service = currentServiceContainer().getRequiredService(name);
StatefulSessionComponent component = (StatefulSessionComponent) service.getValue();
final Map<Object, Object> context = new HashMap<Object, Object>();
for(final Map.Entry<Object, Object> entry : serializableInterceptors.entrySet()) {
context.put(entry.getKey(), entry.getValue());
}
context.put(SessionID.class, sessionID);
context.put(BasicComponentInstance.INSTANCE_KEY, instance);
return component.constructComponentInstance(instance, false, context);
}
private static ServiceContainer currentServiceContainer() {
if(System.getSecurityManager() == null) {
return CurrentServiceContainer.getServiceContainer();
}
return AccessController.doPrivileged(CurrentServiceContainer.GET_ACTION);
}
}
| 3,337 | 39.216867 | 185 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/StatefulComponentSessionIdGeneratingInterceptor.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, 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.ejb3.component.stateful;
import org.jboss.as.ee.component.Component;
import org.jboss.as.ee.component.ComponentClientInstance;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.ejb.client.SessionID;
import org.jboss.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
/**
* User: jpai
*/
public class StatefulComponentSessionIdGeneratingInterceptor implements Interceptor {
public static final InterceptorFactory FACTORY = new ImmediateInterceptorFactory(new org.jboss.as.ejb3.component.stateful.StatefulComponentSessionIdGeneratingInterceptor());
private StatefulComponentSessionIdGeneratingInterceptor() {
}
@Override
public Object processInvocation(InterceptorContext context) throws Exception {
final Component component = context.getPrivateData(Component.class);
if (component instanceof StatefulSessionComponent == false) {
throw EjbLogger.ROOT_LOGGER.unexpectedComponent(component, StatefulSessionComponent.class);
}
ComponentClientInstance clientInstance = context.getPrivateData(ComponentClientInstance.class);
SessionID existing = context.getPrivateData(SessionID.class);
if (existing != null) {
clientInstance.setViewInstanceData(SessionID.class, existing);
} else {
StatefulSessionComponent statefulComponent = (StatefulSessionComponent) component;
statefulComponent.waitForComponentStart();
clientInstance.setViewInstanceData(SessionID.class, statefulComponent.getCache().createStatefulSessionBean());
}
// move to the next interceptor in chain
return context.proceed();
}
}
| 2,841 | 43.40625 | 177 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/StatefulIdentityInterceptor.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.ejb3.component.stateful;
import org.jboss.as.ee.component.ComponentView;
import org.jboss.ejb.client.SessionID;
import org.jboss.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
/**
* Interceptor for equals / hashCode for SFSB's
*
* @author Stuart Douglas
*/
public class StatefulIdentityInterceptor implements Interceptor {
public static final InterceptorFactory FACTORY = new ImmediateInterceptorFactory(new StatefulIdentityInterceptor());
private StatefulIdentityInterceptor() {
}
@Override
public Object processInvocation(final InterceptorContext context) throws Exception {
if (context.getMethod().getName().equals("equals")
|| context.getMethod().getName().equals("isIdentical")) {
final Object other = context.getParameters()[0];
final ComponentView componentView = context.getPrivateData(ComponentView.class);
final Class<?> proxyType = componentView.getProxyClass();
final SessionID sessionId = context.getPrivateData(SessionID.class);
if( proxyType.isAssignableFrom(other.getClass())) {
//now we know that this is an Jakarta Enterprise Beans for the correct component view
//as digging out the session id from the proxy object is not really
//a viable option, we invoke equals() for the other instance with a
//SessionIdHolder as the other side
return other.equals(new SessionIdHolder(sessionId));
} else if(other instanceof SessionIdHolder) {
return sessionId.equals( ((SessionIdHolder)other).sessionId);
} else {
return false;
}
} else if (context.getMethod().getName().equals("hashCode")) {
final SessionID sessionId = context.getPrivateData(SessionID.class);
//use the identity of the component view as a hash code
return sessionId.hashCode();
} else {
return context.proceed();
}
}
private static class SessionIdHolder {
private final SessionID sessionId;
public SessionIdHolder(final SessionID sessionId) {
this.sessionId = sessionId;
}
}
}
| 3,513 | 43.481013 | 120 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/StatefulComponentDescription.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.ejb3.component.stateful;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Supplier;
import jakarta.ejb.EJBLocalObject;
import jakarta.ejb.EJBObject;
import jakarta.ejb.TransactionManagementType;
import org.jboss.as.controller.capability.CapabilityServiceSupport;
import org.jboss.as.ee.component.Attachments;
import org.jboss.as.ee.component.Component;
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.ComponentInstanceInterceptorFactory;
import org.jboss.as.ee.component.EEApplicationClasses;
import org.jboss.as.ee.component.ViewConfiguration;
import org.jboss.as.ee.component.ViewConfigurator;
import org.jboss.as.ee.component.ViewDescription;
import org.jboss.as.ee.component.interceptors.InterceptorClassDescription;
import org.jboss.as.ee.component.interceptors.InterceptorOrder;
import org.jboss.as.ee.component.serialization.WriteReplaceInterface;
import org.jboss.as.ee.metadata.MetadataCompleteMarker;
import org.jboss.as.ejb3.cache.CacheInfo;
import org.jboss.as.ejb3.component.EJBViewDescription;
import org.jboss.as.ejb3.component.interceptors.ComponentTypeIdentityInterceptorFactory;
import org.jboss.as.ejb3.component.session.SessionBeanComponentDescription;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanCacheProvider;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanCacheProviderServiceNameProvider;
import org.jboss.as.ejb3.deployment.EjbJarDescription;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.ejb3.tx.LifecycleCMTTxInterceptor;
import org.jboss.as.ejb3.tx.StatefulBMTInterceptor;
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.reflect.ClassReflectionIndex;
import org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex;
import org.jboss.ejb.client.SessionID;
import org.jboss.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorFactory;
import org.jboss.invocation.InterceptorFactoryContext;
import org.jboss.invocation.proxy.MethodIdentifier;
import org.jboss.metadata.ejb.spec.MethodInterfaceType;
import org.jboss.metadata.ejb.spec.SessionBeanMetaData;
import org.jboss.modules.ModuleLoader;
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.wildfly.clustering.service.ChildTargetService;
/**
* User: jpai
*/
public class StatefulComponentDescription extends SessionBeanComponentDescription {
private Method afterBegin;
private Method afterCompletion;
private Method beforeCompletion;
private final Map<MethodIdentifier, StatefulRemoveMethod> removeMethods = new HashMap<MethodIdentifier, StatefulRemoveMethod>();
private StatefulTimeoutInfo statefulTimeout;
private CacheInfo cache;
// by default stateful beans are passivation capable, but beans can override it via annotation or deployment descriptor, starting Jakarta Enterprise Beans 3.2
private boolean passivationApplicable = true;
private final ServiceName deploymentUnitServiceName;
/**
* Map of init method, to the corresponding home create method on the home interface
*/
private final Map<Method, String> initMethods = new HashMap<Method, String>(0);
public static final class StatefulRemoveMethod {
private final MethodIdentifier methodIdentifier;
private final boolean retainIfException;
StatefulRemoveMethod(final MethodIdentifier method, final boolean retainIfException) {
if (method == null) {
throw EjbLogger.ROOT_LOGGER.removeMethodIsNull();
}
this.methodIdentifier = method;
this.retainIfException = retainIfException;
}
public MethodIdentifier getMethodIdentifier() {
return methodIdentifier;
}
public boolean getRetainIfException() {
return retainIfException;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
StatefulRemoveMethod that = (StatefulRemoveMethod) o;
if (!methodIdentifier.equals(that.methodIdentifier)) return false;
return true;
}
@Override
public int hashCode() {
return methodIdentifier.hashCode();
}
}
/**
* Construct a new instance.
*
* @param componentName the component name
* @param componentClassName the component instance class name
* @param ejbJarDescription the module description
*/
public StatefulComponentDescription(final String componentName, final String componentClassName, final EjbJarDescription ejbJarDescription,
final DeploymentUnit deploymentUnit, final SessionBeanMetaData descriptorData) {
super(componentName, componentClassName, ejbJarDescription, deploymentUnit, descriptorData);
this.deploymentUnitServiceName = deploymentUnit.getServiceName();
addInitMethodInvokingInterceptor();
}
private void addInitMethodInvokingInterceptor() {
getConfigurators().addFirst(new ComponentConfigurator() {
@Override
public void configure(DeploymentPhaseContext context, ComponentDescription description, ComponentConfiguration configuration) throws DeploymentUnitProcessingException {
configuration.addPostConstructInterceptor(StatefulInitMethodInterceptor.INSTANCE, InterceptorOrder.ComponentPostConstruct.SFSB_INIT_METHOD);
}
});
}
private void addStatefulSessionSynchronizationInterceptor() {
// we must run before the DefaultFirstConfigurator
getConfigurators().addFirst(new ComponentConfigurator() {
@Override
public void configure(DeploymentPhaseContext context, ComponentDescription description, ComponentConfiguration configuration) throws DeploymentUnitProcessingException {
final InterceptorFactory interceptorFactory = StatefulSessionSynchronizationInterceptor.factory(getTransactionManagementType());
configuration.addComponentInterceptor(interceptorFactory, InterceptorOrder.Component.SYNCHRONIZATION_INTERCEPTOR, false);
}
});
}
@Override
public ComponentConfiguration createConfiguration(final ClassReflectionIndex classIndex, final ClassLoader moduleClassLoader, final ModuleLoader moduleLoader) {
final ComponentConfiguration statefulComponentConfiguration = new ComponentConfiguration(this, classIndex, moduleClassLoader, moduleLoader);
// setup the component create service
statefulComponentConfiguration.setComponentCreateServiceFactory(new StatefulComponentCreateServiceFactory());
if (getTransactionManagementType() == TransactionManagementType.BEAN) {
getConfigurators().add(new ComponentConfigurator() {
@Override
public void configure(final DeploymentPhaseContext context, final ComponentDescription description, final ComponentConfiguration configuration) throws DeploymentUnitProcessingException {
final ComponentInstanceInterceptorFactory bmtComponentInterceptorFactory = new ComponentInstanceInterceptorFactory() {
@Override
protected Interceptor create(Component component, InterceptorFactoryContext context) {
if (!(component instanceof StatefulSessionComponent)) {
throw EjbLogger.ROOT_LOGGER.componentNotInstanceOfSessionComponent(component, component.getComponentClass(), "stateful");
}
return new StatefulBMTInterceptor((StatefulSessionComponent) component);
}
};
configuration.addComponentInterceptor(bmtComponentInterceptorFactory, InterceptorOrder.Component.BMT_TRANSACTION_INTERCEPTOR, false);
}
});
} else {
getConfigurators().add(new ComponentConfigurator() {
@Override
public void configure(final DeploymentPhaseContext context, final ComponentDescription description, final ComponentConfiguration configuration) throws DeploymentUnitProcessingException {
final EEApplicationClasses applicationClasses = context.getDeploymentUnit().getAttachment(Attachments.EE_APPLICATION_CLASSES_DESCRIPTION);
InterceptorClassDescription interceptorConfig = ComponentDescription.mergeInterceptorConfig(configuration.getComponentClass(), applicationClasses.getClassByName(description.getComponentClassName()), description, MetadataCompleteMarker.isMetadataComplete(context.getDeploymentUnit()));
configuration.addPostConstructInterceptor(new LifecycleCMTTxInterceptor.Factory(interceptorConfig.getPostConstruct(), false), InterceptorOrder.ComponentPostConstruct.TRANSACTION_INTERCEPTOR);
configuration.addPreDestroyInterceptor(new LifecycleCMTTxInterceptor.Factory(interceptorConfig.getPreDestroy(), false), InterceptorOrder.ComponentPreDestroy.TRANSACTION_INTERCEPTOR);
if (description.isPassivationApplicable()) {
configuration.addPrePassivateInterceptor(new LifecycleCMTTxInterceptor.Factory(interceptorConfig.getPrePassivate(), false), InterceptorOrder.ComponentPassivation.TRANSACTION_INTERCEPTOR);
configuration.addPostActivateInterceptor(new LifecycleCMTTxInterceptor.Factory(interceptorConfig.getPostActivate(), false), InterceptorOrder.ComponentPassivation.TRANSACTION_INTERCEPTOR);
}
}
});
}
addStatefulSessionSynchronizationInterceptor();
this.getConfigurators().add(new ComponentConfigurator() {
@Override
public void configure(DeploymentPhaseContext context, ComponentDescription description, ComponentConfiguration configuration) throws DeploymentUnitProcessingException {
DeploymentUnit unit = context.getDeploymentUnit();
CapabilityServiceSupport support = unit.getAttachment(org.jboss.as.server.deployment.Attachments.CAPABILITY_SERVICE_SUPPORT);
StatefulComponentDescription statefulDescription = (StatefulComponentDescription) description;
ServiceTarget target = context.getServiceTarget();
ServiceBuilder<?> builder = target.addService(statefulDescription.getCacheFactoryServiceName().append("installer"));
Supplier<StatefulSessionBeanCacheProvider<SessionID, StatefulSessionComponentInstance>> provider = builder.requires(this.getCacheFactoryBuilderRequirement(statefulDescription));
Service service = new ChildTargetService(new Consumer<ServiceTarget>() {
@Override
public void accept(ServiceTarget target) {
provider.get().getStatefulBeanCacheFactoryServiceConfigurator(unit, statefulDescription, configuration).configure(support).build(target).install();
}
});
builder.setInstance(service).install();
}
private ServiceName getCacheFactoryBuilderRequirement(StatefulComponentDescription description) {
if (!description.isPassivationApplicable()) {
return StatefulSessionBeanCacheProviderServiceNameProvider.DEFAULT_PASSIVATION_DISABLED_CACHE_SERVICE_NAME;
}
CacheInfo cache = description.getCache();
return (cache != null) ? new StatefulSessionBeanCacheProviderServiceNameProvider(cache.getName()).getServiceName() : StatefulSessionBeanCacheProviderServiceNameProvider.DEFAULT_CACHE_SERVICE_NAME;
}
});
return statefulComponentConfiguration;
}
public Method getAfterBegin() {
return afterBegin;
}
public Method getAfterCompletion() {
return afterCompletion;
}
public Method getBeforeCompletion() {
return beforeCompletion;
}
@Override
public SessionBeanType getSessionBeanType() {
return SessionBeanComponentDescription.SessionBeanType.STATEFUL;
}
public void setAfterBegin(final Method afterBegin) {
this.afterBegin = afterBegin;
}
public void setAfterCompletion(final Method afterCompletion) {
this.afterCompletion = afterCompletion;
}
public void setBeforeCompletion(final Method afterCompletion) {
this.beforeCompletion = afterCompletion;
}
@Override
protected void setupViewInterceptors(EJBViewDescription view) {
// let super do its job
super.setupViewInterceptors(view);
// add the @Remove method interceptor
this.addRemoveMethodInterceptor(view);
// setup the instance associating interceptors
this.addStatefulInstanceAssociatingInterceptor(view);
this.addViewSerializationInterceptor(view);
if (view.getMethodIntf() == MethodInterfaceType.Remote) {
view.getConfigurators().add(new ViewConfigurator() {
@Override
public void configure(final DeploymentPhaseContext context, final ComponentConfiguration componentConfiguration, final ViewDescription description, final ViewConfiguration configuration) throws DeploymentUnitProcessingException {
final String earApplicationName = componentConfiguration.getComponentDescription().getModuleDescription().getEarApplicationName();
configuration.setViewInstanceFactory(new StatefulRemoteViewInstanceFactory(earApplicationName, componentConfiguration.getModuleName(), componentConfiguration.getComponentDescription().getModuleDescription().getDistinctName(), componentConfiguration.getComponentName()));
}
});
}
}
@Override
protected ViewConfigurator getSessionBeanObjectViewConfigurator() {
return StatefulSessionBeanObjectViewConfigurator.INSTANCE;
}
private void addViewSerializationInterceptor(final ViewDescription view) {
view.setSerializable(true);
view.setUseWriteReplace(true);
view.getConfigurators().add(new ViewConfigurator() {
@Override
public void configure(final DeploymentPhaseContext context, final ComponentConfiguration componentConfiguration, final ViewDescription description, final ViewConfiguration configuration) throws DeploymentUnitProcessingException {
final DeploymentReflectionIndex index = context.getDeploymentUnit().getAttachment(org.jboss.as.server.deployment.Attachments.REFLECTION_INDEX);
ClassReflectionIndex classIndex = index.getClassIndex(WriteReplaceInterface.class);
for (Method method : (Collection<Method>)classIndex.getMethods()) {
configuration.addClientInterceptor(method, new StatefulWriteReplaceInterceptor.Factory(configuration.getViewServiceName().getCanonicalName()), InterceptorOrder.Client.WRITE_REPLACE);
}
}
});
}
public void addRemoveMethod(final MethodIdentifier removeMethod, final boolean retainIfException) {
if (removeMethod == null) {
throw EjbLogger.ROOT_LOGGER.removeMethodIsNull();
}
this.removeMethods.put(removeMethod, new StatefulRemoveMethod(removeMethod, retainIfException));
}
public Collection<StatefulRemoveMethod> getRemoveMethods() {
return this.removeMethods.values();
}
public StatefulTimeoutInfo getStatefulTimeout() {
return statefulTimeout;
}
public void setStatefulTimeout(final StatefulTimeoutInfo statefulTimeout) {
this.statefulTimeout = statefulTimeout;
}
private void addStatefulInstanceAssociatingInterceptor(final EJBViewDescription view) {
view.getConfigurators().add(new ViewConfigurator() {
@Override
public void configure(final DeploymentPhaseContext context, final ComponentConfiguration componentConfiguration, ViewDescription description, ViewConfiguration viewConfiguration) throws DeploymentUnitProcessingException {
EJBViewDescription ejbViewDescription = (EJBViewDescription) view;
//if this is a home interface we add a different interceptor
if (ejbViewDescription.getMethodIntf() == MethodInterfaceType.Home || ejbViewDescription.getMethodIntf() == MethodInterfaceType.LocalHome) {
for (Method method : viewConfiguration.getProxyFactory().getCachedMethods()) {
if ((method.getName().equals("hashCode") && method.getParameterCount() == 0) ||
method.getName().equals("equals") && method.getParameterCount() == 1 &&
method.getParameterTypes()[0] == Object.class) {
viewConfiguration.addClientInterceptor(method, ComponentTypeIdentityInterceptorFactory.INSTANCE, InterceptorOrder.Client.EJB_EQUALS_HASHCODE);
}
}
} else {
// interceptor factory return an interceptor which sets up the session id on component view instance creation
final InterceptorFactory sessionIdGeneratingInterceptorFactory = StatefulComponentSessionIdGeneratingInterceptor.FACTORY;
// add the session id generating interceptor to the start of the *post-construct interceptor chain of the ComponentViewInstance*
viewConfiguration.addClientPostConstructInterceptor(sessionIdGeneratingInterceptorFactory, InterceptorOrder.ClientPostConstruct.INSTANCE_CREATE);
for (Method method : viewConfiguration.getProxyFactory().getCachedMethods()) {
if ((method.getName().equals("hashCode") && method.getParameterCount() == 0) ||
method.getName().equals("equals") && method.getParameterCount() == 1 &&
method.getParameterTypes()[0] == Object.class) {
viewConfiguration.addClientInterceptor(method, StatefulIdentityInterceptor.FACTORY, InterceptorOrder.Client.EJB_EQUALS_HASHCODE);
}
}
}
}
});
if (view.getMethodIntf() != MethodInterfaceType.LocalHome && view.getMethodIntf() != MethodInterfaceType.Home) {
view.getConfigurators().add(new ViewConfigurator() {
@Override
public void configure(DeploymentPhaseContext context, ComponentConfiguration componentConfiguration, ViewDescription description, ViewConfiguration configuration) throws DeploymentUnitProcessingException {
// add the instance associating interceptor to the *start of the invocation interceptor chain*
configuration.addViewInterceptor(StatefulComponentInstanceInterceptor.FACTORY, InterceptorOrder.View.ASSOCIATING_INTERCEPTOR);
}
});
}
}
private void addRemoveMethodInterceptor(final ViewDescription view) {
view.getConfigurators().add(new ViewConfigurator() {
@Override
public void configure(DeploymentPhaseContext context, ComponentConfiguration componentConfiguration, ViewDescription description, ViewConfiguration configuration) throws DeploymentUnitProcessingException {
final StatefulComponentDescription statefulComponentDescription = (StatefulComponentDescription) componentConfiguration.getComponentDescription();
final Collection<StatefulRemoveMethod> removeMethods = statefulComponentDescription.getRemoveMethods();
if (removeMethods.isEmpty()) {
return;
}
for (final Method viewMethod : configuration.getProxyFactory().getCachedMethods()) {
final MethodIdentifier viewMethodIdentifier = MethodIdentifier.getIdentifierForMethod(viewMethod);
for (final StatefulRemoveMethod removeMethod : removeMethods) {
if (removeMethod.methodIdentifier.equals(viewMethodIdentifier)) {
//we do not want to add this if it is the Ejb(Local)Object.remove() method, as that is handed elsewhere
final boolean object = EJBObject.class.isAssignableFrom(configuration.getViewClass()) || EJBLocalObject.class.isAssignableFrom(configuration.getViewClass());
if (!object || !viewMethodIdentifier.getName().equals("remove") || viewMethodIdentifier.getParameterTypes().length != 0) {
configuration.addViewInterceptor(viewMethod, new ImmediateInterceptorFactory(new StatefulRemoveInterceptor(removeMethod.retainIfException)), InterceptorOrder.View.SESSION_REMOVE_INTERCEPTOR);
}
break;
}
}
}
}
});
}
public void addInitMethod(final Method method, final String createMethod) {
initMethods.put(method, createMethod);
}
public Map<Method, String> getInitMethods() {
return Collections.unmodifiableMap(initMethods);
}
public CacheInfo getCache() {
return this.cache;
}
public void setCache(CacheInfo cache) {
this.cache = cache;
}
@Override
public boolean isPassivationApplicable() {
return this.passivationApplicable;
}
public void setPassivationApplicable(final boolean passivationApplicable) {
this.passivationApplicable = passivationApplicable;
}
/**
* EJB 3.2 spec allows the {@link jakarta.ejb.TimerService} to be injected/looked up/accessed from the stateful bean so as to allow access to the {@link jakarta.ejb.TimerService#getAllTimers()}
* method from a stateful bean. Hence we make {@link jakarta.ejb.TimerService} applicable for stateful beans too. However, we return <code>false</code> in {@link #isTimerServiceRequired()} so that a {@link org.jboss.as.ejb3.timerservice.NonFunctionalTimerService}
* is made available for the stateful bean. The {@link org.jboss.as.ejb3.timerservice.NonFunctionalTimerService} only allows access to {@link jakarta.ejb.TimerService#getAllTimers()} and {@link jakarta.ejb.TimerService#getTimers()}
* methods and throws an {@link IllegalStateException} for all other methods on the {@link jakarta.ejb.TimerService} and that's exactly how we want it to behave for stateful beans
*
* @return
* @see {@link #isTimerServiceRequired()}
*/
@Override
public boolean isTimerServiceApplicable() {
return true;
}
/**
* Timeout methods and auto timer methods aren't applicable for stateful beans, hence we return false.
* @return
* @see {@link #isTimerServiceApplicable()}
*/
@Override
public boolean isTimerServiceRequired() {
return false;
}
public ServiceName getDeploymentUnitServiceName() {
return this.deploymentUnitServiceName;
}
public ServiceName getCacheFactoryServiceName() {
return this.getServiceName().append("cache");
}
}
| 25,086 | 53.183585 | 304 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/StatefulSessionBeanClassTableContributor.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, 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.ejb3.component.stateful;
import java.io.Serializable;
import java.util.List;
import java.util.UUID;
import jakarta.ejb.EJBHome;
import jakarta.ejb.EJBMetaData;
import jakarta.ejb.EJBObject;
import jakarta.ejb.Handle;
import jakarta.ejb.HomeHandle;
import jakarta.ejb.SessionContext;
import jakarta.ejb.Timer;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.transaction.UserTransaction;
import org.jboss.as.ee.component.BasicComponentInstance;
import org.jboss.as.ejb3.component.EjbComponentInstance;
import org.jboss.as.ejb3.component.session.SessionBeanComponentInstance;
import org.jboss.as.naming.ImmediateManagedReference;
import org.jboss.as.naming.ManagedReference;
import org.jboss.as.naming.ValueManagedReferenceFactory;
import org.jboss.ejb.client.SessionID;
import org.kohsuke.MetaInfServices;
import org.wildfly.clustering.marshalling.jboss.ClassTableContributor;
/**
* Contributes to the JBoss Marshalling class table used when marshalling stateful session bean instances.
* @author Paul Ferraro
*/
@MetaInfServices(ClassTableContributor.class)
public class StatefulSessionBeanClassTableContributor implements ClassTableContributor {
@Override
public List<Class<?>> getKnownClasses() {
return List.of(
SessionContext.class,
UserTransaction.class,
EntityManager.class,
EntityManagerFactory.class,
Timer.class,
SessionID.class,
SessionID.Serialized.class,
EJBHome.class,
EJBObject.class,
Handle.class,
HomeHandle.class,
EJBMetaData.class,
UUID.class,
StatefulSessionComponentInstance.class,
SessionBeanComponentInstance.class,
EjbComponentInstance.class,
BasicComponentInstance.class,
Serializable.class,
StatefulSerializedProxy.class,
ManagedReference.class,
ValueManagedReferenceFactory.ValueManagedReference.class,
SerializedCdiInterceptorsKey.class,
SerializedStatefulSessionComponent.class,
ImmediateManagedReference.class);
}
}
| 3,359 | 38.069767 | 106 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/SerializedCdiInterceptorsKey.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.ejb3.component.stateful;
/**
* @author Stuart Douglas
*/
public class SerializedCdiInterceptorsKey {
private SerializedCdiInterceptorsKey() {
}
}
| 1,204 | 34.441176 | 70 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/StatefulComponentInstanceInterceptor.java | /*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, 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.ejb3.component.stateful;
import static org.jboss.as.ejb3.logging.EjbLogger.ROOT_LOGGER;
import jakarta.transaction.TransactionSynchronizationRegistry;
import org.jboss.as.ee.component.ComponentInstance;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.ejb3.component.interceptors.AbstractEJBInterceptor;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBean;
import org.jboss.ejb.client.SessionID;
import org.jboss.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
/**
* Associate the proper component instance to the invocation based on the passed in session identifier.
*
* @author <a href="mailto:[email protected]">Carlo de Wolf</a>
*/
public class StatefulComponentInstanceInterceptor extends AbstractEJBInterceptor {
public static final InterceptorFactory FACTORY = new ImmediateInterceptorFactory(new StatefulComponentInstanceInterceptor());
private static final Object STATEFUL_BEAN_KEY = StatefulSessionBean.class;
@Override
public Object processInvocation(InterceptorContext context) throws Exception {
StatefulSessionComponent component = getComponent(context, StatefulSessionComponent.class);
// TODO: this is a contract with the client interceptor
SessionID sessionId = context.getPrivateData(SessionID.class);
if (sessionId == null) {
throw EjbLogger.ROOT_LOGGER.statefulSessionIdIsNull(component.getComponentName());
}
TransactionSynchronizationRegistry tsr = component.getTransactionSynchronizationRegistry();
// Use bean associated with current tx, if one exists
@SuppressWarnings({ "resource", "unchecked" })
StatefulSessionBean<SessionID, StatefulSessionComponentInstance> bean = (tsr.getTransactionKey() != null) ? (StatefulSessionBean<SessionID, StatefulSessionComponentInstance>) tsr.getResource(sessionId) : null;
if (bean == null) {
ROOT_LOGGER.debugf("Looking for stateful component instance with session id: %s", sessionId);
bean = component.getCache().findStatefulSessionBean(sessionId);
}
if (bean == null) {
//This exception will be transformed into the correct exception type by the exception transforming interceptor
throw EjbLogger.ROOT_LOGGER.couldNotFindEjb(sessionId.toString());
}
try {
context.putPrivateData(StatefulSessionBean.class, bean);
context.putPrivateData(ComponentInstance.class, bean.getInstance());
return context.proceed();
} catch (Exception ex) {
if (component.shouldDiscard(ex, context.getMethod())) {
ROOT_LOGGER.tracef(ex, "Removing bean %s because of exception", sessionId);
bean.discard();
}
throw ex;
} catch (Error e) {
ROOT_LOGGER.tracef(e, "Removing bean %s because of error", sessionId);
bean.discard();
throw e;
} catch (Throwable t) {
ROOT_LOGGER.tracef(t, "Removing bean %s because of Throwable", sessionId);
bean.discard();
throw new RuntimeException(t);
}
}
@SuppressWarnings("unchecked")
static StatefulSessionBean<SessionID, StatefulSessionComponentInstance> getBean(InterceptorContext context) {
return (StatefulSessionBean<SessionID, StatefulSessionComponentInstance>) context.getPrivateData(STATEFUL_BEAN_KEY);
}
}
| 4,585 | 48.311828 | 217 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/CurrentSynchronizationCallback.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.ejb3.component.stateful;
/**
* Thread local that tracks the current state of SFSB synchronization callbacks
*
* @author Stuart Douglas
*/
public class CurrentSynchronizationCallback {
public enum CallbackType {
AFTER_BEGIN,
AFTER_COMPLETION,
BEFORE_COMPLETION
}
private static final ThreadLocal<CallbackType> type = new ThreadLocal<CallbackType>();
public static CallbackType get() {
return type.get();
}
public static void set(CallbackType callback) {
type.set(callback);
}
public static void clear() {
//set to null instead of removing to prevent thread local entry churn
type.set(null);
}
}
| 1,742 | 31.277778 | 90 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/StatefulAllowedMethodsInformation.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.ejb3.component.stateful;
import java.util.Set;
import org.jboss.as.ee.component.interceptors.InvocationType;
import org.jboss.as.ejb3.component.allowedmethods.DeniedMethodKey;
import org.jboss.as.ejb3.component.allowedmethods.MethodType;
import org.jboss.as.ejb3.component.session.SessionBeanAllowedMethodsInformation;
/**
* @author Stuart Douglas
*/
public class StatefulAllowedMethodsInformation extends SessionBeanAllowedMethodsInformation {
public static final StatefulAllowedMethodsInformation INSTANCE_BMT = new StatefulAllowedMethodsInformation(true);
public static final StatefulAllowedMethodsInformation INSTANCE_CMT = new StatefulAllowedMethodsInformation(false);
protected StatefulAllowedMethodsInformation(boolean beanManagedTransaction) {
super(beanManagedTransaction);
}
@Override
protected void setup(Set<DeniedMethodKey> denied) {
super.setup(denied);
add(denied, InvocationType.POST_CONSTRUCT, MethodType.TIMER_SERVICE_METHOD);
add(denied, InvocationType.PRE_DESTROY, MethodType.TIMER_SERVICE_METHOD);
add(denied, InvocationType.SFSB_INIT_METHOD, MethodType.TIMER_SERVICE_METHOD);
add(denied, InvocationType.DEPENDENCY_INJECTION, MethodType.TIMER_SERVICE_METHOD);
}
}
| 2,315 | 41.888889 | 118 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/StatefulInitMethodInterceptor.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.ejb3.component.stateful;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import jakarta.ejb.CreateException;
import org.jboss.as.ee.component.interceptors.InvocationType;
import org.jboss.as.ejb3.component.interceptors.EjbExceptionTransformingInterceptorFactories;
import org.jboss.as.ejb3.component.interceptors.SessionBeanHomeInterceptorFactory;
import org.jboss.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
import org.jboss.invocation.Interceptors;
/**
* Interceptor factory for SFSB's that invokes the ejbCreate method. This interceptor
* is only used when a component is created via a home interface method.
*
* @author Stuart Douglas
*/
public class StatefulInitMethodInterceptor implements Interceptor {
public static final InterceptorFactory INSTANCE = new ImmediateInterceptorFactory(new StatefulInitMethodInterceptor());
private StatefulInitMethodInterceptor() {
}
@Override
public Object processInvocation(final InterceptorContext context) throws Exception {
final Method method = SessionBeanHomeInterceptorFactory.INIT_METHOD.get();
final Object[] params = SessionBeanHomeInterceptorFactory.INIT_PARAMETERS.get();
//we remove them immediately, so they are not set for the rest of the invocation
//TODO: find a better way to handle this
SessionBeanHomeInterceptorFactory.INIT_METHOD.remove();
SessionBeanHomeInterceptorFactory.INIT_PARAMETERS.remove();
if (method != null) {
final InvocationType invocationType = context.getPrivateData(InvocationType.class);
try {
context.putPrivateData(InvocationType.class, InvocationType.SFSB_INIT_METHOD);
method.invoke(context.getTarget(), params);
} catch (InvocationTargetException e) {
if (CreateException.class.isAssignableFrom(e.getCause().getClass())) {
EjbExceptionTransformingInterceptorFactories.setCreateException((CreateException) e.getCause());
}
throw Interceptors.rethrow(e.getCause());
} finally {
context.putPrivateData(InvocationType.class, invocationType);
}
}
return context.proceed();
}
}
| 3,454 | 41.654321 | 123 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/StatefulWriteReplaceInterceptor.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, 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.ejb3.component.stateful;
import org.jboss.ejb.client.SessionID;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
import org.jboss.invocation.InterceptorFactoryContext;
/**
* Interceptor that handles the writeReplace method for a SFSB
*
* @author Stuart Douglas
*/
public class StatefulWriteReplaceInterceptor implements Interceptor {
private final String serviceName;
public StatefulWriteReplaceInterceptor(final String serviceName) {
this.serviceName = serviceName;
}
@Override
public Object processInvocation(final InterceptorContext context) throws Exception {
SessionID sessionId = context.getPrivateData(SessionID.class);
return new StatefulSerializedProxy(serviceName, sessionId);
}
public static class Factory implements InterceptorFactory {
private final StatefulWriteReplaceInterceptor interceptor;
public Factory(final String serviceName) {
interceptor = new StatefulWriteReplaceInterceptor(serviceName);
}
@Override
public Interceptor create(final InterceptorFactoryContext context) {
return interceptor;
}
}
}
| 2,295 | 35.444444 | 88 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/StatefulSessionBeanSerializabilityChecker.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.ejb3.component.stateful;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.Set;
import org.jboss.as.ejb3.component.EJBComponent;
import org.jboss.as.ejb3.deployment.EjbDeploymentInformation;
import org.jboss.as.ejb3.deployment.ModuleDeployment;
import org.jboss.marshalling.SerializabilityChecker;
/**
* @author Paul Ferraro
*/
public class StatefulSessionBeanSerializabilityChecker implements SerializabilityChecker {
private final Set<Class<?>> serializableClasses = Collections.newSetFromMap(new IdentityHashMap<Class<?>, Boolean>());
public StatefulSessionBeanSerializabilityChecker(ModuleDeployment deployment) {
// Find component classes of any stateful components and any superclasses
for (EjbDeploymentInformation info: deployment.getEjbs().values()) {
EJBComponent component = info.getEjbComponent();
if (component instanceof StatefulSessionComponent) {
Class<?> componentClass = component.getComponentClass();
while (componentClass != Object.class) {
this.serializableClasses.add(componentClass);
componentClass = componentClass.getSuperclass();
}
}
}
}
@Override
public boolean isSerializable(Class<?> targetClass) {
return (targetClass != Object.class) && (this.serializableClasses.contains(targetClass) || DEFAULT.isSerializable(targetClass));
}
}
| 2,525 | 41.1 | 136 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/StatefulRemoveInterceptor.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, 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.ejb3.component.stateful;
import java.lang.reflect.Method;
import org.jboss.as.ee.component.Component;
import org.jboss.as.ee.component.ComponentView;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.ejb3.component.EJBComponent;
import org.jboss.as.ejb3.component.Ejb2xViewType;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBean;
import org.jboss.ejb.client.SessionID;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
/**
* An interceptor which handles an invocation on a {@link jakarta.ejb.Remove} method of a stateful session bean. This interceptor
* removes the stateful session once the method completes (either successfully or with an exception). If the remove method
* was marked with "retainIfException" to true and if the remove method threw a {@link jakarta.ejb.ApplicationException} then
* this interceptor does *not* remove the stateful session.
* <p/>
* User: Jaikiran Pai
*/
public class StatefulRemoveInterceptor implements Interceptor {
private final boolean retainIfException;
public StatefulRemoveInterceptor(final boolean retainIfException) {
this.retainIfException = retainIfException;
}
@Override
public Object processInvocation(InterceptorContext context) throws Exception {
final EJBComponent component = (EJBComponent) context.getPrivateData(Component.class);
//if a session bean is participating in a transaction, it
//is an error for a client to invoke the remove method
//on the session object's home or component interface.
final ComponentView view = context.getPrivateData(ComponentView.class);
if (view != null) {
Ejb2xViewType viewType = view.getPrivateData(Ejb2xViewType.class);
if (viewType != null) {
//this means it is an Enterprise Beans 2.x view
//which is not allowed to remove while enrolled in a TX
final StatefulTransactionMarker marker = context.getPrivateData(StatefulTransactionMarker.class);
if (marker != null && !marker.isFirstInvocation()) {
throw EjbLogger.ROOT_LOGGER.cannotRemoveWhileParticipatingInTransaction();
}
}
}
// just log a WARN and throw back the original exception
if (component instanceof StatefulSessionComponent == false) {
throw EjbLogger.ROOT_LOGGER.unexpectedComponent(component, StatefulSessionComponent.class);
}
Object invocationResult = null;
try {
// proceed
invocationResult = context.proceed();
} catch (Exception e) {
// Exception caught during call to @Remove method. Handle it appropriately
// If it's an application exception and if the @Remove method has set "retainIfException" to true
// then just throw back the exception and don't remove the session instance.
if (isApplicationException(component, e.getClass(), context.getMethod()) && this.retainIfException) {
throw e;
}
// otherwise, just remove it and throw back the original exception
remove(context);
throw e;
}
// just remove the session because of a call to @Remove method
remove(context);
// return the invocation result
return invocationResult;
}
private static void remove(InterceptorContext context) {
StatefulSessionBean<SessionID, StatefulSessionComponentInstance> bean = StatefulComponentInstanceInterceptor.getBean(context);
if (bean.isClosed()) {
// Bean may have been closed by a previous interceptor
// If so, look it up again
StatefulSessionComponent component = (StatefulSessionComponent) context.getPrivateData(Component.class);
SessionID id = context.getPrivateData(SessionID.class);
bean = component.getCache().findStatefulSessionBean(id);
}
if (bean != null) {
bean.remove();
}
}
/**
* Returns true if the passed <code>exceptionClass</code> is an application exception. Else returns false.
*
* @param ejbComponent The EJB component
* @param exceptionClass The exception class
* @return
*/
private static boolean isApplicationException(final EJBComponent ejbComponent, final Class<?> exceptionClass, final Method invokedMethod) {
return ejbComponent.getApplicationException(exceptionClass, invokedMethod) != null;
}
}
| 5,644 | 44.894309 | 143 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/StatefulSessionComponentInstance.java | /*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, 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.ejb3.component.stateful;
import java.io.ObjectStreamException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import jakarta.ejb.EJBException;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionSynchronizationRegistry;
import org.jboss.as.ee.component.Component;
import org.jboss.as.ee.component.ComponentInstance;
import org.jboss.as.ejb3.component.InvokeMethodOnTargetInterceptor;
import org.jboss.as.ejb3.component.session.SessionBeanComponentInstance;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanInstance;
import org.jboss.as.ejb3.tx.OwnableReentrantLock;
import org.jboss.as.naming.ManagedReference;
import org.jboss.ejb.client.SessionID;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.wildfly.transaction.client.AbstractTransaction;
import org.wildfly.transaction.client.ContextTransactionManager;
/**
* @author <a href="mailto:[email protected]">Carlo de Wolf</a>
*/
public class StatefulSessionComponentInstance extends SessionBeanComponentInstance implements StatefulSessionBeanInstance<SessionID> {
private static final long serialVersionUID = 3803978357389448971L;
private final SessionID id;
private final Interceptor afterBegin;
private final Interceptor afterCompletion;
private final Interceptor beforeCompletion;
private final Interceptor prePassivate;
private final Interceptor postActivate;
private final Interceptor ejb2XRemoveInterceptor;
/**
* If this is a BMT bean this stores the active transaction
*/
private volatile Transaction transaction;
/**
* The transaction lock for the stateful bean
*/
private final OwnableReentrantLock lock = new OwnableReentrantLock();
/**
* The thread based lock for the stateful bean
*/
private final Object threadLock = new Object();
/**
* State that is used to defer afterCompletion invocation if an invocation is currently in progress.
*
* States:
* 0 = No invocation in progress
* 1 = Invocation in progress
* 2 = Invocation in progress, afterCompletion delayed
*
*/
private final AtomicInteger invocationSyncState = new AtomicInteger();
public static final int SYNC_STATE_NO_INVOCATION = 0;
public static final int SYNC_STATE_INVOCATION_IN_PROGRESS = 1;
public static final int SYNC_STATE_AFTER_COMPLETE_DELAYED_NO_COMMIT = 2;
public static final int SYNC_STATE_AFTER_COMPLETE_DELAYED_COMMITTED = 3;
Object getThreadLock() {
return threadLock;
}
OwnableReentrantLock getLock() {
return lock;
}
AtomicInteger getInvocationSyncState() {
return invocationSyncState;
}
/**
* Construct a new instance.
*
* @param component the component
*/
protected StatefulSessionComponentInstance(final StatefulSessionComponent component, final Interceptor preDestroyInterceptor, final Map<Method, Interceptor> methodInterceptors, final Map<Object, Object> context) {
super(component, preDestroyInterceptor, methodInterceptors);
final SessionID existingSession = (SessionID) context.get(SessionID.class);
this.id = (existingSession != null) ? existingSession : component.getCache().getIdentifierFactory().get();
this.afterBegin = component.getAfterBegin();
this.afterCompletion = component.getAfterCompletion();
this.beforeCompletion = component.getBeforeCompletion();
this.prePassivate = component.getPrePassivate();
this.postActivate = component.getPostActivate();
this.ejb2XRemoveInterceptor = component.getEjb2XRemoveMethod();
}
protected void afterBegin() {
CurrentSynchronizationCallback.set(CurrentSynchronizationCallback.CallbackType.AFTER_BEGIN);
try {
execute(afterBegin, getComponent().getAfterBeginMethod());
} finally {
CurrentSynchronizationCallback.clear();
}
}
protected void afterCompletion(boolean committed) {
CurrentSynchronizationCallback.set(CurrentSynchronizationCallback.CallbackType.AFTER_COMPLETION);
try {
execute(afterCompletion, getComponent().getAfterCompletionMethod(), committed);
} finally {
CurrentSynchronizationCallback.clear();
}
}
protected void beforeCompletion() {
CurrentSynchronizationCallback.set(CurrentSynchronizationCallback.CallbackType.BEFORE_COMPLETION);
try {
execute(beforeCompletion, getComponent().getBeforeCompletionMethod());
} finally {
CurrentSynchronizationCallback.clear();
}
}
@Override
public void prePassivate() {
this.execute(prePassivate, null);
}
@Override
public void postActivate() {
this.execute(postActivate, null);
}
private Object execute(final Interceptor interceptor, final Method method, final Object... parameters) {
if (interceptor == null)
return null;
final InterceptorContext interceptorContext = new InterceptorContext();
//we need the method so this does not count as a lifecycle invocation
interceptorContext.setMethod(method);
interceptorContext.putPrivateData(Component.class, getComponent());
interceptorContext.putPrivateData(ComponentInstance.class, this);
interceptorContext.putPrivateData(InvokeMethodOnTargetInterceptor.PARAMETERS_KEY, parameters);
interceptorContext.setContextData(new HashMap<String, Object>());
interceptorContext.setTarget(getInstance());
final AbstractTransaction transaction = ContextTransactionManager.getInstance().getTransaction();
interceptorContext.setTransactionSupplier(() -> transaction);
try {
return interceptor.processInvocation(interceptorContext);
} catch (Error e) {
throw e;
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new EJBException(e);
}
}
@Override
public StatefulSessionComponent getComponent() {
return (StatefulSessionComponent) super.getComponent();
}
@Override
public SessionID getId() {
return this.id;
}
public Interceptor getEjb2XRemoveInterceptor() {
return ejb2XRemoveInterceptor;
}
@Override
public String toString() {
return " Instance of " + getComponent().getComponentName() + " {" + id + "}";
}
public Object writeReplace() throws ObjectStreamException {
Set<Object> keys = getComponent().getSerialiableInterceptorContextKeys();
final Map<Object, Object> serializableInterceptors = new HashMap<Object, Object>();
for(Object key : keys) {
serializableInterceptors.put(key, getInstanceData(key));
}
return new SerializedStatefulSessionComponent((ManagedReference)getInstanceData(INSTANCE_KEY), id, getComponent().getCreateServiceName().getCanonicalName(), serializableInterceptors);
}
public Transaction getTransaction() {
return transaction;
}
public void setTransaction(Transaction transaction) {
this.transaction = transaction;
}
@Override
public void removed() {
TransactionSynchronizationRegistry tsr = this.getComponent().getTransactionSynchronizationRegistry();
// Trigger preDestroy callback, but only if bean is not associated with a current tx
// Otherwise, bean destroy is deferred until tx commit
if ((tsr.getTransactionKey() == null) || (tsr.getResource(this.id) == null)) {
this.destroy();
}
}
}
| 8,876 | 37.595652 | 217 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/StatefulSessionComponent.java | /*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, 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.ejb3.component.stateful;
import java.lang.reflect.Method;
import java.rmi.RemoteException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;
import jakarta.ejb.ConcurrentAccessException;
import jakarta.ejb.ConcurrentAccessTimeoutException;
import jakarta.ejb.EJBException;
import jakarta.ejb.EJBLocalObject;
import jakarta.ejb.EJBObject;
import jakarta.ejb.RemoveException;
import org.jboss.as.ee.component.BasicComponentInstance;
import org.jboss.as.ee.component.ComponentInstance;
import org.jboss.as.ee.component.ComponentIsStoppedException;
import org.jboss.as.ee.component.ComponentView;
import org.jboss.as.ejb3.component.DefaultAccessTimeoutService;
import org.jboss.as.ejb3.component.EJBBusinessMethod;
import org.jboss.as.ejb3.component.EJBComponentUnavailableException;
import org.jboss.as.ejb3.component.allowedmethods.AllowedMethodsInformation;
import org.jboss.as.ejb3.component.session.SessionBeanComponent;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanCache;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanCacheConfiguration;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanCacheFactory;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanInstanceFactory;
import org.jboss.as.ejb3.concurrency.AccessTimeoutDetails;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.naming.ManagedReference;
import org.jboss.as.server.CurrentServiceContainer;
import org.jboss.ejb.client.EJBClient;
import org.jboss.ejb.client.SessionID;
import org.jboss.ejb.client.StatefulEJBLocator;
import org.jboss.ejb.client.UUIDSessionID;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
import org.jboss.invocation.InterceptorFactoryContext;
import org.jboss.msc.service.ServiceContainer;
import org.jboss.msc.service.ServiceController;
import org.wildfly.extension.requestcontroller.ControlPoint;
import org.wildfly.extension.requestcontroller.RunResult;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* Stateful Session Bean
*
* @author <a href="mailto:[email protected]">Carlo de Wolf</a>
*/
public class StatefulSessionComponent extends SessionBeanComponent implements StatefulSessionBeanInstanceFactory<StatefulSessionComponentInstance> {
enum IdentifierFactory implements Supplier<SessionID> {
UUID() {
@Override
public SessionID get() {
return new UUIDSessionID(java.util.UUID.randomUUID());
}
};
}
private volatile StatefulSessionBeanCache<SessionID, StatefulSessionComponentInstance> cache;
private final InterceptorFactory afterBegin;
private Interceptor afterBeginInterceptor;
private final Method afterBeginMethod;
private final InterceptorFactory afterCompletion;
private Interceptor afterCompletionInterceptor;
private final Method afterCompletionMethod;
private final InterceptorFactory beforeCompletion;
private Interceptor beforeCompletionInterceptor;
private final Method beforeCompletionMethod;
private final InterceptorFactory prePassivate;
private Interceptor prePassivateInterceptor;
private final InterceptorFactory postActivate;
private Interceptor postActivateInterceptor;
private final Map<EJBBusinessMethod, AccessTimeoutDetails> methodAccessTimeouts;
private final DefaultAccessTimeoutService defaultAccessTimeoutProvider;
private final Supplier<StatefulSessionBeanCacheFactory<SessionID, StatefulSessionComponentInstance>> cacheFactory;
private final InterceptorFactory ejb2XRemoveMethod;
private Interceptor ejb2XRemoveMethodInterceptor;
/**
* Set of context keys for serializable interceptors.
* <p/>
* These are used to serialize the user provided interceptors
*/
private final Set<Object> serialiableInterceptorContextKeys;
/**
* Construct a new instance.
*
* @param ejbComponentCreateService the component configuration
*/
protected StatefulSessionComponent(final StatefulSessionComponentCreateService ejbComponentCreateService) {
super(ejbComponentCreateService);
ejbComponentCreateService.setDefaultStatefulSessionTimeout();
this.afterBegin = ejbComponentCreateService.getAfterBegin();
this.afterBeginMethod = ejbComponentCreateService.getAfterBeginMethod();
this.afterCompletion = ejbComponentCreateService.getAfterCompletion();
this.afterCompletionMethod = ejbComponentCreateService.getAfterCompletionMethod();
this.beforeCompletion = ejbComponentCreateService.getBeforeCompletion();
this.beforeCompletionMethod = ejbComponentCreateService.getBeforeCompletionMethod();
this.prePassivate = ejbComponentCreateService.getPrePassivate();
this.postActivate = ejbComponentCreateService.getPostActivate();
this.methodAccessTimeouts = ejbComponentCreateService.getMethodApplicableAccessTimeouts();
this.defaultAccessTimeoutProvider = ejbComponentCreateService.getDefaultAccessTimeoutService();
this.ejb2XRemoveMethod = ejbComponentCreateService.getEjb2XRemoveMethod();
this.serialiableInterceptorContextKeys = ejbComponentCreateService.getSerializableInterceptorContextKeys();
this.cacheFactory = ejbComponentCreateService.getCacheFactory();
}
@Override
public StatefulSessionComponentInstance createInstance() {
return (StatefulSessionComponentInstance) super.createInstance();
}
@Override
public StatefulSessionComponentInstance createInstance(final Object instance) {
return (StatefulSessionComponentInstance) super.createInstance();
}
@Override
protected StatefulSessionComponentInstance constructComponentInstance(ManagedReference instance, boolean invokePostConstruct) {
return (StatefulSessionComponentInstance) super.constructComponentInstance(instance, invokePostConstruct);
}
@Override
protected StatefulSessionComponentInstance constructComponentInstance(ManagedReference instance, boolean invokePostConstruct, Map<Object, Object> context) {
return (StatefulSessionComponentInstance) super.constructComponentInstance(instance, invokePostConstruct, context);
}
protected SessionID getSessionIdOf(final InterceptorContext ctx) {
final StatefulSessionComponentInstance instance = (StatefulSessionComponentInstance) ctx.getPrivateData(ComponentInstance.class);
return instance.getId();
}
@Override
public <T> T getBusinessObject(Class<T> businessInterface, final InterceptorContext context) throws IllegalStateException {
if (businessInterface == null) {
throw EjbLogger.ROOT_LOGGER.businessInterfaceIsNull();
}
return createViewInstanceProxy(businessInterface, Collections.<Object, Object>singletonMap(SessionID.class, getSessionIdOf(context)));
}
@Override
public EJBLocalObject getEJBLocalObject(final InterceptorContext ctx) throws IllegalStateException {
if (getEjbLocalObjectViewServiceName() == null) {
throw EjbLogger.ROOT_LOGGER.ejbLocalObjectUnavailable(getComponentName());
}
return createViewInstanceProxy(EJBLocalObject.class, Collections.<Object, Object>singletonMap(SessionID.class, getSessionIdOf(ctx)), getEjbLocalObjectViewServiceName());
}
@SuppressWarnings("unchecked")
@Override
public EJBObject getEJBObject(final InterceptorContext ctx) throws IllegalStateException {
if (getEjbObjectViewServiceName() == null) {
throw EjbLogger.ROOT_LOGGER.beanComponentMissingEjbObject(getComponentName(), "EJBObject");
}
final ServiceController<?> serviceController = currentServiceContainer().getRequiredService(getEjbObjectViewServiceName());
final ComponentView view = (ComponentView) serviceController.getValue();
final String locatorAppName = getEarApplicationName() == null ? "" : getEarApplicationName();
if(WildFlySecurityManager.isChecking()) {
//need to use doPrivileged rather than doUnchecked, as this can run user code in the proxy constructor
return AccessController.doPrivileged(new PrivilegedAction<EJBObject>() {
@Override
public EJBObject run() {
return EJBClient.createProxy(new StatefulEJBLocator<EJBObject>((Class<EJBObject>) view.getViewClass(), locatorAppName, getModuleName(), getComponentName(), getDistinctName(), getSessionIdOf(ctx), getCache().getStrongAffinity()));
}
});
} else {
return EJBClient.createProxy(new StatefulEJBLocator<EJBObject>((Class<EJBObject>) view.getViewClass(), locatorAppName, getModuleName(), getComponentName(), getDistinctName(), getSessionIdOf(ctx), this.getCache().getStrongAffinity()));
}
}
/**
* Returns the {@link jakarta.ejb.AccessTimeout} applicable to given method
*/
public AccessTimeoutDetails getAccessTimeout(Method method) {
final EJBBusinessMethod ejbMethod = new EJBBusinessMethod(method);
final AccessTimeoutDetails accessTimeout = this.methodAccessTimeouts.get(ejbMethod);
if (accessTimeout != null) {
return accessTimeout;
}
// check bean level access timeout
final AccessTimeoutDetails timeout = this.beanLevelAccessTimeout.get(method.getDeclaringClass().getName());
if (timeout != null) {
return timeout;
}
return defaultAccessTimeoutProvider.getDefaultAccessTimeout();
}
public SessionID createSession() {
return this.cache.createStatefulSessionBean();
}
/**
* creates a session using the global request controller.
*
* This should only be used by callers that service remote requests (i.e. places that represent a remote entry point into the container)
* @return The session id
*/
public SessionID createSessionRemote() {
ControlPoint controlPoint = getControlPoint();
if(controlPoint == null) {
return createSession();
} else {
try {
RunResult result = controlPoint.beginRequest();
if (result == RunResult.REJECTED) {
throw EjbLogger.ROOT_LOGGER.containerSuspended();
}
try {
return createSession();
} finally {
controlPoint.requestComplete();
}
} catch (EJBComponentUnavailableException | ComponentIsStoppedException e) {
throw e;
} catch (Exception e) {
throw new EJBException(e);
}
}
}
public StatefulSessionBeanCache<SessionID, StatefulSessionComponentInstance> getCache() {
return this.cache;
}
@Override
protected BasicComponentInstance instantiateComponentInstance(final Interceptor preDestroyInterceptor, final Map<Method, Interceptor> methodInterceptors, Map<Object, Object> context) {
StatefulSessionComponentInstance instance = new StatefulSessionComponentInstance(this, preDestroyInterceptor, methodInterceptors, context);
for(Object key : serialiableInterceptorContextKeys) {
instance.setInstanceData(key, context.get(key));
}
instance.setInstanceData(BasicComponentInstance.INSTANCE_KEY, context.get(BasicComponentInstance.INSTANCE_KEY));
return instance;
}
public Interceptor getAfterBegin() {
return afterBeginInterceptor;
}
public Interceptor getAfterCompletion() {
return afterCompletionInterceptor;
}
public Interceptor getBeforeCompletion() {
return beforeCompletionInterceptor;
}
public Method getAfterBeginMethod() {
return afterBeginMethod;
}
public Method getAfterCompletionMethod() {
return afterCompletionMethod;
}
public Method getBeforeCompletionMethod() {
return beforeCompletionMethod;
}
public Interceptor getPrePassivate() {
return this.prePassivateInterceptor;
}
public Interceptor getPostActivate() {
return this.postActivateInterceptor;
}
public Interceptor getEjb2XRemoveMethod() {
return this.ejb2XRemoveMethodInterceptor;
}
@Override
public synchronized void init() {
super.init();
this.cache = this.cacheFactory.get().createStatefulBeanCache(new StatefulSessionBeanCacheConfiguration<>() {
@Override
public StatefulSessionBeanInstanceFactory<StatefulSessionComponentInstance> getInstanceFactory() {
return StatefulSessionComponent.this;
}
@Override
public Supplier<SessionID> getIdentifierFactory() {
return IdentifierFactory.UUID;
}
@Override
public Duration getTimeout() {
StatefulComponentDescription description = (StatefulComponentDescription) StatefulSessionComponent.this.getComponentDescription();
StatefulTimeoutInfo info = description.getStatefulTimeout();
return (info != null && info.getValue() >= 0) ? Duration.of(info.getValue(), info.getTimeUnit().toChronoUnit()) : null;
}
@Override
public String getComponentName() {
return StatefulSessionComponent.this.getComponentName();
}
});
this.cache.start();
}
@Override
protected void createInterceptors(InterceptorFactoryContext context) {
super.createInterceptors(context);
if(afterBegin != null) {
afterBeginInterceptor = afterBegin.create(context);
}
if(afterCompletion != null) {
afterCompletionInterceptor = afterCompletion.create(context);
}
if(beforeCompletion != null) {
beforeCompletionInterceptor = beforeCompletion.create(context);
}
if(prePassivate != null) {
prePassivateInterceptor = prePassivate.create(context);
}
if(postActivate != null) {
postActivateInterceptor = postActivate.create(context);
}
if(ejb2XRemoveMethod != null) {
ejb2XRemoveMethodInterceptor = ejb2XRemoveMethod.create(context);
}
}
@Override
public void done() {
this.cache.stop();
cache = null;
afterBeginInterceptor = null;
afterCompletionInterceptor = null;
beforeCompletionInterceptor = null;
prePassivateInterceptor = null;
postActivateInterceptor = null;
ejb2XRemoveMethodInterceptor = null;
super.done();
}
@Override
public AllowedMethodsInformation getAllowedMethodsInformation() {
return isBeanManagedTransaction() ? StatefulAllowedMethodsInformation.INSTANCE_BMT : StatefulAllowedMethodsInformation.INSTANCE_CMT;
}
public Set<Object> getSerialiableInterceptorContextKeys() {
return serialiableInterceptorContextKeys;
}
private static ServiceContainer currentServiceContainer() {
if(System.getSecurityManager() == null) {
return CurrentServiceContainer.getServiceContainer();
}
return AccessController.doPrivileged(CurrentServiceContainer.GET_ACTION);
}
@Override
public boolean isRemotable(Throwable throwable) {
return cache.isRemotable(throwable);
}
public boolean shouldDiscard(Exception ex, Method method) {
// Detect app exception
if (getApplicationException(ex.getClass(), method) != null // it's an application exception, just throw it back.
|| ex instanceof ConcurrentAccessTimeoutException
|| ex instanceof ConcurrentAccessException) {
return false;
}
return (!(ex instanceof RemoveException)
&& (ex instanceof RuntimeException || ex instanceof RemoteException));
}
}
| 17,316 | 41.652709 | 248 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/StatefulRemoteViewInstanceFactory.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.ejb3.component.stateful;
import java.util.Map;
import org.jboss.as.ee.component.ComponentView;
import org.jboss.as.ee.component.ViewInstanceFactory;
import org.jboss.as.naming.ManagedReference;
import org.jboss.as.naming.ValueManagedReference;
import org.jboss.ejb.client.Affinity;
import org.jboss.ejb.client.EJBClient;
import org.jboss.ejb.client.EJBIdentifier;
import org.jboss.ejb.client.SessionID;
import org.jboss.ejb.client.StatefulEJBLocator;
import org.jboss.ejb.client.StatelessEJBLocator;
/**
* @author Stuart Douglas
*/
public class StatefulRemoteViewInstanceFactory implements ViewInstanceFactory {
private final EJBIdentifier identifier;
public StatefulRemoteViewInstanceFactory(final String applicationName, final String moduleName, final String distinctName, final String beanName) {
this(new EJBIdentifier(applicationName == null ? "" : applicationName, moduleName, beanName, distinctName));
}
public StatefulRemoteViewInstanceFactory(final EJBIdentifier identifier) {
this.identifier = identifier;
}
@Override
public ManagedReference createViewInstance(final ComponentView componentView, final Map<Object, Object> contextData) throws Exception {
SessionID sessionID = (SessionID) contextData.get(SessionID.class);
final StatefulEJBLocator<?> statefulEJBLocator;
final StatefulSessionComponent statefulSessionComponent = (StatefulSessionComponent) componentView.getComponent();
if (sessionID == null) {
statefulEJBLocator = EJBClient.createSession(StatelessEJBLocator.create(componentView.getViewClass(), identifier, Affinity.LOCAL));
} else {
statefulEJBLocator = StatefulEJBLocator.create(componentView.getViewClass(), identifier, sessionID, statefulSessionComponent.getCache().getStrongAffinity());
}
final Object ejbProxy = EJBClient.createProxy(statefulEJBLocator);
return new ValueManagedReference(ejbProxy);
}
}
| 3,020 | 43.426471 | 169 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/StatefulSerializedProxy.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.ejb3.component.stateful;
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.security.AccessController;
import java.util.Collections;
import org.jboss.as.ee.component.ComponentView;
import org.jboss.as.server.CurrentServiceContainer;
import org.jboss.ejb.client.SessionID;
import org.jboss.msc.service.ServiceContainer;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
/**
* Serialized form of a SFSB
*
* @author Stuart Douglas
*/
public class StatefulSerializedProxy implements Serializable {
private static final long serialVersionUID = 627023970448688592L;
private final String viewName;
private final SessionID sessionID;
public StatefulSerializedProxy(final String viewName, final SessionID sessionID) {
this.viewName = viewName;
this.sessionID = sessionID;
}
public String getViewName() {
return this.viewName;
}
public SessionID getSessionID() {
return this.sessionID;
}
private Object readResolve() throws ObjectStreamException {
ServiceController<ComponentView> view = (ServiceController<ComponentView>) currentServiceContainer().getRequiredService(ServiceName.parse(viewName));
try {
return view.getValue().createInstance(Collections.<Object, Object>singletonMap(SessionID.class, sessionID)).getInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static ServiceContainer currentServiceContainer() {
if(System.getSecurityManager() == null) {
return CurrentServiceContainer.getServiceContainer();
}
return AccessController.doPrivileged(CurrentServiceContainer.GET_ACTION);
}
}
| 2,807 | 35.467532 | 157 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/StatefulSessionBeanObjectViewConfigurator.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.ejb3.component.stateful;
import java.lang.reflect.Method;
import org.jboss.as.ee.component.ComponentConfiguration;
import org.jboss.as.ee.component.ViewConfiguration;
import org.jboss.as.ee.component.ViewDescription;
import org.jboss.as.ee.component.interceptors.InterceptorOrder;
import org.jboss.as.ejb3.component.session.SessionBeanObjectViewConfigurator;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex;
/**
* @author Stuart Douglas
*/
public class StatefulSessionBeanObjectViewConfigurator extends SessionBeanObjectViewConfigurator {
public static final StatefulSessionBeanObjectViewConfigurator INSTANCE = new StatefulSessionBeanObjectViewConfigurator();
@Override
protected void handleIsIdenticalMethod(final ComponentConfiguration componentConfiguration, final ViewConfiguration configuration, final DeploymentReflectionIndex index, final Method method) {
configuration.addClientInterceptor(method, StatefulIdentityInterceptor.FACTORY, InterceptorOrder.Client.EJB_EQUALS_HASHCODE);
}
@Override
protected void handleRemoveMethod(final ComponentConfiguration componentConfiguration, final ViewConfiguration configuration, final DeploymentReflectionIndex index, final Method method) throws DeploymentUnitProcessingException {
configuration.addClientInterceptor(method, ViewDescription.CLIENT_DISPATCHER_INTERCEPTOR_FACTORY, InterceptorOrder.Client.CLIENT_DISPATCHER);
configuration.addViewInterceptor(method, StatefulRemoveDelegationInterceptor.FACTORY, InterceptorOrder.View.COMPONENT_DISPATCHER);
}
}
| 2,703 | 50.018868 | 232 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/StatefulSessionComponentCreateService.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, 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.ejb3.component.stateful;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Supplier;
import org.jboss.as.ee.component.BasicComponent;
import org.jboss.as.ee.component.ComponentConfiguration;
import org.jboss.as.ejb3.component.DefaultAccessTimeoutService;
import org.jboss.as.ejb3.component.InvokeMethodOnTargetInterceptor;
import org.jboss.as.ejb3.component.interceptors.CurrentInvocationContextInterceptor;
import org.jboss.as.ejb3.component.session.SessionBeanComponentCreateService;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanCacheFactory;
import org.jboss.as.ejb3.deployment.ApplicationExceptions;
import org.jboss.ejb.client.SessionID;
import org.jboss.invocation.ContextClassLoaderInterceptor;
import org.jboss.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.InterceptorFactory;
import org.jboss.invocation.Interceptors;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.value.InjectedValue;
/**
* @author Stuart Douglas
*/
public class StatefulSessionComponentCreateService extends SessionBeanComponentCreateService {
private final InterceptorFactory afterBegin;
private final Method afterBeginMethod;
private final InterceptorFactory afterCompletion;
private final Method afterCompletionMethod;
private final InterceptorFactory beforeCompletion;
private final Method beforeCompletionMethod;
private final InterceptorFactory prePassivate;
private final InterceptorFactory postActivate;
private final InjectedValue<DefaultAccessTimeoutService> defaultAccessTimeoutService = new InjectedValue<DefaultAccessTimeoutService>();
private final InjectedValue<AtomicLong> defaultStatefulSessionTimeoutValue = new InjectedValue<>();
private final InterceptorFactory ejb2XRemoveMethod;
private final Supplier<StatefulSessionBeanCacheFactory<SessionID, StatefulSessionComponentInstance>> cacheFactory;
private final Set<Object> serializableInterceptorContextKeys;
private final StatefulComponentDescription componentDescription;
final boolean passivationCapable;
/**
* Construct a new instance.
*
* @param componentConfiguration the component configuration
*/
public StatefulSessionComponentCreateService(final ComponentConfiguration componentConfiguration, final ApplicationExceptions ejbJarConfiguration, Supplier<StatefulSessionBeanCacheFactory<SessionID, StatefulSessionComponentInstance>> cacheFactory) {
super(componentConfiguration, ejbJarConfiguration);
final StatefulComponentDescription componentDescription = (StatefulComponentDescription) componentConfiguration.getComponentDescription();
final ClassLoader classLoader = componentConfiguration.getModuleClassLoader();
final InterceptorFactory tcclInterceptorFactory = new ImmediateInterceptorFactory(new ContextClassLoaderInterceptor(classLoader));
final InterceptorFactory namespaceContextInterceptorFactory = componentConfiguration.getNamespaceContextInterceptorFactory();
this.afterBeginMethod = componentDescription.getAfterBegin();
this.afterBegin = (this.afterBeginMethod != null) ? Interceptors.getChainedInterceptorFactory(tcclInterceptorFactory, namespaceContextInterceptorFactory, CurrentInvocationContextInterceptor.FACTORY, invokeMethodOnTarget(this.afterBeginMethod)) : null;
this.afterCompletionMethod = componentDescription.getAfterCompletion();
this.afterCompletion = (this.afterCompletionMethod != null) ? Interceptors.getChainedInterceptorFactory(tcclInterceptorFactory, namespaceContextInterceptorFactory, CurrentInvocationContextInterceptor.FACTORY, invokeMethodOnTarget(this.afterCompletionMethod)) : null;
this.beforeCompletionMethod = componentDescription.getBeforeCompletion();
this.beforeCompletion = (this.beforeCompletionMethod != null) ? Interceptors.getChainedInterceptorFactory(tcclInterceptorFactory, namespaceContextInterceptorFactory, CurrentInvocationContextInterceptor.FACTORY, invokeMethodOnTarget(this.beforeCompletionMethod)) : null;
this.prePassivate = Interceptors.getChainedInterceptorFactory(componentConfiguration.getPrePassivateInterceptors());
this.postActivate = Interceptors.getChainedInterceptorFactory(componentConfiguration.getPostActivateInterceptors());
//the interceptor chain for EJB e.x remove methods
this.ejb2XRemoveMethod = Interceptors.getChainedInterceptorFactory(StatefulSessionSynchronizationInterceptor.factory(componentDescription.getTransactionManagementType()), new ImmediateInterceptorFactory(new StatefulRemoveInterceptor(false)), Interceptors.getTerminalInterceptorFactory());
this.serializableInterceptorContextKeys = componentConfiguration.getInterceptorContextKeys();
this.passivationCapable = componentDescription.isPassivationApplicable();
this.cacheFactory = cacheFactory;
this.componentDescription = componentDescription;
}
private static InterceptorFactory invokeMethodOnTarget(final Method method) {
method.setAccessible(true);
return InvokeMethodOnTargetInterceptor.factory(method);
}
@Override
protected BasicComponent createComponent() {
return new StatefulSessionComponent(this);
}
public InterceptorFactory getAfterBegin() {
return afterBegin;
}
public InterceptorFactory getAfterCompletion() {
return afterCompletion;
}
public InterceptorFactory getBeforeCompletion() {
return beforeCompletion;
}
public InterceptorFactory getPrePassivate() {
return this.prePassivate;
}
public InterceptorFactory getPostActivate() {
return this.postActivate;
}
public Method getAfterBeginMethod() {
return afterBeginMethod;
}
public Method getAfterCompletionMethod() {
return afterCompletionMethod;
}
public Method getBeforeCompletionMethod() {
return beforeCompletionMethod;
}
public DefaultAccessTimeoutService getDefaultAccessTimeoutService() {
return defaultAccessTimeoutService.getValue();
}
Injector<DefaultAccessTimeoutService> getDefaultAccessTimeoutInjector() {
return this.defaultAccessTimeoutService;
}
Injector<AtomicLong> getDefaultStatefulSessionTimeoutInjector() {
return this.defaultStatefulSessionTimeoutValue;
}
void setDefaultStatefulSessionTimeout() {
if (componentDescription.getStatefulTimeout() == null) {
final long timeoutVal = defaultStatefulSessionTimeoutValue.getValue().get();
if (timeoutVal >= 0) {
componentDescription.setStatefulTimeout(new StatefulTimeoutInfo(timeoutVal, TimeUnit.MILLISECONDS));
}
}
}
public InterceptorFactory getEjb2XRemoveMethod() {
return ejb2XRemoveMethod;
}
public Set<Object> getSerializableInterceptorContextKeys() {
return serializableInterceptorContextKeys;
}
Supplier<StatefulSessionBeanCacheFactory<SessionID, StatefulSessionComponentInstance>> getCacheFactory() {
return this.cacheFactory;
}
}
| 8,313 | 47.337209 | 296 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/cache/StatefulSessionBeanCacheProviderServiceNameProvider.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2013, 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.ejb3.component.stateful.cache;
import org.jboss.msc.service.ServiceName;
import org.wildfly.clustering.service.SimpleServiceNameProvider;
/**
* Provides a {@link ServiceName} for a statful session bean cache provider.
* @author Paul Ferraro
*/
public class StatefulSessionBeanCacheProviderServiceNameProvider extends SimpleServiceNameProvider {
private static final ServiceName BASE_CACHE_SERVICE_NAME = ServiceName.JBOSS.append("ejb", "cache");
public static final ServiceName DEFAULT_CACHE_SERVICE_NAME = BASE_CACHE_SERVICE_NAME.append("sfsb-default");
public static final ServiceName DEFAULT_PASSIVATION_DISABLED_CACHE_SERVICE_NAME = BASE_CACHE_SERVICE_NAME.append("sfsb-default-passivation-disabled");
protected static final ServiceName BASE_CACHE_PROVIDER_SERVICE_NAME = BASE_CACHE_SERVICE_NAME.append("provider");
public StatefulSessionBeanCacheProviderServiceNameProvider(String cacheName) {
this(BASE_CACHE_PROVIDER_SERVICE_NAME.append(cacheName));
}
protected StatefulSessionBeanCacheProviderServiceNameProvider(ServiceName name) {
super(name);
}
}
| 2,159 | 44.957447 | 154 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/cache/StatefulSessionBeanCacheProvider.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.ejb3.component.stateful.cache;
import org.jboss.as.clustering.controller.CapabilityServiceConfigurator;
import org.jboss.as.ee.component.ComponentConfiguration;
import org.jboss.as.ee.component.EEModuleConfiguration;
import org.jboss.as.ejb3.component.stateful.StatefulComponentDescription;
import org.jboss.as.server.deployment.DeploymentUnit;
/**
* Provides configurators for services to install a stateful session bean cache factory.
* @author Paul Ferraro
* @param <K> the bean identifier type
* @param <V> the bean instance type
*/
public interface StatefulSessionBeanCacheProvider<K, V extends StatefulSessionBeanInstance<K>> {
/**
* Returns configurators for services to be installed for the specified deployment.
* @param unit a deployment unit
* @return a collection of service configurators
*/
Iterable<CapabilityServiceConfigurator> getDeploymentServiceConfigurators(DeploymentUnit unit, EEModuleConfiguration moduleConfiguration);
/**
* Returns a configurator for a service supplying a cache factory.
* @param unit the deployment unit containing this EJB component.
* @param description the EJB component description
* @param configuration the component configuration
* @return a service configurator
*/
CapabilityServiceConfigurator getStatefulBeanCacheFactoryServiceConfigurator(DeploymentUnit unit, StatefulComponentDescription description, ComponentConfiguration configuration);
/**
* Indicates whether or not cache factories provides by this object can support passivation.
* @return true, if passivation is supported, false otherwise.
*/
boolean supportsPassivation();
}
| 2,732 | 44.55 | 182 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/cache/StatefulSessionBeanCache.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.ejb3.component.stateful.cache;
import java.util.function.Supplier;
import org.wildfly.clustering.ee.Restartable;
import org.wildfly.clustering.ejb.bean.BeanStatistics;
import org.wildfly.clustering.ejb.remote.AffinitySupport;
/**
* A stateful session bean cache.
* Any {@link StatefulSessionBean} retrieved from this cache *must* invoke either {@link StatefulSessionBean#close()}, {@link StatefulSessionBean#remove()}, or {@link StatefulSessionBean#discard()} when complete.
* @author Paul Ferraro
* @param <K> the bean identifier type
* @param <V> the bean instance type
*/
public interface StatefulSessionBeanCache<K, V extends StatefulSessionBeanInstance<K>> extends Restartable, BeanStatistics, AffinitySupport<K> {
ThreadLocal<Object> CURRENT_GROUP = new ThreadLocal<>();
/**
* Creates and caches a stateful bean using a generated identifier.
* @return the identifier of the created session bean
*/
K createStatefulSessionBean();
/**
* Returns the stateful bean with the specified identifier, or null if no such bean exists.
* @return an existing stateful bean, or null if none was found
*/
StatefulSessionBean<K, V> findStatefulSessionBean(K id);
/**
* Checks whether the supplied {@link Throwable} is remotable - meaning it can be safely sent to the client over the wire.
*/
default boolean isRemotable(Throwable throwable) {
return true;
}
/**
* Returns the identifier factory of this cache.
* @return an identifier factory
*/
Supplier<K> getIdentifierFactory();
}
| 2,634 | 38.924242 | 212 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/cache/StatefulSessionBeanCacheFactory.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.ejb3.component.stateful.cache;
/**
* Factory for creating a stateful session bean cache for a component.
* @author Paul Ferraro
* @param <K> the bean identifier type
* @param <V> the bean instance type
*/
public interface StatefulSessionBeanCacheFactory<K, V extends StatefulSessionBeanInstance<K>> {
/**
* Creates a stateful session bean cache for a given {@link jakarta.ejb.Stateful} EJB.
* @param configuration configuration of a stateful bean cache
* @return a cache for a given {@link jakarta.ejb.Stateful} EJB.
*/
StatefulSessionBeanCache<K, V> createStatefulBeanCache(StatefulSessionBeanCacheConfiguration<K, V> configuration);
}
| 1,717 | 41.95 | 118 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/cache/StatefulSessionBeanCacheConfiguration.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.ejb3.component.stateful.cache;
import java.time.Duration;
import java.util.function.Supplier;
/**
* Configuration of a stateful session bean cache.
* @author Paul Ferraro
* @param <K> the bean identifier type
* @param <V> the bean instance type
*/
public interface StatefulSessionBeanCacheConfiguration<K, V extends StatefulSessionBeanInstance<K>> {
String getComponentName();
Supplier<K> getIdentifierFactory();
StatefulSessionBeanInstanceFactory<V> getInstanceFactory();
Duration getTimeout();
}
| 1,567 | 37.243902 | 101 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/cache/StatefulSessionBeanInstanceFactory.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.ejb3.component.stateful.cache;
/**
* Factory for creating stateful session bean instances.
* @author Paul Ferraro
* @param <V> the bean instance type
*/
public interface StatefulSessionBeanInstanceFactory<V> {
/**
* Create a new instance of this component. This may be invoked by a component interceptor, a client interceptor,
* or in the course of creating a new client, or in the case of an "eager" singleton, at component start. This
* method will block until the component is available. If the component fails to start then a runtime exception
* will be thrown.
* <p/>
* The instance has been injected and post-construct has been called.
* @return the component instance
*/
V createInstance();
}
| 1,801 | 41.904762 | 118 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/cache/StatefulSessionBeanInstance.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.ejb3.component.stateful.cache;
import org.wildfly.clustering.ejb.bean.BeanInstance;
/**
* A removable stateful session bean instance.
* @author Paul Ferraro
* @param <K> the bean identifier type
*/
public interface StatefulSessionBeanInstance<K> extends BeanInstance<K> {
/**
* Indicates that this bean instance was removed from its cache.
*/
void removed();
}
| 1,431 | 35.717949 | 73 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/cache/StatefulSessionBean.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.ejb3.component.stateful.cache;
/**
* A cached stateful session bean.
* @author Paul Ferraro
* @param <K> the bean identifier type
* @param <V> the bean instance type
*/
public interface StatefulSessionBean<K, V extends StatefulSessionBeanInstance<K>> extends AutoCloseable {
/**
* Returns the bean identifier.
* @return the bean identifier.
*/
default K getId() {
return this.getInstance().getId();
}
/**
* Returns the bean instance.
* @return a bean instance.
*/
V getInstance();
/**
* Indicates whether or not this bean was closed, i.e. {@link #close()} was invoked.
* @return true, if this bean is valid, false otherwise.
*/
boolean isClosed();
/**
* Indicates whether or not this bean was discarded, i.e. {@link #discard()} was invoked.
* @return true, if this bean was discarded, false otherwise.
*/
boolean isDiscarded();
/**
* Indicates whether or not this bean was removed, i.e. {@link #remove()} was invoked.
* @return true, if this bean was removed, false otherwise.
*/
boolean isRemoved();
/**
* Removes this bean from the cache without triggering any events.
* A discarded bean does not need to be closed.
*/
void discard();
/**
* Removes this bean from the cache, triggering requisite {@link jakarta.annotation.PreDestroy} events.
* A removed bean does not need to be closed.
*/
void remove();
/**
* Closes any resources associated with this bean.
* If bean has an associated timeout, it will schedule its expiration.
*/
@Override
void close();
}
| 2,718 | 31.759036 | 107 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/cache/simple/SimpleStatefulSessionBeanCacheConfiguration.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.ejb3.component.stateful.cache.simple;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanCacheConfiguration;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanInstance;
import org.jboss.as.server.ServerEnvironment;
/**
* Configuration of a simple stateful session bean cache.
* @author Paul Ferraro
* @param <K> the bean identifier type
* @param <V> the bean instance type
*/
public interface SimpleStatefulSessionBeanCacheConfiguration<K, V extends StatefulSessionBeanInstance<K>> extends StatefulSessionBeanCacheConfiguration<K, V> {
ServerEnvironment getEnvironment();
}
| 1,668 | 41.794872 | 159 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/cache/simple/SimpleStatefulSessionBeanCacheProviderServiceConfigurator.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.ejb3.component.stateful.cache.simple;
import java.util.Collections;
import java.util.function.Consumer;
import org.jboss.as.clustering.controller.CapabilityServiceConfigurator;
import org.jboss.as.clustering.controller.ResourceServiceConfigurator;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.ee.component.ComponentConfiguration;
import org.jboss.as.ee.component.EEModuleConfiguration;
import org.jboss.as.ejb3.component.stateful.StatefulComponentDescription;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanCacheProvider;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanCacheProviderServiceNameProvider;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanInstance;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.msc.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
/**
* Configures a service that provides a simple stateful session bean cache provider.
* @author Paul Ferraro
* @param <K> the bean identifier type
* @param <V> the bean instance type
*/
public class SimpleStatefulSessionBeanCacheProviderServiceConfigurator<K, V extends StatefulSessionBeanInstance<K>> extends StatefulSessionBeanCacheProviderServiceNameProvider implements ResourceServiceConfigurator, StatefulSessionBeanCacheProvider<K, V> {
public SimpleStatefulSessionBeanCacheProviderServiceConfigurator(PathAddress address) {
super(address.getLastElement().getValue());
}
@Override
public ServiceBuilder<?> build(ServiceTarget target) {
ServiceName name = this.getServiceName();
ServiceBuilder<?> builder = target.addService(name);
Consumer<StatefulSessionBeanCacheProvider<K, V>> provider = builder.provides(name);
Service service = Service.newInstance(provider, this);
return builder.setInstance(service);
}
@Override
public Iterable<CapabilityServiceConfigurator> getDeploymentServiceConfigurators(DeploymentUnit unit, EEModuleConfiguration moduleConfiguration) {
return Collections.emptyList();
}
@Override
public CapabilityServiceConfigurator getStatefulBeanCacheFactoryServiceConfigurator(DeploymentUnit unit, StatefulComponentDescription description, ComponentConfiguration configuration) {
return new SimpleStatefulSessionBeanCacheFactoryServiceConfigurator<>(description);
}
@Override
public boolean supportsPassivation() {
return false;
}
}
| 3,604 | 44.632911 | 256 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/cache/simple/SimpleStatefulSessionBean.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.ejb3.component.stateful.cache.simple;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBean;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanInstance;
/**
* A simple stateful session bean cache.
* @author Paul Ferraro
* @param <K> the bean identifier type
* @param <V> the bean instance type
*/
public class SimpleStatefulSessionBean<K, V extends StatefulSessionBeanInstance<K>> implements StatefulSessionBean<K, V> {
enum State {
VALID, DISCARDED, REMOVED, CLOSED;
}
private final V instance;
private final Consumer<K> remover;
private final Consumer<StatefulSessionBean<K, V>> closeTask;
private final AtomicReference<State> state = new AtomicReference<>(State.VALID);
public SimpleStatefulSessionBean(V instance, Consumer<K> remover, Consumer<StatefulSessionBean<K, V>> closeTask) {
this.instance = instance;
this.remover = remover;
this.closeTask = closeTask;
}
@Override
public V getInstance() {
return this.instance;
}
@Override
public boolean isClosed() {
return this.state.get() == State.CLOSED;
}
@Override
public boolean isDiscarded() {
return this.state.get() == State.DISCARDED;
}
@Override
public boolean isRemoved() {
return this.state.get() == State.REMOVED;
}
@Override
public void discard() {
if (this.state.compareAndSet(State.VALID, State.DISCARDED)) {
this.remover.accept(this.instance.getId());
}
}
@Override
public void remove() {
if (this.state.compareAndSet(State.VALID, State.REMOVED)) {
this.remover.accept(this.instance.getId());
this.instance.removed();
}
}
@Override
public void close() {
if (this.state.compareAndSet(State.VALID, State.CLOSED)) {
this.closeTask.accept(this);
}
}
} | 3,073 | 32.053763 | 122 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/cache/simple/SimpleStatefulSessionBeanCacheFactoryServiceConfigurator.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.ejb3.component.stateful.cache.simple;
import java.time.Duration;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.jboss.as.clustering.controller.CapabilityServiceConfigurator;
import org.jboss.as.ejb3.component.stateful.StatefulComponentDescription;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanCache;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanCacheConfiguration;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanCacheFactory;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanInstance;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanInstanceFactory;
import org.jboss.as.server.ServerEnvironment;
import org.jboss.as.server.ServerEnvironmentService;
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.wildfly.clustering.service.ServiceSupplierDependency;
import org.wildfly.clustering.service.SimpleServiceNameProvider;
import org.wildfly.clustering.service.SupplierDependency;
/**
* Configures a service that provides a simple stateful session bean cache factory.
*
* @author Paul Ferraro
* @param <K> the bean identifier type
* @param <V> the bean instance type
*/
public class SimpleStatefulSessionBeanCacheFactoryServiceConfigurator<K, V extends StatefulSessionBeanInstance<K>> extends SimpleServiceNameProvider implements CapabilityServiceConfigurator, StatefulSessionBeanCacheFactory<K, V> {
private final SupplierDependency<ServerEnvironment> environment = new ServiceSupplierDependency<>(ServerEnvironmentService.SERVICE_NAME);
public SimpleStatefulSessionBeanCacheFactoryServiceConfigurator(StatefulComponentDescription description) {
super(description.getCacheFactoryServiceName());
}
@Override
public ServiceBuilder<?> build(ServiceTarget target) {
ServiceName name = this.getServiceName();
ServiceBuilder<?> builder = target.addService(name);
Consumer<StatefulSessionBeanCacheFactory<K, V>> factory = this.environment.register(builder).provides(name);
Service service = Service.newInstance(factory, this);
return builder.setInstance(service);
}
@Override
public StatefulSessionBeanCache<K, V> createStatefulBeanCache(StatefulSessionBeanCacheConfiguration<K, V> configuration) {
ServerEnvironment environment = this.environment.get();
return new SimpleStatefulSessionBeanCache<>(new SimpleStatefulSessionBeanCacheConfiguration<>() {
@Override
public StatefulSessionBeanInstanceFactory<V> getInstanceFactory() {
return configuration.getInstanceFactory();
}
@Override
public Supplier<K> getIdentifierFactory() {
return configuration.getIdentifierFactory();
}
@Override
public Duration getTimeout() {
return configuration.getTimeout();
}
@Override
public ServerEnvironment getEnvironment() {
return environment;
}
@Override
public String getComponentName() {
return configuration.getComponentName();
}
});
}
}
| 4,415 | 42.722772 | 230 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/cache/simple/SimpleStatefulSessionBeanCache.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.ejb3.component.stateful.cache.simple;
import java.time.Duration;
import java.time.Instant;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBean;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanCache;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanInstance;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanInstanceFactory;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.ejb.client.Affinity;
import org.jboss.ejb.client.NodeAffinity;
import org.wildfly.clustering.ee.Scheduler;
import org.wildfly.clustering.ee.cache.scheduler.LinkedScheduledEntries;
import org.wildfly.clustering.ee.cache.scheduler.LocalScheduler;
/**
* A simple stateful session bean cache implementation.
* Bean instances are stored in memory and are lost on undeploy, shutdown, or server crash.
* @author Paul Ferraro
* @param <K> the bean identifier type
* @param <V> the bean instance type
*/
public class SimpleStatefulSessionBeanCache<K, V extends StatefulSessionBeanInstance<K>> implements StatefulSessionBeanCache<K, V>, Predicate<K>, Consumer<StatefulSessionBean<K, V>> {
private final Map<K, V> instances = new ConcurrentHashMap<>();
private final Consumer<K> remover = this.instances::remove;
private final StatefulSessionBeanInstanceFactory<V> factory;
private final Supplier<K> identifierFactory;
private final Duration timeout;
private final Affinity strongAffinity;
private volatile Scheduler<K, Instant> scheduler;
public SimpleStatefulSessionBeanCache(SimpleStatefulSessionBeanCacheConfiguration<K, V> configuration) {
this.factory = configuration.getInstanceFactory();
this.identifierFactory = configuration.getIdentifierFactory();
this.timeout = configuration.getTimeout();
this.strongAffinity = new NodeAffinity(configuration.getEnvironment().getNodeName());
}
@Override
public void start() {
this.scheduler = (this.timeout != null) && !this.timeout.isZero() ? new LocalScheduler<>(new LinkedScheduledEntries<>(), this, Duration.ZERO) : null;
}
@Override
public void stop() {
if (this.scheduler != null) {
this.scheduler.close();
}
for (V instance : this.instances.values()) {
instance.removed();
}
this.instances.clear();
}
@Override
public Affinity getStrongAffinity() {
return this.strongAffinity;
}
@Override
public Affinity getWeakAffinity(K id) {
return Affinity.NONE;
}
@Override
public void accept(StatefulSessionBean<K, V> bean) {
if (this.timeout != null) {
K id = bean.getId();
if (this.scheduler != null) {
// Timeout > 0, schedule bean to expire
this.scheduler.schedule(id, Instant.now().plus(this.timeout));
} else {
// Timeout = 0, remove bean immediately
this.test(id);
}
}
}
@Override
public boolean test(K id) {
V instance = this.instances.remove(id);
if (instance != null) {
instance.removed();
}
return true;
}
@Override
public K createStatefulSessionBean() {
if (CURRENT_GROUP.get() != null) {
// An SFSB that uses a distributable cache cannot contain an SFSB that uses a simple cache
throw EjbLogger.ROOT_LOGGER.incompatibleCaches();
}
V instance = this.factory.createInstance();
K id = instance.getId();
this.instances.put(id, instance);
return id;
}
@Override
public StatefulSessionBean<K, V> findStatefulSessionBean(K id) {
V instance = this.instances.get(id);
if (instance == null) return null;
if (this.scheduler != null) {
this.scheduler.cancel(id);
}
return new SimpleStatefulSessionBean<>(instance, this.remover, this);
}
@Override
public int getActiveCount() {
return this.instances.size();
}
@Override
public int getPassiveCount() {
return 0;
}
@Override
public Supplier<K> getIdentifierFactory() {
return this.identifierFactory;
}
}
| 5,502 | 34.503226 | 183 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/cache/distributable/DistributableStatefulSessionBeanCacheConfiguration.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.ejb3.component.stateful.cache.distributable;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanCacheConfiguration;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanInstance;
import org.wildfly.clustering.ee.Batch;
import org.wildfly.clustering.ejb.bean.BeanManager;
/**
* Configuration of a distributable stateful session bean cache.
* @author Paul Ferraro
* @param <K> the bean identifier type
* @param <V> the bean instance type
*/
public interface DistributableStatefulSessionBeanCacheConfiguration<K, V extends StatefulSessionBeanInstance<K>> extends StatefulSessionBeanCacheConfiguration<K, V> {
BeanManager<K, V, Batch> getBeanManager();
}
| 1,742 | 42.575 | 166 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/cache/distributable/LegacyDistributableStatefulSessionBeanCacheProviderServiceConfigurator.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.ejb3.component.stateful.cache.distributable;
import java.security.PrivilegedAction;
import java.util.Iterator;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanInstance;
import org.wildfly.clustering.ejb.bean.LegacyBeanManagementConfiguration;
import org.wildfly.clustering.ejb.bean.LegacyBeanManagementProviderFactory;
import org.wildfly.clustering.service.SimpleSupplierDependency;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* A legacy distributable stateful session bean cache provider that does not use the distributable-ejb subsystem.
* @author Paul Ferraro
* @param <K> the bean identifier type
* @param <V> the bean instance type
*/
@Deprecated
public class LegacyDistributableStatefulSessionBeanCacheProviderServiceConfigurator<K, V extends StatefulSessionBeanInstance<K>> extends AbstractDistributableStatefulSessionBeanCacheProviderServiceConfigurator<K, V> {
public LegacyDistributableStatefulSessionBeanCacheProviderServiceConfigurator(PathAddress address, LegacyBeanManagementConfiguration config) {
super(address);
this.accept(new SimpleSupplierDependency<>(load().createBeanManagementProvider(address.getLastElement().getValue(), config)));
}
private static LegacyBeanManagementProviderFactory load() {
PrivilegedAction<Iterable<LegacyBeanManagementProviderFactory>> action = new PrivilegedAction<>() {
@Override
public Iterable<LegacyBeanManagementProviderFactory> run() {
return ServiceLoader.load(LegacyBeanManagementProviderFactory.class, LegacyBeanManagementProviderFactory.class.getClassLoader());
}
};
Iterator<LegacyBeanManagementProviderFactory> providers = WildFlySecurityManager.doUnchecked(action).iterator();
if (!providers.hasNext()) {
throw new ServiceConfigurationError(LegacyBeanManagementProviderFactory.class.getName());
}
return providers.next();
}
}
| 3,146 | 47.415385 | 217 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/cache/distributable/DistributableStatefulSessionBeanCacheFactoryServiceConfigurator.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.ejb3.component.stateful.cache.distributable;
import java.time.Duration;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.jboss.as.clustering.controller.CapabilityServiceConfigurator;
import org.jboss.as.controller.capability.CapabilityServiceSupport;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanCache;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanCacheConfiguration;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanCacheFactory;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanInstance;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanInstanceFactory;
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.wildfly.clustering.ee.Batch;
import org.wildfly.clustering.ejb.bean.BeanExpirationConfiguration;
import org.wildfly.clustering.ejb.bean.BeanManager;
import org.wildfly.clustering.ejb.bean.BeanManagerConfiguration;
import org.wildfly.clustering.ejb.bean.BeanManagerFactory;
import org.wildfly.clustering.service.CompositeDependency;
import org.wildfly.clustering.service.ServiceConfigurator;
import org.wildfly.clustering.service.ServiceSupplierDependency;
import org.wildfly.clustering.service.SimpleServiceNameProvider;
import org.wildfly.clustering.service.SupplierDependency;
/**
* Configures a service providing a distributable stateful session bean cache factory.
* @author Paul Ferraro
* @param <K> the bean identifier type
* @param <V> the bean instance type
*/
public class DistributableStatefulSessionBeanCacheFactoryServiceConfigurator<K, V extends StatefulSessionBeanInstance<K>> extends SimpleServiceNameProvider implements CapabilityServiceConfigurator, StatefulSessionBeanCacheFactory<K, V> {
private final CapabilityServiceConfigurator configurator;
private final SupplierDependency<BeanManagerFactory<K, V, Batch>> factory;
public DistributableStatefulSessionBeanCacheFactoryServiceConfigurator(ServiceName name, CapabilityServiceConfigurator configurator) {
super(name);
this.configurator = configurator;
this.factory = new ServiceSupplierDependency<>(configurator);
}
@Override
public ServiceConfigurator configure(CapabilityServiceSupport support) {
this.configurator.configure(support);
return this;
}
@Override
public ServiceBuilder<?> build(ServiceTarget target) {
this.configurator.build(target).install();
ServiceName name = this.getServiceName();
ServiceBuilder<?> builder = target.addService(name);
Consumer<StatefulSessionBeanCacheFactory<K, V>> factory = new CompositeDependency(this.factory).register(builder).provides(name);
Service service = Service.newInstance(factory, this);
return builder.setInstance(service);
}
@Override
public StatefulSessionBeanCache<K, V> createStatefulBeanCache(StatefulSessionBeanCacheConfiguration<K, V> configuration) {
Duration timeout = configuration.getTimeout();
Consumer<V> timeoutListener = StatefulSessionBeanInstance::removed;
BeanExpirationConfiguration<K, V> expiration = (timeout != null) ? new BeanExpirationConfiguration<>() {
@Override
public Duration getTimeout() {
return timeout;
}
@Override
public Consumer<V> getExpirationListener() {
return timeoutListener;
}
} : null;
BeanManager<K, V, Batch> manager = this.factory.get().createBeanManager(new BeanManagerConfiguration<>() {
@Override
public Supplier<K> getIdentifierFactory() {
return configuration.getIdentifierFactory();
}
@Override
public String getBeanName() {
return configuration.getComponentName();
}
@Override
public BeanExpirationConfiguration<K, V> getExpiration() {
return expiration;
}
});
return new DistributableStatefulSessionBeanCache<>(new DistributableStatefulSessionBeanCacheConfiguration<>() {
@Override
public StatefulSessionBeanInstanceFactory<V> getInstanceFactory() {
return configuration.getInstanceFactory();
}
@Override
public Supplier<K> getIdentifierFactory() {
return manager.getIdentifierFactory();
}
@Override
public BeanManager<K, V, Batch> getBeanManager() {
return manager;
}
@Override
public Duration getTimeout() {
return timeout;
}
@Override
public String getComponentName() {
return configuration.getComponentName();
}
});
}
}
| 6,059 | 41.377622 | 237 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/cache/distributable/DistributableStatefulSessionBeanCacheProviderServiceConfigurator.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.ejb3.component.stateful.cache.distributable;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanInstance;
import org.jboss.as.ejb3.subsystem.DistributableStatefulSessionBeanCacheProviderResourceDefinition;
import org.jboss.dmr.ModelNode;
import org.wildfly.clustering.ejb.bean.BeanProviderRequirement;
import org.wildfly.clustering.service.ServiceConfigurator;
import org.wildfly.clustering.service.ServiceSupplierDependency;
/**
* Configures a service providing a distributable stateful session bean cache provider that uses capabilities provided by the distributable-ejb subsystem.
* @author Paul Ferraro
* @param <K> the bean identifier type
* @param <V> the bean instance type
*/
public class DistributableStatefulSessionBeanCacheProviderServiceConfigurator<K, V extends StatefulSessionBeanInstance<K>> extends AbstractDistributableStatefulSessionBeanCacheProviderServiceConfigurator<K, V> {
public DistributableStatefulSessionBeanCacheProviderServiceConfigurator(PathAddress address) {
super(address);
}
@Override
public ServiceConfigurator configure(OperationContext context, ModelNode model) throws OperationFailedException {
// if the attribute is undefined, pass null when generating the service name to pick up the default bean management provider
String provider = DistributableStatefulSessionBeanCacheProviderResourceDefinition.Attribute.BEAN_MANAGEMENT.resolveModelAttribute(context, model).asStringOrNull();
this.accept(new ServiceSupplierDependency<>(BeanProviderRequirement.BEAN_MANAGEMENT_PROVIDER.getServiceName(context, provider)));
return this;
}
}
| 2,851 | 50.854545 | 211 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/cache/distributable/DistributableStatefulSessionBean.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.ejb3.component.stateful.cache.distributable;
import java.time.Instant;
import java.util.function.Consumer;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBean;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanInstance;
import org.wildfly.clustering.ee.Batch;
import org.wildfly.clustering.ee.BatchContext;
import org.wildfly.clustering.ee.Batcher;
import org.wildfly.clustering.ejb.bean.Bean;
import org.wildfly.common.function.Functions;
/**
* A distributable stateful session bean cache.
* @author Paul Ferraro
* @param <K> the bean identifier type
* @param <V> the bean instance type
*/
public class DistributableStatefulSessionBean<K, V extends StatefulSessionBeanInstance<K>> implements StatefulSessionBean<K, V> {
private final Batcher<Batch> batcher;
private final Bean<K, V> bean;
private final Batch batch;
private final V instance;
private volatile boolean discarded;
private volatile boolean removed;
public DistributableStatefulSessionBean(Batcher<Batch> batcher, Bean<K, V> bean, Batch batch) {
this.batcher = batcher;
this.bean = bean;
// Store reference to bean instance eagerly, so that it is accessible even after removal
this.instance = bean.getInstance();
this.batch = batch;
}
@Override
public K getId() {
return this.bean.getId();
}
@Override
public V getInstance() {
return this.instance;
}
@Override
public boolean isClosed() {
return !this.bean.isValid();
}
@Override
public boolean isDiscarded() {
return this.discarded;
}
@Override
public boolean isRemoved() {
return this.removed;
}
@Override
public void discard() {
if (this.bean.isValid()) {
this.remove(Functions.discardingConsumer());
this.discarded = true;
}
}
@Override
public void remove() {
if (this.bean.isValid()) {
this.remove(StatefulSessionBeanInstance::removed);
this.removed = true;
}
}
private void remove(Consumer<V> removeTask) {
try (BatchContext context = this.batcher.resumeBatch(this.batch)) {
try {
this.bean.remove(removeTask);
} finally {
this.batch.close();
}
}
}
@Override
public void close() {
if (this.bean.isValid()) {
try (BatchContext context = this.batcher.resumeBatch(this.batch)) {
this.bean.getMetaData().setLastAccessTime(Instant.now());
this.bean.close();
} finally {
this.batch.close();
}
}
}
}
| 3,794 | 29.853659 | 129 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/cache/distributable/DistributableStatefulSessionBeanCache.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.ejb3.component.stateful.cache.distributable;
import java.util.concurrent.TimeoutException;
import java.util.function.Supplier;
import jakarta.ejb.ConcurrentAccessTimeoutException;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBean;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanCache;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanInstance;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanInstanceFactory;
import org.jboss.ejb.client.Affinity;
import org.wildfly.clustering.ee.Batch;
import org.wildfly.clustering.ee.Batcher;
import org.wildfly.clustering.ejb.bean.Bean;
import org.wildfly.clustering.ejb.bean.BeanManager;
/**
* A distributable stateful session bean cache.
* The availability of bean instances managed by this cache is determined by the underlying bean manager implementation.
* @author Paul Ferraro
* @param <K> the bean identifier type
* @param <V> the bean instance type
*/
public class DistributableStatefulSessionBeanCache<K, V extends StatefulSessionBeanInstance<K>> implements StatefulSessionBeanCache<K, V> {
private static final Object UNSET = Boolean.TRUE;
private final BeanManager<K, V, Batch> manager;
private final StatefulSessionBeanInstanceFactory<V> factory;
public DistributableStatefulSessionBeanCache(DistributableStatefulSessionBeanCacheConfiguration<K, V> configuration) {
this.manager = configuration.getBeanManager();
this.factory = configuration.getInstanceFactory();
}
@Override
public void start() {
this.manager.start();
}
@Override
public void stop() {
this.manager.stop();
}
@Override
public Affinity getStrongAffinity() {
return this.manager.getStrongAffinity();
}
@Override
public Affinity getWeakAffinity(K id) {
return this.manager.getWeakAffinity(id);
}
@Override
public K createStatefulSessionBean() {
boolean newGroup = CURRENT_GROUP.get() == null;
if (newGroup) {
CURRENT_GROUP.set(UNSET);
}
Batcher<Batch> batcher = this.manager.getBatcher();
try (Batch batch = batcher.createBatch()) {
try {
// This will invoke createStatefulBean() for nested beans
// Nested beans will share the same group identifier
V instance = this.factory.createInstance();
K id = instance.getId();
if (CURRENT_GROUP.get() == UNSET) {
CURRENT_GROUP.set(id);
}
try (@SuppressWarnings("unchecked") Bean<K, V> bean = this.manager.createBean(instance, (K) CURRENT_GROUP.get())) {
return bean.getId();
}
} catch (RuntimeException | Error e) {
batch.discard();
throw e;
}
} finally {
if (newGroup) {
CURRENT_GROUP.remove();
}
}
}
@Override
public StatefulSessionBean<K, V> findStatefulSessionBean(K id) {
Batcher<Batch> batcher = this.manager.getBatcher();
// Batch is not closed here - it will be closed by the StatefulSessionBean
@SuppressWarnings("resource")
Batch batch = batcher.createBatch();
try {
// TODO WFLY-14167 Cache lookup timeout should reflect @AccessTimeout of associated bean/invocation
Bean<K, V> bean = this.manager.findBean(id);
if (bean == null) {
batch.close();
return null;
}
return new DistributableStatefulSessionBean<>(batcher, bean, batcher.suspendBatch());
} catch (TimeoutException e) {
batch.close();
throw new ConcurrentAccessTimeoutException(e.getMessage());
} catch (RuntimeException | Error e) {
batch.discard();
batch.close();
throw e;
}
}
@Override
public int getActiveCount() {
return this.manager.getActiveCount();
}
@Override
public int getPassiveCount() {
return this.manager.getPassiveCount();
}
@Override
public Supplier<K> getIdentifierFactory() {
return this.manager.getIdentifierFactory();
}
@Override
public boolean isRemotable(Throwable throwable) {
return this.manager.isRemotable(throwable);
}
}
| 5,503 | 35.210526 | 139 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateful/cache/distributable/AbstractDistributableStatefulSessionBeanCacheProviderServiceConfigurator.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.ejb3.component.stateful.cache.distributable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import org.jboss.as.clustering.controller.CapabilityServiceConfigurator;
import org.jboss.as.clustering.controller.ResourceServiceConfigurator;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.ee.component.ComponentConfiguration;
import org.jboss.as.ee.component.EEModuleConfiguration;
import org.jboss.as.ejb3.component.stateful.StatefulComponentDescription;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanCacheProvider;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanCacheProviderServiceNameProvider;
import org.jboss.as.ejb3.component.stateful.cache.StatefulSessionBeanInstance;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.modules.Module;
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.wildfly.clustering.ejb.DeploymentConfiguration;
import org.wildfly.clustering.ejb.bean.BeanConfiguration;
import org.wildfly.clustering.ejb.bean.BeanDeploymentConfiguration;
import org.wildfly.clustering.ejb.bean.BeanManagementProvider;
import org.wildfly.clustering.service.SupplierDependency;
/**
* Configures a service providing a distributable stateful session bean cache provider.
* @author Paul Ferraro
* @param <K> the bean identifier type
* @param <V> the bean instance type
*/
public abstract class AbstractDistributableStatefulSessionBeanCacheProviderServiceConfigurator<K, V extends StatefulSessionBeanInstance<K>> extends StatefulSessionBeanCacheProviderServiceNameProvider implements ResourceServiceConfigurator, StatefulSessionBeanCacheProvider<K, V>, Consumer<SupplierDependency<BeanManagementProvider>> {
private volatile SupplierDependency<BeanManagementProvider> provider;
public AbstractDistributableStatefulSessionBeanCacheProviderServiceConfigurator(PathAddress address) {
super(address.getLastElement().getValue());
}
@Override
public ServiceBuilder<?> build(ServiceTarget target) {
ServiceName name = this.getServiceName();
ServiceBuilder<?> builder = target.addService(name);
Consumer<StatefulSessionBeanCacheProvider<K, V>> provider = this.provider.register(builder).provides(name);
Service service = Service.newInstance(provider, this);
return builder.setInstance(service);
}
@Override
public void accept(SupplierDependency<BeanManagementProvider> provider) {
this.provider = provider;
}
String getBeanManagerName(DeploymentUnit unit) {
BeanManagementProvider provider = this.provider.get();
List<String> parts = new ArrayList<>(3);
DeploymentUnit parent = unit.getParent();
if (parent != null) {
parts.add(parent.getServiceName().getSimpleName());
}
parts.add(unit.getServiceName().getSimpleName());
parts.add(provider.getName());
return String.join("/", parts);
}
@Override
public Iterable<CapabilityServiceConfigurator> getDeploymentServiceConfigurators(DeploymentUnit unit, EEModuleConfiguration moduleConfiguration) {
return this.provider.get().getDeploymentServiceConfigurators(new BeanDeploymentUnitConfiguration(this.provider.get(), unit, moduleConfiguration));
}
@Override
public CapabilityServiceConfigurator getStatefulBeanCacheFactoryServiceConfigurator(DeploymentUnit unit, StatefulComponentDescription description, ComponentConfiguration configuration) {
CapabilityServiceConfigurator configurator = this.provider.get().getBeanManagerFactoryServiceConfigurator(new DeploymentUnitBeanConfiguration(this.provider.get(), unit, configuration));
return new DistributableStatefulSessionBeanCacheFactoryServiceConfigurator<>(description.getCacheFactoryServiceName(), configurator);
}
@Override
public boolean supportsPassivation() {
return true;
}
private static class DeploymentUnitConfiguration implements DeploymentConfiguration {
private final String deploymentName;
private final DeploymentUnit unit;
DeploymentUnitConfiguration(BeanManagementProvider provider, DeploymentUnit unit) {
List<String> parts = new ArrayList<>(3);
DeploymentUnit parent = unit.getParent();
if (parent != null) {
parts.add(parent.getServiceName().getSimpleName());
}
parts.add(unit.getServiceName().getSimpleName());
parts.add(provider.getName());
this.deploymentName = String.join("/", parts);
this.unit = unit;
}
@Override
public String getDeploymentName() {
return this.deploymentName;
}
@Override
public ServiceName getDeploymentServiceName() {
return this.unit.getServiceName();
}
@Override
public Module getModule() {
return this.unit.getAttachment(Attachments.MODULE);
}
}
private static class BeanDeploymentUnitConfiguration extends DeploymentUnitConfiguration implements BeanDeploymentConfiguration {
private final Set<Class<?>> beanClasses = Collections.newSetFromMap(new IdentityHashMap<Class<?>, Boolean>());
BeanDeploymentUnitConfiguration(BeanManagementProvider provider, DeploymentUnit unit, EEModuleConfiguration moduleConfiguration) {
super(provider, unit);
for (ComponentConfiguration configuration : moduleConfiguration.getComponentConfigurations()) {
if (configuration.getComponentDescription() instanceof StatefulComponentDescription) {
Class<?> componentClass = configuration.getComponentClass();
while (componentClass != Object.class) {
this.beanClasses.add(componentClass);
componentClass = componentClass.getSuperclass();
}
}
}
}
@Override
public Set<Class<?>> getBeanClasses() {
return this.beanClasses;
}
}
private static class DeploymentUnitBeanConfiguration extends DeploymentUnitConfiguration implements BeanConfiguration {
private final ComponentConfiguration configuration;
DeploymentUnitBeanConfiguration(BeanManagementProvider provider, DeploymentUnit unit, ComponentConfiguration configuration) {
super(provider, unit);
this.configuration = configuration;
}
@Override
public String getName() {
return this.configuration.getComponentName();
}
}
}
| 7,979 | 43.333333 | 334 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/concurrent/EJBContextHandleFactory.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2013, 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.ejb3.component.concurrent;
import org.jboss.as.ee.component.interceptors.InvocationType;
import org.jboss.as.ee.concurrent.handle.ContextHandleFactory;
import org.jboss.as.ee.concurrent.handle.ResetContextHandle;
import org.jboss.as.ee.concurrent.handle.SetupContextHandle;
import org.jboss.as.ejb3.context.CurrentInvocationContext;
import org.jboss.invocation.InterceptorContext;
import jakarta.enterprise.concurrent.ContextService;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Map;
/**
* The context handle factory responsible for saving and setting the ejb context.
* @author Eduardo Martins
*/
public class EJBContextHandleFactory implements ContextHandleFactory {
public static final String NAME = "EJB";
public static final EJBContextHandleFactory INSTANCE = new EJBContextHandleFactory();
private EJBContextHandleFactory() {
}
@Override
public SetupContextHandle saveContext(ContextService contextService, Map<String, String> contextObjectProperties) {
return new EJBContextHandle();
}
@Override
public String getName() {
return NAME;
}
@Override
public int getChainPriority() {
return 500;
}
@Override
public void writeSetupContextHandle(SetupContextHandle contextHandle, ObjectOutputStream out) throws IOException {
out.writeObject(contextHandle);
}
@Override
public SetupContextHandle readSetupContextHandle(ObjectInputStream in) throws IOException, ClassNotFoundException {
return (SetupContextHandle) in.readObject();
}
private static class EJBContextHandle implements SetupContextHandle, ResetContextHandle {
private static final long serialVersionUID = 9158258921823908698L;
private final transient InterceptorContext interceptorContext;
private EJBContextHandle() {
final InterceptorContext interceptorContext = CurrentInvocationContext.get();
if(interceptorContext != null) {
this.interceptorContext = interceptorContext.clone();
// overwrite invocation type so EE concurrency tasks have special access to resources such as the user tx
this.interceptorContext.putPrivateData(InvocationType.class, InvocationType.CONCURRENT_CONTEXT);
} else {
this.interceptorContext = null;
}
}
@Override
public String getFactoryName() {
return NAME;
}
@Override
public ResetContextHandle setup() throws IllegalStateException {
if(interceptorContext != null) {
CurrentInvocationContext.push(interceptorContext);
}
return this;
}
@Override
public void reset() {
if(interceptorContext != null) {
CurrentInvocationContext.pop();
}
}
}
}
| 4,010 | 34.8125 | 121 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/session/SessionBeanComponentInstance.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, 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.ejb3.component.session;
import java.lang.reflect.Method;
import java.util.Map;
import org.jboss.as.ee.component.BasicComponent;
import org.jboss.as.ejb3.component.EjbComponentInstance;
import org.jboss.as.ejb3.context.SessionContextImpl;
import org.jboss.ejb.client.SessionID;
import org.jboss.invocation.Interceptor;
/**
* @author <a href="mailto:[email protected]">Carlo de Wolf</a>
*/
public abstract class SessionBeanComponentInstance extends EjbComponentInstance {
private static final long serialVersionUID = 5176535401148504579L;
private transient volatile SessionContextImpl sessionContext;
/**
* Construct a new instance.
*
* @param component the component
*/
protected SessionBeanComponentInstance(final BasicComponent component, final Interceptor preDestroyInterceptor, final Map<Method, Interceptor> methodInterceptors) {
super(component, preDestroyInterceptor, methodInterceptors);
}
@Override
public SessionBeanComponent getComponent() {
return (SessionBeanComponent) super.getComponent();
}
protected abstract SessionID getId();
@Override
public SessionContextImpl getEjbContext() {
if (sessionContext == null) {
synchronized (this) {
if (sessionContext == null) {
this.sessionContext = new SessionContextImpl(this);
}
}
}
return sessionContext;
}
}
| 2,504 | 35.304348 | 168 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/session/StatelessWriteReplaceInterceptor.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, 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.ejb3.component.session;
import org.jboss.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
/**
* Interceptor that handles the writeReplace method for a stateless and singleton session beans
*
* @author Stuart Douglas
*/
public class StatelessWriteReplaceInterceptor implements Interceptor {
private final String serviceName;
public StatelessWriteReplaceInterceptor(final String serviceName) {
this.serviceName = serviceName;
}
@Override
public Object processInvocation(final InterceptorContext context) throws Exception {
return new StatelessSerializedProxy(serviceName);
}
public static InterceptorFactory factory(final String serviceName) {
return new ImmediateInterceptorFactory(new StatelessWriteReplaceInterceptor(serviceName));
}
}
| 1,975 | 37.745098 | 98 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/session/SessionBeanObjectViewConfigurator.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.ejb3.component.session;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import jakarta.ejb.EJBLocalObject;
import jakarta.ejb.EJBObject;
import org.jboss.as.ee.component.ComponentConfiguration;
import org.jboss.as.ee.component.ComponentStartService;
import org.jboss.as.ee.component.ComponentView;
import org.jboss.as.ee.component.DependencyConfigurator;
import org.jboss.as.ee.component.ViewConfiguration;
import org.jboss.as.ee.component.ViewConfigurator;
import org.jboss.as.ee.component.ViewDescription;
import org.jboss.as.ee.component.interceptors.ComponentDispatcherInterceptor;
import org.jboss.as.ee.component.interceptors.InterceptorOrder;
import org.jboss.as.ee.component.serialization.WriteReplaceInterface;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.ejb3.util.EjbValidationsUtil;
import org.jboss.as.ejb3.component.EjbHomeViewDescription;
import org.jboss.as.ejb3.component.interceptors.GetHomeInterceptorFactory;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.reflect.ClassReflectionIndexUtil;
import org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex;
import org.jboss.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
import org.jboss.invocation.Interceptors;
import org.jboss.invocation.proxy.MethodIdentifier;
import org.jboss.msc.service.ServiceBuilder;
/**
* configurator that sets up interceptors for an Jakarta Enterprise Beans's object view
*
* @author Stuart Douglas
*/
public abstract class SessionBeanObjectViewConfigurator implements ViewConfigurator {
@Override
public void configure(final DeploymentPhaseContext context, final ComponentConfiguration componentConfiguration, final ViewDescription description, final ViewConfiguration configuration) throws DeploymentUnitProcessingException {
//note that we don't have to handle all methods on the EJBObject, as some are handled client side
final DeploymentReflectionIndex index = context.getDeploymentUnit().getAttachment(Attachments.REFLECTION_INDEX);
for (final Method method : configuration.getProxyFactory().getCachedMethods()) {
if (method.getName().equals("getPrimaryKey") && method.getParameterCount() == 0) {
configuration.addClientInterceptor(method, ViewDescription.CLIENT_DISPATCHER_INTERCEPTOR_FACTORY, InterceptorOrder.Client.CLIENT_DISPATCHER);
configuration.addViewInterceptor(method, PRIMARY_KEY_INTERCEPTOR, InterceptorOrder.View.COMPONENT_DISPATCHER);
} else if (method.getName().equals("remove") && method.getParameterCount() == 0) {
handleRemoveMethod(componentConfiguration, configuration, index, method);
} else if (method.getName().equals("getEJBLocalHome") && method.getParameterCount() == 0) {
configuration.addClientInterceptor(method, ViewDescription.CLIENT_DISPATCHER_INTERCEPTOR_FACTORY, InterceptorOrder.Client.CLIENT_DISPATCHER);
final GetHomeInterceptorFactory factory = new GetHomeInterceptorFactory();
configuration.addViewInterceptor(method, factory, InterceptorOrder.View.COMPONENT_DISPATCHER);
final SessionBeanComponentDescription componentDescription = (SessionBeanComponentDescription) componentConfiguration.getComponentDescription();
componentConfiguration.getStartDependencies().add(new DependencyConfigurator<ComponentStartService>() {
@Override
public void configureDependency(final ServiceBuilder<?> serviceBuilder, final ComponentStartService service) throws DeploymentUnitProcessingException {
EjbHomeViewDescription ejbLocalHomeView = componentDescription.getEjbLocalHomeView();
if (ejbLocalHomeView == null) {
throw EjbLogger.ROOT_LOGGER.beanLocalHomeInterfaceIsNull(componentDescription.getComponentName());
}
serviceBuilder.addDependency(ejbLocalHomeView.getServiceName(), ComponentView.class, factory.getViewToCreate());
}
});
} else if (method.getName().equals("getEJBHome") && method.getParameterCount() == 0) {
configuration.addClientInterceptor(method, ViewDescription.CLIENT_DISPATCHER_INTERCEPTOR_FACTORY, InterceptorOrder.Client.CLIENT_DISPATCHER);
final GetHomeInterceptorFactory factory = new GetHomeInterceptorFactory();
configuration.addViewInterceptor(method, factory, InterceptorOrder.View.COMPONENT_DISPATCHER);
final SessionBeanComponentDescription componentDescription = (SessionBeanComponentDescription) componentConfiguration.getComponentDescription();
componentConfiguration.getStartDependencies().add(new DependencyConfigurator<ComponentStartService>() {
@Override
public void configureDependency(final ServiceBuilder<?> serviceBuilder, final ComponentStartService service) throws DeploymentUnitProcessingException {
EjbHomeViewDescription ejbHomeView = componentDescription.getEjbHomeView();
if (ejbHomeView == null) {
throw EjbLogger.ROOT_LOGGER.beanHomeInterfaceIsNull(componentDescription.getComponentName());
}
serviceBuilder.addDependency(ejbHomeView.getServiceName(), ComponentView.class, factory.getViewToCreate());
}
});
} else if (method.getName().equals("getHandle") && method.getParameterCount() == 0) {
//ignore, handled client side
} else if (method.getName().equals("isIdentical") && method.getParameterCount() == 1 && (method.getParameterTypes()[0].equals(EJBObject.class) || method.getParameterTypes()[0].equals(EJBLocalObject.class))) {
handleIsIdenticalMethod(componentConfiguration, configuration, index, method);
} else {
final Method componentMethod = ClassReflectionIndexUtil.findMethod(index, componentConfiguration.getComponentClass(), MethodIdentifier.getIdentifierForMethod(method));
if (componentMethod != null) {
if(!Modifier.isPublic(componentMethod.getModifiers())) {
EjbLogger.ROOT_LOGGER.ejbBusinessMethodMustBePublic(componentMethod);
}
configuration.addViewInterceptor(method, new ImmediateInterceptorFactory(new ComponentDispatcherInterceptor(componentMethod)), InterceptorOrder.View.COMPONENT_DISPATCHER);
configuration.addClientInterceptor(method, ViewDescription.CLIENT_DISPATCHER_INTERCEPTOR_FACTORY, InterceptorOrder.Client.CLIENT_DISPATCHER);
} else if(method.getDeclaringClass() != Object.class && method.getDeclaringClass() != WriteReplaceInterface.class) {
throw EjbLogger.ROOT_LOGGER.couldNotFindViewMethodOnEjb(method, description.getViewClassName(), componentConfiguration.getComponentName());
}
}
EjbValidationsUtil.verifyMethodIsNotFinalNorStatic(method, index.getClass().getName());
}
configuration.addClientPostConstructInterceptor(Interceptors.getTerminalInterceptorFactory(), InterceptorOrder.ClientPostConstruct.TERMINAL_INTERCEPTOR);
configuration.addClientPreDestroyInterceptor(Interceptors.getTerminalInterceptorFactory(), InterceptorOrder.ClientPreDestroy.TERMINAL_INTERCEPTOR);
}
protected abstract void handleIsIdenticalMethod(final ComponentConfiguration componentConfiguration, final ViewConfiguration configuration, final DeploymentReflectionIndex index, final Method method);
protected abstract void handleRemoveMethod(final ComponentConfiguration componentConfiguration, final ViewConfiguration configuration, final DeploymentReflectionIndex index, final Method method) throws DeploymentUnitProcessingException;
private static final InterceptorFactory PRIMARY_KEY_INTERCEPTOR = new ImmediateInterceptorFactory(new Interceptor() {
@Override
public Object processInvocation(final InterceptorContext context) throws Exception {
throw EjbLogger.ROOT_LOGGER.cannotCallGetPKOnSessionBean();
}
});
}
| 9,678 | 64.398649 | 240 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/session/SessionBeanComponentCreateService.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, 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.ejb3.component.session;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import jakarta.ejb.LockType;
import org.jboss.as.ee.component.ComponentConfiguration;
import org.jboss.as.ejb3.PrimitiveClassLoaderUtil;
import org.jboss.as.ejb3.component.EJBBusinessMethod;
import org.jboss.as.ejb3.component.EJBComponentCreateService;
import org.jboss.as.ejb3.concurrency.AccessTimeoutDetails;
import org.jboss.as.ejb3.deployment.ApplicationExceptions;
import org.jboss.invocation.proxy.MethodIdentifier;
import org.jboss.metadata.ejb.spec.MethodInterfaceType;
import org.jboss.msc.value.InjectedValue;
/**
* User: jpai
*/
public abstract class SessionBeanComponentCreateService extends EJBComponentCreateService {
private final Map<String, LockType> beanLevelLockType;
private final Map<EJBBusinessMethod, LockType> methodApplicableLockTypes;
private final Map<String, AccessTimeoutDetails> beanLevelAccessTimeout;
private final Map<EJBBusinessMethod, AccessTimeoutDetails> methodApplicableAccessTimeouts;
private final InjectedValue<ExecutorService> asyncExecutorService = new InjectedValue<ExecutorService>();
/**
* Construct a new instance.
*
* @param componentConfiguration the component configuration
*/
public SessionBeanComponentCreateService(final ComponentConfiguration componentConfiguration, final ApplicationExceptions ejbJarConfiguration) {
super(componentConfiguration, ejbJarConfiguration);
final SessionBeanComponentDescription sessionBeanComponentDescription = (SessionBeanComponentDescription) componentConfiguration.getComponentDescription();
this.beanLevelLockType = sessionBeanComponentDescription.getBeanLevelLockType();
Map<MethodIdentifier, LockType> methodLocks = sessionBeanComponentDescription.getMethodApplicableLockTypes();
if (methodLocks == null) {
this.methodApplicableLockTypes = Collections.emptyMap();
} else {
final Map<EJBBusinessMethod, LockType> locks = new HashMap<EJBBusinessMethod, LockType>();
for (Map.Entry<MethodIdentifier, LockType> entry : methodLocks.entrySet()) {
final MethodIdentifier ejbMethodDescription = entry.getKey();
final EJBBusinessMethod ejbMethod = this.getEJBBusinessMethod(ejbMethodDescription);
locks.put(ejbMethod, entry.getValue());
}
this.methodApplicableLockTypes = Collections.unmodifiableMap(locks);
}
this.beanLevelAccessTimeout = sessionBeanComponentDescription.getBeanLevelAccessTimeout();
final Map<MethodIdentifier, AccessTimeoutDetails> methodAccessTimeouts = sessionBeanComponentDescription.getMethodApplicableAccessTimeouts();
if (methodAccessTimeouts == null) {
this.methodApplicableAccessTimeouts = Collections.emptyMap();
} else {
final Map<EJBBusinessMethod, AccessTimeoutDetails> accessTimeouts = new HashMap<EJBBusinessMethod, AccessTimeoutDetails>();
for (Map.Entry<MethodIdentifier, AccessTimeoutDetails> entry : methodAccessTimeouts.entrySet()) {
final MethodIdentifier ejbMethodDescription = entry.getKey();
final EJBBusinessMethod ejbMethod = this.getEJBBusinessMethod(ejbMethodDescription);
accessTimeouts.put(ejbMethod, entry.getValue());
}
this.methodApplicableAccessTimeouts = Collections.unmodifiableMap(accessTimeouts);
}
if (sessionBeanComponentDescription.getScheduleMethods() != null) {
for (Method method : sessionBeanComponentDescription.getScheduleMethods().keySet()) {
processTxAttr(sessionBeanComponentDescription, MethodInterfaceType.Timer, method);
}
}
if (sessionBeanComponentDescription.getTimeoutMethod() != null) {
this.processTxAttr(sessionBeanComponentDescription, MethodInterfaceType.Timer,
sessionBeanComponentDescription.getTimeoutMethod());
}
}
public Map<String, LockType> getBeanLockType() {
return this.beanLevelLockType;
}
public Map<EJBBusinessMethod, LockType> getMethodApplicableLockTypes() {
return this.methodApplicableLockTypes;
}
public Map<EJBBusinessMethod, AccessTimeoutDetails> getMethodApplicableAccessTimeouts() {
return this.methodApplicableAccessTimeouts;
}
public Map<String, AccessTimeoutDetails> getBeanAccessTimeout() {
return this.beanLevelAccessTimeout;
}
private EJBBusinessMethod getEJBBusinessMethod(final MethodIdentifier method) {
final ClassLoader classLoader = this.getComponentClass().getClassLoader();
final String methodName = method.getName();
final String[] types = method.getParameterTypes();
if (types == null || types.length == 0) {
return new EJBBusinessMethod(methodName);
}
Class<?>[] paramTypes = new Class<?>[types.length];
int i = 0;
for (String type : types) {
try {
paramTypes[i++] = PrimitiveClassLoaderUtil.loadClass(type, classLoader);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
return new EJBBusinessMethod(methodName, paramTypes);
}
public InjectedValue<ExecutorService> getAsyncExecutorService() {
return asyncExecutorService;
}
}
| 6,609 | 45.549296 | 163 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/session/StatelessSerializedProxy.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.ejb3.component.session;
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.security.AccessController;
import org.jboss.as.ee.component.ComponentView;
import org.jboss.as.server.CurrentServiceContainer;
import org.jboss.msc.service.ServiceContainer;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
/**
* Serialized form of a singleton or session bean
*
* @author Stuart Douglas
*/
public class StatelessSerializedProxy implements Serializable {
private static final long serialVersionUID = 45678904536435L;
private final String viewName;
public StatelessSerializedProxy(final String viewName) {
this.viewName = viewName;
}
public String getViewName() {
return this.viewName;
}
private Object readResolve() throws ObjectStreamException {
ServiceController<ComponentView> view = (ServiceController<ComponentView>) currentServiceContainer().getRequiredService(ServiceName.parse(viewName));
try {
return view.getValue().createInstance().getInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static ServiceContainer currentServiceContainer() {
if(System.getSecurityManager() == null) {
return CurrentServiceContainer.getServiceContainer();
}
return AccessController.doPrivileged(CurrentServiceContainer.GET_ACTION);
}
}
| 2,510 | 35.391304 | 157 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/session/SessionBeanSetSessionContextMethodInvocationInterceptor.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.ejb3.component.session;
import jakarta.ejb.SessionBean;
import org.jboss.as.ee.component.ComponentInstance;
import org.jboss.as.ee.component.interceptors.InvocationType;
import org.jboss.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
/**
* Interceptor that invokes the {@link SessionBean#setSessionContext(jakarta.ejb.SessionContext)} on session beans
* which implement the {@link SessionBean} interface.
*
* @author Stuart Douglas
*/
public class SessionBeanSetSessionContextMethodInvocationInterceptor implements Interceptor {
public static final InterceptorFactory FACTORY = new ImmediateInterceptorFactory(new SessionBeanSetSessionContextMethodInvocationInterceptor());
private SessionBeanSetSessionContextMethodInvocationInterceptor() {
}
@Override
public Object processInvocation(final InterceptorContext context) throws Exception {
SessionBeanComponentInstance instance = (SessionBeanComponentInstance) context.getPrivateData(ComponentInstance.class);
final InvocationType invocationType = context.getPrivateData(InvocationType.class);
try {
context.putPrivateData(InvocationType.class, InvocationType.DEPENDENCY_INJECTION);
((SessionBean) context.getTarget()).setSessionContext(instance.getEjbContext());
} finally {
context.putPrivateData(InvocationType.class, invocationType);
}
return context.proceed();
}
}
| 2,605 | 43.169492 | 148 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/session/SessionBeanComponentDescription.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.ejb3.component.session;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import jakarta.ejb.ConcurrencyManagementType;
import jakarta.ejb.LockType;
import jakarta.ejb.TransactionManagementType;
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.ViewConfiguration;
import org.jboss.as.ee.component.ViewConfigurator;
import org.jboss.as.ee.component.ViewDescription;
import org.jboss.as.ee.component.interceptors.InterceptorOrder;
import org.jboss.as.ejb3.component.EJBComponentDescription;
import org.jboss.as.ejb3.component.EJBViewDescription;
import org.jboss.as.ejb3.component.concurrent.EJBContextHandleFactory;
import org.jboss.as.ejb3.component.interceptors.CurrentInvocationContextInterceptor;
import org.jboss.as.ejb3.concurrency.AccessTimeoutDetails;
import org.jboss.as.ejb3.deployment.EjbJarDescription;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.ejb3.tx.CMTTxInterceptor;
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.reflect.ClassReflectionIndexUtil;
import org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex;
import org.jboss.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.proxy.MethodIdentifier;
import org.jboss.metadata.ejb.spec.MethodInterfaceType;
import org.jboss.metadata.ejb.spec.SessionBeanMetaData;
/**
* @author Jaikiran Pai
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public abstract class SessionBeanComponentDescription extends EJBComponentDescription {
/**
* Flag marking the presence/absence of a no-interface view on the session bean
*/
private boolean noInterfaceViewPresent;
/**
* The {@link jakarta.ejb.ConcurrencyManagementType} for this bean
*/
private ConcurrencyManagementType concurrencyManagementType;
/**
* Map of class name to default {@link LockType} for this bean.
*/
private final Map<String, LockType> beanLevelLockType = new HashMap<String, LockType>();
/**
* Map of class name to default {@link AccessTimeoutDetails} for this component.
*/
private final Map<String, AccessTimeoutDetails> beanLevelAccessTimeout = new HashMap<String, AccessTimeoutDetails>();
/**
* The {@link LockType} applicable for a specific bean methods.
*/
private final Map<MethodIdentifier, LockType> methodLockTypes = new HashMap<MethodIdentifier, LockType>();
/**
* The {@link jakarta.ejb.AccessTimeout} applicable for a specific bean methods.
*/
private final Map<MethodIdentifier, AccessTimeoutDetails> methodAccessTimeouts = new HashMap<MethodIdentifier, AccessTimeoutDetails>();
/**
* Methods on the component marked as @Asynchronous
*/
private final Set<MethodIdentifier> asynchronousMethods = new HashSet<MethodIdentifier>();
/**
* Classes the component marked as @Asynchronous
*/
private final Set<String> asynchronousClasses = new HashSet<String>();
/**
* mapped-name of the session bean
*/
private String mappedName;
public enum SessionBeanType {
STATELESS,
STATEFUL,
SINGLETON
}
/**
* Construct a new instance.
*
* @param componentName the component name
* @param componentClassName the component instance class name
* @param ejbJarDescription the module description
*/
public SessionBeanComponentDescription(final String componentName, final String componentClassName,
final EjbJarDescription ejbJarDescription, final DeploymentUnit deploymentUnit,
final SessionBeanMetaData descriptorData) {
super(componentName, componentClassName, ejbJarDescription, deploymentUnit, descriptorData);
}
public void addLocalBusinessInterfaceViews(final Collection<String> classNames) {
for (final String viewClassName : classNames) {
assertNoRemoteView(viewClassName);
registerView(viewClassName, MethodInterfaceType.Local);
}
}
public void addLocalBusinessInterfaceViews(final String... classNames) {
addLocalBusinessInterfaceViews(Arrays.asList(classNames));
}
public void addNoInterfaceView() {
noInterfaceViewPresent = true;
final ViewDescription viewDescription = registerView(getEJBClassName(), MethodInterfaceType.Local);
//set up interceptor for non-business methods
viewDescription.getConfigurators().add(new ViewConfigurator() {
@Override
public void configure(final DeploymentPhaseContext context, final ComponentConfiguration componentConfiguration, final ViewDescription description, final ViewConfiguration configuration) throws DeploymentUnitProcessingException {
DeploymentReflectionIndex index = context.getDeploymentUnit().getAttachment(Attachments.REFLECTION_INDEX);
for (final Method method : configuration.getProxyFactory().getCachedMethods()) {
if (!Modifier.isPublic(method.getModifiers()) && isNotOverriden(method, componentConfiguration.getComponentClass(), index)) {
configuration.addClientInterceptor(method, new ImmediateInterceptorFactory(new NotBusinessMethodInterceptor(method)), InterceptorOrder.Client.NOT_BUSINESS_METHOD_EXCEPTION);
}
}
}
});
}
public EJBViewDescription addWebserviceEndpointView() {
return registerView(getEJBClassName(), MethodInterfaceType.ServiceEndpoint);
}
public void addRemoteBusinessInterfaceViews(final Collection<String> classNames) {
for (final String viewClassName : classNames) {
assertNoLocalView(viewClassName);
registerView(viewClassName, MethodInterfaceType.Remote);
}
}
private void assertNoRemoteView(final String viewClassName) {
EJBViewDescription ejbView = null;
for (final ViewDescription view : getViews()) {
ejbView = (EJBViewDescription) view;
if (viewClassName.equals(ejbView.getViewClassName()) && ejbView.getMethodIntf() == MethodInterfaceType.Remote) {
throw EjbLogger.ROOT_LOGGER.failToAddClassToLocalView(viewClassName, getEJBName());
}
}
}
private void assertNoLocalView(final String viewClassName) {
EJBViewDescription ejbView = null;
for (final ViewDescription view : getViews()) {
ejbView = (EJBViewDescription) view;
if (viewClassName.equals(ejbView.getViewClassName()) && ejbView.getMethodIntf() == MethodInterfaceType.Local) {
throw EjbLogger.ROOT_LOGGER.failToAddClassToLocalView(viewClassName, getEJBName());
}
}
}
public boolean hasNoInterfaceView() {
return this.noInterfaceViewPresent;
}
/**
* Sets the {@link jakarta.ejb.LockType} applicable for the bean.
*
* @param className The class that has the annotation
* @param locktype The lock type applicable for the bean
*/
public void setBeanLevelLockType(String className, LockType locktype) {
this.beanLevelLockType.put(className, locktype);
}
/**
* Returns the {@link LockType} applicable for the bean.
*
* @return
*/
public Map<String, LockType> getBeanLevelLockType() {
return this.beanLevelLockType;
}
/**
* Sets the {@link LockType} for the specific bean method
*
* @param lockType The applicable lock type for the method
* @param method The method
*/
public void setLockType(LockType lockType, MethodIdentifier method) {
this.methodLockTypes.put(method, lockType);
}
public Map<MethodIdentifier, LockType> getMethodApplicableLockTypes() {
return this.methodLockTypes;
}
/**
* Returns the {@link jakarta.ejb.AccessTimeout} applicable for the bean.
*
* @return
*/
public Map<String, AccessTimeoutDetails> getBeanLevelAccessTimeout() {
return this.beanLevelAccessTimeout;
}
/**
* Sets the {@link jakarta.ejb.AccessTimeout} applicable for the bean.
*
* @param accessTimeout The access timeout applicable for the class
*/
public void setBeanLevelAccessTimeout(String className, AccessTimeoutDetails accessTimeout) {
this.beanLevelAccessTimeout.put(className, accessTimeout);
}
/**
* Sets the {@link jakarta.ejb.AccessTimeout} for the specific bean method
*
* @param accessTimeout The applicable access timeout for the method
* @param method The method
*/
public void setAccessTimeout(AccessTimeoutDetails accessTimeout, MethodIdentifier method) {
this.methodAccessTimeouts.put(method, accessTimeout);
}
public Map<MethodIdentifier, AccessTimeoutDetails> getMethodApplicableAccessTimeouts() {
return this.methodAccessTimeouts;
}
/**
* Returns the concurrency management type for this bean.
* <p/>
* This method returns null if the concurrency management type hasn't explicitly been set on this
* {@link SessionBeanComponentDescription}
*
* @return
*/
public ConcurrencyManagementType getConcurrencyManagementType() {
return this.concurrencyManagementType;
}
public void setConcurrencyManagementType(final ConcurrencyManagementType concurrencyManagementType) {
this.concurrencyManagementType = concurrencyManagementType;
}
/**
* Returns the mapped-name of this bean
*
* @return
*/
public String getMappedName() {
return this.mappedName;
}
/**
* Sets the mapped-name for this bean
*
* @param mappedName
*/
public void setMappedName(String mappedName) {
this.mappedName = mappedName;
}
/**
* Add an asynchronous method.
*
* @param methodIdentifier The identifier for an async method
*/
public void addAsynchronousMethod(final MethodIdentifier methodIdentifier) {
asynchronousMethods.add(methodIdentifier);
}
/**
* @return The identifier of all async methods
*/
public Set<MethodIdentifier> getAsynchronousMethods() {
return asynchronousMethods;
}
/**
* Add a bean class or superclass that has been marked asynchronous
*
* @param viewName The view name
*/
public void addAsynchronousClass(final String viewName) {
asynchronousClasses.add(viewName);
}
/**
* @return The class name of all asynchronous classes
*/
public Set<String> getAsynchronousClasses() {
return asynchronousClasses;
}
/**
* Returns the type of the session bean
*
* @return
*/
public abstract SessionBeanType getSessionBeanType();
@Override
protected void setupViewInterceptors(EJBViewDescription view) {
// let super do it's job first
super.setupViewInterceptors(view);
// tx management interceptor(s)
addTxManagementInterceptorForView(view);
if(view.isEjb2xView()) {
view.getConfigurators().add(getSessionBeanObjectViewConfigurator());
}
}
protected abstract ViewConfigurator getSessionBeanObjectViewConfigurator();
/**
* Sets up the transaction management interceptor for all methods of the passed view.
*
* @param view The EJB bean view
*/
protected static void addTxManagementInterceptorForView(ViewDescription view) {
// add a Tx configurator
view.getConfigurators().add(new ViewConfigurator() {
@Override
public void configure(DeploymentPhaseContext context, ComponentConfiguration componentConfiguration, ViewDescription description, ViewConfiguration configuration) throws DeploymentUnitProcessingException {
EJBComponentDescription ejbComponentDescription = (EJBComponentDescription) componentConfiguration.getComponentDescription();
// Add CMT interceptor factory
if (TransactionManagementType.CONTAINER.equals(ejbComponentDescription.getTransactionManagementType())) {
configuration.addViewInterceptor(CMTTxInterceptor.FACTORY, InterceptorOrder.View.CMT_TRANSACTION_INTERCEPTOR);
}
}
});
}
@Override
protected void addCurrentInvocationContextFactory() {
// add the current invocation context interceptor at the beginning of the component instance post construct chain
this.getConfigurators().add(new ComponentConfigurator() {
@Override
public void configure(DeploymentPhaseContext context, ComponentDescription description, ComponentConfiguration configuration) throws DeploymentUnitProcessingException {
configuration.addPostConstructInterceptor(CurrentInvocationContextInterceptor.FACTORY, InterceptorOrder.ComponentPostConstruct.EJB_SESSION_CONTEXT_INTERCEPTOR);
configuration.addPreDestroyInterceptor(CurrentInvocationContextInterceptor.FACTORY, InterceptorOrder.ComponentPreDestroy.EJB_SESSION_CONTEXT_INTERCEPTOR);
if(description.isPassivationApplicable()) {
configuration.addPrePassivateInterceptor(CurrentInvocationContextInterceptor.FACTORY, InterceptorOrder.ComponentPassivation.EJB_SESSION_CONTEXT_INTERCEPTOR);
configuration.addPostActivateInterceptor(CurrentInvocationContextInterceptor.FACTORY, InterceptorOrder.ComponentPassivation.EJB_SESSION_CONTEXT_INTERCEPTOR);
}
configuration.getConcurrentContext().addFactory(EJBContextHandleFactory.INSTANCE);
}
});
}
@Override
protected void addCurrentInvocationContextFactory(ViewDescription view) {
view.getConfigurators().add(new ViewConfigurator() {
@Override
public void configure(DeploymentPhaseContext context, ComponentConfiguration componentConfiguration, ViewDescription description, ViewConfiguration configuration) throws DeploymentUnitProcessingException {
configuration.addViewInterceptor(CurrentInvocationContextInterceptor.FACTORY, InterceptorOrder.View.INVOCATION_CONTEXT_INTERCEPTOR);
}
});
}
@Override
public boolean isSession() {
return true;
}
@Override
public boolean isSingleton() {
return getSessionBeanType() == SessionBeanType.SINGLETON;
}
@Override
public boolean isStateful() {
return getSessionBeanType() == SessionBeanType.STATEFUL;
}
@Override
public boolean isStateless() {
return getSessionBeanType() == SessionBeanType.STATELESS;
}
@Override
public SessionBeanMetaData getDescriptorData() {
return (SessionBeanMetaData) super.getDescriptorData();
}
private boolean isNotOverriden(final Method method, final Class<?> actualClass, final DeploymentReflectionIndex deploymentReflectionIndex) throws DeploymentUnitProcessingException {
return Modifier.isPrivate(method.getModifiers()) || ClassReflectionIndexUtil.findRequiredMethod(deploymentReflectionIndex, actualClass, method).getDeclaringClass() == method.getDeclaringClass();
}
}
| 16,894 | 38.566745 | 241 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/session/SessionBeanAllowedMethodsInformation.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.ejb3.component.session;
import java.util.Set;
import org.jboss.as.ee.component.interceptors.InvocationType;
import org.jboss.as.ejb3.component.allowedmethods.AllowedMethodsInformation;
import org.jboss.as.ejb3.component.allowedmethods.DeniedMethodKey;
import org.jboss.as.ejb3.component.allowedmethods.MethodType;
/**
* @author Stuart Douglas
*/
public class SessionBeanAllowedMethodsInformation extends AllowedMethodsInformation {
protected SessionBeanAllowedMethodsInformation(boolean beanManagedTransaction) {
super(beanManagedTransaction);
}
@Override
protected void setup(Set<DeniedMethodKey> denied) {
super.setup(denied);
add(denied, InvocationType.DEPENDENCY_INJECTION, MethodType.GET_EJB_LOCAL_OBJECT);
add(denied, InvocationType.DEPENDENCY_INJECTION, MethodType.GET_EJB_OBJECT);
add(denied, InvocationType.DEPENDENCY_INJECTION, MethodType.GET_CALLER_PRINCIPLE);
add(denied, InvocationType.DEPENDENCY_INJECTION, MethodType.IS_CALLER_IN_ROLE);
add(denied, InvocationType.DEPENDENCY_INJECTION, MethodType.GET_USER_TRANSACTION);
add(denied, InvocationType.DEPENDENCY_INJECTION, MethodType.GET_TIMER_SERVICE);
}
}
| 2,256 | 42.403846 | 90 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/session/SessionBeanComponent.java | /*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, 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.ejb3.component.session;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import jakarta.ejb.EJBLocalObject;
import jakarta.ejb.EJBObject;
import jakarta.ejb.TransactionAttributeType;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.ejb3.component.EJBComponent;
import org.jboss.as.ejb3.concurrency.AccessTimeoutDetails;
import org.jboss.invocation.InterceptorContext;
import static java.util.Collections.emptyMap;
/**
* @author <a href="mailto:[email protected]">Carlo de Wolf</a>
*/
public abstract class SessionBeanComponent extends EJBComponent {
protected final Map<String, AccessTimeoutDetails> beanLevelAccessTimeout;
private final ExecutorService asyncExecutor;
/**
* Construct a new instance.
*
* @param ejbComponentCreateService the component configuration
*/
protected SessionBeanComponent(final SessionBeanComponentCreateService ejbComponentCreateService) {
super(ejbComponentCreateService);
this.beanLevelAccessTimeout = ejbComponentCreateService.getBeanAccessTimeout();
//ejbComponentCreateService.getAsynchronousMethods();
// this.asyncExecutor = (Executor) ejbComponentCreateService.getInjection(ASYNC_EXECUTOR_SERVICE_NAME).getValue();
//if this bean has no async methods, then this will not be injected
this.asyncExecutor = ejbComponentCreateService.getAsyncExecutorService().getOptionalValue();
}
public <T> T getBusinessObject(Class<T> businessInterface, final InterceptorContext context) throws IllegalStateException {
if (businessInterface == null) {
throw EjbLogger.ROOT_LOGGER.businessInterfaceIsNull();
}
return createViewInstanceProxy(businessInterface, emptyMap());
}
public EJBLocalObject getEJBLocalObject(final InterceptorContext ctx) throws IllegalStateException {
if (getEjbLocalObjectViewServiceName() == null) {
throw EjbLogger.ROOT_LOGGER.beanComponentMissingEjbObject(getComponentName(), "EJBLocalObject");
}
return createViewInstanceProxy(EJBLocalObject.class, Collections.<Object, Object>emptyMap(), getEjbLocalObjectViewServiceName());
}
public EJBObject getEJBObject(final InterceptorContext ctx) throws IllegalStateException {
if (getEjbObjectViewServiceName() == null) {
throw EjbLogger.ROOT_LOGGER.beanComponentMissingEjbObject(getComponentName(), "EJBObject");
}
return createViewInstanceProxy(EJBObject.class, Collections.<Object, Object>emptyMap(), getEjbObjectViewServiceName());
}
/**
* Return the {@link java.util.concurrent.Executor} used for asynchronous invocations.
*
* @return the async executor
*/
public ExecutorService 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 EjbLogger.ROOT_LOGGER.getRollBackOnlyIsNotAllowWithSupportsAttribute();
}
return super.getRollbackOnly();
}
@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 EjbLogger.ROOT_LOGGER.setRollbackOnlyNotAllowedForSupportsTxAttr();
}
super.setRollbackOnly();
}
}
| 4,729 | 40.858407 | 137 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/session/InvalidRemoveExceptionMethodInterceptor.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.ejb3.component.session;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
/**
* @author Stuart Douglas
*/
public class InvalidRemoveExceptionMethodInterceptor implements Interceptor {
public static final InterceptorFactory FACTORY = new ImmediateInterceptorFactory(new InvalidRemoveExceptionMethodInterceptor());
public InvalidRemoveExceptionMethodInterceptor() {
}
@Override
public Object processInvocation(final InterceptorContext context) throws Exception {
throw EjbLogger.ROOT_LOGGER.illegalCallToEjbHomeRemove();
}
}
| 1,787 | 38.733333 | 132 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/session/NotBusinessMethodInterceptor.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.ejb3.component.session;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import java.lang.reflect.Method;
/**
* @author Stuart Douglas
*/
public class NotBusinessMethodInterceptor implements Interceptor {
private final Method method;
public NotBusinessMethodInterceptor(final Method method) {
this.method = method;
}
@Override
public Object processInvocation(final InterceptorContext context) throws Exception {
throw EjbLogger.ROOT_LOGGER.failToCallBusinessOnNonePublicMethod(method);
}
}
| 1,659 | 35.086957 | 88 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/session/StatelessRemoteViewInstanceFactory.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.ejb3.component.session;
import java.util.Map;
import org.jboss.as.ee.component.ComponentView;
import org.jboss.as.ee.component.ViewInstanceFactory;
import org.jboss.as.naming.ManagedReference;
import org.jboss.as.naming.ValueManagedReference;
import org.jboss.ejb.client.Affinity;
import org.jboss.ejb.client.EJBClient;
import org.jboss.ejb.client.EJBIdentifier;
import org.jboss.ejb.client.StatelessEJBLocator;
/**
* @author Stuart Douglas
*/
public class StatelessRemoteViewInstanceFactory implements ViewInstanceFactory {
private final EJBIdentifier identifier;
public StatelessRemoteViewInstanceFactory(final String applicationName, final String moduleName, final String distinctName, final String beanName) {
this(new EJBIdentifier(applicationName == null ? "" : applicationName, moduleName, beanName, distinctName));
}
public StatelessRemoteViewInstanceFactory(final EJBIdentifier identifier) {
this.identifier = identifier;
}
@Override
public ManagedReference createViewInstance(final ComponentView componentView, final Map<Object, Object> contextData) {
Object value = EJBClient.createProxy(StatelessEJBLocator.create(componentView.getViewClass(), identifier, Affinity.LOCAL));
return new ValueManagedReference(value);
}
}
| 2,342 | 40.105263 | 152 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/allowedmethods/AllowedMethodsInformation.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.ejb3.component.allowedmethods;
import org.jboss.as.ee.component.Component;
import org.jboss.as.ee.component.interceptors.InvocationType;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.ejb3.component.EJBComponent;
import org.jboss.as.ejb3.component.stateful.CurrentSynchronizationCallback;
import org.jboss.as.ejb3.context.CurrentInvocationContext;
import org.jboss.invocation.InterceptorContext;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
* This class and its subclasses can be used to determine if a given method
* is allowed to be invoked.
*
* @see CurrentInvocationContext
* @see CurrentSynchronizationCallback
*
* @author Stuart Douglas
*/
public class AllowedMethodsInformation {
public static final AllowedMethodsInformation INSTANCE_BMT = new AllowedMethodsInformation(true);
public static final AllowedMethodsInformation INSTANCE_CMT = new AllowedMethodsInformation(false);
private final Set<DeniedMethodKey> denied;
private final Set<DeniedSyncMethodKey> deniedSyncMethods;
private final boolean beanManagedTransaction;
protected AllowedMethodsInformation(boolean beanManagedTransaction) {
this.beanManagedTransaction = beanManagedTransaction;
final Set<DeniedMethodKey> denied = new HashSet<DeniedMethodKey>();
add(denied, InvocationType.SET_ENTITY_CONTEXT, MethodType.TIMER_SERVICE_METHOD);
add(denied, InvocationType.SET_ENTITY_CONTEXT, MethodType.TIMER_SERVICE_METHOD);
add(denied, InvocationType.SET_ENTITY_CONTEXT, MethodType.GET_PRIMARY_KEY);
add(denied, InvocationType.SET_ENTITY_CONTEXT, MethodType.GET_TIMER_SERVICE);
add(denied, InvocationType.SET_ENTITY_CONTEXT, MethodType.IS_CALLER_IN_ROLE);
add(denied, InvocationType.SET_ENTITY_CONTEXT, MethodType.GET_CALLER_PRINCIPLE);
add(denied, InvocationType.HOME_METHOD, MethodType.TIMER_SERVICE_METHOD);
add(denied, InvocationType.HOME_METHOD, MethodType.GET_PRIMARY_KEY);
add(denied, InvocationType.ENTITY_EJB_CREATE, MethodType.TIMER_SERVICE_METHOD);
add(denied, InvocationType.ENTITY_EJB_CREATE, MethodType.GET_PRIMARY_KEY);
setup(denied);
this.denied = Collections.unmodifiableSet(denied);
final Set<DeniedSyncMethodKey> deniedSync = new HashSet<DeniedSyncMethodKey>();
add(deniedSync, CurrentSynchronizationCallback.CallbackType.AFTER_COMPLETION, MethodType.TIMER_SERVICE_METHOD);
add(deniedSync, CurrentSynchronizationCallback.CallbackType.AFTER_COMPLETION, MethodType.GET_ROLLBACK_ONLY);
add(deniedSync, CurrentSynchronizationCallback.CallbackType.AFTER_COMPLETION, MethodType.SET_ROLLBACK_ONLY);
this.deniedSyncMethods = Collections.unmodifiableSet(deniedSync);
}
protected void setup(Set<DeniedMethodKey> denied) {
}
protected static void add(Set<DeniedMethodKey> otherDenied, InvocationType setEntityContext, MethodType timerServiceMethod) {
otherDenied.add(new DeniedMethodKey(setEntityContext, timerServiceMethod));
}
protected static void add(Set<DeniedSyncMethodKey> otherDenied, CurrentSynchronizationCallback.CallbackType callbackType, MethodType timerServiceMethod) {
otherDenied.add(new DeniedSyncMethodKey(callbackType, timerServiceMethod));
}
/**
* Checks that the current method
*/
public static void checkAllowed(final MethodType methodType) {
final InterceptorContext context = CurrentInvocationContext.get();
if (context == null) {
return;
}
final Component component = context.getPrivateData(Component.class);
if (!(component instanceof EJBComponent)) {
return;
}
final InvocationType invocationType = context.getPrivateData(InvocationType.class);
((EJBComponent) component).getAllowedMethodsInformation().realCheckPermission(methodType, invocationType);
}
/**
* transaction sync is not affected by the current invocation, as multiple Jakarta Enterprise Beans methods may be invoked from afterCompletion
*/
private void checkTransactionSync(MethodType methodType) {
//first we have to check the synchronization status
//as the sync is not affected by the current invocation
final CurrentSynchronizationCallback.CallbackType currentSync = CurrentSynchronizationCallback.get();
if (currentSync != null
&& deniedSyncMethods.contains(new DeniedSyncMethodKey(currentSync, methodType))) {
throwException(methodType, currentSync);
}
}
protected void realCheckPermission(MethodType methodType, InvocationType invocationType) {
checkTransactionSync(methodType);
if (invocationType != null
&& denied.contains(new DeniedMethodKey(invocationType, methodType))) {
throwException(methodType, invocationType);
}
if (invocationType != InvocationType.CONCURRENT_CONTEXT
&& !beanManagedTransaction
&& methodType == MethodType.GET_USER_TRANSACTION) {
throw EjbLogger.ROOT_LOGGER.unauthorizedAccessToUserTransaction();
}
}
/**
* throw an exception when a method cannot be invoked
*
* @param methodType the method
* @param invocationType the type of invocation that caused it to be disabled
*/
protected void throwException(MethodType methodType, InvocationType invocationType) {
throw EjbLogger.ROOT_LOGGER.cannotCallMethod(methodType.getLabel(), invocationType.getLabel());
}
/**
* throw an exception when a method cannot be invoked
*
* @param methodType the method
* @param callback the type of invocation that caused it to be disabled
*/
protected void throwException(MethodType methodType, CurrentSynchronizationCallback.CallbackType callback) {
throw EjbLogger.ROOT_LOGGER.cannotCallMethod(methodType.getLabel(), callback.name());
}
private static class DeniedSyncMethodKey {
private final CurrentSynchronizationCallback.CallbackType callbackType;
private final MethodType methodType;
public DeniedSyncMethodKey(CurrentSynchronizationCallback.CallbackType callbackType, MethodType methodType) {
this.callbackType = callbackType;
this.methodType = methodType;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DeniedSyncMethodKey that = (DeniedSyncMethodKey) o;
if (callbackType != that.callbackType) return false;
if (methodType != that.methodType) return false;
return true;
}
@Override
public int hashCode() {
int result = callbackType != null ? callbackType.hashCode() : 0;
result = 31 * result + (methodType != null ? methodType.hashCode() : 0);
return result;
}
}
}
| 8,130 | 40.912371 | 158 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/allowedmethods/MethodType.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.ejb3.component.allowedmethods;
/**
* Enum of Jakarta Enterprise Beans methods controlled by {@link AllowedMethodsInformation}
*
* @author Stuart Douglas
*/
public enum MethodType {
TIMER_SERVICE_METHOD("timer service method"),
GET_EJB_LOCAL_OBJECT("getEJBLocalObject()"),
GET_EJB_OBJECT("getEJBObject()"),
GET_ROLLBACK_ONLY("getRollbackOnly()"),
SET_ROLLBACK_ONLY("setRollbackOnly()"),
GET_PRIMARY_KEY("getPrimaryKey()"),
GET_TIMER_SERVICE("getTimerService()"),
IS_CALLER_IN_ROLE("isCallerInRole()"),
GET_CALLER_PRINCIPLE("getCallerPrinciple()"),
GET_USER_TRANSACTION("getUserTransaction()"),
;
private final String label;
MethodType(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
}
| 1,851 | 33.296296 | 91 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/allowedmethods/DeniedMethodKey.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.ejb3.component.allowedmethods;
import org.jboss.as.ee.component.interceptors.InvocationType;
/**
* @author Stuart Douglas
*/
public final class DeniedMethodKey {
private final InvocationType invocationType;
private final MethodType methodType;
public DeniedMethodKey(InvocationType invocationType, MethodType methodType) {
this.invocationType = invocationType;
this.methodType = methodType;
}
public InvocationType getInvocationType() {
return invocationType;
}
public MethodType getMethodType() {
return methodType;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DeniedMethodKey deniedMethodKey = (DeniedMethodKey) o;
if (invocationType != deniedMethodKey.invocationType) return false;
if (methodType != deniedMethodKey.methodType) return false;
return true;
}
@Override
public int hashCode() {
int result = invocationType != null ? invocationType.hashCode() : 0;
result = 31 * result + (methodType != null ? methodType.hashCode() : 0);
return result;
}
}
| 2,261 | 32.264706 | 82 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/invocationmetrics/InvocationMetrics.java | /*
* JBoss, Home of Professional Open Source.
* Copyright (c) 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.ejb3.component.invocationmetrics;
import java.lang.reflect.Method;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
/**
* @author <a href="mailto:[email protected]">Carlo de Wolf</a>
*/
public class InvocationMetrics {
public static class Values {
final long invocations;
final long executionTime;
final long waitTime;
private Values(final long invocations, final long waitTime, final long executionTime) {
this.invocations = invocations;
this.executionTime = executionTime;
this.waitTime = waitTime;
}
public long getExecutionTime() {
return executionTime;
}
public long getInvocations() {
return invocations;
}
public long getWaitTime() {
return waitTime;
}
}
private final AtomicReference<Values> values = new AtomicReference<Values>(new Values(0, 0, 0));
private final AtomicLong concurrent = new AtomicLong(0);
private final AtomicLong peakConcurrent = new AtomicLong(0);
private final ConcurrentMap<String, AtomicReference<Values>> methods = new ConcurrentHashMap<String, AtomicReference<Values>>();
void finishInvocation(final Method method, final long invocationWaitTime, final long invocationExecutionTime) {
concurrent.decrementAndGet();
for(;;) {
final Values oldv = values.get();
final Values newv = new Values(oldv.invocations + 1, oldv.waitTime + invocationWaitTime, oldv.executionTime + invocationExecutionTime);
if (values.compareAndSet(oldv, newv))
break;
}
final AtomicReference<Values> methodValues = ref(methods, method.getName());
for (;;) {
final Values oldv = methodValues.get();
final Values newv = new Values(oldv.invocations + 1, oldv.waitTime + invocationWaitTime, oldv.executionTime + invocationExecutionTime);
if (methodValues.compareAndSet(oldv, newv))
break;
}
}
private static AtomicReference<Values> ref(final ConcurrentMap<String, AtomicReference<Values>> map, final String key) {
AtomicReference<Values> ref = map.get(key);
if (ref == null) {
ref = new AtomicReference<Values>(new Values(0, 0, 0));
final AtomicReference<Values> prevRef = map.putIfAbsent(key, ref);
if (prevRef != null)
ref = prevRef;
}
return ref;
}
public long getConcurrent() {
return concurrent.get();
}
public long getExecutionTime() {
return values.get().executionTime;
}
public long getInvocations() {
return values.get().invocations;
}
public Map<String, Values> getMethods() {
return new AbstractMap<String, Values>() {
@Override
public Set<Entry<String, Values>> entrySet() {
return new AbstractSet<Entry<String, Values>>() {
@Override
public Iterator<Entry<String, Values>> iterator() {
final Iterator<Entry<String, AtomicReference<Values>>> delegate = methods.entrySet().iterator();
return new Iterator<Entry<String, Values>>() {
@Override
public boolean hasNext() {
return delegate.hasNext();
}
@Override
public Entry<String, Values> next() {
final Entry<String, AtomicReference<Values>> next = delegate.next();
return new Entry<String, Values>() {
@Override
public String getKey() {
return next.getKey();
}
@Override
public Values getValue() {
return next.getValue().get();
}
@Override
public Values setValue(final Values value) {
throw new UnsupportedOperationException("NYI");
}
};
}
@Override
public void remove() {
throw new UnsupportedOperationException("NYI");
}
};
}
@Override
public int size() {
return methods.size();
}
};
}
};
}
public long getPeakConcurrent() {
return peakConcurrent.get();
}
public long getWaitTime() {
return values.get().waitTime;
}
void startInvocation() {
final long v = concurrent.incrementAndGet();
// concurrent might decrement here, but we take that missing peak for granted.
if (peakConcurrent.get() < v)
peakConcurrent.incrementAndGet();
}
}
| 6,665 | 37.091429 | 147 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/invocationmetrics/WaitTimeInterceptor.java | /*
* JBoss, Home of Professional Open Source.
* Copyright (c) 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.ejb3.component.invocationmetrics;
import org.jboss.as.ejb3.component.EJBComponent;
import org.jboss.as.ejb3.component.interceptors.AbstractEJBInterceptor;
import org.jboss.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
/**
* @author <a href="mailto:[email protected]">Carlo de Wolf</a>
*/
public class WaitTimeInterceptor extends AbstractEJBInterceptor {
public static final InterceptorFactory FACTORY = new ImmediateInterceptorFactory(new WaitTimeInterceptor());
static final Object START_WAIT_TIME = new Object();
private WaitTimeInterceptor() {
}
@Override
public Object processInvocation(final InterceptorContext context) throws Exception {
final EJBComponent component = getComponent(context, EJBComponent.class);
if (component.isStatisticsEnabled()) {
context.putPrivateData(START_WAIT_TIME, System.currentTimeMillis());
}
return context.proceed();
}
}
| 2,076 | 40.54 | 112 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/invocationmetrics/ExecutionTimeInterceptor.java | /*
* JBoss, Home of Professional Open Source.
* Copyright (c) 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.ejb3.component.invocationmetrics;
import org.jboss.as.ejb3.component.EJBComponent;
import org.jboss.as.ejb3.component.interceptors.AbstractEJBInterceptor;
import org.jboss.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
/**
* @author <a href="mailto:[email protected]">Carlo de Wolf</a>
*/
public class ExecutionTimeInterceptor extends AbstractEJBInterceptor {
public static final InterceptorFactory FACTORY = new ImmediateInterceptorFactory(new ExecutionTimeInterceptor());
private ExecutionTimeInterceptor() {
}
@Override
public Object processInvocation(final InterceptorContext context) throws Exception {
final EJBComponent component = getComponent(context, EJBComponent.class);
if (!component.isStatisticsEnabled())
return context.proceed();
final Long startWaitTime = (Long) context.getPrivateData(WaitTimeInterceptor.START_WAIT_TIME);
final long waitTime = startWaitTime != null && startWaitTime != 0L ? System.currentTimeMillis() - startWaitTime : 0L;
component.getInvocationMetrics().startInvocation();
final long start = System.currentTimeMillis();
try {
return context.proceed();
} finally {
final long executionTime = System.currentTimeMillis() - start;
component.getInvocationMetrics().finishInvocation(context.getMethod(), waitTime, executionTime);
}
}
}
| 2,556 | 44.660714 | 125 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/pool/StrictMaxPoolConfig.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, 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.ejb3.component.pool;
import org.jboss.as.ejb3.pool.Pool;
import org.jboss.as.ejb3.pool.StatelessObjectFactory;
import org.jboss.as.ejb3.pool.strictmax.StrictMaxPool;
import java.util.concurrent.TimeUnit;
/**
* User: Jaikiran Pai
*/
public class StrictMaxPoolConfig extends PoolConfig {
public static final int DEFAULT_MAX_POOL_SIZE = 20;
public static final long DEFAULT_TIMEOUT = 5;
public static final TimeUnit DEFAULT_TIMEOUT_UNIT = TimeUnit.MINUTES;
private volatile int maxPoolSize;
private volatile TimeUnit timeoutUnit;
private volatile long timeout;
public StrictMaxPoolConfig(final String poolName, int maxSize, long timeout, TimeUnit timeUnit) {
super(poolName);
this.maxPoolSize = maxSize;
this.timeout = timeout;
this.timeoutUnit = timeUnit;
}
@Override
public <T> Pool<T> createPool(final StatelessObjectFactory<T> statelessObjectFactory) {
return new StrictMaxPool<T>(statelessObjectFactory, this.maxPoolSize, this.timeout, this.timeoutUnit);
}
public int getMaxPoolSize() {
return maxPoolSize;
}
public void setMaxPoolSize(int maxPoolSize) {
this.maxPoolSize = maxPoolSize;
}
public TimeUnit getTimeoutUnit() {
return timeoutUnit;
}
public void setTimeoutUnit(TimeUnit timeoutUnit) {
this.timeoutUnit = timeoutUnit;
}
public long getTimeout() {
return timeout;
}
public void setTimeout(long timeout) {
this.timeout = timeout;
}
@Override
public String toString() {
return "StrictMaxPoolConfig{" +
"name=" + this.poolName +
", maxPoolSize=" + maxPoolSize +
", timeoutUnit=" + timeoutUnit +
", timeout=" + timeout +
'}';
}
}
| 2,884 | 29.368421 | 110 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/pool/StrictMaxPoolConfigService.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, 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.ejb3.component.pool;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
/**
* User: jpai
*/
public class StrictMaxPoolConfigService implements Service<StrictMaxPoolConfig> {
private final Consumer<StrictMaxPoolConfig> configConsumer;
private final Supplier<Integer> maxThreadsSupplier;
private final StrictMaxPoolConfig poolConfig;
private volatile int declaredMaxSize;
public enum Derive {NONE, FROM_WORKER_POOLS, FROM_CPU_COUNT}
private volatile Derive derive;
public StrictMaxPoolConfigService(final Consumer<StrictMaxPoolConfig> configConsumer, final Supplier<Integer> maxThreadsSupplier, final String poolName, int declaredMaxSize, Derive derive, long timeout, TimeUnit timeUnit) {
this.configConsumer = configConsumer;
this.maxThreadsSupplier = maxThreadsSupplier;
this.declaredMaxSize = declaredMaxSize;
this.derive = derive;
this.poolConfig = new StrictMaxPoolConfig(poolName, declaredMaxSize, timeout, timeUnit);
}
@Override
public void start(final StartContext context) throws StartException {
setDerive(derive);
configConsumer.accept(poolConfig);
}
@Override
public void stop(final StopContext context) {
configConsumer.accept(null);
}
@Override
public StrictMaxPoolConfig getValue() {
return poolConfig;
}
private int calcMaxFromWorkPools() {
Integer max = maxThreadsSupplier != null ? maxThreadsSupplier.get() : null;
return max != null && max > 0 ? max : calcMaxFromCPUCount();
}
private int calcMaxFromCPUCount() {
return Runtime.getRuntime().availableProcessors() * 4;
}
public synchronized void setMaxPoolSize(int newMax) {
this.declaredMaxSize = newMax;
if (derive == Derive.NONE) {
poolConfig.setMaxPoolSize(newMax);
}
}
public synchronized int getDerivedSize() {
return poolConfig.getMaxPoolSize();
}
public synchronized void setDerive(Derive derive) {
this.derive = derive;
int max = this.declaredMaxSize;
switch (derive) {
case FROM_WORKER_POOLS: {
max = calcMaxFromWorkPools();
EjbLogger.ROOT_LOGGER.strictPoolDerivedFromWorkers(poolConfig.getPoolName(), max);
break;
}
case FROM_CPU_COUNT: {
max = calcMaxFromCPUCount();
EjbLogger.ROOT_LOGGER.strictPoolDerivedFromCPUs(poolConfig.getPoolName(), max);
break;
}
}
poolConfig.setMaxPoolSize(max);
}
public void setTimeout(long timeout) {
poolConfig.setTimeout(timeout);
}
public void setTimeoutUnit(TimeUnit timeUnit) {
poolConfig.setTimeoutUnit(timeUnit);
}
}
| 4,135 | 32.626016 | 227 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/pool/PooledComponent.java | /*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, 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.ejb3.component.pool;
import org.jboss.as.ee.component.Component;
import org.jboss.as.ee.component.ComponentInstance;
import org.jboss.as.ejb3.pool.Pool;
/**
* @author <a href="mailto:[email protected]">Carlo de Wolf</a>
*/
public interface PooledComponent<I extends ComponentInstance> extends Component {
Pool<I> getPool();
String getPoolName();
}
| 1,410 | 38.194444 | 81 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/pool/PooledInstanceInterceptor.java | /*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, 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.ejb3.component.pool;
import java.rmi.RemoteException;
import jakarta.ejb.ConcurrentAccessException;
import jakarta.ejb.ConcurrentAccessTimeoutException;
import org.jboss.as.ee.component.ComponentInstance;
import org.jboss.as.ejb3.component.interceptors.AbstractEJBInterceptor;
import org.jboss.as.ejb3.component.EJBComponent;
import org.jboss.invocation.InterceptorContext;
/**
* @author <a href="mailto:[email protected]">Carlo de Wolf</a>
*/
public class PooledInstanceInterceptor extends AbstractEJBInterceptor {
public static final PooledInstanceInterceptor INSTANCE = new PooledInstanceInterceptor();
private PooledInstanceInterceptor() {
}
@Override
public Object processInvocation(InterceptorContext context) throws Exception {
PooledComponent<ComponentInstance> component = (PooledComponent<ComponentInstance>) getComponent(context, EJBComponent.class);
ComponentInstance instance = component.getPool().get();
context.putPrivateData(ComponentInstance.class, instance);
boolean discarded = false;
try {
return context.proceed();
} catch (Exception ex) {
final EJBComponent ejbComponent = (EJBComponent)component;
// Detect app exception
if (ejbComponent.getApplicationException(ex.getClass(), context.getMethod()) != null) {
// it's an application exception, just throw it back.
throw ex;
}
if(ex instanceof ConcurrentAccessTimeoutException || ex instanceof ConcurrentAccessException) {
throw ex;
}
if (ex instanceof RuntimeException || ex instanceof RemoteException) {
discarded = true;
component.getPool().discard(instance);
}
throw ex;
} catch (final Error e) {
discarded = true;
component.getPool().discard(instance);
throw e;
} catch (final Throwable t) {
discarded = true;
component.getPool().discard(instance);
throw new RuntimeException(t);
} finally {
if (!discarded) {
component.getPool().release(instance);
}
}
}
}
| 3,308 | 39.353659 | 134 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/pool/PoolConfig.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, 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.ejb3.component.pool;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.ejb3.pool.Pool;
import org.jboss.as.ejb3.pool.StatelessObjectFactory;
/**
* User: jpai
*/
public abstract class PoolConfig {
protected final String poolName;
public PoolConfig(final String poolName) {
if (poolName == null || poolName.trim().isEmpty()) {
throw EjbLogger.ROOT_LOGGER.poolConfigIsEmpty();
}
this.poolName = poolName;
}
public String getPoolName() {
return this.poolName;
}
public abstract <T> Pool<T> createPool(final StatelessObjectFactory<T> statelessObjectFactory);
}
| 1,691 | 33.530612 | 99 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateless/StatelessSessionComponent.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.ejb3.component.stateless;
import java.lang.reflect.Method;
import java.util.Map;
import org.jboss.as.ee.component.BasicComponentInstance;
import org.jboss.as.ejb3.component.allowedmethods.AllowedMethodsInformation;
import org.jboss.as.ejb3.component.pool.PoolConfig;
import org.jboss.as.ejb3.component.pool.PooledComponent;
import org.jboss.as.ejb3.component.session.SessionBeanComponent;
import org.jboss.as.ejb3.pool.Pool;
import org.jboss.as.ejb3.pool.StatelessObjectFactory;
import org.jboss.ejb.client.Affinity;
import org.jboss.invocation.Interceptor;
import static org.jboss.as.ejb3.logging.EjbLogger.ROOT_LOGGER;
/**
* {@link org.jboss.as.ee.component.Component} responsible for managing EJB3 stateless session beans
* <p/>
* <p/>
* Author : Jaikiran Pai
*/
public class StatelessSessionComponent extends SessionBeanComponent implements PooledComponent<StatelessSessionComponentInstance> {
private final Pool<StatelessSessionComponentInstance> pool;
private final String poolName;
private final Method timeoutMethod;
private final Affinity weakAffinity;
/**
* Constructs a StatelessEJBComponent for a stateless session bean
*
* @param slsbComponentCreateService
*/
public StatelessSessionComponent(final StatelessSessionComponentCreateService slsbComponentCreateService) {
super(slsbComponentCreateService);
StatelessObjectFactory<StatelessSessionComponentInstance> factory = new StatelessObjectFactory<StatelessSessionComponentInstance>() {
@Override
public StatelessSessionComponentInstance create() {
return (StatelessSessionComponentInstance) createInstance();
}
@Override
public void destroy(StatelessSessionComponentInstance obj) {
obj.destroy();
}
};
final PoolConfig poolConfig = slsbComponentCreateService.getPoolConfig();
if (poolConfig == null) {
ROOT_LOGGER.debugf("Pooling is disabled for Stateless EJB %s", slsbComponentCreateService.getComponentName());
this.pool = null;
this.poolName = null;
} else {
ROOT_LOGGER.debugf("Using pool config %s to create pool for Stateless EJB %s", poolConfig, slsbComponentCreateService.getComponentName());
this.pool = poolConfig.createPool(factory);
this.poolName = poolConfig.getPoolName();
}
this.timeoutMethod = slsbComponentCreateService.getTimeoutMethod();
this.weakAffinity = slsbComponentCreateService.getWeakAffinity();
}
@Override
protected BasicComponentInstance instantiateComponentInstance(Interceptor preDestroyInterceptor, Map<Method, Interceptor> methodInterceptors, Map<Object, Object> context) {
return new StatelessSessionComponentInstance(this, preDestroyInterceptor, methodInterceptors);
}
@Override
public Pool<StatelessSessionComponentInstance> getPool() {
return pool;
}
@Override
public String getPoolName() {
return poolName;
}
@Override
public Method getTimeoutMethod() {
return timeoutMethod;
}
@Override
public void init() {
super.init();
if(this.pool!=null){
this.pool.start();
}
}
@Override
public void done() {
if(this.pool!=null){
this.pool.stop();
}
super.done();
}
@Override
public AllowedMethodsInformation getAllowedMethodsInformation() {
return isBeanManagedTransaction() ? StatelessAllowedMethodsInformation.INSTANCE_BMT : StatelessAllowedMethodsInformation.INSTANCE_CMT;
}
}
| 4,733 | 35.415385 | 176 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateless/StatelessSessionBeanObjectViewConfigurator.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.ejb3.component.stateless;
import java.lang.reflect.Method;
import org.jboss.as.ee.component.ComponentConfiguration;
import org.jboss.as.ee.component.ViewConfiguration;
import org.jboss.as.ee.component.ViewDescription;
import org.jboss.as.ee.component.interceptors.InterceptorOrder;
import org.jboss.as.ejb3.component.interceptors.ComponentTypeIdentityInterceptorFactory;
import org.jboss.as.ejb3.component.session.SessionBeanObjectViewConfigurator;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex;
import org.jboss.invocation.Interceptors;
/**
* @author Stuart Douglas
*/
public class StatelessSessionBeanObjectViewConfigurator extends SessionBeanObjectViewConfigurator {
public static final StatelessSessionBeanObjectViewConfigurator INSTANCE = new StatelessSessionBeanObjectViewConfigurator();
@Override
protected void handleIsIdenticalMethod(final ComponentConfiguration componentConfiguration, final ViewConfiguration configuration, final DeploymentReflectionIndex index, final Method method) {
configuration.addClientInterceptor(method, ComponentTypeIdentityInterceptorFactory.INSTANCE, InterceptorOrder.Client.EJB_EQUALS_HASHCODE);
}
@Override
protected void handleRemoveMethod(final ComponentConfiguration componentConfiguration, final ViewConfiguration configuration, final DeploymentReflectionIndex index, final Method method) throws DeploymentUnitProcessingException {
configuration.addClientInterceptor(method, ViewDescription.CLIENT_DISPATCHER_INTERCEPTOR_FACTORY, InterceptorOrder.Client.CLIENT_DISPATCHER);
configuration.addViewInterceptor(method, Interceptors.getTerminalInterceptorFactory(), InterceptorOrder.View.COMPONENT_DISPATCHER);
}
}
| 2,852 | 50.872727 | 232 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateless/StatelessComponentCreateServiceFactory.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, 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.ejb3.component.stateless;
import org.jboss.as.ee.component.BasicComponentCreateService;
import org.jboss.as.ee.component.ComponentConfiguration;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.ejb3.component.EJBComponentCreateServiceFactory;
/**
* User: jpai
*/
public class StatelessComponentCreateServiceFactory extends EJBComponentCreateServiceFactory {
@Override
public BasicComponentCreateService constructService(ComponentConfiguration configuration) {
if (this.ejbJarConfiguration == null) {
throw EjbLogger.ROOT_LOGGER.ejbJarConfigNotBeenSet(this, configuration.getComponentName());
}
return new StatelessSessionComponentCreateService(configuration, this.ejbJarConfiguration);
}
}
| 1,803 | 40.953488 | 103 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateless/StatelessComponentDescription.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.ejb3.component.stateless;
import static org.jboss.as.server.deployment.Attachments.CAPABILITY_SERVICE_SUPPORT;
import java.lang.reflect.Method;
import java.util.Collection;
import jakarta.ejb.TransactionManagementType;
import org.jboss.as.controller.capability.CapabilityServiceSupport;
import org.jboss.as.ee.component.Attachments;
import org.jboss.as.ee.component.Component;
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.DependencyConfigurator;
import org.jboss.as.ee.component.EEApplicationClasses;
import org.jboss.as.ee.component.ViewConfiguration;
import org.jboss.as.ee.component.ViewConfigurator;
import org.jboss.as.ee.component.ViewDescription;
import org.jboss.as.ee.component.interceptors.InterceptorClassDescription;
import org.jboss.as.ee.component.interceptors.InterceptorOrder;
import org.jboss.as.ee.component.serialization.WriteReplaceInterface;
import org.jboss.as.ee.metadata.MetadataCompleteMarker;
import org.jboss.as.ejb3.component.EJBViewDescription;
import org.jboss.as.ejb3.component.interceptors.ComponentTypeIdentityInterceptorFactory;
import org.jboss.as.ejb3.component.pool.PoolConfig;
import org.jboss.as.ejb3.component.session.SessionBeanComponentDescription;
import org.jboss.as.ejb3.component.session.StatelessRemoteViewInstanceFactory;
import org.jboss.as.ejb3.component.session.StatelessWriteReplaceInterceptor;
import org.jboss.as.ejb3.deployment.EjbJarDescription;
import org.jboss.as.ejb3.tx.EjbBMTInterceptor;
import org.jboss.as.ejb3.tx.LifecycleCMTTxInterceptor;
import org.jboss.as.ejb3.tx.TimerCMTTxInterceptor;
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.reflect.ClassReflectionIndex;
import org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex;
import org.jboss.metadata.ejb.spec.MethodInterfaceType;
import org.jboss.metadata.ejb.spec.SessionBeanMetaData;
import org.jboss.modules.ModuleLoader;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
/**
* User: jpai
*/
public class StatelessComponentDescription extends SessionBeanComponentDescription {
private static final String STRICT_MAX_POOL_CONFIG_CAPABILITY_NAME = "org.wildfly.ejb3.pool-config";
private static final String DEFAULT_SLSB_POOL_CONFIG_CAPABILITY_NAME = "org.wildfly.ejb3.pool-config.slsb-default";
private String poolConfigName;
private final boolean defaultSlsbPoolAvailable;
/**
* Construct a new instance.
*
* @param componentName the component name
* @param componentClassName the component instance class name
* @param ejbModuleDescription the module description
*/
public StatelessComponentDescription(final String componentName, final String componentClassName, final EjbJarDescription ejbModuleDescription,
final DeploymentUnit deploymentUnit, final SessionBeanMetaData descriptorData, final boolean defaultSlsbPoolAvailable) {
super(componentName, componentClassName, ejbModuleDescription, deploymentUnit, descriptorData);
this.defaultSlsbPoolAvailable = defaultSlsbPoolAvailable;
}
@Override
public ComponentConfiguration createConfiguration(final ClassReflectionIndex classIndex, final ClassLoader moduleClassLoader, final ModuleLoader moduleLoader) {
final ComponentConfiguration statelessComponentConfiguration = new ComponentConfiguration(this, classIndex, moduleClassLoader, moduleLoader);
// setup the component create service
statelessComponentConfiguration.setComponentCreateServiceFactory(new StatelessComponentCreateServiceFactory());
// setup the configurator to inject the PoolConfig in the StatelessSessionComponentCreateService
final StatelessComponentDescription statelessComponentDescription = (StatelessComponentDescription) statelessComponentConfiguration.getComponentDescription();
// setup a configurator to inject the PoolConfig in the StatelessSessionComponentCreateService
getConfigurators().add(new ComponentConfigurator() {
@Override
public void configure(DeploymentPhaseContext context, ComponentDescription description, ComponentConfiguration configuration) throws DeploymentUnitProcessingException {
//get CapabilitySupport to resolve service names
final CapabilityServiceSupport support = context.getDeploymentUnit().getAttachment(CAPABILITY_SERVICE_SUPPORT);
configuration.getCreateDependencies().add(new DependencyConfigurator<Service<Component>>() {
@Override
public void configureDependency(ServiceBuilder<?> serviceBuilder, Service<Component> service) throws DeploymentUnitProcessingException {
final StatelessSessionComponentCreateService statelessSessionComponentCreateService = (StatelessSessionComponentCreateService) service;
final String poolName = statelessComponentDescription.getPoolConfigName();
// if no pool name has been explicitly set, then inject the *optional* "default slsb pool config".
// If the default slsb pool config itself is not configured, then the pooling is disabled for the bean
if (poolName == null) {
if (statelessComponentDescription.isDefaultSlsbPoolAvailable()) {
ServiceName defaultPoolConfigServiceName = support.getCapabilityServiceName(DEFAULT_SLSB_POOL_CONFIG_CAPABILITY_NAME);
serviceBuilder.addDependency(defaultPoolConfigServiceName, PoolConfig.class, statelessSessionComponentCreateService.getPoolConfigInjector());
}
} else {
// pool name has been explicitly set so the pool config is a required dependency
ServiceName poolConfigServiceName = support.getCapabilityServiceName(STRICT_MAX_POOL_CONFIG_CAPABILITY_NAME, poolName);
serviceBuilder.addDependency(poolConfigServiceName, PoolConfig.class, statelessSessionComponentCreateService.getPoolConfigInjector());
}
}
});
}
});
// add the bmt interceptor
if (TransactionManagementType.BEAN.equals(this.getTransactionManagementType())) {
getConfigurators().add(new ComponentConfigurator() {
@Override
public void configure(final DeploymentPhaseContext context, final ComponentDescription description, final ComponentConfiguration configuration) throws DeploymentUnitProcessingException {
// add the bmt interceptor factory
configuration.addComponentInterceptor(EjbBMTInterceptor.FACTORY, InterceptorOrder.Component.BMT_TRANSACTION_INTERCEPTOR, false);
}
});
}
getConfigurators().add(new ComponentConfigurator() {
@Override
public void configure(final DeploymentPhaseContext context, final ComponentDescription description, final ComponentConfiguration configuration) throws DeploymentUnitProcessingException {
if (TransactionManagementType.CONTAINER.equals(getTransactionManagementType())) {
final EEApplicationClasses applicationClasses = context.getDeploymentUnit().getAttachment(Attachments.EE_APPLICATION_CLASSES_DESCRIPTION);
InterceptorClassDescription interceptorConfig = ComponentDescription.mergeInterceptorConfig(configuration.getComponentClass(), applicationClasses.getClassByName(description.getComponentClassName()), description, MetadataCompleteMarker.isMetadataComplete(context.getDeploymentUnit()));
configuration.addPostConstructInterceptor(new LifecycleCMTTxInterceptor.Factory(interceptorConfig.getPostConstruct(), true), InterceptorOrder.ComponentPostConstruct.TRANSACTION_INTERCEPTOR);
configuration.addPreDestroyInterceptor(new LifecycleCMTTxInterceptor.Factory(interceptorConfig.getPreDestroy(), true), InterceptorOrder.ComponentPreDestroy.TRANSACTION_INTERCEPTOR);
configuration.addTimeoutViewInterceptor(TimerCMTTxInterceptor.FACTORY, InterceptorOrder.View.CMT_TRANSACTION_INTERCEPTOR);
}
configuration.addTimeoutViewInterceptor(StatelessComponentInstanceAssociatingFactory.instance(), InterceptorOrder.View.ASSOCIATING_INTERCEPTOR);
}
});
return statelessComponentConfiguration;
}
@Override
public SessionBeanType getSessionBeanType() {
return SessionBeanComponentDescription.SessionBeanType.STATELESS;
}
@Override
protected void setupViewInterceptors(EJBViewDescription view) {
// let super do its job first
super.setupViewInterceptors(view);
addViewSerializationInterceptor(view);
// add the instance associating interceptor at the start of the interceptor chain
view.getConfigurators().addFirst(new ViewConfigurator() {
@Override
public void configure(DeploymentPhaseContext context, ComponentConfiguration componentConfiguration, ViewDescription description, ViewConfiguration configuration) throws DeploymentUnitProcessingException {
//add equals/hashCode interceptor
//add equals/hashCode interceptor
for (Method method : configuration.getProxyFactory().getCachedMethods()) {
if ((method.getName().equals("hashCode") && method.getParameterCount() == 0) ||
method.getName().equals("equals") && method.getParameterCount() == 1 &&
method.getParameterTypes()[0] == Object.class) {
configuration.addClientInterceptor(method, ComponentTypeIdentityInterceptorFactory.INSTANCE, InterceptorOrder.Client.EJB_EQUALS_HASHCODE);
}
}
// add the stateless component instance associating interceptor
configuration.addViewInterceptor(StatelessComponentInstanceAssociatingFactory.instance(), InterceptorOrder.View.ASSOCIATING_INTERCEPTOR);
}
});
if (view.getMethodIntf() == MethodInterfaceType.Remote) {
view.getConfigurators().add(new ViewConfigurator() {
@Override
public void configure(final DeploymentPhaseContext context, final ComponentConfiguration componentConfiguration, final ViewDescription description, final ViewConfiguration configuration) throws DeploymentUnitProcessingException {
final String earApplicationName = componentConfiguration.getComponentDescription().getModuleDescription().getEarApplicationName();
configuration.setViewInstanceFactory(new StatelessRemoteViewInstanceFactory(earApplicationName, componentConfiguration.getModuleName(), componentConfiguration.getComponentDescription().getModuleDescription().getDistinctName(), componentConfiguration.getComponentName()));
}
});
}
}
private void addViewSerializationInterceptor(final ViewDescription view) {
view.setSerializable(true);
view.setUseWriteReplace(true);
view.getConfigurators().add(new ViewConfigurator() {
@Override
public void configure(final DeploymentPhaseContext context, final ComponentConfiguration componentConfiguration, final ViewDescription description, final ViewConfiguration configuration) throws DeploymentUnitProcessingException {
final DeploymentReflectionIndex index = context.getDeploymentUnit().getAttachment(org.jboss.as.server.deployment.Attachments.REFLECTION_INDEX);
ClassReflectionIndex classIndex = index.getClassIndex(WriteReplaceInterface.class);
for (Method method : (Collection<Method>)classIndex.getMethods()) {
configuration.addClientInterceptor(method, StatelessWriteReplaceInterceptor.factory(configuration.getViewServiceName().getCanonicalName()), InterceptorOrder.Client.WRITE_REPLACE);
}
}
});
}
@Override
protected ViewConfigurator getSessionBeanObjectViewConfigurator() {
return StatelessSessionBeanObjectViewConfigurator.INSTANCE;
}
boolean isDefaultSlsbPoolAvailable() {
return defaultSlsbPoolAvailable;
}
@Override
public boolean isTimerServiceApplicable() {
return true;
}
public void setPoolConfigName(final String poolConfigName) {
this.poolConfigName = poolConfigName;
}
public String getPoolConfigName() {
return this.poolConfigName;
}
}
| 14,271 | 57.975207 | 304 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateless/StatelessSessionComponentCreateService.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, 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.ejb3.component.stateless;
import org.jboss.as.ee.component.BasicComponent;
import org.jboss.as.ee.component.ComponentConfiguration;
import org.jboss.as.ejb3.component.pool.PoolConfig;
import org.jboss.as.ejb3.component.session.SessionBeanComponentCreateService;
import org.jboss.as.ejb3.deployment.ApplicationExceptions;
import org.jboss.ejb.client.Affinity;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.value.InjectedValue;
/**
* @author Stuart Douglas
*/
public class StatelessSessionComponentCreateService extends SessionBeanComponentCreateService {
private final InjectedValue<PoolConfig> poolConfig = new InjectedValue<>();
/**
* Construct a new instance.
*
* @param componentConfiguration the component configuration
*/
public StatelessSessionComponentCreateService(final ComponentConfiguration componentConfiguration, final ApplicationExceptions ejbJarConfiguration) {
super(componentConfiguration, ejbJarConfiguration);
}
@Override
protected BasicComponent createComponent() {
return new StatelessSessionComponent(this);
}
public PoolConfig getPoolConfig() {
return this.poolConfig.getOptionalValue();
}
public Injector<PoolConfig> getPoolConfigInjector() {
return this.poolConfig;
}
public Affinity getWeakAffinity() {
return Affinity.NONE;
}
}
| 2,436 | 34.838235 | 153 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateless/StatelessSessionComponentInstance.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.ejb3.component.stateless;
import java.lang.reflect.Method;
import java.util.Map;
import org.jboss.as.ee.component.BasicComponent;
import org.jboss.as.ejb3.component.session.SessionBeanComponentInstance;
import org.jboss.ejb.client.SessionID;
import org.jboss.invocation.Interceptor;
/**
* Author : Jaikiran Pai
*/
public class StatelessSessionComponentInstance extends SessionBeanComponentInstance {
/**
* Construct a new instance.
*
* @param component the component
*/
protected StatelessSessionComponentInstance(final BasicComponent component, final Interceptor preDestroyInterceptor, final Map<Method, Interceptor> methodInterceptors) {
super(component, preDestroyInterceptor, methodInterceptors);
}
@Override
protected SessionID getId() {
return null;
}
}
| 1,883 | 34.54717 | 173 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateless/StatelessAllowedMethodsInformation.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.ejb3.component.stateless;
import java.util.Set;
import org.jboss.as.ee.component.interceptors.InvocationType;
import org.jboss.as.ejb3.component.allowedmethods.DeniedMethodKey;
import org.jboss.as.ejb3.component.allowedmethods.MethodType;
import org.jboss.as.ejb3.component.session.SessionBeanAllowedMethodsInformation;
/**
* @author Stuart Douglas
*/
public class StatelessAllowedMethodsInformation extends SessionBeanAllowedMethodsInformation {
public static final StatelessAllowedMethodsInformation INSTANCE_BMT = new StatelessAllowedMethodsInformation(true);
public static final StatelessAllowedMethodsInformation INSTANCE_CMT = new StatelessAllowedMethodsInformation(false);
protected StatelessAllowedMethodsInformation(boolean beanManagedTransaction) {
super(beanManagedTransaction);
}
@Override
protected void setup(Set<DeniedMethodKey> denied) {
super.setup(denied);
add(denied, InvocationType.POST_CONSTRUCT, MethodType.GET_CALLER_PRINCIPLE);
add(denied, InvocationType.PRE_DESTROY, MethodType.GET_CALLER_PRINCIPLE);
add(denied, InvocationType.POST_CONSTRUCT, MethodType.IS_CALLER_IN_ROLE);
add(denied, InvocationType.PRE_DESTROY, MethodType.IS_CALLER_IN_ROLE);
}
}
| 2,304 | 42.490566 | 120 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/stateless/StatelessComponentInstanceAssociatingFactory.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, 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.ejb3.component.stateless;
import org.jboss.as.ee.component.Component;
import org.jboss.as.ee.component.ComponentInterceptorFactory;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.ejb3.component.interceptors.NonPooledEJBComponentInstanceAssociatingInterceptor;
import org.jboss.as.ejb3.component.pool.PooledInstanceInterceptor;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorFactoryContext;
/**
* User: jpai
*/
public class StatelessComponentInstanceAssociatingFactory extends ComponentInterceptorFactory {
private static final StatelessComponentInstanceAssociatingFactory INSTANCE = new StatelessComponentInstanceAssociatingFactory();
private StatelessComponentInstanceAssociatingFactory() {
}
public static StatelessComponentInstanceAssociatingFactory instance() {
return INSTANCE;
}
@Override
protected Interceptor create(Component component, InterceptorFactoryContext context) {
if (component instanceof StatelessSessionComponent == false) {
throw EjbLogger.ROOT_LOGGER.unexpectedComponent(component, StatelessSessionComponent.class);
}
final StatelessSessionComponent statelessSessionComponent = (StatelessSessionComponent) component;
if (statelessSessionComponent.getPool() != null) {
return PooledInstanceInterceptor.INSTANCE;
} else {
return NonPooledEJBComponentInstanceAssociatingInterceptor.INSTANCE;
}
}
}
| 2,545 | 40.737705 | 132 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/messagedriven/MdbDeliveryControllerService.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2015, 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.ejb3.component.messagedriven;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
/**
* Service that controls delivery for a specific MDB.
*
* When started, delivery to a mdb is enabled, when stopped, it is disabled.
*
* @author Flavia Rainone
*/
public class MdbDeliveryControllerService implements Service<MdbDeliveryControllerService> {
private final InjectedValue<MessageDrivenComponent> mdbComponent = new InjectedValue<MessageDrivenComponent>();
public MdbDeliveryControllerService getValue() throws IllegalStateException, IllegalArgumentException {
return this;
}
public InjectedValue<MessageDrivenComponent> getMdbComponent() {
return mdbComponent;
}
public void start(final StartContext context) throws StartException {
mdbComponent.getValue().startDelivery();
}
public void stop(final StopContext context) {
mdbComponent.getValue().stopDelivery();
}
}
| 2,146 | 36.017241 | 115 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/messagedriven/MessageDrivenAllowedMethodsInformation.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.ejb3.component.messagedriven;
import java.util.Set;
import org.jboss.as.ee.component.interceptors.InvocationType;
import org.jboss.as.ejb3.component.allowedmethods.AllowedMethodsInformation;
import org.jboss.as.ejb3.component.allowedmethods.DeniedMethodKey;
import org.jboss.as.ejb3.component.allowedmethods.MethodType;
/**
* @author Stuart Douglas
*/
public class MessageDrivenAllowedMethodsInformation extends AllowedMethodsInformation {
public static final MessageDrivenAllowedMethodsInformation INSTANCE_BMT = new MessageDrivenAllowedMethodsInformation(true);
public static final MessageDrivenAllowedMethodsInformation INSTANCE_CMT = new MessageDrivenAllowedMethodsInformation(false);
protected MessageDrivenAllowedMethodsInformation(boolean beanManagedTransaction) {
super(beanManagedTransaction);
}
@Override
protected void setup(Set<DeniedMethodKey> denied) {
super.setup(denied);
add(denied, InvocationType.DEPENDENCY_INJECTION, MethodType.GET_CALLER_PRINCIPLE);
add(denied, InvocationType.DEPENDENCY_INJECTION, MethodType.IS_CALLER_IN_ROLE);
add(denied, InvocationType.DEPENDENCY_INJECTION, MethodType.GET_USER_TRANSACTION);
add(denied, InvocationType.DEPENDENCY_INJECTION, MethodType.GET_TIMER_SERVICE);
add(denied, InvocationType.POST_CONSTRUCT, MethodType.GET_CALLER_PRINCIPLE);
add(denied, InvocationType.PRE_DESTROY, MethodType.GET_CALLER_PRINCIPLE);
add(denied, InvocationType.POST_CONSTRUCT, MethodType.IS_CALLER_IN_ROLE);
add(denied, InvocationType.PRE_DESTROY, MethodType.IS_CALLER_IN_ROLE);
}
}
| 2,675 | 45.947368 | 128 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/messagedriven/MessageDrivenComponentCreateServiceFactory.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, 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.ejb3.component.messagedriven;
import org.jboss.as.ee.component.BasicComponentCreateService;
import org.jboss.as.ee.component.ComponentConfiguration;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.ejb3.component.EJBComponentCreateServiceFactory;
/**
* User: jpai
*/
public class MessageDrivenComponentCreateServiceFactory extends EJBComponentCreateServiceFactory {
private final Class<?> messageListenerInterface;
public MessageDrivenComponentCreateServiceFactory(final Class<?> messageListenerInterface) {
this.messageListenerInterface = messageListenerInterface;
}
@Override
public BasicComponentCreateService constructService(ComponentConfiguration configuration) {
if (this.ejbJarConfiguration == null) {
throw EjbLogger.ROOT_LOGGER.ejbJarConfigNotBeenSet(this, configuration.getComponentName());
}
return new MessageDrivenComponentCreateService(configuration, this.ejbJarConfiguration, messageListenerInterface);
}
}
| 2,057 | 41.875 | 122 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/messagedriven/MessageDrivenBeanSetMessageDrivenContextInterceptor.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, 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.ejb3.component.messagedriven;
import jakarta.ejb.MessageDrivenBean;
import jakarta.ejb.MessageDrivenContext;
import org.jboss.as.ee.component.ComponentInstance;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
/**
* An interceptor for MDBs, which will invoke the {@link MessageDrivenBean#setMessageDrivenContext(jakarta.ejb.MessageDrivenContext)}
* method.
*
* @author Jaikiran Pai
*/
public class MessageDrivenBeanSetMessageDrivenContextInterceptor implements Interceptor {
static final MessageDrivenBeanSetMessageDrivenContextInterceptor INSTANCE = new MessageDrivenBeanSetMessageDrivenContextInterceptor();
private MessageDrivenBeanSetMessageDrivenContextInterceptor() {
}
@Override
public Object processInvocation(InterceptorContext context) throws Exception {
final MessageDrivenComponentInstance componentInstance = (MessageDrivenComponentInstance) context.getPrivateData(ComponentInstance.class);
final MessageDrivenContext messageDrivenContext = (MessageDrivenContext) componentInstance.getEjbContext();
((MessageDrivenBean) context.getTarget()).setMessageDrivenContext(messageDrivenContext);
return context.proceed();
}
}
| 2,284 | 41.314815 | 146 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/messagedriven/MessageDrivenComponentInstance.java | /*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, 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.ejb3.component.messagedriven;
import java.lang.reflect.Method;
import java.util.Map;
import org.jboss.as.ee.component.BasicComponent;
import org.jboss.as.ejb3.component.EjbComponentInstance;
import org.jboss.as.ejb3.context.EJBContextImpl;
import org.jboss.as.ejb3.context.MessageDrivenContext;
import org.jboss.invocation.Interceptor;
/**
* @author <a href="mailto:[email protected]">Carlo de Wolf</a>
*/
public class MessageDrivenComponentInstance extends EjbComponentInstance {
private final MessageDrivenContext messageDrivenContext;
/**
* Construct a new instance.
*
* @param component the component
*/
public MessageDrivenComponentInstance(final BasicComponent component, final Interceptor preDestroyInterceptor, final Map<Method, Interceptor> methodInterceptors) {
super(component, preDestroyInterceptor, methodInterceptors);
this.messageDrivenContext = new MessageDrivenContext(this);
}
@Override
public MessageDrivenComponent getComponent() {
return (MessageDrivenComponent) super.getComponent();
}
/**
* Returns a {@link jakarta.ejb.MessageDrivenContext}
* @return
*/
@Override
public EJBContextImpl getEjbContext() {
return messageDrivenContext;
}
}
| 2,331 | 34.876923 | 167 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/messagedriven/DefaultResourceAdapterService.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, 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.ejb3.component.messagedriven;
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;
/**
* User: jpai
*/
public class DefaultResourceAdapterService implements Service<DefaultResourceAdapterService> {
public static final ServiceName DEFAULT_RA_NAME_SERVICE_NAME = ServiceName.JBOSS.append("ejb").append("default-resource-adapter-name-service");
private volatile String defaultResourceAdapterName;
public DefaultResourceAdapterService(final String resourceAdapterName) {
this.defaultResourceAdapterName = resourceAdapterName;
}
@Override
public void start(StartContext context) throws StartException {
}
@Override
public void stop(StopContext context) {
}
@Override
public DefaultResourceAdapterService getValue() throws IllegalStateException, IllegalArgumentException {
return this;
}
public synchronized void setResourceAdapterName(final String resourceAdapterName) {
this.defaultResourceAdapterName = resourceAdapterName;
}
public synchronized String getDefaultResourceAdapterName() {
return this.defaultResourceAdapterName;
}
}
| 2,344 | 34 | 147 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/messagedriven/MessageDrivenComponent.java | /*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, 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.ejb3.component.messagedriven;
import static java.security.AccessController.doPrivileged;
import static java.util.Collections.emptyMap;
import static org.jboss.as.ejb3.logging.EjbLogger.ROOT_LOGGER;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import jakarta.ejb.TransactionAttributeType;
import jakarta.resource.ResourceException;
import jakarta.resource.spi.ActivationSpec;
import jakarta.resource.spi.endpoint.MessageEndpointFactory;
import jakarta.transaction.TransactionManager;
import org.jboss.as.ee.component.BasicComponentInstance;
import org.jboss.as.ejb3.component.EJBComponent;
import org.jboss.as.ejb3.component.allowedmethods.AllowedMethodsInformation;
import org.jboss.as.ejb3.component.pool.PoolConfig;
import org.jboss.as.ejb3.component.pool.PooledComponent;
import org.jboss.as.ejb3.inflow.JBossMessageEndpointFactory;
import org.jboss.as.ejb3.inflow.MessageEndpointService;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.ejb3.pool.Pool;
import org.jboss.as.ejb3.pool.StatelessObjectFactory;
import org.jboss.as.naming.context.NamespaceContextSelector;
import org.jboss.as.server.suspend.ServerActivity;
import org.jboss.as.server.suspend.ServerActivityCallback;
import org.jboss.as.server.suspend.SuspendController;
import org.jboss.invocation.Interceptor;
import org.jboss.jca.core.spi.rar.Endpoint;
import org.jboss.metadata.ejb.spec.MethodInterfaceType;
import org.jboss.msc.service.ServiceName;
import org.wildfly.security.manager.WildFlySecurityManager;
import org.wildfly.security.manager.action.GetClassLoaderAction;
/**
* @author <a href="mailto:[email protected]">Carlo de Wolf</a>
*/
public class MessageDrivenComponent extends EJBComponent implements PooledComponent<MessageDrivenComponentInstance> {
private final Pool<MessageDrivenComponentInstance> pool;
private final String poolName;
private final SuspendController suspendController;
private final ActivationSpec activationSpec;
private final MessageEndpointFactory endpointFactory;
private final ClassLoader classLoader;
private boolean started;
private boolean deliveryActive;
private final ServiceName deliveryControllerName;
private Endpoint endpoint;
private String activationName;
private volatile boolean suspended = false;
/**
* Server activity that stops delivery before suspend starts.
*
* Note that there is a very small (but unavoidable) race here. It is possible
* that a message will have started delivery when preSuspend is called, but has
* not make it to the {@link org.jboss.as.ejb3.deployment.processors.EjbSuspendInterceptor},
* if this happens the message will be rejected with an exception.
*
*/
private final ServerActivity serverActivity = new ServerActivity() {
@Override
public void preSuspend(ServerActivityCallback listener) {
synchronized (MessageDrivenComponent.this) {
if (deliveryActive) {
deactivate();
}
}
listener.done();
}
public void suspended(ServerActivityCallback listener) {
suspended = true;
listener.done();
}
@Override
public void resume() {
synchronized (MessageDrivenComponent.this) {
suspended = false;
if (deliveryActive) {
activate();
}
}
}
};
/**
* Construct a new instance.
*
* @param ejbComponentCreateService the component configuration
* @param deliveryActive true if the component must start delivering messages as soon as it is started
*/
protected MessageDrivenComponent(final MessageDrivenComponentCreateService ejbComponentCreateService, final Class<?> messageListenerInterface, final ActivationSpec activationSpec, final boolean deliveryActive, final ServiceName deliveryControllerName, final String activeResourceAdapterName) {
super(ejbComponentCreateService);
StatelessObjectFactory<MessageDrivenComponentInstance> factory = new StatelessObjectFactory<MessageDrivenComponentInstance>() {
@Override
public MessageDrivenComponentInstance create() {
return (MessageDrivenComponentInstance) createInstance();
}
@Override
public void destroy(MessageDrivenComponentInstance obj) {
obj.destroy();
}
};
final PoolConfig poolConfig = ejbComponentCreateService.getPoolConfig();
if (poolConfig == null) {
ROOT_LOGGER.debugf("Pooling is disabled for MDB %s", ejbComponentCreateService.getComponentName());
this.pool = null;
this.poolName = null;
} else {
ROOT_LOGGER.debugf("Using pool config %s to create pool for MDB %s", poolConfig, ejbComponentCreateService.getComponentName());
this.pool = poolConfig.createPool(factory);
this.poolName = poolConfig.getPoolName();
}
this.classLoader = ejbComponentCreateService.getModuleClassLoader();
this.suspendController = ejbComponentCreateService.getSuspendControllerInjectedValue().getValue();
this.activationSpec = activationSpec;
this.activationName = activeResourceAdapterName + messageListenerInterface.getName();
final ClassLoader componentClassLoader = doPrivileged(new GetClassLoaderAction(ejbComponentCreateService.getComponentClass()));
final MessageEndpointService<?> service = new MessageEndpointService<Object>() {
@Override
public Class<Object> getMessageListenerInterface() {
return (Class<Object>) messageListenerInterface;
}
@Override
public TransactionManager getTransactionManager() {
return MessageDrivenComponent.this.getTransactionManager();
}
@Override
public boolean isDeliveryTransacted(Method method) throws NoSuchMethodException {
if(isBeanManagedTransaction())
return false;
// an MDB doesn't expose a real view
TransactionAttributeType transactionAttributeType = getTransactionAttributeType(MethodInterfaceType.MessageEndpoint, method);
switch (transactionAttributeType) {
case REQUIRED:
return true;
case NOT_SUPPORTED:
return false;
default:
// WFLY-5074 - treat any other unspecified tx attribute type as NOT_SUPPORTED
ROOT_LOGGER.invalidTransactionTypeForMDB(transactionAttributeType, method.getName(), getComponentName());
return false;
}
}
@Override
public String getActivationName() {
return activationName;
}
@Override
public Object obtain(long timeout, TimeUnit unit) {
// like this it's a disconnected invocation
// return getComponentView(messageListenerInterface).getViewForInstance(null);
return createViewInstanceProxy(getComponentClass(), emptyMap());
}
@Override
public void release(Object obj) {
// do nothing
}
@Override
public ClassLoader getClassLoader() {
return componentClassLoader;
}
};
this.endpointFactory = new JBossMessageEndpointFactory(componentClassLoader, service, (Class<Object>) getComponentClass(), messageListenerInterface);
this.started = false;
this.deliveryActive = deliveryActive;
this.deliveryControllerName = deliveryControllerName;
}
@Override
protected BasicComponentInstance instantiateComponentInstance(Interceptor preDestroyInterceptor, Map<Method, Interceptor> methodInterceptors, Map<Object, Object> context) {
return new MessageDrivenComponentInstance(this, preDestroyInterceptor, methodInterceptors);
}
@Override
public Pool<MessageDrivenComponentInstance> getPool() {
return pool;
}
@Override
public String getPoolName() {
return poolName;
}
void setEndpoint(final Endpoint endpoint) {
this.endpoint = endpoint;
}
@Override
public void start(){
super.start();
synchronized (this) {
this.started = true;
if (this.deliveryActive && !suspended) {
this.activate();
}
}
}
@Override
public void init() {
if (endpoint == null) {
throw EjbLogger.ROOT_LOGGER.endpointUnAvailable(this.getComponentName());
}
super.init();
suspendController.registerActivity(serverActivity);
if (this.pool != null) {
this.pool.start();
}
}
@Override
public void done() {
synchronized (this) {
if (this.deliveryActive) {
this.deactivate();
}
this.started = false;
}
if (this.pool != null) {
this.pool.stop();
}
suspendController.unRegisterActivity(serverActivity);
super.done();
}
private void activate() {
ClassLoader oldTccl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
try {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader);
NamespaceContextSelector.pushCurrentSelector(this.getNamespaceContextSelector());
try {
this.endpoint.activate(endpointFactory, activationSpec);
} finally {
NamespaceContextSelector.popCurrentSelector();
}
} catch (Exception e) {
throw EjbLogger.ROOT_LOGGER.failedToActivateMdb(getComponentName(), e);
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTccl);
}
}
private void deactivate() {
ClassLoader oldTccl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
try {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader);
endpoint.deactivate(endpointFactory, activationSpec);
} catch (ResourceException re) {
throw EjbLogger.ROOT_LOGGER.failureDuringEndpointDeactivation(this.getComponentName(), re);
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTccl);
}
}
public void startDelivery() {
synchronized (this) {
if (!this.deliveryActive) {
this.deliveryActive = true;
if (this.started) {
this.activate();
ROOT_LOGGER.mdbDeliveryStarted(getApplicationName(), getComponentName());
}
}
}
}
public void stopDelivery() {
synchronized (this) {
if (this.deliveryActive) {
if (this.started) {
this.deactivate();
ROOT_LOGGER.mdbDeliveryStopped(getApplicationName(), getComponentName());
}
this.deliveryActive = false;
}
}
}
public synchronized boolean isDeliveryActive() {
return deliveryActive;
}
public boolean isDeliveryControlled() {
return deliveryControllerName != null;
}
public ServiceName getDeliveryControllerName() {
return deliveryControllerName;
}
@Override
public AllowedMethodsInformation getAllowedMethodsInformation() {
return isBeanManagedTransaction() ? MessageDrivenAllowedMethodsInformation.INSTANCE_BMT : MessageDrivenAllowedMethodsInformation.INSTANCE_CMT;
}
}
| 13,090 | 37.502941 | 297 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/messagedriven/MessageDrivenComponentCreateService.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, 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.ejb3.component.messagedriven;
import java.beans.IntrospectionException;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;
import java.util.List;
import java.util.Properties;
import jakarta.resource.ResourceException;
import jakarta.resource.spi.ActivationSpec;
import jakarta.resource.spi.ResourceAdapter;
import org.jboss.as.connector.util.ConnectorServices;
import org.jboss.as.ee.component.BasicComponent;
import org.jboss.as.ee.component.ComponentConfiguration;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.ejb3.component.EJBComponentCreateService;
import org.jboss.as.ejb3.component.pool.PoolConfig;
import org.jboss.as.ejb3.deployment.ApplicationExceptions;
import org.jboss.as.server.suspend.SuspendController;
import org.jboss.common.beans.property.BeanUtils;
import org.jboss.jca.core.spi.rar.Activation;
import org.jboss.jca.core.spi.rar.Endpoint;
import org.jboss.jca.core.spi.rar.MessageListener;
import org.jboss.jca.core.spi.rar.NotFoundException;
import org.jboss.jca.core.spi.rar.ResourceAdapterRepository;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.value.InjectedValue;
/**
* @author Stuart Douglas
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public class MessageDrivenComponentCreateService extends EJBComponentCreateService {
private final Class<?> messageListenerInterface;
private final Properties activationProps;
private final String resourceAdapterName;
private final boolean deliveryActive;
private final ServiceName deliveryControllerName;
private final InjectedValue<ResourceAdapterRepository> resourceAdapterRepositoryInjectedValue = new InjectedValue<ResourceAdapterRepository>();
private final InjectedValue<ResourceAdapter> resourceAdapterInjectedValue = new InjectedValue<ResourceAdapter>();
private final InjectedValue<PoolConfig> poolConfig = new InjectedValue<PoolConfig>();
private final InjectedValue<SuspendController> suspendControllerInjectedValue = new InjectedValue<>();
private final ClassLoader moduleClassLoader;
/**
* Construct a new instance.
*
* @param componentConfiguration the component configuration
*/
public MessageDrivenComponentCreateService(final ComponentConfiguration componentConfiguration, final ApplicationExceptions ejbJarConfiguration, final Class<?> messageListenerInterface) {
super(componentConfiguration, ejbJarConfiguration);
final MessageDrivenComponentDescription componentDescription = (MessageDrivenComponentDescription) componentConfiguration.getComponentDescription();
this.resourceAdapterName = componentDescription.getResourceAdapterName();
this.deliveryControllerName = componentDescription.isDeliveryControlled()? componentDescription.getDeliveryControllerName(): null;
this.deliveryActive = !componentDescription.isDeliveryControlled() && componentDescription.isDeliveryActive();
// see MessageDrivenComponentDescription.<init>
this.messageListenerInterface = messageListenerInterface;
this.activationProps = componentDescription.getActivationProps();
this.moduleClassLoader = componentConfiguration.getModuleClassLoader();
}
@Override
public void start(StartContext context) throws StartException {
super.start(context);
// AS7-3073 just log a message about the MDB being started
EjbLogger.ROOT_LOGGER.logMDBStart(this.getComponentName(), this.resourceAdapterName);
}
@Override
protected BasicComponent createComponent() {
String configuredResourceAdapterName = resourceAdapterName;
// Match configured value to the actual RA names
final String activeResourceAdapterName = searchActiveResourceAdapterName(configuredResourceAdapterName);
final ActivationSpec activationSpec = createActivationSpecs(activeResourceAdapterName, messageListenerInterface, activationProps, getDeploymentClassLoader());
final MessageDrivenComponent component = new MessageDrivenComponent(this, messageListenerInterface, activationSpec, deliveryActive, deliveryControllerName, activeResourceAdapterName);
// set the endpoint
final Endpoint endpoint = getEndpoint(activeResourceAdapterName);
component.setEndpoint(endpoint);
return component;
}
private ActivationSpec createActivationSpecs(final String resourceAdapterName, final Class<?> messageListenerInterface,
final Properties activationConfigProperties, final ClassLoader classLoader) {
try {
// first get the ra "identifier" (with which it is registered in the resource adapter repository) for the
// ra name
final String raIdentifier = ConnectorServices.getRegisteredResourceAdapterIdentifier(resourceAdapterName);
if (raIdentifier == null) {
throw EjbLogger.ROOT_LOGGER.unknownResourceAdapter(resourceAdapterName);
}
final ResourceAdapterRepository resourceAdapterRepository = resourceAdapterRepositoryInjectedValue.getValue();
if (resourceAdapterRepository == null) {
throw EjbLogger.ROOT_LOGGER.resourceAdapterRepositoryUnAvailable();
}
// now get the message listeners for this specific ra identifier
final List<MessageListener> messageListeners = resourceAdapterRepository.getMessageListeners(raIdentifier);
if (messageListeners == null || messageListeners.isEmpty()) {
throw EjbLogger.ROOT_LOGGER.unknownMessageListenerType(messageListenerInterface.getName(), resourceAdapterName);
}
MessageListener requiredMessageListener = null;
// now find the expected message listener from the list of message listeners for this resource adapter
for (final MessageListener messageListener : messageListeners) {
if (messageListenerInterface.equals(messageListener.getType())) {
requiredMessageListener = messageListener;
break;
}
}
if (requiredMessageListener == null) {
throw EjbLogger.ROOT_LOGGER.unknownMessageListenerType(messageListenerInterface.getName(), resourceAdapterName);
}
// found the message listener, now finally create the activation spec
final Activation activation = requiredMessageListener.getActivation();
// filter out the activation config properties, specified on the MDB, which aren't accepted by the resource
// adaptor
final Properties validActivationConfigProps = this.filterUnknownActivationConfigProperties(resourceAdapterName, activation, activationConfigProperties);
// now set the activation config properties on the ActivationSpec
final ActivationSpec activationSpec = activation.createInstance();
BeanUtils.mapJavaBeanProperties(activationSpec, validActivationConfigProps);
return activationSpec;
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (ResourceException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (NotFoundException e) {
throw new RuntimeException(e);
} catch (IntrospectionException e) {
throw new RuntimeException(e);
}
}
/**
* Removes activation config properties which aren't recognized by the resource adapter <code>activation</code>, from the
* passed <code>activationConfigProps</code> and returns only those Properties which are valid.
*
* @param resourceAdapterName The resource adapter name
* @param activation {@link Activation}
* @param activationConfigProps Activation config properties which will be checked for validity
* @return
*/
private Properties filterUnknownActivationConfigProperties(final String resourceAdapterName, final Activation activation, final Properties activationConfigProps) {
if (activationConfigProps == null) {
return null;
}
final Map<String, Class<?>> raActivationConfigProps = activation.getConfigProperties();
final Set<String> raRequiredConfigProps = activation.getRequiredConfigProperties();
final Enumeration<?> propNames = activationConfigProps.propertyNames();
final Properties validActivationConfigProps = new Properties();
// initialize to all the activation config properties that have been set on the MDB
validActivationConfigProps.putAll(activationConfigProps);
while (propNames.hasMoreElements()) {
final Object propName = propNames.nextElement();
if (raActivationConfigProps.containsKey(propName) == false && raRequiredConfigProps.contains(propName) == false) {
// not a valid activation config property, so log a WARN and filter it out from the valid activation config properties
validActivationConfigProps.remove(propName);
EjbLogger.ROOT_LOGGER.activationConfigPropertyIgnored(propName, resourceAdapterName);
}
}
return validActivationConfigProps;
}
/**
* Returns the {@link org.jboss.jca.core.spi.rar.Endpoint} corresponding to the passed <code>resourceAdapterName</code>
*
* @param resourceAdapterName The resource adapter name
* @return
*/
private Endpoint getEndpoint(final String resourceAdapterName) {
// first get the ra "identifier" (with which it is registered in the resource adapter repository) for the
// ra name
final String raIdentifier = ConnectorServices.getRegisteredResourceAdapterIdentifier(resourceAdapterName);
if (raIdentifier == null) {
throw EjbLogger.ROOT_LOGGER.unknownResourceAdapter(resourceAdapterName);
}
final ResourceAdapterRepository resourceAdapterRepository = resourceAdapterRepositoryInjectedValue.getValue();
if (resourceAdapterRepository == null) {
throw EjbLogger.ROOT_LOGGER.resourceAdapterRepositoryUnAvailable();
}
try {
return resourceAdapterRepository.getEndpoint(raIdentifier);
} catch (NotFoundException nfe) {
throw EjbLogger.ROOT_LOGGER.noSuchEndpointException(resourceAdapterName, nfe);
}
}
private String searchActiveResourceAdapterName(String configuredResourceAdapterName) {
// Use the configured value unless it doesn't match and some variant of it does
String result = configuredResourceAdapterName;
if (configuredResourceAdapterName != null
&& ConnectorServices.getRegisteredResourceAdapterIdentifier(configuredResourceAdapterName) == null) {
// No direct match. See if we have a match with .rar removed or appended
String amended = stripDotRarSuffix(configuredResourceAdapterName);
if (configuredResourceAdapterName.equals(amended)) {
// There was no .rar to strip; try appending
amended = configuredResourceAdapterName + ".rar";
}
if (ConnectorServices.getRegisteredResourceAdapterIdentifier(amended) != null) {
result = amended;
}
}
return result;
}
PoolConfig getPoolConfig() {
return this.poolConfig.getOptionalValue();
}
public InjectedValue<PoolConfig> getPoolConfigInjector() {
return this.poolConfig;
}
private ClassLoader getDeploymentClassLoader() {
return getComponentClass().getClassLoader();
}
public InjectedValue<ResourceAdapterRepository> getResourceAdapterRepositoryInjector() {
return this.resourceAdapterRepositoryInjectedValue;
}
public InjectedValue<ResourceAdapter> getResourceAdapterInjector() {
return this.resourceAdapterInjectedValue;
}
public ClassLoader getModuleClassLoader() {
return moduleClassLoader;
}
public InjectedValue<SuspendController> getSuspendControllerInjectedValue() {
return suspendControllerInjectedValue;
}
private String stripDotRarSuffix(final String raName) {
if (raName == null) {
return null;
}
// See RaDeploymentParsingProcessor
if (raName.endsWith(".rar")) {
return raName.substring(0, raName.indexOf(".rar"));
}
return raName;
}
}
| 13,797 | 47.929078 | 191 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/messagedriven/MessageDrivenComponentDescription.java | /*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, 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.ejb3.component.messagedriven;
import static org.jboss.as.server.deployment.Attachments.CAPABILITY_SERVICE_SUPPORT;
import java.util.Properties;
import jakarta.ejb.MessageDrivenBean;
import jakarta.ejb.TransactionManagementType;
import jakarta.resource.spi.ResourceAdapter;
import org.jboss.as.connector.util.ConnectorServices;
import org.jboss.as.controller.capability.CapabilityServiceSupport;
import org.jboss.as.ee.component.Attachments;
import org.jboss.as.ee.component.Component;
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.DependencyConfigurator;
import org.jboss.as.ee.component.EEApplicationClasses;
import org.jboss.as.ee.component.ViewConfiguration;
import org.jboss.as.ee.component.ViewConfigurator;
import org.jboss.as.ee.component.ViewDescription;
import org.jboss.as.ee.component.interceptors.InterceptorClassDescription;
import org.jboss.as.ee.component.interceptors.InterceptorOrder;
import org.jboss.as.ee.component.interceptors.InvocationType;
import org.jboss.as.ee.metadata.MetadataCompleteMarker;
import org.jboss.as.ejb3.component.EJBComponentDescription;
import org.jboss.as.ejb3.component.EJBViewDescription;
import org.jboss.as.ejb3.component.interceptors.CurrentInvocationContextInterceptor;
import org.jboss.as.ejb3.component.pool.PoolConfig;
import org.jboss.as.ejb3.deployment.EjbJarDescription;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.ejb3.tx.CMTTxInterceptor;
import org.jboss.as.ejb3.tx.EjbBMTInterceptor;
import org.jboss.as.ejb3.tx.LifecycleCMTTxInterceptor;
import org.jboss.as.ejb3.tx.TimerCMTTxInterceptor;
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.reflect.ClassReflectionIndex;
import org.jboss.as.server.suspend.SuspendController;
import org.jboss.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.jca.core.spi.rar.ResourceAdapterRepository;
import org.jboss.metadata.ejb.spec.MessageDrivenBeanMetaData;
import org.jboss.metadata.ejb.spec.MethodInterfaceType;
import org.jboss.modules.ModuleLoader;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
/**
* @author <a href="mailto:[email protected]">Carlo de Wolf</a>
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public class MessageDrivenComponentDescription extends EJBComponentDescription {
private static final String STRICT_MAX_POOL_CONFIG_CAPABILITY_NAME = "org.wildfly.ejb3.pool-config";
private static final String DEFAULT_MDB_POOL_CONFIG_CAPABILITY_NAME = "org.wildfly.ejb3.pool-config.mdb-default";
private final Properties activationProps;
private String resourceAdapterName;
private boolean deliveryActive;
private String[] deliveryGroups;
private boolean clusteredSingleton;
private String mdbPoolConfigName;
private final String messageListenerInterfaceName;
private final boolean defaultMdbPoolAvailable;
/**
* Construct a new instance.
*
* @param componentName the component name
* @param componentClassName the component instance class name
* @param ejbJarDescription the module description
* @param defaultResourceAdapterName The default resource adapter name for this message driven bean. Cannot be null or empty string.
*/
public MessageDrivenComponentDescription(final String componentName, final String componentClassName, final EjbJarDescription ejbJarDescription,
final DeploymentUnit deploymentUnit, final String messageListenerInterfaceName, final Properties activationProps,
final String defaultResourceAdapterName, final MessageDrivenBeanMetaData descriptorData, final boolean defaultMdbPoolAvailable) {
super(componentName, componentClassName, ejbJarDescription, deploymentUnit, descriptorData);
if (messageListenerInterfaceName == null || messageListenerInterfaceName.isEmpty()) {
throw EjbLogger.ROOT_LOGGER.stringParamCannotBeNullOrEmpty("Message listener interface");
}
if (defaultResourceAdapterName == null || defaultResourceAdapterName.trim().isEmpty()) {
throw EjbLogger.ROOT_LOGGER.stringParamCannotBeNullOrEmpty("Default resource adapter name");
}
this.resourceAdapterName = defaultResourceAdapterName;
this.deliveryActive = true;
this.activationProps = activationProps;
this.messageListenerInterfaceName = messageListenerInterfaceName;
this.defaultMdbPoolAvailable = defaultMdbPoolAvailable;
registerView(getEJBClassName(), MethodInterfaceType.MessageEndpoint);
// add the interceptor which will invoke the setMessageDrivenContext() method on a MDB which implements
// MessageDrivenBean interface
this.addSetMessageDrivenContextMethodInvocationInterceptor();
getConfigurators().add(new ComponentConfigurator() {
@Override
public void configure(final DeploymentPhaseContext context, final ComponentDescription description, final ComponentConfiguration configuration) {
configuration.addTimeoutViewInterceptor(MessageDrivenComponentInstanceAssociatingFactory.instance(), InterceptorOrder.View.ASSOCIATING_INTERCEPTOR);
}
});
}
@Override
public ComponentConfiguration createConfiguration(final ClassReflectionIndex classIndex, final ClassLoader moduleClassLoader, final ModuleLoader moduleLoader) {
final ComponentConfiguration mdbComponentConfiguration = new ComponentConfiguration(this, classIndex, moduleClassLoader, moduleLoader);
// setup the component create service
final Class<?> messageListenerInterface;
try {
messageListenerInterface = Class.forName(getMessageListenerInterfaceName(), true, moduleClassLoader);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
mdbComponentConfiguration.setComponentCreateServiceFactory(new MessageDrivenComponentCreateServiceFactory(messageListenerInterface));
final MessageDrivenComponentDescription mdbComponentDescription = (MessageDrivenComponentDescription) mdbComponentConfiguration.getComponentDescription();
// setup a configurator to inject the PoolConfig in the MessageDrivenComponentCreateService
getConfigurators().add(new ComponentConfigurator() {
@Override
public void configure(DeploymentPhaseContext context, ComponentDescription description, ComponentConfiguration configuration) throws DeploymentUnitProcessingException {
//get CapabilitySupport to resolve service names
final CapabilityServiceSupport support = context.getDeploymentUnit().getAttachment(CAPABILITY_SERVICE_SUPPORT);
MessageDrivenComponentDescription mdbDescription = (MessageDrivenComponentDescription) description;
configuration.getCreateDependencies().add(new DependencyConfigurator<Service<Component>>() {
@Override
public void configureDependency(ServiceBuilder<?> serviceBuilder, Service<Component> service) throws DeploymentUnitProcessingException {
// add any dependencies here
final MessageDrivenComponentCreateService mdbComponentCreateService = (MessageDrivenComponentCreateService) service;
final String poolName = mdbComponentDescription.getPoolConfigName();
// if no pool name has been explicitly set, then inject the *optional* "default mdb pool config"
// If the default mdb pool config itself is not configured, then pooling is disabled for the bean
if (poolName == null) {
if (mdbComponentDescription.isDefaultMdbPoolAvailable()) {
ServiceName defaultPoolConfigServiceName = support.getCapabilityServiceName(DEFAULT_MDB_POOL_CONFIG_CAPABILITY_NAME);
serviceBuilder.addDependency(defaultPoolConfigServiceName, PoolConfig.class, mdbComponentCreateService.getPoolConfigInjector());
}
} else {
// pool name has been explicitly set so the pool config is a required dependency
ServiceName poolConfigServiceName = support.getCapabilityServiceName(STRICT_MAX_POOL_CONFIG_CAPABILITY_NAME, poolName);
serviceBuilder.addDependency(poolConfigServiceName, PoolConfig.class, mdbComponentCreateService.getPoolConfigInjector());
}
}
});
}
});
// set up a configurator to inject ResourceAdapterService dependencies into the MessageDrivenComponentCreateService
getConfigurators().add(new ComponentConfigurator() {
@Override
public void configure(DeploymentPhaseContext context, ComponentDescription description, ComponentConfiguration configuration) throws DeploymentUnitProcessingException {
//get CapabilitySupport to resolve service names
final CapabilityServiceSupport support = context.getDeploymentUnit().getAttachment(CAPABILITY_SERVICE_SUPPORT);
configuration.getCreateDependencies().add(new DependencyConfigurator<MessageDrivenComponentCreateService>() {
@Override
public void configureDependency(ServiceBuilder<?> serviceBuilder, MessageDrivenComponentCreateService service) throws DeploymentUnitProcessingException {
final ServiceName raServiceName =
ConnectorServices.getResourceAdapterServiceName(MessageDrivenComponentDescription.this.resourceAdapterName);
// add the dependency on the RA service
serviceBuilder.addDependency(ConnectorServices.RA_REPOSITORY_SERVICE, ResourceAdapterRepository.class, service.getResourceAdapterRepositoryInjector());
serviceBuilder.addDependency(raServiceName, ResourceAdapter.class, service.getResourceAdapterInjector());
}
});
}
});
getConfigurators().add(new ComponentConfigurator() {
@Override
public void configure(DeploymentPhaseContext context, ComponentDescription description, ComponentConfiguration configuration) throws DeploymentUnitProcessingException {
final ServiceName suspendControllerName = context.getDeploymentUnit()
.getAttachment(CAPABILITY_SERVICE_SUPPORT)
.getCapabilityServiceName("org.wildfly.server.suspend-controller");
configuration.getCreateDependencies().add(new DependencyConfigurator<MessageDrivenComponentCreateService>() {
@Override
public void configureDependency(final ServiceBuilder<?> serviceBuilder, final MessageDrivenComponentCreateService mdbComponentCreateService) throws DeploymentUnitProcessingException {
serviceBuilder.addDependency(suspendControllerName, SuspendController.class, mdbComponentCreateService.getSuspendControllerInjectedValue());
}
});
}
});
// add the BMT interceptor
if (TransactionManagementType.BEAN.equals(this.getTransactionManagementType())) {
getConfigurators().add(new ComponentConfigurator() {
@Override
public void configure(final DeploymentPhaseContext context, final ComponentDescription description, final ComponentConfiguration configuration) throws DeploymentUnitProcessingException {
// add the bmt interceptor factory
configuration.addComponentInterceptor(EjbBMTInterceptor.FACTORY, InterceptorOrder.Component.BMT_TRANSACTION_INTERCEPTOR, false);
}
});
} else {
getConfigurators().add(new ComponentConfigurator() {
@Override
public void configure(final DeploymentPhaseContext context, final ComponentDescription description, final ComponentConfiguration configuration) throws DeploymentUnitProcessingException {
final EEApplicationClasses applicationClasses = context.getDeploymentUnit().getAttachment(Attachments.EE_APPLICATION_CLASSES_DESCRIPTION);
InterceptorClassDescription interceptorConfig = ComponentDescription.mergeInterceptorConfig(configuration.getComponentClass(), applicationClasses.getClassByName(description.getComponentClassName()), description, MetadataCompleteMarker.isMetadataComplete(context.getDeploymentUnit()));
configuration.addPostConstructInterceptor(new LifecycleCMTTxInterceptor.Factory(interceptorConfig.getPostConstruct(), true), InterceptorOrder.ComponentPostConstruct.TRANSACTION_INTERCEPTOR);
configuration.addPreDestroyInterceptor(new LifecycleCMTTxInterceptor.Factory(interceptorConfig.getPreDestroy(), true), InterceptorOrder.ComponentPreDestroy.TRANSACTION_INTERCEPTOR);
configuration.addTimeoutViewInterceptor(TimerCMTTxInterceptor.FACTORY, InterceptorOrder.View.CMT_TRANSACTION_INTERCEPTOR);
}
});
}
return mdbComponentConfiguration;
}
boolean isDefaultMdbPoolAvailable() {
return defaultMdbPoolAvailable;
}
public Properties getActivationProps() {
return activationProps;
}
public boolean isDeliveryActive() {
return deliveryActive;
}
public void setDeliveryActive(boolean deliveryActive) {
this.deliveryActive = deliveryActive;
}
public String[] getDeliveryGroups() {
return deliveryGroups;
}
public void setDeliveryGroup(String[] groupNames) {
this.deliveryGroups = groupNames;
}
public boolean isClusteredSingleton() {
return clusteredSingleton;
}
public void setClusteredSingleton(boolean clusteredSingleton) {
this.clusteredSingleton = clusteredSingleton;
}
public boolean isDeliveryControlled() {
return deliveryGroups != null && deliveryGroups.length > 0 && deliveryGroups[0] != null || clusteredSingleton;
}
public ServiceName getDeliveryControllerName() {
return getServiceName().append("DELIVERY");
}
public String getResourceAdapterName() {
return resourceAdapterName;
}
public void setResourceAdapterName(String resourceAdapterName) {
if (resourceAdapterName == null || resourceAdapterName.trim().isEmpty()) {
throw EjbLogger.ROOT_LOGGER.stringParamCannotBeNullOrEmpty("Resource adapter name");
}
this.resourceAdapterName = resourceAdapterName;
}
@Override
protected void setupViewInterceptors(EJBViewDescription view) {
// let the super do its job
super.setupViewInterceptors(view);
view.getConfigurators().add(new ViewConfigurator() {
@Override
public void configure(DeploymentPhaseContext context, ComponentConfiguration componentConfiguration, ViewDescription description, ViewConfiguration configuration) throws DeploymentUnitProcessingException {
//add the invocation type to the start of the chain
//TODO: is there a cleaner way to do this?
configuration.addViewInterceptor(new ImmediateInterceptorFactory(new Interceptor() {
@Override
public Object processInvocation(final InterceptorContext context) throws Exception {
context.putPrivateData(InvocationType.class, InvocationType.MESSAGE_DELIVERY);
return context.proceed();
}
}), InterceptorOrder.View.INVOCATION_TYPE);
// add the instance associating interceptor at the start of the interceptor chain
configuration.addViewInterceptor(MessageDrivenComponentInstanceAssociatingFactory.instance(), InterceptorOrder.View.ASSOCIATING_INTERCEPTOR);
final MessageDrivenComponentDescription mdb = (MessageDrivenComponentDescription) componentConfiguration.getComponentDescription();
if (mdb.getTransactionManagementType() == TransactionManagementType.CONTAINER) {
configuration.addViewInterceptor(CMTTxInterceptor.FACTORY, InterceptorOrder.View.CMT_TRANSACTION_INTERCEPTOR);
}
}
});
}
@Override
protected void addCurrentInvocationContextFactory() {
// add the current invocation context interceptor at the beginning of the component instance post construct chain
this.getConfigurators().add(new ComponentConfigurator() {
@Override
public void configure(DeploymentPhaseContext context, ComponentDescription description, ComponentConfiguration configuration) throws DeploymentUnitProcessingException {
configuration.addPostConstructInterceptor(CurrentInvocationContextInterceptor.FACTORY, InterceptorOrder.ComponentPostConstruct.EJB_SESSION_CONTEXT_INTERCEPTOR);
configuration.addPreDestroyInterceptor(CurrentInvocationContextInterceptor.FACTORY, InterceptorOrder.ComponentPostConstruct.EJB_SESSION_CONTEXT_INTERCEPTOR);
}
});
}
@Override
protected void addCurrentInvocationContextFactory(ViewDescription view) {
view.getConfigurators().add(new ViewConfigurator() {
@Override
public void configure(DeploymentPhaseContext context, ComponentConfiguration componentConfiguration, ViewDescription description, ViewConfiguration configuration) throws DeploymentUnitProcessingException {
configuration.addViewInterceptor(CurrentInvocationContextInterceptor.FACTORY, InterceptorOrder.View.INVOCATION_CONTEXT_INTERCEPTOR);
}
});
}
/**
* Adds an interceptor to invoke the {@link MessageDrivenBean#setMessageDrivenContext(jakarta.ejb.MessageDrivenContext)}
* if the MDB implements the {@link MessageDrivenBean} interface
*/
private void addSetMessageDrivenContextMethodInvocationInterceptor() {
// add the setMessageDrivenContext(MessageDrivenContext) method invocation interceptor for MDB
// implementing the jakarta.ejb.MessageDrivenBean interface
this.getConfigurators().add(new ComponentConfigurator() {
@Override
public void configure(DeploymentPhaseContext context, ComponentDescription description, ComponentConfiguration configuration) throws DeploymentUnitProcessingException {
if (MessageDrivenBean.class.isAssignableFrom(configuration.getComponentClass())) {
configuration.addPostConstructInterceptor(new ImmediateInterceptorFactory(MessageDrivenBeanSetMessageDrivenContextInterceptor.INSTANCE), InterceptorOrder.ComponentPostConstruct.EJB_SET_CONTEXT_METHOD_INVOCATION_INTERCEPTOR);
}
}
});
}
@Override
public boolean isMessageDriven() {
return true;
}
public void setPoolConfigName(final String mdbPoolConfigName) {
this.mdbPoolConfigName = mdbPoolConfigName;
}
public String getPoolConfigName() {
return this.mdbPoolConfigName;
}
public String getMessageListenerInterfaceName() {
return messageListenerInterfaceName;
}
@Override
public boolean isTimerServiceApplicable() {
return true;
}
@Override
public MessageDrivenBeanMetaData getDescriptorData() {
return (MessageDrivenBeanMetaData) super.getDescriptorData();
}
}
| 21,372 | 54.658854 | 304 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.