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/messagedriven/MessageDrivenComponentInstanceAssociatingFactory.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.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 MessageDrivenComponentInstanceAssociatingFactory extends ComponentInterceptorFactory {
private static final MessageDrivenComponentInstanceAssociatingFactory INSTANCE = new MessageDrivenComponentInstanceAssociatingFactory();
private MessageDrivenComponentInstanceAssociatingFactory() {
}
public static MessageDrivenComponentInstanceAssociatingFactory instance() {
return INSTANCE;
}
@Override
protected Interceptor create(Component component, InterceptorFactoryContext context) {
if (component instanceof MessageDrivenComponent == false) {
throw EjbLogger.ROOT_LOGGER.unexpectedComponent(component, MessageDrivenComponent.class);
}
final MessageDrivenComponent mdbComponent = (MessageDrivenComponent) component;
if (mdbComponent.getPool() != null) {
return PooledInstanceInterceptor.INSTANCE;
} else {
return NonPooledEJBComponentInstanceAssociatingInterceptor.INSTANCE;
}
}
}
| 2,531 | 40.508197 | 140 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/singleton/EJBReadWriteLock.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2009, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ejb3.component.singleton;
import java.io.Serializable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.jboss.as.ejb3.logging.EjbLogger;
/**
* An implementation of {@link java.util.concurrent.locks.ReadWriteLock} which throws an {@link jakarta.ejb.IllegalLoopbackException}
* when a thread holding a read lock tries to obtain a write lock.
*
* @author <a href="mailto:[email protected]">Carlo de Wolf</a>
* @version $Revision: $
*/
public class EJBReadWriteLock implements ReadWriteLock, Serializable {
private static final long serialVersionUID = 1L;
/**
* Keep track of the number of read locks held by this thread
*/
private final ThreadLocal<Integer> readLockCount = new ThreadLocal<Integer>();
/**
* We delegate all locking semantics to this {@link java.util.concurrent.locks.ReentrantReadWriteLock}
*/
private final ReentrantReadWriteLock delegate = new ReentrantReadWriteLock();
/**
* Read lock instance which will be handed out to clients
* on a call to {@link #readLock()}
*/
private final Lock readLock = new ReadLock();
/**
* Write lock instance which will be handed out to clients
* on a call to {@link #writeLock()}
*/
private final Lock writeLock = new WriteLock();
/**
* A read lock which increments/decrements the count of
* read locks held by the thread and delegates the locking
* calls to the {@link #delegate}
*
* @author Jaikiran Pai
* @version $Revision: $
*/
public class ReadLock implements Lock, Serializable {
private static final long serialVersionUID = 1L;
/**
* Delegate the call to the internal {@link java.util.concurrent.locks.ReentrantReadWriteLock} instance
* and then increment the read lock count held by the thread
*/
@Override
public void lock() {
delegate.readLock().lock();
incReadLockCount();
}
/**
* Delegate the call to the internal {@link java.util.concurrent.locks.ReentrantReadWriteLock} instance
* and then increment the read lock count held by the thread
*/
@Override
public void lockInterruptibly() throws InterruptedException {
delegate.readLock().lockInterruptibly();
incReadLockCount();
}
/**
* No implementation provided
*
* @throws UnsupportedOperationException
*/
@Override
public Condition newCondition() {
throw new UnsupportedOperationException();
}
/**
* Delegate the call to the internal {@link java.util.concurrent.locks.ReentrantReadWriteLock} instance
* and then on successful acquisition of lock, increment the read lock count held by the thread
*/
@Override
public boolean tryLock() {
if (delegate.readLock().tryLock()) {
incReadLockCount();
return true;
}
return false;
}
/**
* Delegate the call to the internal {@link java.util.concurrent.locks.ReentrantReadWriteLock} instance
* and then on successful acquisition of lock, increment the read lock count held by the thread
*/
@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
if (delegate.readLock().tryLock(time, unit)) {
incReadLockCount();
return true;
}
return false;
}
/**
* Delegate the call to the internal {@link java.util.concurrent.locks.ReentrantReadWriteLock} instance
* and then decrement the read lock count held by the thread
*/
@Override
public void unlock() {
delegate.readLock().unlock();
decReadLockCount();
}
}
/**
* An implementation of lock which first checks the number of {@link ReadLock}
* held by this thread. If the thread already holds a {@link ReadLock}, then
* this implementation throws an {@link jakarta.ejb.IllegalLoopbackException} when a lock
* is requested
*
* @author Jaikiran Pai
* @version $Revision: $
*/
public class WriteLock implements Lock, Serializable {
private static final long serialVersionUID = 1L;
/**
* Ensures that the current thread doesn't hold any read locks. If
* the thread holds any read locks, this method throws a {@link jakarta.ejb.IllegalLoopbackException}.
* If no read locks are held, then this method delegates the call to the
* internal delegate {@link java.util.concurrent.locks.ReentrantReadWriteLock}
*/
@Override
public void lock() {
checkLoopback();
delegate.writeLock().lock();
}
/**
* Ensures that the current thread doesn't hold any read locks. If
* the thread holds any read locks, this method throws a {@link jakarta.ejb.IllegalLoopbackException}.
* If no read locks are held, then this method delegates the call to the
* internal delegate {@link java.util.concurrent.locks.ReentrantReadWriteLock}
*/
@Override
public void lockInterruptibly() throws InterruptedException {
checkLoopback();
delegate.writeLock().lockInterruptibly();
}
/**
* Not implemented
*
* @throws UnsupportedOperationException
*/
@Override
public Condition newCondition() {
throw new UnsupportedOperationException();
}
/**
* Ensures that the current thread doesn't hold any read locks. If
* the thread holds any read locks, this method throws a {@link jakarta.ejb.IllegalLoopbackException}.
* If no read locks are held, then this method delegates the call to the
* internal delegate {@link java.util.concurrent.locks.ReentrantReadWriteLock}
*/
@Override
public boolean tryLock() {
checkLoopback();
return delegate.writeLock().tryLock();
}
/**
* Ensures that the current thread doesn't hold any read locks. If
* the thread holds any read locks, this method throws a {@link jakarta.ejb.IllegalLoopbackException}.
* If no read locks are held, then this method delegates the call to the
* internal delegate {@link java.util.concurrent.locks.ReentrantReadWriteLock}
*/
@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
checkLoopback();
return delegate.writeLock().tryLock(time, unit);
}
/**
* This method delegates the call to the
* internal delegate {@link java.util.concurrent.locks.ReentrantReadWriteLock}
*/
@Override
public void unlock() {
delegate.writeLock().unlock();
}
}
/**
* Ensures that the current thread doesn't hold any read locks. If
* the thread holds any read locks, this method throws a {@link jakarta.ejb.IllegalLoopbackException}.
*/
private void checkLoopback() {
Integer current = readLockCount.get();
if (current != null) {
assert current > 0 : "readLockCount is set, but to 0";
throw EjbLogger.ROOT_LOGGER.failToUpgradeToWriteLock();
}
}
/**
* Decrements the read lock count held by the thread
*/
private void decReadLockCount() {
Integer current = readLockCount.get();
int next;
assert current != null : "can't decrease, readLockCount is not set";
next = current - 1;
if (next == 0)
readLockCount.remove();
else
readLockCount.set(next);
}
/**
* Increments the read lock count held by the thread
*/
private void incReadLockCount() {
Integer current = readLockCount.get();
int next;
if (current == null)
next = 1;
else
next = current + 1;
readLockCount.set(next);
}
/**
* @see java.util.concurrent.locks.ReadWriteLock#readLock()
*/
@Override
public Lock readLock() {
return readLock;
}
/**
* @see java.util.concurrent.locks.ReadWriteLock#writeLock()
*/
@Override
public Lock writeLock() {
return writeLock;
}
}
| 9,814 | 34.179211 | 133 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/singleton/SingletonComponentInstanceAssociationInterceptor.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.singleton;
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.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
/**
* Responsible for associating the single component instance for a singleton bean during invocation.
*
* @author Jaikiran Pai
*/
public class SingletonComponentInstanceAssociationInterceptor extends AbstractEJBInterceptor {
public static final InterceptorFactory FACTORY = new ImmediateInterceptorFactory(new SingletonComponentInstanceAssociationInterceptor());
private SingletonComponentInstanceAssociationInterceptor() {
}
@Override
public Object processInvocation(InterceptorContext interceptorContext) throws Exception {
SingletonComponent singletonComponent = getComponent(interceptorContext, SingletonComponent.class);
ComponentInstance singletonComponentInstance = singletonComponent.getComponentInstance();
if (singletonComponentInstance == null) {
throw EjbLogger.ROOT_LOGGER.componentInstanceNotAvailable(interceptorContext);
}
interceptorContext.putPrivateData(ComponentInstance.class, singletonComponentInstance);
return interceptorContext.proceed();
}
}
| 2,456 | 42.875 | 141 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/singleton/StartupCountDownInterceptor.java | package org.jboss.as.ejb3.component.singleton;
import org.jboss.as.ee.component.deployers.StartupCountdown;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
/**
* Interceptor decreasing value of passed CountDownLatch per invocation.
* Is used on @Startup @Singletons' @PostConstruct methods to signal post-construct successfuly done.
* @author Fedor Gavrilov
*/
public class StartupCountDownInterceptor implements Interceptor {
private final StartupCountdown countdown;
StartupCountDownInterceptor(final StartupCountdown countdown) {
this.countdown = countdown;
}
@Override
public Object processInvocation(final InterceptorContext context) throws Exception {
final StartupCountdown.Frame frame = countdown.enter();
try {
Object proceed = context.proceed();
countdown.countDown();
return proceed;
} finally {
StartupCountdown.restore(frame);
}
}
}
| 953 | 27.909091 | 101 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/singleton/ContainerManagedConcurrencyInterceptorFactory.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.singleton;
import org.jboss.as.ee.component.Component;
import org.jboss.as.ee.component.ComponentInterceptorFactory;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorFactoryContext;
import java.lang.reflect.Method;
import java.util.Map;
/**
* An {@link org.jboss.invocation.InterceptorFactory} which returns a new instance of {@link ContainerManagedConcurrencyInterceptor} on each
* invocation to {@link #create(org.jboss.invocation.InterceptorFactoryContext)}. This {@link org.jboss.invocation.InterceptorFactory} can be used
* for handling container managed concurrency invocations on a {@link SingletonComponent}
* <p/>
* User: Jaikiran Pai
*/
class ContainerManagedConcurrencyInterceptorFactory extends ComponentInterceptorFactory {
private final Map<Method, Method> viewMethodToComponentMethodMap;
public ContainerManagedConcurrencyInterceptorFactory(Map<Method, Method> viewMethodToComponentMethodMap) {
this.viewMethodToComponentMethodMap = viewMethodToComponentMethodMap;
}
@Override
protected Interceptor create(final Component component, final InterceptorFactoryContext context) {
return new ContainerManagedConcurrencyInterceptor((SingletonComponent) component, viewMethodToComponentMethodMap);
}
}
| 2,354 | 42.611111 | 146 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/singleton/SingletonComponentCreateService.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.singleton;
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.session.SessionBeanComponentCreateService;
import org.jboss.as.ejb3.deployment.ApplicationExceptions;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.value.InjectedValue;
import java.util.List;
/**
* @author Stuart Douglas
*/
public class SingletonComponentCreateService extends SessionBeanComponentCreateService {
private final boolean initOnStartup;
private final List<ServiceName> dependsOn;
private final InjectedValue<DefaultAccessTimeoutService> defaultAccessTimeoutService = new InjectedValue<DefaultAccessTimeoutService>();
public SingletonComponentCreateService(final ComponentConfiguration componentConfiguration, final ApplicationExceptions ejbJarConfiguration, final boolean initOnStartup, final List<ServiceName> dependsOn) {
super(componentConfiguration, ejbJarConfiguration);
this.initOnStartup = initOnStartup;
this.dependsOn = dependsOn;
}
@Override
protected BasicComponent createComponent() {
return new SingletonComponent(this, dependsOn);
}
public boolean isInitOnStartup() {
return this.initOnStartup;
}
public DefaultAccessTimeoutService getDefaultAccessTimeoutService() {
return defaultAccessTimeoutService.getValue();
}
Injector<DefaultAccessTimeoutService> getDefaultAccessTimeoutInjector() {
return this.defaultAccessTimeoutService;
}
}
| 2,716 | 38.955882 | 210 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/singleton/SingletonAllowedMethodsInformation.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.singleton;
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 SingletonAllowedMethodsInformation extends SessionBeanAllowedMethodsInformation {
public static final SingletonAllowedMethodsInformation INSTANCE_BMT = new SingletonAllowedMethodsInformation(true);
public static final SingletonAllowedMethodsInformation INSTANCE_CMT = new SingletonAllowedMethodsInformation(false);
protected SingletonAllowedMethodsInformation(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/singleton/SingletonComponentInstance.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.singleton;
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 SingletonComponentInstance extends SessionBeanComponentInstance {
/**
* Construct a new instance.
*
* @param component the component
*/
public SingletonComponentInstance(final BasicComponent component, final Interceptor preDestroyInterceptor, final Map<Method, Interceptor> methodInterceptors) {
super(component, preDestroyInterceptor, methodInterceptors);
}
@Override
protected SessionID getId() {
return null;
}
}
| 1,867 | 33.592593 | 163 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/singleton/SingletonComponentDescription.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.singleton;
import static org.jboss.as.ejb3.logging.EjbLogger.ROOT_LOGGER;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import jakarta.ejb.ConcurrencyManagementType;
import jakarta.ejb.TransactionManagementType;
import org.jboss.as.ee.component.Attachments;
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.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.deployers.StartupCountdown;
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.EJBComponentDescription;
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.session.StatelessRemoteViewInstanceFactory;
import org.jboss.as.ejb3.component.session.StatelessWriteReplaceInterceptor;
import org.jboss.as.ejb3.deployment.EjbJarDescription;
import org.jboss.as.ejb3.logging.EjbLogger;
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.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.InterceptorFactory;
import org.jboss.metadata.ejb.spec.MethodInterfaceType;
import org.jboss.metadata.ejb.spec.SessionBeanMetaData;
import org.jboss.modules.ModuleLoader;
import org.jboss.msc.service.ServiceName;
/**
* Component description for a singleton bean
*
* @author Jaikiran Pai
*/
public class SingletonComponentDescription extends SessionBeanComponentDescription {
/**
* Flag to indicate whether the singleton bean is a @Startup (a.k.a init-on-startup) bean
*/
private boolean initOnStartup;
private final List<ServiceName> dependsOn = new ArrayList<ServiceName>();
/**
* Construct a new instance.
*
* @param componentName the component name
* @param componentClassName the component instance class name
* @param ejbJarDescription the module description
*/
public SingletonComponentDescription(final String componentName, final String componentClassName, final EjbJarDescription ejbJarDescription,
final DeploymentUnit deploymentUnit, final SessionBeanMetaData descriptorData) {
super(componentName, componentClassName, ejbJarDescription, deploymentUnit, descriptorData);
getConfigurators().add(new ComponentConfigurator() {
@Override
public void configure(final DeploymentPhaseContext context, final ComponentDescription description, final ComponentConfiguration configuration) throws DeploymentUnitProcessingException {
configuration.addTimeoutViewInterceptor(SingletonComponentInstanceAssociationInterceptor.FACTORY, InterceptorOrder.View.ASSOCIATING_INTERCEPTOR);
ConcurrencyManagementType concurrencyManagementType = getConcurrencyManagementType();
if (concurrencyManagementType == null || concurrencyManagementType == ConcurrencyManagementType.CONTAINER) {
configuration.addTimeoutViewInterceptor(new ContainerManagedConcurrencyInterceptorFactory(Collections.emptyMap()), InterceptorOrder.View.SINGLETON_CONTAINER_MANAGED_CONCURRENCY_INTERCEPTOR);
}
}
});
}
@Override
public ComponentConfiguration createConfiguration(final ClassReflectionIndex classIndex, final ClassLoader moduleClassLoader, final ModuleLoader moduleLoader) {
ComponentConfiguration singletonComponentConfiguration = new ComponentConfiguration(this, classIndex, moduleClassLoader, moduleLoader);
// setup the component create service
singletonComponentConfiguration.setComponentCreateServiceFactory(new SingletonComponentCreateServiceFactory(this.isInitOnStartup(), dependsOn));
final String definedSecurityDomain = getDefinedSecurityDomain();
final boolean securityRequired = hasBeanLevelSecurityMetadata();
if (securityRequired) {
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;
}
EJBComponentDescription ejbComponentDescription = (EJBComponentDescription) description;
if (getSecurityDomainServiceName() != null) {
ejbComponentDescription.setSecurityRequired(securityRequired);
final HashMap<Integer, InterceptorFactory> elytronInterceptorFactories = getElytronInterceptorFactories(contextID, ejbComponentDescription.requiresJacc(), false);
elytronInterceptorFactories.forEach((priority, elytronInterceptorFactory) -> configuration.addPostConstructInterceptor(elytronInterceptorFactory, priority));
} else if (definedSecurityDomain != null){
throw ROOT_LOGGER.legacySecurityUnsupported(definedSecurityDomain);
}
}
});
}
getConfigurators().add(new ComponentConfigurator() {
@Override
public void configure(DeploymentPhaseContext context, ComponentDescription description, ComponentConfiguration configuration) throws DeploymentUnitProcessingException {
if (isInitOnStartup()) {
final StartupCountdown startupCountdown = context.getDeploymentUnit().getAttachment(Attachments.STARTUP_COUNTDOWN);
configuration.addPostConstructInterceptor(new ImmediateInterceptorFactory(new StartupCountDownInterceptor(startupCountdown)), InterceptorOrder.ComponentPostConstruct.STARTUP_COUNTDOWN_INTERCEPTOR);
}
}
});
if (getTransactionManagementType().equals(TransactionManagementType.CONTAINER)) {
//we need to add the transaction interceptor to the lifecycle methods
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);
}
});
} else {
// add the bmt interceptor
getConfigurators().add(new ComponentConfigurator() {
@Override
public void configure(final DeploymentPhaseContext context, final ComponentDescription description, final ComponentConfiguration configuration) throws DeploymentUnitProcessingException {
configuration.addPostConstructInterceptor(EjbBMTInterceptor.FACTORY, InterceptorOrder.ComponentPostConstruct.TRANSACTION_INTERCEPTOR);
configuration.addPreDestroyInterceptor(EjbBMTInterceptor.FACTORY, InterceptorOrder.ComponentPreDestroy.TRANSACTION_INTERCEPTOR);
// add the bmt interceptor factory
configuration.addComponentInterceptor(EjbBMTInterceptor.FACTORY, InterceptorOrder.Component.BMT_TRANSACTION_INTERCEPTOR, false);
}
});
}
return singletonComponentConfiguration;
}
/**
* Returns true if the singleton bean is marked for init-on-startup (a.k.a @Startup). Else
* returns false
* <p/>
*
* @return
*/
public boolean isInitOnStartup() {
return this.initOnStartup;
}
/**
* Marks the singleton bean for init-on-startup
*/
public void initOnStartup() {
this.initOnStartup = true;
}
@Override
public SessionBeanType getSessionBeanType() {
return SessionBeanComponentDescription.SessionBeanType.SINGLETON;
}
@Override
protected void setupViewInterceptors(EJBViewDescription view) {
// let super do its job first
super.setupViewInterceptors(view);
addViewSerializationInterceptor(view);
// add container managed concurrency interceptor to the component
this.addConcurrencyManagementInterceptor(view);
// add 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
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 singleton component instance associating interceptor
configuration.addViewInterceptor(SingletonComponentInstanceAssociationInterceptor.FACTORY, 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 : classIndex.getMethods()) {
configuration.addClientInterceptor(method, StatelessWriteReplaceInterceptor.factory(configuration.getViewServiceName().getCanonicalName()), InterceptorOrder.Client.WRITE_REPLACE);
}
}
});
}
@Override
protected ViewConfigurator getSessionBeanObjectViewConfigurator() {
throw EjbLogger.ROOT_LOGGER.ejb2xViewNotApplicableForSingletonBeans();
}
private void addConcurrencyManagementInterceptor(final ViewDescription view) {
view.getConfigurators().add(new ViewConfigurator() {
@Override
public void configure(DeploymentPhaseContext context, ComponentConfiguration componentConfiguration, ViewDescription description, ViewConfiguration configuration) throws DeploymentUnitProcessingException {
final SingletonComponentDescription singletonComponentDescription = (SingletonComponentDescription) componentConfiguration.getComponentDescription();
// we don't care about BEAN managed concurrency, so just return
if (singletonComponentDescription.getConcurrencyManagementType() == ConcurrencyManagementType.BEAN) {
return;
}
configuration.addViewInterceptor(new ContainerManagedConcurrencyInterceptorFactory(configuration.getViewToComponentMethodMap()), InterceptorOrder.View.SINGLETON_CONTAINER_MANAGED_CONCURRENCY_INTERCEPTOR);
}
});
}
public List<ServiceName> getDependsOn() {
return dependsOn;
}
@Override
public boolean isTimerServiceApplicable() {
return true;
}
}
| 16,299 | 55.206897 | 304 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/singleton/SingletonComponent.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.singleton;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import jakarta.ejb.LockType;
import org.jboss.as.ee.component.BasicComponentInstance;
import org.jboss.as.ee.component.Component;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.ejb3.component.DefaultAccessTimeoutService;
import org.jboss.as.ejb3.component.EJBBusinessMethod;
import org.jboss.as.ejb3.component.allowedmethods.AllowedMethodsInformation;
import org.jboss.as.ejb3.component.session.SessionBeanComponent;
import org.jboss.as.ejb3.concurrency.AccessTimeoutDetails;
import org.jboss.as.server.CurrentServiceContainer;
import org.jboss.invocation.Interceptor;
import org.jboss.msc.service.ServiceContainer;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import static org.jboss.as.ejb3.logging.EjbLogger.ROOT_LOGGER;
/**
* {@link Component} representing a {@link jakarta.ejb.Singleton} Jakarta Enterprise Beans.
*
* @author Jaikiran Pai
*/
public class SingletonComponent extends SessionBeanComponent {
private volatile SingletonComponentInstance singletonComponentInstance;
private final boolean initOnStartup;
private final Map<String, LockType> beanLevelLockType;
private final Map<EJBBusinessMethod, LockType> methodLockTypes;
private final Map<EJBBusinessMethod, AccessTimeoutDetails> methodAccessTimeouts;
private final List<ServiceName> dependsOn;
private final DefaultAccessTimeoutService defaultAccessTimeoutProvider;
/**
* We can't lock on <code>this</code> because the {@link org.jboss.as.ee.component.BasicComponent#waitForComponentStart()}
* also synchronizes on it, and calls {@link #wait()}.
*/
private final Object creationLock = new Object();
/**
* A spec compliant {@link EJBReadWriteLock}
*/
private final ReadWriteLock readWriteLock = new EJBReadWriteLock();
/**
* Construct a new instance.
*
* @param singletonComponentCreateService
* the component configuration
* @param dependsOn
*/
public SingletonComponent(final SingletonComponentCreateService singletonComponentCreateService, final List<ServiceName> dependsOn) {
super(singletonComponentCreateService);
this.dependsOn = dependsOn;
this.initOnStartup = singletonComponentCreateService.isInitOnStartup();
this.beanLevelLockType = singletonComponentCreateService.getBeanLockType();
this.methodLockTypes = singletonComponentCreateService.getMethodApplicableLockTypes();
this.methodAccessTimeouts = singletonComponentCreateService.getMethodApplicableAccessTimeouts();
this.defaultAccessTimeoutProvider = singletonComponentCreateService.getDefaultAccessTimeoutService();
}
@Override
protected BasicComponentInstance instantiateComponentInstance(Interceptor preDestroyInterceptor, Map<Method, Interceptor> methodInterceptors, Map<Object, Object> context) {
// synchronized from getComponentInstance
assert Thread.holdsLock(creationLock);
if (dependsOn != null) {
for (ServiceName serviceName : dependsOn) {
final ServiceController<Component> service = (ServiceController<Component>) currentServiceContainer().getRequiredService(serviceName);
final Component component = service.getValue();
if (component instanceof SingletonComponent) {
((SingletonComponent) component).getComponentInstance();
}
}
}
return new SingletonComponentInstance(this, preDestroyInterceptor, methodInterceptors);
}
/**
* @return the {@link SingletonComponentInstance}, lazily creating it if necessary.
*/
public SingletonComponentInstance getComponentInstance() {
if (this.singletonComponentInstance == null) {
// Protects from re-entry which can happen if {@link PostConstruct} annotated methods pass a
// view (from {@link SessionContext#getBusinessObject(Class)}) of itself to other Jakarta Enterprise Beans
if (Thread.holdsLock(creationLock))
throw EjbLogger.ROOT_LOGGER.reentrantSingletonCreation(getComponentName(), getComponentClass().getName());
synchronized (creationLock) {
if (this.singletonComponentInstance == null) {
this.singletonComponentInstance = (SingletonComponentInstance) this.createInstance();
}
}
}
return this.singletonComponentInstance;
}
@Override
public void start() {
super.start();
if (this.initOnStartup) {
// Do not call createInstance() because we can't ever assume that the singleton instance
// hasn't already been created.
ROOT_LOGGER.debugf("%s bean is a @Startup (a.k.a init-on-startup) bean, creating/getting the singleton instance", this.getComponentName());
this.getComponentInstance();
}
}
@Override
public void done() {
this.destroySingletonInstance();
super.done();
}
public LockType getLockType(Method method) {
final EJBBusinessMethod ejbMethod = new EJBBusinessMethod(method);
final LockType lockType = this.methodLockTypes.get(ejbMethod);
if (lockType != null) {
return lockType;
}
// check bean level lock type
final LockType type = this.beanLevelLockType.get(method.getDeclaringClass().getName());
if (type != null) {
return type;
}
// default WRITE lock type
return LockType.WRITE;
}
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 beanTimeout = this.beanLevelAccessTimeout.get(method.getDeclaringClass().getName());
if (beanTimeout != null) {
return beanTimeout;
}
return getDefaultAccessTimeout();
}
public AccessTimeoutDetails getDefaultAccessTimeout() {
return defaultAccessTimeoutProvider.getDefaultAccessTimeout();
}
public ReadWriteLock getLock() {
return readWriteLock;
}
private void destroySingletonInstance() {
synchronized (creationLock) {
if (this.singletonComponentInstance != null) {
singletonComponentInstance.destroy();
this.singletonComponentInstance = null;
}
}
}
@Override
public AllowedMethodsInformation getAllowedMethodsInformation() {
return isBeanManagedTransaction() ? SingletonAllowedMethodsInformation.INSTANCE_BMT : SingletonAllowedMethodsInformation.INSTANCE_CMT;
}
private static ServiceContainer currentServiceContainer() {
if(System.getSecurityManager() == null) {
return CurrentServiceContainer.getServiceContainer();
}
return AccessController.doPrivileged(CurrentServiceContainer.GET_ACTION);
}
}
| 8,469 | 39.526316 | 176 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/singleton/SingletonComponentCreateServiceFactory.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.singleton;
import org.jboss.as.ee.component.BasicComponentCreateService;
import org.jboss.as.ee.component.ComponentConfiguration;
import org.jboss.as.ee.component.DependencyConfigurator;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.ejb3.component.DefaultAccessTimeoutService;
import org.jboss.as.ejb3.component.EJBComponentCreateServiceFactory;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import java.util.List;
/**
* User: jpai
*/
public class SingletonComponentCreateServiceFactory extends EJBComponentCreateServiceFactory {
private final boolean initOnStartup;
private final List<ServiceName> dependsOn;
public SingletonComponentCreateServiceFactory(final boolean initServiceOnStartup, final List<ServiceName> dependsOn) {
this.initOnStartup = initServiceOnStartup;
this.dependsOn = dependsOn;
}
@Override
public BasicComponentCreateService constructService(ComponentConfiguration configuration) {
if (this.ejbJarConfiguration == null) {
throw EjbLogger.ROOT_LOGGER.ejbJarConfigNotBeenSet(this, configuration.getComponentName());
}
// setup an injection dependency to inject the DefaultAccessTimeoutService in the singleton bean
// component create service
configuration.getCreateDependencies().add(new DependencyConfigurator<SingletonComponentCreateService>() {
@Override
public void configureDependency(ServiceBuilder<?> serviceBuilder, SingletonComponentCreateService componentCreateService) throws DeploymentUnitProcessingException {
serviceBuilder.addDependency(DefaultAccessTimeoutService.SINGLETON_SERVICE_NAME, DefaultAccessTimeoutService.class, componentCreateService.getDefaultAccessTimeoutInjector());
}
});
return new SingletonComponentCreateService(configuration, this.ejbJarConfiguration, this.initOnStartup, dependsOn);
}
}
| 3,109 | 46.121212 | 190 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/singleton/ContainerManagedConcurrencyInterceptor.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.singleton;
import org.jboss.as.ejb3.concurrency.AccessTimeoutDetails;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import jakarta.ejb.LockType;
import jakarta.interceptor.InvocationContext;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import static org.jboss.as.ejb3.logging.EjbLogger.ROOT_LOGGER;
/**
* @author Jaikiran Pai
*/
class ContainerManagedConcurrencyInterceptor implements Interceptor {
private final SingletonComponent lockableComponent;
private final Map<Method, Method> viewMethodToComponentMethodMap;
public ContainerManagedConcurrencyInterceptor(SingletonComponent component, Map<Method, Method> viewMethodToComponentMethodMap) {
this.viewMethodToComponentMethodMap = viewMethodToComponentMethodMap;
if (component == null) {
throw EjbLogger.ROOT_LOGGER.componentIsNull(SingletonComponent.class.getName());
}
this.lockableComponent = component;
}
protected SingletonComponent getLockableComponent() {
return this.lockableComponent;
}
@Override
public Object processInvocation(final InterceptorContext context) throws Exception {
final InvocationContext invocationContext = context.getInvocationContext();
SingletonComponent lockableComponent = this.getLockableComponent();
// get the invoked method
Method method = invocationContext.getMethod();
if (method == null) {
throw EjbLogger.ROOT_LOGGER.invocationNotApplicableForMethodInvocation(invocationContext);
}
Method invokedMethod = viewMethodToComponentMethodMap.get(method);
if(invokedMethod == null) {
invokedMethod = method;
}
// get the Lock applicable for this method
Lock lock = getLock(lockableComponent, invokedMethod);
// the default access timeout (will be used in the absence of any explicit access timeout value for the invoked method)
AccessTimeoutDetails defaultAccessTimeout = lockableComponent.getDefaultAccessTimeout();
// set to the default values
long time = defaultAccessTimeout.getValue();
TimeUnit unit = defaultAccessTimeout.getTimeUnit();
AccessTimeoutDetails accessTimeoutOnMethod = lockableComponent.getAccessTimeout(invokedMethod);
if (accessTimeoutOnMethod != null) {
if (accessTimeoutOnMethod.getValue() < 0) {
// for any negative value of timeout, we just default to max timeout val and max timeout unit.
// violation of spec! But we don't want to wait indefinitely.
if (ROOT_LOGGER.isDebugEnabled()) {
ROOT_LOGGER.debug("Ignoring a negative @AccessTimeout value: " + accessTimeoutOnMethod.getValue()
+ " and timeout unit: " + accessTimeoutOnMethod.getTimeUnit().name()
+ ". Will default to timeout value: " + defaultAccessTimeout.getValue() + " and timeout unit: "
+ defaultAccessTimeout.getTimeUnit().name());
}
} else {
// use the explicit access timeout values specified on the method
time = accessTimeoutOnMethod.getValue();
unit = accessTimeoutOnMethod.getTimeUnit();
}
}
// try getting the lock
boolean success = lock.tryLock(time, unit);
if (!success) {
throw EjbLogger.ROOT_LOGGER.concurrentAccessTimeoutException(lockableComponent.getComponentName(), time + unit.name());
}
try {
// lock obtained. now proceed!
return invocationContext.proceed();
} finally {
lock.unlock();
}
}
private Lock getLock(SingletonComponent lockableComponent, Method method) {
LockType lockType = lockableComponent.getLockType(method);
switch (lockType) {
case READ:
return lockableComponent.getLock().readLock();
case WRITE:
return lockableComponent.getLock().writeLock();
}
throw EjbLogger.ROOT_LOGGER.failToObtainLockIllegalType(lockType, method, lockableComponent);
}
}
| 5,425 | 42.758065 | 133 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/interceptors/GetHomeInterceptorFactory.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.interceptors;
import org.jboss.as.ee.component.ComponentView;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
import org.jboss.invocation.InterceptorFactoryContext;
import org.jboss.msc.value.InjectedValue;
/**
* Interceptor that can return a home interface for an Jakarta Enterprise Beans
*
* @author Stuart Douglas
*/
public class GetHomeInterceptorFactory implements InterceptorFactory {
private final InjectedValue<ComponentView> viewToCreate = new InjectedValue<ComponentView>();
private final Interceptor interceptor;
public GetHomeInterceptorFactory() {
interceptor = new Interceptor() {
@Override
public Object processInvocation(final InterceptorContext context) throws Exception {
return viewToCreate.getValue().createInstance().getInstance();
}
};
}
@Override
public Interceptor create(final InterceptorFactoryContext context) {
return interceptor;
}
public InjectedValue<ComponentView> getViewToCreate() {
return viewToCreate;
}
}
| 2,215 | 35.327869 | 97 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/interceptors/EjbMetadataInterceptor.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.interceptors;
import jakarta.ejb.EJBHome;
import jakarta.ejb.EJBObject;
import org.jboss.as.ee.component.ComponentView;
import org.jboss.ejb.client.EJBClient;
import org.jboss.ejb.client.EntityEJBMetaData;
import org.jboss.ejb.client.StatefulEJBMetaData;
import org.jboss.ejb.client.StatelessEJBMetaData;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.msc.value.InjectedValue;
/**
* Interceptor that handles the Jakarta Enterprise Beans metadata for non-IIOP invocations.
*
* @author Stuart Douglas
*/
public class EjbMetadataInterceptor implements Interceptor {
private final InjectedValue<ComponentView> homeView = new InjectedValue<ComponentView>();
private final Class<?> remoteClass;
private final Class<? extends EJBHome> homeClass;
private final Class<?> pkClass;
private final boolean session;
private final boolean stateless;
public EjbMetadataInterceptor(Class<?> remoteClass, Class<? extends EJBHome> homeClass, Class<?> pkClass, boolean session, boolean stateless) {
this.remoteClass = remoteClass;
this.homeClass = homeClass;
this.pkClass = pkClass;
this.session = session;
this.stateless = stateless;
}
@Override
public Object processInvocation(final InterceptorContext context) throws Exception {
final EJBHome home = (EJBHome) homeView.getValue().createInstance().getInstance();
if (session) {
if (stateless) {
return createStatelessMetaData(remoteClass.asSubclass(EJBObject.class), homeClass, home);
} else {
return createStatefulMetaData(remoteClass.asSubclass(EJBObject.class), homeClass, home);
}
} else {
return createEntityMetaData(remoteClass.asSubclass(EJBObject.class), homeClass, home, pkClass);
}
}
private static <T extends EJBObject, H extends EJBHome> StatelessEJBMetaData<T, ? extends H> createStatelessMetaData(Class<T> remoteClass, Class<H> homeClass, EJBHome home) {
return new StatelessEJBMetaData<>(remoteClass, EJBClient.getLocatorFor(home).<H>narrowAsHome(homeClass));
}
private static <T extends EJBObject, H extends EJBHome> StatefulEJBMetaData<T, ? extends H> createStatefulMetaData(Class<T> remoteClass, Class<H> homeClass, EJBHome home) {
return new StatefulEJBMetaData<>(remoteClass, EJBClient.getLocatorFor(home).<H>narrowAsHome(homeClass));
}
private static <T extends EJBObject, H extends EJBHome> EntityEJBMetaData<T, ? extends H> createEntityMetaData(Class<T> remoteClass, Class<H> homeClass, EJBHome home, Class<?> pkClass) {
return new EntityEJBMetaData<>(remoteClass, EJBClient.getLocatorFor(home).<H>narrowAsHome(homeClass), pkClass);
}
public InjectedValue<ComponentView> getHomeView() {
return homeView;
}
}
| 3,948 | 43.875 | 190 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/interceptors/AsyncFutureInterceptorFactory.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.interceptors;
import java.util.concurrent.Callable;
import org.jboss.as.ee.component.Component;
import org.jboss.as.ee.component.deployers.StartupCountdown;
import org.jboss.as.ee.component.interceptors.InvocationType;
import org.jboss.as.ejb3.component.session.SessionBeanComponent;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
import org.jboss.invocation.InterceptorFactoryContext;
import org.wildfly.security.auth.server.SecurityDomain;
import org.wildfly.security.auth.server.SecurityIdentity;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* An asynchronous execution interceptor for methods returning {@link java.util.concurrent.Future}. Because asynchronous invocations
* necessarily run in a concurrent thread, any thread context setup interceptors should run <b>after</b> this
* interceptor to prevent that context from becoming lost. This interceptor should be associated with the client
* interceptor stack.
* <p/>
* Cancellation notification is accomplished via the {@link CancellationFlag} private data attachment. This interceptor
* will create and attach a new cancellation flag, which will be set to {@code true} if the request was cancelled.
* <p/>
* This interceptor should only be used for local invocations.
*
* @author Stuart Douglas
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
*/
public final class AsyncFutureInterceptorFactory implements InterceptorFactory {
public static final InterceptorFactory INSTANCE = new AsyncFutureInterceptorFactory();
private AsyncFutureInterceptorFactory() {
}
@Override
public Interceptor create(final InterceptorFactoryContext context) {
final SessionBeanComponent component = (SessionBeanComponent) context.getContextData().get(Component.class);
if (component.isSecurityDomainKnown()) {
return new Interceptor() {
@Override
public Object processInvocation(final InterceptorContext context) throws Exception {
if (! context.isBlockingCaller()) {
return context.proceed();
}
final InterceptorContext asyncInterceptorContext = context.clone();
asyncInterceptorContext.putPrivateData(InvocationType.class, InvocationType.ASYNC);
final CancellationFlag flag = new CancellationFlag();
final SecurityDomain securityDomain = context.getPrivateData(SecurityDomain.class);
final StartupCountdown.Frame frame = StartupCountdown.current();
final SecurityIdentity currentIdentity = securityDomain == null ? null : securityDomain.getCurrentSecurityIdentity();
Callable<Object> invocationTask = () -> {
StartupCountdown.restore(frame);
try {
return asyncInterceptorContext.proceed();
} finally {
StartupCountdown.restore(null);
}
};
final AsyncInvocationTask task = new AsyncInvocationTask(flag) {
@Override
protected Object runInvocation() throws Exception {
if(currentIdentity != null) {
return currentIdentity.runAs(invocationTask);
} else {
return invocationTask.call();
}
}
};
asyncInterceptorContext.putPrivateData(CancellationFlag.class, flag);
asyncInterceptorContext.setBlockingCaller(false);
return execute(component, task);
}
};
} else {
return new Interceptor() {
@Override
public Object processInvocation(final InterceptorContext context) throws Exception {
if (! context.isBlockingCaller()) {
return context.proceed();
}
final InterceptorContext asyncInterceptorContext = context.clone();
asyncInterceptorContext.putPrivateData(InvocationType.class, InvocationType.ASYNC);
final CancellationFlag flag = new CancellationFlag();
final StartupCountdown.Frame frame = StartupCountdown.current();
final AsyncInvocationTask task = new AsyncInvocationTask(flag) {
@Override
protected Object runInvocation() throws Exception {
StartupCountdown.restore(frame);
try {
return asyncInterceptorContext.proceed();
} finally {
StartupCountdown.restore(null);
}
}
};
asyncInterceptorContext.putPrivateData(CancellationFlag.class, flag);
asyncInterceptorContext.setBlockingCaller(false);
return execute(component, task);
}
};
}
}
private AsyncInvocationTask execute(SessionBeanComponent component, AsyncInvocationTask task) {
// The interceptor runs in user application's context classloader. Triggering an execute via an executor service from here can potentially lead to
// new thread creation which will assign themselves the context classloader of the parent thread (i.e. this thread). This effectively can lead to
// deployment's classloader leak. See https://issues.jboss.org/browse/WFLY-1375
// To prevent this, we set the TCCL of this thread to null and then trigger the "execute" before "finally" setting the TCCL back to the original one.
final ClassLoader oldClassLoader = WildFlySecurityManager.setCurrentContextClassLoaderPrivileged((ClassLoader) null);
try {
component.getAsynchronousExecutor().execute(task);
} finally {
// reset to the original TCCL
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldClassLoader);
}
return task;
}
}
| 7,531 | 48.552632 | 157 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/interceptors/NonPooledEJBComponentInstanceAssociatingInterceptor.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.interceptors;
import org.jboss.as.ee.component.ComponentInstance;
import org.jboss.as.ejb3.component.EJBComponent;
import org.jboss.invocation.InterceptorContext;
import jakarta.ejb.ConcurrentAccessException;
import jakarta.ejb.ConcurrentAccessTimeoutException;
import java.rmi.RemoteException;
/**
* A {@link ComponentInstance} associating interceptor for Jakarta Enterprise Beans components (SLSB and message driven) which
* have pooling disabled. Upon each {@link #processInvocation(org.jboss.invocation.InterceptorContext) invocation}
* this interceptor creates a new {@link ComponentInstance} and associates it with the invocation. It then
* {@link org.jboss.as.ee.component.ComponentInstance#destroy() destroys} the instance upon method completion.
* <p/>
* User: Jaikiran Pai
*/
public class NonPooledEJBComponentInstanceAssociatingInterceptor extends AbstractEJBInterceptor {
public static final NonPooledEJBComponentInstanceAssociatingInterceptor INSTANCE = new NonPooledEJBComponentInstanceAssociatingInterceptor();
private NonPooledEJBComponentInstanceAssociatingInterceptor() {
}
@Override
public Object processInvocation(InterceptorContext context) throws Exception {
final EJBComponent component = getComponent(context, EJBComponent.class);
// create the instance
final ComponentInstance componentInstance = component.createInstance();
context.putPrivateData(ComponentInstance.class, componentInstance);
//if this is set to true we do not invoke instance.destroy
//as we are not allowed to invoke pre-destroy callbacks
boolean discard = false;
try {
return context.proceed();
} catch (Exception ex) {
final 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) {
discard = true;
}
throw ex;
} catch (final Error e) {
discard = true;
throw e;
} catch (final Throwable t) {
discard = true;
throw new RuntimeException(t);
} finally {
// destroy the instance
if (!discard) {
componentInstance.destroy();
}
}
}
}
| 3,750 | 41.146067 | 145 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/interceptors/AsyncInvocationTask.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.interceptors;
import static java.lang.Math.max;
import java.lang.reflect.UndeclaredThrowableException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.wildfly.common.Assert;
/**
* runnable used to invoke local Jakarta Enterprise Beans async methods
*
* @author Stuart Douglas
*/
public abstract class AsyncInvocationTask implements Runnable, Future<Object> {
private final CancellationFlag cancelledFlag;
private static final int ST_RUNNING = 0;
private static final int ST_DONE = 1;
private static final int ST_CANCELLED = 2;
private static final int ST_FAILED = 3;
private volatile int status = ST_RUNNING;
private Object result;
private Exception failed;
public AsyncInvocationTask(final CancellationFlag cancelledFlag) {
this.cancelledFlag = cancelledFlag;
}
@Override
public synchronized boolean cancel(final boolean mayInterruptIfRunning) {
if (status != ST_RUNNING) {
return status == ST_CANCELLED;
}
if (cancelledFlag.cancel(mayInterruptIfRunning)) {
status = ST_CANCELLED;
done();
return true;
}
return false;
}
protected abstract Object runInvocation() throws Exception;
public void run() {
synchronized (this) {
if (! cancelledFlag.runIfNotCancelled()) {
status = ST_CANCELLED;
done();
return;
}
}
Object result;
try {
result = runInvocation();
} catch (Exception e) {
setFailed(e);
return;
}
Future<?> asyncResult = (Future<?>) result;
try {
if(asyncResult != null) {
result = asyncResult.get();
}
} catch (InterruptedException e) {
setFailed(new IllegalStateException(e));
return;
} catch (ExecutionException e) {
try {
throw e.getCause();
} catch (Exception ex) {
setFailed(ex);
return;
} catch (Throwable throwable) {
setFailed(new UndeclaredThrowableException(throwable));
return;
}
}
setResult(result);
return;
}
private synchronized void setResult(final Object result) {
this.result = result;
status = ST_DONE;
done();
}
private synchronized void setFailed(final Exception e) {
this.failed = e;
status = ST_FAILED;
done();
}
private void done() {
notifyAll();
}
@Override
public boolean isCancelled() {
return status == ST_CANCELLED;
}
@Override
public boolean isDone() {
return status != ST_RUNNING;
}
@Override
public synchronized Object get() throws InterruptedException, ExecutionException {
for (;;) switch (status) {
case ST_RUNNING: wait(); break;
case ST_CANCELLED: throw EjbLogger.ROOT_LOGGER.taskWasCancelled();
case ST_FAILED: throw new ExecutionException(failed);
case ST_DONE: return result;
default: throw Assert.impossibleSwitchCase(status);
}
}
@Override
public synchronized Object get(final long timeout, final TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
long remaining = unit.toNanos(timeout);
long start = System.nanoTime();
for (;;) switch (status) {
case ST_RUNNING: {
if (remaining <= 0L) {
throw EjbLogger.ROOT_LOGGER.failToCompleteTaskBeforeTimeOut(timeout, unit);
}
// round up to the nearest millisecond
wait((remaining + 999_999L) / 1_000_000L);
remaining -= max(0L, System.nanoTime() - start);
break;
}
case ST_CANCELLED: throw EjbLogger.ROOT_LOGGER.taskWasCancelled();
case ST_FAILED: throw new ExecutionException(failed);
case ST_DONE: return result;
default: throw Assert.impossibleSwitchCase(status);
}
}
}
| 5,446 | 31.616766 | 143 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/interceptors/ShutDownInterceptorFactory.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2014, 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
* 2110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ejb3.component.interceptors;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
import org.jboss.invocation.InterceptorFactoryContext;
/**
* A per component interceptor that allows the Jakarta Enterprise Beans to shutdown gracefully.
*
* @author Stuart Douglas
*/
public class ShutDownInterceptorFactory implements InterceptorFactory {
private static final int SHUTDOWN_FLAG = 1 << 31;
private static final int INVERSE_SHUTDOWN_FLAG = ~SHUTDOWN_FLAG;
private static final AtomicIntegerFieldUpdater<ShutDownInterceptorFactory> updater = AtomicIntegerFieldUpdater.newUpdater(ShutDownInterceptorFactory.class, "invocationCount");
@SuppressWarnings("unused")
private volatile int invocationCount;
private final Object lock = new Object();
private Interceptor interceptor = new Interceptor() {
@Override
public Object processInvocation(InterceptorContext context) throws Exception {
int value;
int oldValue;
do {
oldValue = invocationCount;
if ((oldValue & SHUTDOWN_FLAG) != 0) {
throw EjbLogger.ROOT_LOGGER.componentIsShuttingDown();
}
value = oldValue + 1;
} while (!updater.compareAndSet(ShutDownInterceptorFactory.this, oldValue, value));
try {
return context.proceed();
} finally {
do {
oldValue = invocationCount;
boolean shutDown = (oldValue & SHUTDOWN_FLAG) != 0;
int oldCount = oldValue & INVERSE_SHUTDOWN_FLAG;
value = oldCount - 1;
if(shutDown) {
value = value | SHUTDOWN_FLAG;
}
} while (!updater.compareAndSet(ShutDownInterceptorFactory.this, oldValue, value));
//if the count is zero and the component is shutting down
if (value == SHUTDOWN_FLAG) {
synchronized (lock) {
lock.notifyAll();
}
}
}
}
};
@Override
public Interceptor create(InterceptorFactoryContext context) {
return interceptor;
}
/**
* Upon calling this method the Jakarta Enterprise Beans will be set to a shutdown state, and no further invocations will be allowed.
* It will then wait for all active invocation to finish and then return.
*/
public void shutdown() {
int value;
int oldValue;
//set the shutdown bit
do {
oldValue = invocationCount;
value = SHUTDOWN_FLAG | oldValue;
//the component has already been shutdown
if (oldValue == value) {
return;
}
} while (!updater.compareAndSet(this, oldValue, value));
synchronized (lock) {
value = invocationCount;
while (value != SHUTDOWN_FLAG) {
try {
lock.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
value = invocationCount;
if((value & SHUTDOWN_FLAG) == 0) {
return; //component has been restarted
}
}
}
}
public void start() {
int value;
int oldValue;
//set the shutdown bit
do {
oldValue = invocationCount;
value = INVERSE_SHUTDOWN_FLAG & oldValue;
//the component has already been started
if (oldValue == value) {
return;
}
} while (!updater.compareAndSet(this, oldValue, value));
synchronized (lock) {
lock.notifyAll();
}
}
}
| 5,093 | 35.385714 | 179 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/interceptors/EjbExceptionTransformingInterceptorFactories.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.interceptors;
import java.rmi.NoSuchObjectException;
import java.rmi.RemoteException;
import jakarta.ejb.CreateException;
import jakarta.ejb.EJBException;
import jakarta.ejb.EJBTransactionRequiredException;
import jakarta.ejb.EJBTransactionRolledbackException;
import jakarta.ejb.NoSuchEJBException;
import jakarta.ejb.NoSuchEntityException;
import jakarta.ejb.NoSuchObjectLocalException;
import jakarta.ejb.TransactionRequiredLocalException;
import jakarta.ejb.TransactionRolledbackLocalException;
import jakarta.transaction.TransactionRequiredException;
import jakarta.transaction.TransactionRolledbackException;
import org.jboss.as.ejb3.component.EJBComponentUnavailableException;
import org.jboss.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
/**
* An interceptor that transforms Enterprise Beans 3.0 business interface exceptions to Enterprise Beans 2.x exceptions when required.
* <p/>
* This allows us to keep the actual
*
* @author Stuart Douglas
*/
public class EjbExceptionTransformingInterceptorFactories {
/**
* We need to return a CreateException to the client.
* <p/>
* Rather than forcing all create exceptions everywhere to propagate, and generally making a mess, we stash
* the exception here, and then re-throw it from the exception transforming interceptor.
*/
private static final ThreadLocal<CreateException> CREATE_EXCEPTION = new ThreadLocal<CreateException>();
private static <T extends Throwable> T copyCause(T newThrowable, Throwable originalThrowable) {
Throwable cause = originalThrowable.getCause();
if (cause != null) try {
newThrowable.initCause(cause);
} catch (IllegalStateException ignored) {
// some exceptions rudely don't allow cause initialization
}
return newThrowable;
}
private static <T extends Throwable> T copyStackTrace(T newThrowable, Throwable originalThrowable) {
newThrowable.setStackTrace(originalThrowable.getStackTrace());
return newThrowable;
}
public static final InterceptorFactory REMOTE_INSTANCE = new ImmediateInterceptorFactory(new Interceptor() {
@Override
public Object processInvocation(final InterceptorContext context) throws Exception {
try {
return context.proceed();
} catch (EJBTransactionRequiredException e) {
// this exception explicitly forbids initializing a cause
throw copyStackTrace(new TransactionRequiredException(e.getMessage()), e);
} catch (EJBTransactionRolledbackException e) {
// this exception explicitly forbids initializing a cause
throw copyStackTrace(new TransactionRolledbackException(e.getMessage()), e);
} catch (NoSuchEJBException e) {
// this exception explicitly forbids initializing a cause
throw copyStackTrace(new NoSuchObjectException(e.getMessage()), e);
} catch (NoSuchEntityException e) {
// this exception explicitly forbids initializing a cause
throw copyStackTrace(new NoSuchObjectException(e.getMessage()), e);
} catch(EJBComponentUnavailableException e) {
// do not wrap this exception in RemoteException as it is not destined for the client (WFLY-13871)
throw e;
} catch (EJBException e) {
//as the create exception is not propagated the init method interceptor just stashes it in a ThreadLocal
CreateException createException = popCreateException();
if (createException != null) {
throw createException;
}
throw new RemoteException("Invocation failed", e);
}
}
});
public static final InterceptorFactory LOCAL_INSTANCE = new ImmediateInterceptorFactory(new Interceptor() {
@Override
public Object processInvocation(final InterceptorContext context) throws Exception {
try {
return context.proceed();
} catch (EJBTransactionRequiredException e) {
throw copyStackTrace(copyCause(new TransactionRequiredLocalException(e.getMessage()), e), e);
} catch (EJBTransactionRolledbackException e) {
throw copyStackTrace(new TransactionRolledbackLocalException(e.getMessage(), e), e);
} catch (NoSuchEJBException e) {
throw copyStackTrace(new NoSuchObjectLocalException(e.getMessage(), e), e);
} catch (NoSuchEntityException e) {
throw copyStackTrace(new NoSuchObjectLocalException(e.getMessage(), e), e);
} catch (EJBException e) {
CreateException createException = popCreateException();
if (createException != null) {
throw createException;
}
throw e;
}
}
});
public static void setCreateException(CreateException exception) {
CREATE_EXCEPTION.set(exception);
}
public static CreateException popCreateException() {
try {
return CREATE_EXCEPTION.get();
} finally {
CREATE_EXCEPTION.remove();
}
}
}
| 6,482 | 44.020833 | 134 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/interceptors/LogDiagnosticContextRecoveryInterceptor.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.interceptors;
import static org.jboss.as.ejb3.component.interceptors.StoredLogDiagnosticContext.KEY;
import java.util.Map;
import org.jboss.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.logging.MDC;
import org.jboss.logging.NDC;
/**
* An interceptor which restores the saved logging NDC and MDC for asynchronous invocations.
*
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
*/
public final class LogDiagnosticContextRecoveryInterceptor implements Interceptor {
private static final LogDiagnosticContextRecoveryInterceptor INSTANCE = new LogDiagnosticContextRecoveryInterceptor();
private static final ImmediateInterceptorFactory FACTORY = new ImmediateInterceptorFactory(INSTANCE);
private LogDiagnosticContextRecoveryInterceptor() {
}
/**
* Get the interceptor factory.
*
* @return the interceptor factory
*/
public static ImmediateInterceptorFactory getFactory() {
return FACTORY;
}
/**
* Get the interceptor instance.
*
* @return the interceptor instance
*/
public static LogDiagnosticContextRecoveryInterceptor getInstance() {
return INSTANCE;
}
public Object processInvocation(final InterceptorContext context) throws Exception {
final Map<String, Object> mdc = MDC.getMap();
if (mdc != null) {
for (String str : mdc.keySet()) {
MDC.remove(str);
}
}
final StoredLogDiagnosticContext data = (StoredLogDiagnosticContext) context.getPrivateData(KEY);
context.putPrivateData(KEY, null);
if (data != null && data.getMdc() != null) {
for (Map.Entry<String, Object> entry : data.getMdc().entrySet()) {
MDC.put(entry.getKey(), entry.getValue());
}
final int depth = NDC.getDepth();
NDC.push(data.getNdc());
try {
return context.proceed();
} finally {
NDC.setMaxDepth(depth);
for (String str : MDC.getMap().keySet()) {
MDC.remove(str);
}
}
}
return context.proceed();
}
}
| 3,355 | 35.086022 | 122 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/interceptors/LoggingInterceptor.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.interceptors;
import java.lang.reflect.Method;
import org.jboss.as.ee.component.Component;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.ejb3.component.EJBComponentUnavailableException;
import org.jboss.as.ejb3.component.EJBComponent;
import org.jboss.as.ejb3.tx.ApplicationExceptionDetails;
import org.jboss.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
import org.jboss.msc.service.ServiceName;
/**
* Logs any exceptions/errors that happen during invocation of Jakarta Enterprise Beans methods, as specified by the
* Enterprise Beans 3 spec, section 14.3
* <p/>
* Note: This should be the near the start of interceptor in the chain of interceptors, for this to be able to
* catch all kinds of errors/exceptions.
*
* It should also be run inside the exception transforming interceptor, to make sure that the original exception is logged
*
* @author Jaikiran Pai
*/
public class LoggingInterceptor implements Interceptor {
public static final ServiceName LOGGING_ENABLED_SERVICE_NAME = ServiceName.JBOSS.append("ejb3", "logging", "enabled");
public static final InterceptorFactory FACTORY = new ImmediateInterceptorFactory(new LoggingInterceptor());
private LoggingInterceptor() {
}
@Override
public Object processInvocation(InterceptorContext interceptorContext) throws Exception {
final EJBComponent component = (EJBComponent) interceptorContext.getPrivateData(Component.class);
if(!component.isExceptionLoggingEnabled()) {
return interceptorContext.proceed();
}
try {
// we just pass on the control and do our work only when an exception occurs
return interceptorContext.proceed();
} catch ( EJBComponentUnavailableException ex) {
if ( EjbLogger.EJB3_INVOCATION_LOGGER.isTraceEnabled() )
EjbLogger.EJB3_INVOCATION_LOGGER.trace(ex.getMessage());
throw ex;
} catch (Throwable t) {
final Method invokedMethod = interceptorContext.getMethod();
// check if it's an application exception. If yes, then *don't* log
final ApplicationExceptionDetails appException = component.getApplicationException(t.getClass(), invokedMethod);
if (appException == null) {
EjbLogger.EJB3_INVOCATION_LOGGER.invocationFailed(component.getComponentName(), invokedMethod, t);
}
if (t instanceof Exception) {
throw (Exception) t;
}
// Typically, this interceptor (which would be the first one in the chain) would catch Exception and not Throwable since the other Jakarta Enterprise Beans interceptors
// down the chain would have already wrapped the Throwable accordingly. However, if for some reason,
// the failure happened even before those interceptors could come into play, then we just wrap the throwable
// here and return it as an exception
throw new Exception(t);
}
}
}
| 4,216 | 45.855556 | 180 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/interceptors/LogDiagnosticContextStorageInterceptor.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.interceptors;
import static org.jboss.as.ejb3.component.interceptors.StoredLogDiagnosticContext.KEY;
import java.util.Map;
import org.jboss.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.logging.MDC;
import org.jboss.logging.NDC;
/**
* An interceptor which saves the logging NDC and MDC for asynchronous invocations.
*
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
*/
public final class LogDiagnosticContextStorageInterceptor implements Interceptor {
private static final LogDiagnosticContextStorageInterceptor INSTANCE = new LogDiagnosticContextStorageInterceptor();
private static final ImmediateInterceptorFactory FACTORY = new ImmediateInterceptorFactory(INSTANCE);
private LogDiagnosticContextStorageInterceptor() {
}
/**
* Get the interceptor factory for this interceptor.
*
* @return the interceptor factory for this interceptor
*/
public static ImmediateInterceptorFactory getFactory() {
return FACTORY;
}
/**
* Get this interceptor instance.
*
* @return this interceptor instance
*/
public static LogDiagnosticContextStorageInterceptor getInstance() {
return INSTANCE;
}
public Object processInvocation(final InterceptorContext context) throws Exception {
final Map<String, Object> mdc = MDC.getMap();
if(mdc != null){
context.putPrivateData(KEY, new StoredLogDiagnosticContext(mdc, NDC.get()));
try {
return context.proceed();
} finally {
context.putPrivateData(KEY, null);
}
} else {
return context.proceed();
}
}
}
| 2,850 | 34.6375 | 120 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/interceptors/AbstractEJBInterceptor.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.interceptors;
import org.jboss.as.ee.component.Component;
import org.jboss.as.ejb3.logging.EjbLogger;
import org.jboss.as.ejb3.component.EJBComponent;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
/**
* @author <a href="mailto:[email protected]">Carlo de Wolf</a>
*/
public abstract class AbstractEJBInterceptor implements Interceptor {
protected static <C extends EJBComponent> C getComponent(InterceptorContext context, Class<C> componentType) {
Component component = context.getPrivateData(Component.class);
if (component == null) {
throw EjbLogger.ROOT_LOGGER.componentNotSetInInterceptor(context);
}
return componentType.cast(component);
}
}
| 1,810 | 41.116279 | 114 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/interceptors/ComponentTypeIdentityInterceptorFactory.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.interceptors;
import org.jboss.as.ee.component.ComponentView;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
import org.jboss.invocation.InterceptorFactoryContext;
/**
* Interceptor for equals / hashCode for SLSB's and Singleton beans
*
* @author Stuart Douglas
*/
public class ComponentTypeIdentityInterceptorFactory implements InterceptorFactory {
public static final ComponentTypeIdentityInterceptorFactory INSTANCE = new ComponentTypeIdentityInterceptorFactory();
private ComponentTypeIdentityInterceptorFactory() {
}
@Override
public Interceptor create(final InterceptorFactoryContext context) {
final ComponentView componentView = (ComponentView) context.getContextData().get(ComponentView.class);
return new ProxyTypeEqualsInterceptor(componentView);
}
private static class ProxyTypeEqualsInterceptor implements Interceptor {
private final ComponentView componentView;
public ProxyTypeEqualsInterceptor(final ComponentView componentView) {
this.componentView = componentView;
}
@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];
if (other == null) {
return false;
}
final Class<?> proxyType = componentView.getProxyClass();
return proxyType.isAssignableFrom(other.getClass());
} else if (context.getMethod().getName().equals("hashCode")) {
//use the identity of the component view as a hash code
return componentView.hashCode();
} else {
return context.proceed();
}
}
}
}
| 3,065 | 38.307692 | 121 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/interceptors/StoredLogDiagnosticContext.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.interceptors;
import java.util.Map;
/**
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
*/
final class StoredLogDiagnosticContext {
static final Object KEY = new Object();
final Map<String, Object> mdc;
final String ndc;
StoredLogDiagnosticContext(final Map<String, Object> mdc, final String ndc) {
this.mdc = mdc;
this.ndc = ndc;
}
Map<String, Object> getMdc() {
return mdc;
}
String getNdc() {
return ndc;
}
}
| 1,569 | 31.040816 | 81 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/interceptors/CancellationFlag.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.interceptors;
import java.util.concurrent.atomic.AtomicInteger;
import org.wildfly.common.Assert;
/**
* An invocation cancellation flag.
*
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
*/
public final class CancellationFlag {
private final AtomicInteger stateRef = new AtomicInteger(0);
private static final int ST_WAITING = 0;
private static final int ST_STARTED = 1;
private static final int ST_STARTED_FLAG_SET = 2;
private static final int ST_CANCELLED = 3;
private static final int ST_CANCELLED_FLAG_SET = 4;
/**
* Construct a new instance.
*/
public CancellationFlag() {
}
/**
* Attempt to cancel the corresponding invocation.
*
* @param setFlag {@code true} to set the Jakarta Enterprise Beans context cancellation flag (or equivalent), {@code false} otherwise
* @return {@code true} if the invocation was definitely cancelled, or {@code false} if it was not cancelled or it could not be determined if it was cancelled
*/
public boolean cancel(boolean setFlag) {
final AtomicInteger stateRef = this.stateRef;
int oldVal, newVal;
do {
oldVal = stateRef.get();
if (oldVal == ST_WAITING) {
newVal = ST_CANCELLED;
} else if (oldVal == ST_CANCELLED) {
if (! setFlag) {
return true;
}
newVal = ST_CANCELLED_FLAG_SET;
} else if (oldVal == ST_CANCELLED_FLAG_SET) {
// do nothing
return true;
} else if (oldVal == ST_STARTED) {
if (! setFlag) {
return false;
}
newVal = ST_STARTED_FLAG_SET;
} else {
assert oldVal == ST_STARTED_FLAG_SET;
return false;
}
} while (! stateRef.compareAndSet(oldVal, newVal));
return newVal == ST_CANCELLED || newVal == ST_CANCELLED_FLAG_SET;
}
/**
* Attempt to determine whether the invocation should proceed or whether it should be cancelled. This method should only
* be called once per flag instance.
*
* @return {@code true} if the invocation should proceed, or {@code false} if it was cancelled
*/
public boolean runIfNotCancelled() {
final AtomicInteger stateRef = this.stateRef;
int oldVal;
do {
oldVal = stateRef.get();
if (oldVal == ST_CANCELLED || oldVal == ST_CANCELLED_FLAG_SET) {
return false;
} else if (oldVal != ST_WAITING) {
throw Assert.unreachableCode();
}
} while (! stateRef.compareAndSet(oldVal, ST_STARTED));
return true;
}
/**
* Determine if the cancel flag was set.
*
* @return {@code true} if the flag was set, {@code false} otherwise
*/
public boolean isCancelFlagSet() {
final int state = stateRef.get();
return state == ST_STARTED_FLAG_SET || state == ST_CANCELLED_FLAG_SET;
}
/**
* Determine if the request was cancelled before it could complete.
*
* @return {@code true} if the request was cancelled, {@code false} otherwise
*/
public boolean isCancelled() {
final int state = stateRef.get();
return state == ST_CANCELLED || state == ST_CANCELLED_FLAG_SET;
}
}
| 4,532 | 35.556452 | 162 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/interceptors/AdditionalSetupInterceptor.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.interceptors;
import java.util.Collections;
import java.util.List;
import org.jboss.as.server.deployment.SetupAction;
import org.jboss.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
/**
* Interceptor that performs additional setup for remote and timer invocations (i.e invocations that are performed
* from outside an existing EE context).
*
* @author Stuart Douglas
*/
public class AdditionalSetupInterceptor implements Interceptor {
private final SetupAction[] actions;
public AdditionalSetupInterceptor(final List<SetupAction> actions) {
this.actions = actions.toArray(new SetupAction[actions.size()]);
}
@Override
public Object processInvocation(final InterceptorContext context) throws Exception {
Throwable originalException = null;
Object retValue = null;
try {
for (int i = 0; i < actions.length; ++i) {
actions[i].setup(Collections.<String, Object>emptyMap());
}
retValue = context.proceed();
} catch(Throwable ex) {
if (ex instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
originalException = ex;
} finally {
Throwable suppressed = originalException;
for (int i = actions.length - 1; i >=0; --i) {
SetupAction action = actions[i];
try {
action.teardown(Collections.<String, Object>emptyMap());
} catch (Throwable t) {
if (suppressed != null) {
suppressed.addSuppressed(t);
} else {
suppressed = t instanceof RuntimeException ? t : new RuntimeException(t);
}
}
}
if (suppressed != null) {
if (suppressed instanceof RuntimeException) {
throw (RuntimeException) suppressed;
}
if (suppressed instanceof Exception) {
throw (Exception) suppressed;
}
if (suppressed instanceof Error) {
throw (Error) suppressed;
}
}
}
return retValue;
}
public static InterceptorFactory factory(final List<SetupAction> actions) {
final AdditionalSetupInterceptor interceptor = new AdditionalSetupInterceptor(actions);
return new ImmediateInterceptorFactory(interceptor);
}
}
| 3,710 | 37.65625 | 114 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/interceptors/HomeRemoveInterceptor.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.interceptors;
import jakarta.ejb.Handle;
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 HomeRemoveInterceptor implements Interceptor {
public static final InterceptorFactory FACTORY = new ImmediateInterceptorFactory(new HomeRemoveInterceptor());
private HomeRemoveInterceptor() {
}
@Override
public Object processInvocation(final InterceptorContext context) throws Exception {
final Handle handle = (Handle) context.getParameters()[0];
handle.getEJBObject().remove();
return null;
}
}
| 1,799 | 34.294118 | 114 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/interceptors/CurrentInvocationContextInterceptor.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.interceptors;
import org.jboss.as.ejb3.context.CurrentInvocationContext;
import org.jboss.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.Interceptor;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
/**
* @author <a href="mailto:[email protected]">Carlo de Wolf</a>
*/
public class CurrentInvocationContextInterceptor implements Interceptor {
public static final InterceptorFactory FACTORY = new ImmediateInterceptorFactory(new CurrentInvocationContextInterceptor());
@Override
public Object processInvocation(InterceptorContext context) throws Exception {
CurrentInvocationContext.push(context);
try {
return context.proceed();
} finally {
CurrentInvocationContext.pop();
}
}
}
| 1,890 | 38.395833 | 128 | java |
null | wildfly-main/ejb3/src/main/java/org/jboss/as/ejb3/component/interceptors/SessionBeanHomeInterceptorFactory.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.interceptors;
import java.lang.reflect.Method;
import org.jboss.as.ee.component.ComponentView;
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.msc.value.InjectedValue;
/**
* Interceptor that handles home views for session beans
*
* @author Stuart Douglas
*/
public class SessionBeanHomeInterceptorFactory implements InterceptorFactory {
private final InjectedValue<ComponentView> viewToCreate = new InjectedValue<ComponentView>();
//TODO: there has to be a better way to pass this into the create interceptor chain
public static final ThreadLocal<Method> INIT_METHOD = new ThreadLocal<Method>();
public static final ThreadLocal<Object[]> INIT_PARAMETERS = new ThreadLocal<Object[]>();
/**
* The init method to invoke on the SFSB
*/
private final Method method;
public SessionBeanHomeInterceptorFactory(final Method method) {
this.method = method;
}
@Override
public Interceptor create(final InterceptorFactoryContext context) {
return new Interceptor() {
@Override
public Object processInvocation(final InterceptorContext context) throws Exception {
final ComponentView view = viewToCreate.getValue();
try {
INIT_METHOD.set(method);
INIT_PARAMETERS.set(context.getParameters());
final ManagedReference instance = view.createInstance();
return instance.getInstance();
} finally {
INIT_METHOD.remove();
INIT_PARAMETERS.remove();
}
}
};
}
public InjectedValue<ComponentView> getViewToCreate() {
return viewToCreate;
}
}
| 3,003 | 36.55 | 97 | java |
null | wildfly-main/weld/transactions/src/main/java/org/jboss/as/weld/deployment/processor/TransactionsBootstrapDependencyInstaller.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment.processor;
import org.jboss.as.controller.capability.CapabilityServiceSupport;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.weld.ServiceNames;
import org.jboss.as.weld.services.bootstrap.WeldTransactionServices;
import org.jboss.as.weld.spi.BootstrapDependencyInstaller;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import java.util.function.Consumer;
/**
* @author Martin Kouba
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public class TransactionsBootstrapDependencyInstaller implements BootstrapDependencyInstaller {
private static final String CAPABILITY_NAME = "org.wildfly.transactions.global-default-local-provider";
@Override
public ServiceName install(ServiceTarget serviceTarget, DeploymentUnit deploymentUnit, boolean jtsEnabled) {
final CapabilityServiceSupport capabilities = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT);
if (capabilities.hasCapability(CAPABILITY_NAME)) {
final ServiceName weldTransactionServiceName = deploymentUnit.getServiceName()
.append(WeldTransactionServices.SERVICE_NAME);
final ServiceBuilder<?> sb = serviceTarget.addService(weldTransactionServiceName);
final Consumer<WeldTransactionServices> weldTransactionServicesConsumer = sb.provides(weldTransactionServiceName);
// Ensure the local transaction provider is started before we start
sb.requires(ServiceNames.capabilityServiceName(deploymentUnit, CAPABILITY_NAME));
sb.setInstance(new WeldTransactionServices(jtsEnabled, weldTransactionServicesConsumer));
sb.install();
return weldTransactionServiceName;
}
return null;
}
}
| 2,957 | 46.709677 | 126 | java |
null | wildfly-main/weld/transactions/src/main/java/org/jboss/as/weld/services/bootstrap/WeldTransactionServices.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.services.bootstrap;
import java.util.function.Consumer;
import jakarta.transaction.RollbackException;
import jakarta.transaction.Status;
import jakarta.transaction.Synchronization;
import jakarta.transaction.SystemException;
import jakarta.transaction.UserTransaction;
import org.jboss.as.weld.ServiceNames;
import org.jboss.msc.Service;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StopContext;
import org.jboss.weld.transaction.spi.TransactionServices;
import org.wildfly.transaction.client.ContextTransactionManager;
import org.wildfly.transaction.client.LocalUserTransaction;
/**
* Service that implements welds {@link TransactionServices}
* <p>
* This class is thread safe, and does not require a happens-before action between construction and usage
*
* @author Stuart Douglas
* @author <a href="mailto:[email protected]">Tomasz Adamski</a>
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public class WeldTransactionServices implements TransactionServices, Service {
public static final ServiceName SERVICE_NAME = ServiceNames.WELD_TRANSACTION_SERVICES_SERVICE_NAME;
private final Consumer<WeldTransactionServices> weldTransactionServicesConsumer;
private final boolean jtsEnabled;
public WeldTransactionServices(final boolean jtsEnabled, final Consumer<WeldTransactionServices> weldTransactionServicesConsumer) {
this.jtsEnabled = jtsEnabled;
this.weldTransactionServicesConsumer = weldTransactionServicesConsumer;
}
@Override
public UserTransaction getUserTransaction() {
return LocalUserTransaction.getInstance();
}
@Override
public boolean isTransactionActive() {
try {
final int status = ContextTransactionManager.getInstance().getStatus();
return status == Status.STATUS_ACTIVE ||
status == Status.STATUS_COMMITTING ||
status == Status.STATUS_MARKED_ROLLBACK ||
status == Status.STATUS_PREPARED ||
status == Status.STATUS_PREPARING ||
status == Status.STATUS_ROLLING_BACK;
} catch (SystemException e) {
throw new RuntimeException(e);
}
}
@Override
public void cleanup() {
}
@Override
public void registerSynchronization(Synchronization synchronizedObserver) {
try {
final Synchronization synchronization;
if (!jtsEnabled) {
synchronization = synchronizedObserver;
} else {
synchronization = new JTSSynchronizationWrapper(synchronizedObserver);
}
ContextTransactionManager.getInstance().getTransaction().registerSynchronization(synchronization);
} catch (IllegalStateException e) {
throw new RuntimeException(e);
} catch (RollbackException e) {
throw new RuntimeException(e);
} catch (SystemException e) {
throw new RuntimeException(e);
}
}
@Override
public void start(final StartContext context) {
weldTransactionServicesConsumer.accept(this);
}
@Override
public void stop(final StopContext context) {
weldTransactionServicesConsumer.accept(null);
}
}
| 4,379 | 36.758621 | 135 | java |
null | wildfly-main/weld/transactions/src/main/java/org/jboss/as/weld/services/bootstrap/JTSSynchronizationWrapper.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2014, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.services.bootstrap;
import jakarta.transaction.Synchronization;
/**
*
* Stores NamespaceContextSelector during synchronization, and pushes it on top of the selector stack each time synchronization
* callback method is executed. This enables synchronization callbacks served by corba threads to work correctly.
*
* @author <a href="mailto:[email protected]">Tomasz Adamski</a>
*/
import org.jboss.as.naming.context.NamespaceContextSelector;
public class JTSSynchronizationWrapper implements Synchronization {
private final Synchronization synchronization;
private final NamespaceContextSelector selector;
public JTSSynchronizationWrapper(final Synchronization synchronization) {
this.synchronization = synchronization;
selector = NamespaceContextSelector.getCurrentSelector();
}
@Override
public void beforeCompletion() {
try {
NamespaceContextSelector.pushCurrentSelector(selector);
synchronization.beforeCompletion();
} finally {
NamespaceContextSelector.popCurrentSelector();
}
}
@Override
public void afterCompletion(final int status) {
try {
NamespaceContextSelector.pushCurrentSelector(selector);
synchronization.afterCompletion(status);
} finally {
NamespaceContextSelector.popCurrentSelector();
}
}
}
| 2,448 | 34.492754 | 128 | java |
null | wildfly-main/weld/spi/src/main/java/org/jboss/as/weld/spi/DeploymentUnitProcessorProvider.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.spi;
import org.jboss.as.server.DeploymentProcessorTarget;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.Phase;
/**
* Allows to add additional deployment unit processors to a {@link DeploymentProcessorTarget}.
*
* @author Martin Kouba
* @see DeploymentUnitProcessor
*/
public interface DeploymentUnitProcessorProvider {
/**
*
* @return the processor
*/
DeploymentUnitProcessor getProcessor();
/**
*
* @return the phase
*/
Phase getPhase();
/**
*
* @return the priority
*/
int getPriority();
}
| 1,671 | 29.4 | 94 | java |
null | wildfly-main/weld/spi/src/main/java/org/jboss/as/weld/spi/ResourceInjectionResolver.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.spi;
/**
*
* @author Martin Kouba
*/
public interface ResourceInjectionResolver {
/**
*
* @param resourceName
* @return the resolved object or <code>null</code> if not able to resolve the given name
*/
Object resolve(String resourceName);
}
| 1,317 | 33.684211 | 93 | java |
null | wildfly-main/weld/spi/src/main/java/org/jboss/as/weld/spi/BeanDeploymentArchiveServicesProvider.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.spi;
import java.util.Collection;
import org.jboss.weld.bootstrap.api.Service;
import org.jboss.weld.bootstrap.spi.BeanDeploymentArchive;
/**
* Provides services which should be added to a bean deployment archve.
*
* @author Martin Kouba
* @see Service
* @see BeanDeploymentArchive
* @see ModuleServicesProvider
*/
public interface BeanDeploymentArchiveServicesProvider {
/**
*
* @param archive
* @return the services for the given bean deployment archive
*/
Collection<Service> getServices(BeanDeploymentArchive archive);
}
| 1,607 | 33.212766 | 73 | java |
null | wildfly-main/weld/spi/src/main/java/org/jboss/as/weld/spi/WildFlyBeanDeploymentArchive.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.spi;
import org.jboss.weld.bootstrap.spi.BeanDeploymentArchive;
import org.jboss.weld.ejb.spi.EjbDescriptor;
/**
* WildFly bean deployment archive contract.
*
* @author Martin Kouba
*/
public interface WildFlyBeanDeploymentArchive extends BeanDeploymentArchive {
/**
*
* @param clazz
*/
void addBeanClass(String clazz);
/**
*
* @param clazz
*/
void addBeanClass(Class<?> clazz);
/**
*
* @param descriptor
*/
void addEjbDescriptor(EjbDescriptor<?> descriptor);
}
| 1,583 | 28.886792 | 77 | java |
null | wildfly-main/weld/spi/src/main/java/org/jboss/as/weld/spi/InterceptorInstances.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.spi;
import java.util.Map;
import jakarta.enterprise.context.spi.CreationalContext;
import jakarta.enterprise.inject.spi.Interceptor;
import org.jboss.weld.serialization.spi.helpers.SerializableContextualInstance;
/**
* Holds interceptor instances of a Jakarta EE component.
*
* @author Martin Kouba
*/
public interface InterceptorInstances {
Map<String, SerializableContextualInstance<Interceptor<Object>, Object>> getInstances();
CreationalContext<?> getCreationalContext();
}
| 1,540 | 34.837209 | 92 | java |
null | wildfly-main/weld/spi/src/main/java/org/jboss/as/weld/spi/ComponentSupport.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.spi;
import jakarta.enterprise.inject.spi.InjectionTarget;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.weld.manager.api.WeldInjectionTarget;
import org.jboss.weld.manager.api.WeldManager;
/**
* Jakarta EE component support tools.
*
* @author Martin Kouba
*/
public interface ComponentSupport {
/**
* See also <a href="https://issues.jboss.org/browse/WFLY-4185">WFLY-4185</a>
*
* @param componentDescription
* @return <code>false</code> if the specified component type should be discovered, <code>false</code> otherwise
*/
default boolean isDiscoveredExternalType(ComponentDescription componentDescription) {
return true;
}
/**
* The first component suppor processing the given description is later allowed to {@link #processInjectionTarget(WeldInjectionTarget, ComponentDescription, WeldManager)}.
*
* @param componentDescription
* @return
*/
boolean isProcessing(ComponentDescription componentDescription);
/**
*
* @param injectionTarget
* @param componentDescription
* @param beanManager
* @return the processed injection target
* @see #isProcessing(ComponentDescription)
*/
default <T> InjectionTarget<T> processInjectionTarget(WeldInjectionTarget<T> injectionTarget, ComponentDescription componentDescription, WeldManager beanManager) {
return beanManager.fireProcessInjectionTarget(injectionTarget.getAnnotatedType(), injectionTarget);
}
}
| 2,559 | 36.647059 | 175 | java |
null | wildfly-main/weld/spi/src/main/java/org/jboss/as/weld/spi/ComponentInterceptorSupport.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.spi;
import java.util.List;
import jakarta.enterprise.inject.spi.InterceptionType;
import jakarta.enterprise.inject.spi.Interceptor;
import jakarta.interceptor.InvocationContext;
import org.jboss.as.ee.component.ComponentInstance;
import org.jboss.as.weld.spi.ComponentIntegrator.DefaultInterceptorIntegrationAction;
import org.jboss.weld.ejb.spi.InterceptorBindings;
import org.jboss.weld.manager.api.WeldManager;
/**
* NOTE: There must be exactly one implementation available if {@link DefaultInterceptorIntegrationAction} is performed during component integration.
* <p>
* This implementation must be able to handle all integrated component types.
*
* @author Martin Kouba
*/
public interface ComponentInterceptorSupport {
/**
*
* @param componentInstance
* @return the interceptor instance for the given component
*/
InterceptorInstances getInterceptorInstances(ComponentInstance componentInstance);
/**
* Set the interceptor instances to the given component.
*
* @param componentInstance
* @param interceptorInstances
*/
void setInterceptorInstances(ComponentInstance componentInstance, InterceptorInstances interceptorInstances);
/**
* Delegate the invocation processing.
*
* @return the result of subsequent interceptor method processing
*/
Object delegateInterception(InvocationContext invocationContext, InterceptionType interceptionType, List<Interceptor<?>> currentInterceptors,
List<Object> currentInterceptorInstances) throws Exception;
/**
*
* @param componentName
* @return the interceptor bindings
*/
InterceptorBindings getInterceptorBindings(String componentName, WeldManager manager);
}
| 2,792 | 36.24 | 149 | java |
null | wildfly-main/weld/spi/src/main/java/org/jboss/as/weld/spi/BootstrapDependencyInstaller.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.spi;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.weld.bootstrap.api.Service;
/**
* Allows to install a Weld {@link Service} as a MSC {@link org.jboss.msc.service.Service}.
* <p>
* The service installed is later added as a dependency of the Weld bootstrap service.
*
* @author Martin Kouba
*/
public interface BootstrapDependencyInstaller {
/**
*
* @param serviceTarget
* @param deploymentUnit
* @param jtsEnabled
* @return the service name
*/
ServiceName install(ServiceTarget serviceTarget, DeploymentUnit deploymentUnit, boolean jtsEnabled);
}
| 1,749 | 35.458333 | 104 | java |
null | wildfly-main/weld/spi/src/main/java/org/jboss/as/weld/spi/ComponentDescriptionProcessor.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.spi;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.server.deployment.module.ResourceRoot;
import org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex;
/**
* Jakarta EE component description processor.
* <p>
* Processors may be stateful and are not suitable for sharing between threads.
*
* @author Martin Kouba
*/
public interface ComponentDescriptionProcessor {
/**
*
* @param description
*/
void processComponentDescription(ResourceRoot resourceRoot, ComponentDescription component);
/**
*
* @param resourceRoot
* @return <code>true</code> if any components were previously processed by this handler, <code>false</code> otherwise
* @see ComponentDescriptionProcessor#processComponentDescription(ResourceRoot, ComponentDescription)
*/
boolean hasBeanComponents(ResourceRoot resourceRoot);
/**
*
* @param beanDeploymentArchive
*/
void registerComponents(ResourceRoot resourceRoot, WildFlyBeanDeploymentArchive beanDeploymentArchive, DeploymentReflectionIndex reflectionIndex);
}
| 2,153 | 36.137931 | 150 | java |
null | wildfly-main/weld/spi/src/main/java/org/jboss/as/weld/spi/ModuleServicesProvider.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.spi;
import java.util.Collection;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.module.ResourceRoot;
import org.jboss.modules.Module;
import org.jboss.weld.bootstrap.api.Service;
/**
* Provides services which should be added to all bean deployment archves of a specific EE module.
*
* @author Martin Kouba
* @see Service
* @see BeanDeploymentArchiveServicesProvider
*/
public interface ModuleServicesProvider {
/**
*
* @param deploymentUnit
* @return the services for the given deployment unit
*/
Collection<Service> getServices(DeploymentUnit rootDeploymentUnit, DeploymentUnit deploymentUnit, Module module, ResourceRoot resourceRoot);
}
| 1,767 | 35.833333 | 144 | java |
null | wildfly-main/weld/spi/src/main/java/org/jboss/as/weld/spi/DeploymentUnitDependenciesProvider.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.spi;
import java.util.Set;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.msc.service.ServiceName;
/**
* Allows to add service dependencies for a deployment unit.
*
* @author Martin Kouba
*/
public interface DeploymentUnitDependenciesProvider {
/**
*
* @param deploymentUnit
* @return the set of dependencies for the given deployment unit
*/
Set<ServiceName> getDependencies(DeploymentUnit deploymentUnit);
}
| 1,512 | 33.386364 | 73 | java |
null | wildfly-main/weld/spi/src/main/java/org/jboss/as/weld/spi/ImplicitBeanArchiveDetector.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.spi;
import org.jboss.as.ee.component.ComponentDescription;
/**
* Certain Jakarta EE components imply an existence of an implicit bean archive.
*
* @author Martin Kouba
*/
public interface ImplicitBeanArchiveDetector {
/**
*
* @param description
* @return <code>true</code> if the specified component implies an implicit bean archive, <code>false</code> otherwise
*/
boolean isImplicitBeanArchiveRequired(ComponentDescription description);
}
| 1,520 | 36.097561 | 122 | java |
null | wildfly-main/weld/spi/src/main/java/org/jboss/as/weld/spi/ComponentIntegrator.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.spi;
import java.util.function.Supplier;
import org.jboss.as.ee.component.ComponentConfiguration;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
/**
* Jakarta EE component integrator.
*
* @author Martin Kouba
*/
public interface ComponentIntegrator {
/**
* Probably just for Jakarta Enterprise Beans.
*
* @return <code>true</code> if the given description requires a bean name, <code>false</code> otherwise
*/
boolean isBeanNameRequired(ComponentDescription description);
/**
*
* @return <code>true</code> if the description represents a component with view, <code>false</code> otherwise
*/
boolean isComponentWithView(ComponentDescription description);
/**
*
* @param beanManagerServiceName
* @param configuration
* @param description
* @param weldComponentServiceBuilder
* @param bindingServiceName
* @param integrationAction
* @param interceptorSupport
* @return <code>true</code> if an integration was performed, <code>false</code> otherwise
*/
boolean integrate(ServiceName beanManagerServiceName, ComponentConfiguration configuration, ComponentDescription description,
ServiceBuilder<?> weldComponentServiceBuilder, Supplier<ServiceName> bindingServiceNameSupplier,
DefaultInterceptorIntegrationAction integrationAction, ComponentInterceptorSupport interceptorSupport);
/**
* NOTE: If performed, exactly one implementation of {@link ComponentInterceptorSupport} must be available.
*/
@FunctionalInterface
interface DefaultInterceptorIntegrationAction {
void perform(ServiceName bindingServiceName);
}
}
| 2,827 | 35.727273 | 129 | java |
null | wildfly-main/weld/common/src/main/java/org/jboss/as/weld/WeldCapability.java | /*
* JBoss, Home of Professional Open Source
*
* Copyright 2018 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.weld;
import java.util.function.Supplier;
import jakarta.enterprise.inject.spi.BeanManager;
import jakarta.enterprise.inject.spi.Extension;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
/**
* API exposed by the Weld capability.
*
* @author Yeray Borges
*/
public interface WeldCapability {
/**
* Registers a CDI Portable Extension for the {@link DeploymentUnit} passed as argument to
* this method.
* <p>
* The extension is registered if only if the DeploymentUnit is part of a Weld Deployment. Specifically,
* if a call to {@link #isPartOfWeldDeployment(DeploymentUnit)} using the DeploymentUnit argument
* returns {@code true}. Otherwise this method will return immediately.
*
* @param extension An instance of the CDI portable extension to add.
* @param unit The deployment unit where the extension will be registered.
*/
void registerExtensionInstance(final Extension extension, final DeploymentUnit unit);
/**
* Adds the Bean Manager service associated to the {@link DeploymentUnit} to ServiceBuilder passed as argument.
* <p>
* The Bean Manager service is added if only if the DeploymentUnit is part of a Weld Deployment. Specifically,
* if a call to {@link #isPartOfWeldDeployment(DeploymentUnit)} using the DeploymentUnit argument
* returns {@code true}. Otherwise this method will return {@code null}.
*
* @param unit DeploymentUnit used to get the Bean Manager service name. Cannot be null.
* @param serviceBuilder The service builder used to add the dependency. Cannot be null.
* @return A supplier that contains the BeanManager instance if the DeploymentUnit is part of a Weld Deployment, otherwise
* returns {@code null}.
* @throws IllegalStateException if this method
* have been called after {@link ServiceBuilder#setInstance(org.jboss.msc.Service)} method.
* @throws UnsupportedOperationException if this service builder
* wasn't created via {@link ServiceTarget#addService(ServiceName)} method.
*/
Supplier<BeanManager> addBeanManagerService(final DeploymentUnit unit, final ServiceBuilder<?> serviceBuilder);
/**
* Adds the Bean Manager service associated to the {@link DeploymentUnit} to ServiceBuilder passed as argument.
* Use this method to add the service dependency for legacy msc services.
* <p>
* The Bean Manager service is added if only if the DeploymentUnit is part of a Weld Deployment. Specifically,
* if a call to {@link #isPartOfWeldDeployment(DeploymentUnit)} using the DeploymentUnit argument
* returns {@code true}. Otherwise this method will return immediately without applying any modification to the serviceBuilder.
*
* @param unit {@link DeploymentUnit} used to get the Bean Manager service name. Cannot be null.
* @param serviceBuilder The service builder used to add the dependency. Cannot be null.
* @param targetInjector the injector into which the dependency should be stored. Cannot be null.
* @return the ServiceBuilder with the Bean Manager service added.
* @throws UnsupportedOperationException if the service builder was created via
* {@link ServiceTarget#addService(ServiceName)} method.
*/
ServiceBuilder<?> addBeanManagerService(final DeploymentUnit unit, final ServiceBuilder<?> serviceBuilder, final Injector<BeanManager> targetInjector);
/**
* Returns true if the {@link DeploymentUnit} is part of a weld deployment.
*
* @param unit {@link DeploymentUnit} to check.
* @return true if the {@link DeploymentUnit} is part of a weld deployment.
*/
boolean isPartOfWeldDeployment(DeploymentUnit unit);
/**
* Returns true if the {@link DeploymentUnit} has a beans.xml in any of it's resource roots,
* or is a top level deployment that contains sub-deployments that are weld deployments.
*
* @param unit {@link DeploymentUnit} to check.
* @return true if the {@link DeploymentUnit} has a beans.xml in any of it's resource roots,
* or is a top level deployment that contains sub-deployments that are weld deployments.
*/
boolean isWeldDeployment(DeploymentUnit unit);
/**
* Registers a deployment as a Weld deployment, even in the absence of spec-compliant configuration files or annotations. After
* a call to this method, calls to {@code isWeldDeployment(DeploymentUnit unit)} will return true.
*/
void markAsWeldDeployment(DeploymentUnit unit);
}
| 5,542 | 48.936937 | 155 | java |
null | wildfly-main/weld/common/src/main/java/org/jboss/as/weld/ServiceNames.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld;
import org.jboss.as.controller.capability.CapabilityServiceSupport;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.msc.service.ServiceName;
public final class ServiceNames {
public static final ServiceName WELD_START_SERVICE_NAME = ServiceName.of("WeldStartService");
public static final ServiceName BEAN_MANAGER_SERVICE_NAME = ServiceName.of("beanmanager");
public static final ServiceName WELD_SECURITY_SERVICES_SERVICE_NAME = ServiceName.of("WeldSecurityServices");
public static final ServiceName WELD_TRANSACTION_SERVICES_SERVICE_NAME = ServiceName.of("WeldTransactionServices");
public static final ServiceName WELD_START_COMPLETION_SERVICE_NAME = ServiceName.of("WeldEndInitService");
/**
* Gets the Bean Manager MSC service name relative to the Deployment Unit.
* <p>
* Modules outside of weld subsystem should use WeldCapability instead to get the name of the Bean Manager service
* associated to the deployment unit.
*
* @param deploymentUnit The deployment unit to be used.
*
* @return The Bean Manager service name.
*/
public static ServiceName beanManagerServiceName(final DeploymentUnit deploymentUnit) {
return deploymentUnit.getServiceName().append(BEAN_MANAGER_SERVICE_NAME);
}
public static ServiceName capabilityServiceName(final DeploymentUnit deploymentUnit, final String baseCapabilityName, final String... dynamicParts) {
CapabilityServiceSupport capabilityServiceSupport = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT);
if (dynamicParts == null || dynamicParts.length == 0) {
return capabilityServiceSupport.getCapabilityServiceName(baseCapabilityName);
} else {
return capabilityServiceSupport.getCapabilityServiceName(baseCapabilityName, dynamicParts);
}
}
}
| 2,985 | 44.938462 | 153 | java |
null | wildfly-main/weld/common/src/main/java/org/jboss/as/weld/Capabilities.java | /*
* JBoss, Home of Professional Open Source
*
* Copyright 2018 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.weld;
/**
* Capability names exposed by Weld subsystem.
* <p>
* This class is designed to be used outside of the weld subsystem. Other subsystems that require the name of a Weld
* capability can safely import this class without adding a jboss module dependency. To archive it, this class must
* only declare string constants, which are resolved at compile time.
*
* @author Yeray Borges
*/
public final class Capabilities {
public static final String WELD_CAPABILITY_NAME = "org.wildfly.weld";
}
| 1,196 | 36.40625 | 116 | java |
null | wildfly-main/weld/common/src/main/java/org/jboss/as/weld/logging/WeldLogger.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2021, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.logging;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.net.URL;
import java.util.Set;
import jakarta.enterprise.inject.spi.InjectionPoint;
import org.jboss.as.ee.component.ViewDescription;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.logging.BasicLogger;
import org.jboss.logging.Logger;
import org.jboss.logging.annotations.Cause;
import org.jboss.logging.annotations.LogMessage;
import org.jboss.logging.annotations.Message;
import org.jboss.logging.annotations.MessageLogger;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.weld.bootstrap.spi.BeanDeploymentArchive;
import org.jboss.weld.resources.spi.ClassFileInfoException;
/**
* Date: 05.11.2011
*
* @author <a href="mailto:[email protected]">James R. Perkins</a>
*/
@SuppressWarnings("deprecation")
@MessageLogger(projectCode = "WFLYWELD", length = 4)
public interface WeldLogger extends BasicLogger {
/**
* A logger with a category of the package name.
*/
WeldLogger ROOT_LOGGER = Logger.getMessageLogger(WeldLogger.class, "org.jboss.as.weld");
/**
* A logger with the category {@code org.jboss.weld}.
*/
WeldLogger DEPLOYMENT_LOGGER = Logger.getMessageLogger(WeldLogger.class, "org.jboss.weld.deployer");
@LogMessage(level= Logger.Level.ERROR)
@Message(id = 1, value = "Failed to setup Weld contexts")
void failedToSetupWeldContexts(@Cause Throwable throwable);
@LogMessage(level= Logger.Level.ERROR)
@Message(id = 2, value = "Failed to tear down Weld contexts")
void failedToTearDownWeldContexts(@Cause Throwable throwable);
@LogMessage(level= Logger.Level.INFO)
@Message(id = 3, value = "Processing weld deployment %s")
void processingWeldDeployment(String deployment);
// @LogMessage(level = Logger.Level.WARN)
// @Message(id = 4, value = "Found beans.xml file in non-standard location: %s, war deployments should place beans.xml files into WEB-INF/beans.xml")
// void beansXmlInNonStandardLocation(String location);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 5, value = "Could not find BeanManager for deployment %s")
void couldNotFindBeanManagerForDeployment(String beanManager);
@LogMessage(level = Logger.Level.DEBUG)
@Message(id = 6, value = "Starting Services for Jakarta Contexts and Dependency Injection deployment: %s")
void startingServicesForCDIDeployment(String deploymentName);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 7, value = "Could not load portable extension class %s")
void couldNotLoadPortableExceptionClass(String className, @Cause Throwable throwable);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 8, value = "@Resource injection of type %s is not supported for non-Jakarta Enterprise Beans components. Injection point: %s")
void injectionTypeNotValue(String type, Member injectionPoint);
@LogMessage(level = Logger.Level.DEBUG)
@Message(id = 9, value = "Starting weld service for deployment %s")
void startingWeldService(String deploymentName);
@LogMessage(level = Logger.Level.DEBUG)
@Message(id = 10, value = "Stopping weld service for deployment %s")
void stoppingWeldService(String deploymentName);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 11, value = "Warning while parsing %s:%s %s")
void beansXmlValidationWarning(URL file, int line , String message);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 12, value = "Warning while parsing %s:%s %s")
void beansXmlValidationError(URL file, int line , String message);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 13, value = "Deployment %s contains Jakarta Contexts and Dependency Injection annotations but no bean archive was found (no beans.xml or class with bean defining annotations was present).")
void cdiAnnotationsButNotBeanArchive(String deploymentUnit);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 14, value = "Exception tearing down thread state")
void exceptionClearingThreadState(@Cause Exception e);
// @LogMessage(level = Logger.Level.ERROR)
// @Message(id = 15, value = "Error loading file %s")
// void errorLoadingFile(String newPath);
@LogMessage(level = Logger.Level.ERROR)
@Message(id = 16, value = "Could not read entries")
void couldNotReadEntries(@Cause IOException ioe);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 17, value = "URL scanner does not understand the URL protocol %s, Jakarta Contexts and Dependency Injection beans will not be scanned.")
void doNotUnderstandProtocol(URL url);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 18, value = "Found both WEB-INF/beans.xml and WEB-INF/classes/META-INF/beans.xml. It is not portable to use both locations at the same time. Weld is going to use the former location for this deployment.")
void duplicateBeansXml();
@Message(id = 19, value = "Could get beans.xml file as URL when processing file: %s")
DeploymentUnitProcessingException couldNotGetBeansXmlAsURL(String beansXml, @Cause Throwable cause);
@Message(id = 20, value = "Could not load interceptor class : %s")
DeploymentUnitProcessingException couldNotLoadInterceptorClass(String interceptorClass, @Cause Throwable cause);
@Message(id = 21, value = "Service %s didn't implement the jakarta.enterprise.inject.spi.Extension interface")
DeploymentUnitProcessingException extensionDoesNotImplementExtension(Class<?> clazz);
@Message(id = 22, value = "View of type %s not found on Jakarta Enterprise Beans %s")
IllegalArgumentException viewNotFoundOnEJB(String viewType, String ejb);
// @Message(id = 23, value = "Jakarta Enterprise Beans has been removed")
// NoSuchEJBException ejbHashBeenRemoved();
// @Message(id = 24, value = "Failed to perform Jakarta Contexts and Dependency Injection injection of field: %s on %s")
// RuntimeException couldNotInjectField(Field field, Class<?> beanClass, @Cause Throwable cause);
//
// @Message(id = 25, value = "Failed to perform Jakarta Contexts and Dependency Injection injection of method: %s on %s")
// RuntimeException couldNotInjectMethod(Method method, Class<?> beanClass, @Cause Throwable cause);
//
// @Message(id = 26, value = "Class %s has more that one constructor annotated with @Inject")
// RuntimeException moreThanOneBeanConstructor(Class<?> beanClass);
//
// @Message(id = 27, value = "Component %s is attempting to inject the InjectionPoint into a field: %s")
// RuntimeException attemptingToInjectInjectionPointIntoField(Class<?> clazz, Field field);
//
// @Message(id = 28, value = "Could not resolve Jakarta Contexts and Dependency Injection bean for injection point %s with qualifiers %s")
// RuntimeException couldNotResolveInjectionPoint(String injectionPoint, Set<Annotation> qualifier);
//
// @Message(id = 29, value = "Component %s is attempting to inject the InjectionPoint into a method on a component that is not a Jakarta Contexts and Dependency Injection bean %s")
// RuntimeException attemptingToInjectInjectionPointIntoNonBean(Class<?> componentClass, Method injectionPoint);
@Message(id = 30, value = "Unknown interceptor class for Jakarta Contexts and Dependency Injection %s")
IllegalArgumentException unknownInterceptorClassForCDIInjection(Class<?> interceptorClass);
@Message(id = 31, value = "%s cannot be null")
IllegalArgumentException parameterCannotBeNull(String param);
@Message(id = 32, value = "Injection point represents a method which doesn't follow JavaBean conventions (must have exactly one parameter) %s")
IllegalArgumentException injectionPointNotAJavabean(Method method);
@Message(id = 33, value = "%s annotation not found on %s")
IllegalArgumentException annotationNotFound(Class<? extends Annotation> type, Member member);
@Message(id = 34, value = "Could not resolve @EJB injection for %s on %s")
IllegalStateException ejbNotResolved(Object ejb, Member member);
@Message(id = 35, value = "Resolved more than one Jakarta Enterprise Beans for @EJB injection of %s on %s. Found %s")
IllegalStateException moreThanOneEjbResolved(Object ejb, Member member, final Set<ViewDescription> viewService);
@Message(id = 36, value = "Could not determine bean class from injection point type of %s")
IllegalArgumentException couldNotDetermineUnderlyingType(Type type);
@Message(id = 37, value = "Error injecting persistence unit into Jakarta Contexts and Dependency Injection managed bean. Can't find a persistence unit named '%s' in deployment %s for injection point %s")
IllegalArgumentException couldNotFindPersistenceUnit(String unitName, String deployment, Member injectionPoint);
@Message(id = 38, value = "Could not inject SecurityManager, security is not enabled")
IllegalStateException securityNotEnabled();
@Message(id = 39, value = "Singleton not set for %s. This means that you are trying to access a weld deployment with a Thread Context ClassLoader that is not associated with the deployment.")
IllegalStateException singletonNotSet(ClassLoader classLoader);
@Message(id = 40, value = "%s is already running")
IllegalStateException alreadyRunning(String object);
@Message(id = 41, value = "%s is not started")
IllegalStateException notStarted(String object);
// @Message(id = 42, value = "services cannot be added after weld has started")
// IllegalStateException cannotAddServicesAfterStart();
@Message(id = 43, value = "BeanDeploymentArchive with id %s not found in deployment")
IllegalArgumentException beanDeploymentNotFound(String beanDeploymentId);
@Message(id = 44, value = "Error injecting resource into Jakarta Contexts and Dependency Injection managed bean. Can't find a resource named %s")
IllegalArgumentException couldNotFindResource(String resourceName, @Cause Throwable cause);
@Message(id = 45, value = "Cannot determine resource name. Both jndiName and mappedName are null")
IllegalArgumentException cannotDetermineResourceName();
@Message(id = 46, value = "Cannot inject injection point %s")
IllegalArgumentException cannotInject(InjectionPoint ip);
@Message(id = 47, value = "%s cannot be used at runtime")
IllegalStateException cannotUseAtRuntime(String description);
@Message(id = 48, value = "These attributes must be 'true' for use with CDI 1.0 '%s'")
String rejectAttributesMustBeTrue(Set<String> keySet);
@Message(id = 49, value = "Error injecting resource into Jakarta Contexts and Dependency Injection managed bean. Can't find a resource named %s defined on %s")
IllegalArgumentException couldNotFindResource(String resourceName, String member, @Cause Throwable cause);
@LogMessage(level = Logger.Level.DEBUG)
@Message(value = "Discovered %s")
void beanArchiveDiscovered(BeanDeploymentArchive bda);
@Message(id = 50, value = "%s was not found in composite index")
ClassFileInfoException nameNotFoundInIndex(String name);
@LogMessage(level = Logger.Level.DEBUG)
@Message(id = Message.NONE, value = "Unable to load annotation %s")
void unableToLoadAnnotation(String annotationClassName);
@Message(id = 51, value = "Cannot load %s")
ClassFileInfoException cannotLoadClass(String name, @Cause Throwable throwable);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 52, value = "Using deployment classloader to load proxy classes for module %s. Package-private access will not work. To fix this the module should declare dependencies on %s")
void loadingProxiesUsingDeploymentClassLoader(ModuleIdentifier moduleIdentifier, String dependencies);
@Message(id = 53, value = "Component interceptor support not available for: %s")
IllegalStateException componentInterceptorSupportNotAvailable(Object componentClass);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 54, value = "Could not read provided index of an external bean archive: %s")
void cannotLoadAnnotationIndexOfExternalBeanArchive(Object indexUrl);
@LogMessage(level = Logger.Level.WARN)
@Message(id = 55, value = "Could not index class [%s] from an external bean archive: %s")
void cannotIndexClassName(Object name, Object bda);
@Message(id = 56, value = "Weld is not initialized yet")
IllegalStateException weldNotInitialized();
@Message(id = 57, value = "Persistence unit '%s' failed.")
IllegalStateException persistenceUnitFailed(String scopedPuName);
@Message(id = 58, value = "Persistence unit '%s' removed.")
IllegalStateException persistenceUnitRemoved(String scopedPuName);
}
| 13,919 | 50.555556 | 222 | java |
null | wildfly-main/weld/common/src/main/java/org/jboss/as/weld/deployment/WeldPortableExtensions.java | package org.jboss.as.weld.deployment;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import jakarta.enterprise.inject.spi.Extension;
import org.jboss.as.server.deployment.AttachmentKey;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.weld.logging.WeldLogger;
import org.jboss.weld.bootstrap.spi.Metadata;
import org.jboss.weld.bootstrap.spi.helpers.MetadataImpl;
/**
* Container class that is attached to the top level deployment that holds all portable extension metadata.
* <p/>
* A portable extension may be available to multiple deployment class loaders, however for each PE we
* only want to register a single instance.
* <p/>
* This container provides a mechanism for making sure that only a single PE of a given type is registered.
*
* @author Stuart Douglas
*
* @deprecated Use WeldCapability to get access to the functionality of this class.
*/
@Deprecated
public class WeldPortableExtensions {
// Once we can remove this class from this package, we should move it under org.jboss.as.weld._private.
// It will protect their uses outside of weld subsystem and will force external callers to use WeldCapability
// instead to utilize this class.
public static final AttachmentKey<WeldPortableExtensions> ATTACHMENT_KEY = AttachmentKey.create(WeldPortableExtensions.class);
public static WeldPortableExtensions getPortableExtensions(final DeploymentUnit deploymentUnit) {
if (deploymentUnit.getParent() == null) {
WeldPortableExtensions pes = deploymentUnit.getAttachment(WeldPortableExtensions.ATTACHMENT_KEY);
if (pes == null) {
deploymentUnit.putAttachment(ATTACHMENT_KEY, pes = new WeldPortableExtensions());
}
return pes;
} else {
return getPortableExtensions(deploymentUnit.getParent());
}
}
private final Map<Class<?>, Metadata<Extension>> extensions = new HashMap<>();
public synchronized void tryRegisterExtension(final Class<?> extensionClass, final DeploymentUnit deploymentUnit) throws DeploymentUnitProcessingException {
if (!Extension.class.isAssignableFrom(extensionClass)) {
throw WeldLogger.ROOT_LOGGER.extensionDoesNotImplementExtension(extensionClass);
}
if (extensions.containsKey(extensionClass)) {
return;
}
try {
extensions.put(extensionClass, new MetadataImpl<>((Extension) extensionClass.newInstance(), deploymentUnit.getName()));
} catch (Exception e) {
WeldLogger.DEPLOYMENT_LOGGER.couldNotLoadPortableExceptionClass(extensionClass.getName(), e);
}
}
public synchronized void registerExtensionInstance(final Extension extension, final DeploymentUnit deploymentUnit) {
extensions.put(extension.getClass(), new MetadataImpl<>(extension, deploymentUnit.getName()));
}
public Collection<Metadata<Extension>> getExtensions() {
return new HashSet<>(extensions.values());
}
}
| 3,151 | 41.026667 | 160 | java |
null | wildfly-main/weld/common/src/main/java/org/jboss/as/weld/services/bootstrap/AbstractResourceInjectionServices.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.services.bootstrap;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import jakarta.enterprise.inject.spi.InjectionPoint;
import org.jboss.as.ee.component.EEModuleDescription;
import org.jboss.as.naming.ContextListManagedReferenceFactory;
import org.jboss.as.naming.ManagedReference;
import org.jboss.as.naming.ManagedReferenceFactory;
import org.jboss.as.naming.deployment.ContextNames;
import org.jboss.modules.Module;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceRegistry;
import org.jboss.weld.injection.spi.ResourceReference;
import org.jboss.weld.injection.spi.ResourceReferenceFactory;
import org.jboss.weld.injection.spi.helpers.SimpleResourceReference;
import org.jboss.weld.logging.BeanLogger;
import org.jboss.weld.util.reflection.HierarchyDiscovery;
import org.jboss.weld.util.reflection.Reflections;
public abstract class AbstractResourceInjectionServices {
protected final ServiceRegistry serviceRegistry;
protected final EEModuleDescription moduleDescription;
private final Module module;
protected AbstractResourceInjectionServices(ServiceRegistry serviceRegistry, EEModuleDescription moduleDescription, Module module) {
this.serviceRegistry = serviceRegistry;
this.moduleDescription = moduleDescription;
this.module = module;
}
protected abstract ContextNames.BindInfo getBindInfo(final String result);
protected ManagedReferenceFactory getManagedReferenceFactory(ContextNames.BindInfo ejbBindInfo) {
try {
ServiceController<?> controller = serviceRegistry.getRequiredService(ejbBindInfo.getBinderServiceName());
return (ManagedReferenceFactory) controller.getValue();
} catch (Exception e) {
return null;
}
}
protected ResourceReferenceFactory<Object> handleServiceLookup(final String result, InjectionPoint injectionPoint) {
final ContextNames.BindInfo ejbBindInfo = getBindInfo(result);
/*
* Try to obtain ManagedReferenceFactory and validate the resource type
*/
final ManagedReferenceFactory factory = getManagedReferenceFactory(ejbBindInfo);
validateResourceInjectionPointType(factory, injectionPoint);
if (factory != null) {
return new ManagedReferenceFactoryToResourceReferenceFactoryAdapter<Object>(factory);
} else {
return createLazyResourceReferenceFactory(ejbBindInfo);
}
}
protected void validateResourceInjectionPointType(ManagedReferenceFactory fact, InjectionPoint injectionPoint) {
if (!(fact instanceof ContextListManagedReferenceFactory) || injectionPoint == null) {
return; // validation is skipped as we have no information about the resource type
}
final ContextListManagedReferenceFactory factory = (ContextListManagedReferenceFactory) fact;
// the resource class may come from JBoss AS
Class<?> resourceClass = org.jboss.as.weld.util.Reflections.loadClass(factory.getInstanceClassName(), factory.getClass().getClassLoader());
// or it may come from deployment
if (resourceClass == null) {
resourceClass = org.jboss.as.weld.util.Reflections.loadClass(factory.getInstanceClassName(), module.getClassLoader());
}
if (resourceClass != null) {
validateResourceInjectionPointType(resourceClass, injectionPoint);
}
// otherwise, the validation is skipped as we have no information about the resource type
}
private static final Map<Class<?>, Class<?>> BOXED_TYPES;
static {
Map<Class<?>, Class<?>> types = new HashMap<Class<?>, Class<?>>();
types.put(int.class, Integer.class);
types.put(byte.class, Byte.class);
types.put(short.class, Short.class);
types.put(long.class, Long.class);
types.put(char.class, Character.class);
types.put(float.class, Float.class);
types.put(double.class, Double.class);
types.put(boolean.class, Boolean.class);
BOXED_TYPES = Collections.unmodifiableMap(types);
}
protected static void validateResourceInjectionPointType(Class<?> resourceType, InjectionPoint injectionPoint) {
Class<?> injectionPointRawType = Reflections.getRawType(injectionPoint.getType());
HierarchyDiscovery discovery = new HierarchyDiscovery(resourceType);
for (Type type : discovery.getTypeClosure()) {
if (Reflections.getRawType(type).equals(injectionPointRawType)) {
return;
}
}
// type autoboxing
if (resourceType.isPrimitive() && BOXED_TYPES.get(resourceType).equals(injectionPointRawType)) {
return;
} else if (injectionPointRawType.isPrimitive() && BOXED_TYPES.get(injectionPointRawType).equals(resourceType)) {
return;
}
throw BeanLogger.LOG.invalidResourceProducerType(injectionPoint.getAnnotated(), resourceType.getName());
}
protected ResourceReferenceFactory<Object> createLazyResourceReferenceFactory(final ContextNames.BindInfo ejbBindInfo) {
return new ResourceReferenceFactory<Object>() {
@Override
public ResourceReference<Object> createResource() {
final ManagedReferenceFactory factory = getManagedReferenceFactory(ejbBindInfo);
if (factory == null) {
return new SimpleResourceReference<>(null);
}
final ManagedReference instance = factory.getReference();
return new ResourceReference<Object>() {
@Override
public Object getInstance() {
return instance.getInstance();
}
@Override
public void release() {
instance.release();
}
};
}
};
}
}
| 7,089 | 43.037267 | 147 | java |
null | wildfly-main/weld/common/src/main/java/org/jboss/as/weld/services/bootstrap/ManagedReferenceToResourceReferenceAdapter.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.services.bootstrap;
import static org.jboss.weld.util.reflection.Reflections.cast;
import org.jboss.as.naming.ManagedReference;
import org.jboss.weld.injection.spi.ResourceReference;
/**
* {@link ResourceReference} backed by {@link ManagedReference}.
*
* @author Jozef Hartinger
*
* @param <T>
*/
public class ManagedReferenceToResourceReferenceAdapter<T> implements ResourceReference<T> {
private final ManagedReference reference;
public ManagedReferenceToResourceReferenceAdapter(ManagedReference reference) {
this.reference = reference;
}
@Override
public T getInstance() {
return cast(reference.getInstance());
}
@Override
public void release() {
reference.release();
}
}
| 1,791 | 32.185185 | 92 | java |
null | wildfly-main/weld/common/src/main/java/org/jboss/as/weld/services/bootstrap/ManagedReferenceFactoryToResourceReferenceFactoryAdapter.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.services.bootstrap;
import org.jboss.as.naming.ManagedReference;
import org.jboss.as.naming.ManagedReferenceFactory;
import org.jboss.weld.injection.spi.ResourceReference;
import org.jboss.weld.injection.spi.ResourceReferenceFactory;
/**
* {@link ResourceReferenceFactory} backed by {@link ManagedReferenceFactory}.
*
* @author Jozef Hartinger
*
* @param <T>
*/
public class ManagedReferenceFactoryToResourceReferenceFactoryAdapter<T> implements ResourceReferenceFactory<T> {
private final ManagedReferenceFactory factory;
public ManagedReferenceFactoryToResourceReferenceFactoryAdapter(ManagedReferenceFactory factory) {
this.factory = factory;
}
@Override
public ResourceReference<T> createResource() {
final ManagedReference instance = factory.getReference();
return new ManagedReferenceToResourceReferenceAdapter<T>(instance);
}
}
| 1,936 | 37.74 | 113 | java |
null | wildfly-main/weld/common/src/main/java/org/jboss/as/weld/services/bootstrap/ComponentViewToResourceReferenceFactoryAdapter.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.services.bootstrap;
import org.jboss.as.ee.component.ComponentView;
import org.jboss.as.naming.ManagedReference;
import org.jboss.weld.injection.spi.ResourceReference;
import org.jboss.weld.injection.spi.ResourceReferenceFactory;
/**
* {@link ResourceReferenceFactory} backed by a {@link ComponentView}.
*
* @author Jozef Hartinger
*
* @param <T>
*/
public class ComponentViewToResourceReferenceFactoryAdapter<T> implements ResourceReferenceFactory<T> {
private final ComponentView view;
public ComponentViewToResourceReferenceFactoryAdapter(ComponentView view) {
this.view = view;
}
@Override
public ResourceReference<T> createResource() {
try {
final ManagedReference instance = view.createInstance();
return new ManagedReferenceToResourceReferenceAdapter<T>(instance);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| 1,978 | 35.648148 | 103 | java |
null | wildfly-main/weld/common/src/main/java/org/jboss/as/weld/ejb/EjbRequestScopeActivationInterceptor.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2009, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.ejb;
import java.io.Serializable;
import java.security.AccessController;
import jakarta.enterprise.inject.spi.BeanManager;
import jakarta.interceptor.InvocationContext;
import org.jboss.as.server.CurrentServiceContainer;
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.ServiceName;
import org.jboss.weld.bean.builtin.BeanManagerProxy;
import org.jboss.weld.context.ejb.EjbRequestContext;
import org.jboss.weld.manager.BeanManagerImpl;
import org.jboss.weld.module.ejb.AbstractEJBRequestScopeActivationInterceptor;
/**
* Interceptor for activating the Jakarta Contexts and Dependency Injection request scope on some Jakarta Enterprise Beans invocations.
* <p>
* Remote Jakarta Enterprise Beans invocations must also have the request scope active, but it may already be active for in-VM requests.
* <p>
* This interceptor is largely stateless, and can be re-used
* <p>
* Note that {@link EjbRequestContext} is actually bound to {@link InvocationContext} and so it's ok to use this interceptor for other components than Jakarta Enterprise Beans.
*
* @author Stuart Douglas
* @author Jozef Hartinger
*/
public class EjbRequestScopeActivationInterceptor extends AbstractEJBRequestScopeActivationInterceptor implements Serializable, org.jboss.invocation.Interceptor {
private static final long serialVersionUID = -503029523442133584L;
private volatile EjbRequestContext requestContext;
private volatile BeanManagerImpl beanManager;
private final ServiceName beanManagerServiceName;
public EjbRequestScopeActivationInterceptor(final ServiceName beanManagerServiceName) {
this.beanManagerServiceName = beanManagerServiceName;
}
@Override
protected BeanManagerImpl getBeanManager() {
// get the reference to the bean manager on the first invocation
if (beanManager == null) {
beanManager = BeanManagerProxy.unwrap((BeanManager)currentServiceContainer().getRequiredService(beanManagerServiceName).getValue());
}
return beanManager;
}
@Override
protected EjbRequestContext getEjbRequestContext() {
//create the context lazily, on the first invocation
//we can't do this on interceptor creation, as the timed object invoker may create the interceptor
//before we have been injected
if (requestContext == null) {
requestContext = super.getEjbRequestContext();
}
return requestContext;
}
@Override
public Object processInvocation(final InterceptorContext context) throws Exception {
return aroundInvoke(context.getInvocationContext());
}
public static class Factory implements InterceptorFactory {
private final Interceptor interceptor;
public Factory(final ServiceName beanManagerServiceName) {
this.interceptor = new EjbRequestScopeActivationInterceptor(beanManagerServiceName);
}
@Override
public org.jboss.invocation.Interceptor create(final InterceptorFactoryContext context) {
return interceptor;
}
}
private static ServiceContainer currentServiceContainer() {
if(System.getSecurityManager() == null) {
return CurrentServiceContainer.getServiceContainer();
}
return AccessController.doPrivileged(CurrentServiceContainer.GET_ACTION);
}
}
| 4,623 | 39.561404 | 176 | java |
null | wildfly-main/weld/common/src/main/java/org/jboss/as/weld/util/ImmediateResourceReferenceFactory.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.util;
import org.jboss.weld.injection.spi.ResourceReference;
import org.jboss.weld.injection.spi.ResourceReferenceFactory;
import org.jboss.weld.injection.spi.helpers.SimpleResourceReference;
/**
* @author Stuart Douglas
*/
public class ImmediateResourceReferenceFactory<T> implements ResourceReferenceFactory<T> {
private final T instance;
public ImmediateResourceReferenceFactory(final T instance) {
this.instance = instance;
}
@Override
public ResourceReference<T> createResource() {
return new SimpleResourceReference<T>(instance);
}
}
| 1,636 | 36.204545 | 90 | java |
null | wildfly-main/weld/common/src/main/java/org/jboss/as/weld/util/ServiceLoaders.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.ServiceLoader;
import java.util.Set;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.module.ResourceRoot;
import org.jboss.as.weld.spi.BeanDeploymentArchiveServicesProvider;
import org.jboss.as.weld.spi.ModuleServicesProvider;
import org.jboss.modules.Module;
import org.jboss.weld.bootstrap.api.BootstrapService;
import org.jboss.weld.bootstrap.api.Service;
import org.jboss.weld.bootstrap.spi.BeanDeploymentArchive;
import org.jboss.weld.exceptions.IllegalStateException;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
*
* @author Martin Kouba
*/
public final class ServiceLoaders {
private ServiceLoaders() {
}
/**
*
* @param serviceClass
* @param loaderClass
* @return
*/
public static <T> Optional<T> loadSingle(Class<T> serviceClass, Class<?> loaderClass) {
Iterator<T> iterator = ServiceLoader.load(serviceClass, WildFlySecurityManager.getClassLoaderPrivileged(loaderClass)).iterator();
T service = null;
while (iterator.hasNext()) {
if (service != null) {
throw new IllegalStateException("Exactly one service provider is required for: " + serviceClass);
}
service = iterator.next();
}
return Optional.ofNullable(service);
}
/**
*
* @param clazz
* @param deploymentUnit
* @return
*/
public static Map<Class<? extends Service>, Service> loadModuleServices(Iterable<ModuleServicesProvider> providers,
DeploymentUnit rootDeploymentUnit, DeploymentUnit deploymentUnit, Module module, ResourceRoot resourceRoot) {
List<Service> services = new ArrayList<>();
for (ModuleServicesProvider provider : providers) {
services.addAll(provider.getServices(rootDeploymentUnit, deploymentUnit, module, resourceRoot));
}
Map<Class<? extends Service>, Service> servicesMap = new HashMap<>();
for (Service service : services) {
for (Class<? extends Service> serviceInterface : identifyServiceInterfaces(service.getClass(), new HashSet<>())) {
servicesMap.put(serviceInterface, service);
}
}
return servicesMap;
}
/**
*
* @param clazz
* @param archive
* @return
*/
public static Map<Class<? extends Service>, Service> loadBeanDeploymentArchiveServices(Class<?> clazz, BeanDeploymentArchive archive) {
ServiceLoader<BeanDeploymentArchiveServicesProvider> serviceLoader = ServiceLoader.load(BeanDeploymentArchiveServicesProvider.class,
WildFlySecurityManager.getClassLoaderPrivileged(clazz));
List<Service> services = new ArrayList<>();
for (BeanDeploymentArchiveServicesProvider provider : serviceLoader) {
services.addAll(provider.getServices(archive));
}
Map<Class<? extends Service>, Service> servicesMap = new HashMap<>();
for (Service service : services) {
for (Class<? extends Service> serviceInterface : identifyServiceInterfaces(service.getClass(), new HashSet<>())) {
servicesMap.put(serviceInterface, service);
}
}
return servicesMap;
}
/**
* Identifies service views for a service implementation class. A service view is either: - an interface that directly extends {@link Service} or
* {@link BootstrapService} - a clazz that directly implements {@link Service} or {@link BootstrapService}
*
* @param clazz the given class
* @param serviceInterfaces a set that this method populates with service views
* @return serviceInterfaces
*/
private static Set<Class<? extends Service>> identifyServiceInterfaces(Class<?> clazz, Set<Class<? extends Service>> serviceInterfaces) {
if (clazz == null || Object.class.equals(clazz) || BootstrapService.class.equals(clazz)) {
return serviceInterfaces;
}
for (Class<?> interfac3 : clazz.getInterfaces()) {
if (Service.class.equals(interfac3) || BootstrapService.class.equals(interfac3)) {
serviceInterfaces.add(Reflections.<Class<? extends Service>> cast(clazz));
}
}
for (Class<?> interfac3 : clazz.getInterfaces()) {
identifyServiceInterfaces(interfac3, serviceInterfaces);
}
identifyServiceInterfaces(clazz.getSuperclass(), serviceInterfaces);
return serviceInterfaces;
}
}
| 5,765 | 40.185714 | 149 | java |
null | wildfly-main/weld/common/src/main/java/org/jboss/as/weld/util/ResourceInjectionUtilities.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.util;
import java.beans.Introspector;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import jakarta.annotation.Resource;
import jakarta.enterprise.inject.spi.Annotated;
import jakarta.enterprise.inject.spi.InjectionPoint;
import org.jboss.as.weld.logging.WeldLogger;
import org.jboss.metadata.property.PropertyReplacer;
import org.jboss.weld.injection.ParameterInjectionPoint;
public class ResourceInjectionUtilities {
private ResourceInjectionUtilities() {
}
public static final String RESOURCE_LOOKUP_PREFIX = "java:comp/env";
public static String getResourceName(String jndiName, String mappedName) {
if (mappedName != null) {
return mappedName;
} else if (jndiName != null) {
return jndiName;
} else {
throw WeldLogger.ROOT_LOGGER.cannotDetermineResourceName();
}
}
public static String getResourceName(InjectionPoint injectionPoint, PropertyReplacer propertyReplacer) {
Resource resource = getResourceAnnotated(injectionPoint).getAnnotation(Resource.class);
String mappedName = resource.mappedName();
if (!mappedName.equals("")) {
return propertyReplacer == null ? mappedName : propertyReplacer.replaceProperties(mappedName);
}
String name = resource.name();
if (!name.equals("")) {
name = propertyReplacer == null ? name : propertyReplacer.replaceProperties(name);
//see if this is a prefixed name
//and if so just return it
int firstSlash = name.indexOf("/");
int colon = name.indexOf(":");
if (colon != -1
&& (firstSlash == -1 || colon < firstSlash)) {
return name;
}
return RESOURCE_LOOKUP_PREFIX + "/" + name;
}
String propertyName;
if (injectionPoint.getMember() instanceof Field) {
propertyName = injectionPoint.getMember().getName();
} else if (injectionPoint.getMember() instanceof Method) {
propertyName = getPropertyName((Method) injectionPoint.getMember());
if (propertyName == null) {
throw WeldLogger.ROOT_LOGGER.injectionPointNotAJavabean((Method) injectionPoint.getMember());
}
} else {
throw WeldLogger.ROOT_LOGGER.cannotInject(injectionPoint);
}
String className = injectionPoint.getMember().getDeclaringClass().getName();
return RESOURCE_LOOKUP_PREFIX + "/" + className + "/" + propertyName;
}
public static String getPropertyName(Method method) {
String methodName = method.getName();
if (methodName.matches("^(get).*") && method.getParameterCount() == 0) {
return Introspector.decapitalize(methodName.substring(3));
} else if (methodName.matches("^(is).*") && method.getParameterCount() == 0) {
return Introspector.decapitalize(methodName.substring(2));
} else if (methodName.matches("^(set).*") && method.getParameterCount() == 1) {
return Introspector.decapitalize(methodName.substring(3));
}
return null;
}
public static String getPropertyName(Member member) {
if (member instanceof Method) {
return getPropertyName((Method) member);
}
return member.getName();
}
public static Annotated getResourceAnnotated(InjectionPoint injectionPoint) {
if(injectionPoint instanceof ParameterInjectionPoint) {
return ((ParameterInjectionPoint<?, ?>)injectionPoint).getAnnotated().getDeclaringCallable();
}
return injectionPoint.getAnnotated();
}
}
| 4,783 | 39.888889 | 109 | java |
null | wildfly-main/weld/common/src/main/java/org/jboss/as/weld/util/Reflections.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.util;
import java.lang.annotation.Annotation;
import java.lang.annotation.Inherited;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
*
* @author Stuart Douglas
*
*/
public class Reflections {
@SuppressWarnings("unchecked")
public static <T> T cast(Object obj) {
return (T) obj;
}
public static <T> T newInstance(String className, ClassLoader classLoader) {
try {
Class<?> clazz = classLoader.loadClass(className);
return (T) clazz.newInstance();
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
}
}
public static boolean isAccessible(String className, ClassLoader classLoader) {
return loadClass(className, classLoader) != null;
}
public static <T> Class<T> loadClass(String className, ClassLoader classLoader) {
try {
return cast(classLoader.loadClass(className));
} catch (Throwable e) {
return null;
}
}
/**
* A simple implementation of the {@link org.jboss.weld.resources.spi.AnnotationDiscovery#containsAnnotation(Class, Class)} contract.
* This implementation uses reflection.
*
* @see org.jboss.as.weld.discovery.WeldAnnotationDiscovery
*/
public static boolean containsAnnotation(Class<?> javaClass, Class<? extends Annotation> requiredAnnotation) {
for (Class<?> clazz = javaClass; clazz != null && clazz != Object.class; clazz = clazz.getSuperclass()) {
// class level annotations
if ((clazz == javaClass || requiredAnnotation.isAnnotationPresent(Inherited.class))
&& containsAnnotations(clazz.getAnnotations(), requiredAnnotation)) {
return true;
}
// fields
for (Field field : clazz.getDeclaredFields()) {
if (containsAnnotations(field.getAnnotations(), requiredAnnotation)) {
return true;
}
}
// constructors
for (Constructor<?> constructor : clazz.getConstructors()) {
if (containsAnnotations(constructor.getAnnotations(), requiredAnnotation)) {
return true;
}
for (Annotation[] parameterAnnotations : constructor.getParameterAnnotations()) {
if (containsAnnotations(parameterAnnotations, requiredAnnotation)) {
return true;
}
}
}
// methods
for (Method method : clazz.getDeclaredMethods()) {
if (containsAnnotations(method.getAnnotations(), requiredAnnotation)) {
return true;
}
for (Annotation[] parameterAnnotations : method.getParameterAnnotations()) {
if (containsAnnotations(parameterAnnotations, requiredAnnotation)) {
return true;
}
}
}
}
return false;
}
public static boolean containsAnnotations(Annotation[] annotations, Class<? extends Annotation> requiredAnnotation) {
return containsAnnotation(annotations, requiredAnnotation, true);
}
private static boolean containsAnnotation(Annotation[] annotations, Class<? extends Annotation> requiredAnnotation, boolean checkMetaAnnotations) {
for (Annotation annotation : annotations) {
Class<? extends Annotation> annotationType = annotation.annotationType();
if (requiredAnnotation.equals(annotationType)) {
return true;
}
if (checkMetaAnnotations && containsAnnotation(annotationType.getAnnotations(), requiredAnnotation, false)) {
return true;
}
}
return false;
}
}
| 5,142 | 38.259542 | 151 | java |
null | wildfly-main/weld/common/src/main/java/org/jboss/as/weld/interceptors/WeldInterceptorInstances.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.interceptors;
import java.io.Serializable;
import java.util.Map;
import jakarta.enterprise.context.spi.CreationalContext;
import jakarta.enterprise.inject.spi.Interceptor;
import org.jboss.as.weld.spi.InterceptorInstances;
import org.jboss.weld.serialization.spi.helpers.SerializableContextualInstance;
/**
* @author Stuart Douglas
*/
public class WeldInterceptorInstances implements InterceptorInstances, Serializable {
private static final long serialVersionUID = 1L;
private final CreationalContext<Object> creationalContext;
private final Map<String, SerializableContextualInstance<Interceptor<Object>, Object>> interceptorInstances;
public WeldInterceptorInstances(final CreationalContext<Object> creationalContext, final Map<String, SerializableContextualInstance<Interceptor<Object>, Object>> interceptorInstances) {
this.creationalContext = creationalContext;
this.interceptorInstances = interceptorInstances;
}
@Override
public CreationalContext<Object> getCreationalContext() {
return creationalContext;
}
@Override
public Map<String, SerializableContextualInstance<Interceptor<Object>, Object>> getInstances() {
return interceptorInstances;
}
}
| 2,289 | 39.175439 | 189 | java |
null | wildfly-main/weld/common/src/main/java/org/jboss/as/weld/interceptors/Jsr299BindingsInterceptor.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2009, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.interceptors;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
import jakarta.enterprise.inject.spi.InterceptionType;
import jakarta.enterprise.inject.spi.Interceptor;
import jakarta.interceptor.InvocationContext;
import org.jboss.as.ee.component.ComponentInstance;
import org.jboss.as.weld.spi.ComponentInterceptorSupport;
import org.jboss.as.weld.spi.InterceptorInstances;
import org.jboss.invocation.ImmediateInterceptorFactory;
import org.jboss.invocation.InterceptorContext;
import org.jboss.invocation.InterceptorFactory;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import org.jboss.weld.ejb.spi.InterceptorBindings;
/**
* Jakarta Interceptors for applying interceptors bindings.
* <p/>
* It is a separate interceptor, as it needs to be applied after all
* the other existing interceptors.
*
* @author Marius Bogoevici
* @author Stuart Douglas
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public class Jsr299BindingsInterceptor implements org.jboss.invocation.Interceptor {
private final InterceptionType interceptionType;
private final ComponentInterceptorSupport interceptorSupport;
private final Supplier<InterceptorBindings> interceptorBindingsSupplier;
private Jsr299BindingsInterceptor(final InterceptionType interceptionType, final ComponentInterceptorSupport interceptorSupport, final Supplier<InterceptorBindings> interceptorBindingsSupplier) {
this.interceptionType = interceptionType;
this.interceptorSupport = interceptorSupport;
this.interceptorBindingsSupplier = interceptorBindingsSupplier;
}
public static InterceptorFactory factory(final InterceptionType interceptionType, final ServiceBuilder<?> builder, final ServiceName interceptorBindingServiceName, final ComponentInterceptorSupport interceptorSupport) {
final Supplier<InterceptorBindings> interceptorBindingsSupplier = builder.requires(interceptorBindingServiceName);
return new ImmediateInterceptorFactory(new Jsr299BindingsInterceptor(interceptionType, interceptorSupport, interceptorBindingsSupplier));
}
protected Object delegateInterception(InvocationContext invocationContext, InterceptionType interceptionType, List<Interceptor<?>> currentInterceptors, InterceptorInstances interceptorInstances)
throws Exception {
List<Object> currentInterceptorInstances = new ArrayList<Object>();
for (Interceptor<?> interceptor : currentInterceptors) {
currentInterceptorInstances.add(interceptorInstances.getInstances().get(interceptor.getBeanClass().getName()).getInstance());
}
if (currentInterceptorInstances.size() > 0) {
return interceptorSupport.delegateInterception(invocationContext, interceptionType, currentInterceptors, currentInterceptorInstances);
} else {
return invocationContext.proceed();
}
}
private Object doMethodInterception(InvocationContext invocationContext, InterceptionType interceptionType, InterceptorInstances interceptorInstances, InterceptorBindings interceptorBindings)
throws Exception {
if (interceptorBindings != null) {
List<Interceptor<?>> currentInterceptors = interceptorBindings.getMethodInterceptors(interceptionType, invocationContext.getMethod());
return delegateInterception(invocationContext, interceptionType, currentInterceptors, interceptorInstances);
} else {
return invocationContext.proceed();
}
}
@Override
public Object processInvocation(final InterceptorContext context) throws Exception {
final ComponentInstance componentInstance = context.getPrivateData(ComponentInstance.class);
final InterceptorInstances interceptorInstances = interceptorSupport.getInterceptorInstances(componentInstance);
final InterceptorBindings interceptorBindings = interceptorBindingsSupplier.get();
switch (interceptionType) {
case AROUND_INVOKE:
return doMethodInterception(context.getInvocationContext(), InterceptionType.AROUND_INVOKE, interceptorInstances, interceptorBindings);
case AROUND_TIMEOUT:
return doMethodInterception(context.getInvocationContext(), InterceptionType.AROUND_TIMEOUT, interceptorInstances, interceptorBindings);
case PRE_DESTROY:
try {
return doLifecycleInterception(context, interceptorInstances, interceptorBindings);
} finally {
interceptorInstances.getCreationalContext().release();
}
case POST_CONSTRUCT:
return doLifecycleInterception(context, interceptorInstances, interceptorBindings);
case AROUND_CONSTRUCT:
return doLifecycleInterception(context, interceptorInstances, interceptorBindings);
default:
//should never happen
return context.proceed();
}
}
private Object doLifecycleInterception(final InterceptorContext context, InterceptorInstances interceptorInstances, final InterceptorBindings interceptorBindings) throws Exception {
if (interceptorBindings == null) {
return context.proceed();
} else {
List<Interceptor<?>> currentInterceptors = interceptorBindings.getLifecycleInterceptors(interceptionType);
return delegateInterception(context.getInvocationContext(), interceptionType, currentInterceptors, interceptorInstances);
}
}
}
| 6,685 | 50.430769 | 223 | java |
null | wildfly-main/weld/bean-validation/src/main/java/org/jboss/as/weld/CdiValidatorFactoryService.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.weld;
import java.util.Iterator;
import java.util.Set;
import java.util.function.Supplier;
import jakarta.enterprise.context.spi.CreationalContext;
import jakarta.enterprise.inject.Default;
import jakarta.enterprise.inject.spi.Bean;
import jakarta.enterprise.inject.spi.BeanManager;
import jakarta.enterprise.util.AnnotationLiteral;
import jakarta.validation.ValidatorFactory;
import org.jboss.as.ee.beanvalidation.BeanValidationAttachments;
import org.jboss.as.ee.beanvalidation.LazyValidatorFactory;
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.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StopContext;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* Service that replaces the delegate of LazyValidatorFactory with a Jakarta Contexts and Dependency Injection enabled
* ValidatorFactory.
*
* @author Farah Juma
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public class CdiValidatorFactoryService implements Service {
public static final ServiceName SERVICE_NAME = ServiceName.of("CdiValidatorFactoryService");
private final Supplier<BeanManager> beanManagerSupplier;
private final ClassLoader classLoader;
private final DeploymentUnit deploymentUnit;
/**
* Create the CdiValidatorFactoryService instance.
*
* @param deploymentUnit the deployment unit
*/
public CdiValidatorFactoryService(final DeploymentUnit deploymentUnit, final Supplier<BeanManager> beanManagerSupplier) {
this.deploymentUnit = deploymentUnit;
final Module module = this.deploymentUnit.getAttachment(Attachments.MODULE);
this.classLoader = module.getClassLoader();
this.beanManagerSupplier = beanManagerSupplier;
}
@Override
public void start(final StartContext context) {
final ClassLoader cl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
try {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader);
// Get the Jakarta Contexts and Dependency Injection enabled ValidatorFactory
ValidatorFactory validatorFactory = getReference(ValidatorFactory.class, beanManagerSupplier.get());
// Replace the delegate of LazyValidatorFactory
LazyValidatorFactory lazyValidatorFactory = (LazyValidatorFactory)(deploymentUnit.getAttachment(BeanValidationAttachments.VALIDATOR_FACTORY));
lazyValidatorFactory.replaceDelegate(validatorFactory);
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(cl);
}
}
@Override
public void stop(final StopContext context) {
final ClassLoader cl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
try {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader);
ValidatorFactory validatorFactory = deploymentUnit.getAttachment(BeanValidationAttachments.VALIDATOR_FACTORY);
if (validatorFactory != null) {
validatorFactory.close();
}
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(cl);
}
}
private <T> T getReference(Class<T> clazz, BeanManager beanManager) {
Set<Bean<?>> beans = beanManager.getBeans(clazz, new AnnotationLiteral<Default>() {});
Iterator<Bean<?>> i = beans.iterator();
if (!i.hasNext()) {
return null;
}
Bean<?> bean = i.next();
CreationalContext<?> context = beanManager.createCreationalContext(bean);
return (T) beanManager.getReference(bean, clazz, context);
}
}
| 4,900 | 40.184874 | 154 | java |
null | wildfly-main/weld/bean-validation/src/main/java/org/jboss/as/weld/deployment/processor/CdiBeanValidationFactoryProcessorProvider.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment.processor;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.Phase;
import org.jboss.as.weld.spi.DeploymentUnitProcessorProvider;
/**
*
* @author Martin Kouba
*/
public class CdiBeanValidationFactoryProcessorProvider implements DeploymentUnitProcessorProvider {
@Override
public DeploymentUnitProcessor getProcessor() {
return new CdiBeanValidationFactoryProcessor();
}
@Override
public Phase getPhase() {
return Phase.INSTALL;
}
@Override
public int getPriority() {
return Phase.INSTALL_CDI_VALIDATOR_FACTORY;
}
}
| 1,688 | 32.78 | 99 | java |
null | wildfly-main/weld/bean-validation/src/main/java/org/jboss/as/weld/deployment/processor/WeldBeanValidationDependencyProcessorProvider.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment.processor;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.Phase;
import org.jboss.as.weld.spi.DeploymentUnitProcessorProvider;
/**
*
* @author Martin Kouba
*/
public class WeldBeanValidationDependencyProcessorProvider implements DeploymentUnitProcessorProvider {
@Override
public DeploymentUnitProcessor getProcessor() {
return new WeldBeanValidationDependencyProcessor();
}
@Override
public Phase getPhase() {
return Phase.DEPENDENCIES;
}
@Override
public int getPriority() {
return Phase.DEPENDENCIES_WELD;
}
}
| 1,689 | 32.8 | 103 | java |
null | wildfly-main/weld/bean-validation/src/main/java/org/jboss/as/weld/deployment/processor/WeldBeanValidationDependencyProcessor.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2016, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.deployment.processor;
import static org.jboss.as.weld.Capabilities.WELD_CAPABILITY_NAME;
import org.jboss.as.controller.capability.CapabilityServiceSupport;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.module.ModuleDependency;
import org.jboss.as.server.deployment.module.ModuleSpecification;
import org.jboss.as.weld.WeldCapability;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.modules.ModuleLoader;
/**
*
* @author Martin Kouba
*/
public class WeldBeanValidationDependencyProcessor implements DeploymentUnitProcessor {
private static final ModuleIdentifier CDI_BEAN_VALIDATION_ID = ModuleIdentifier.create("org.hibernate.validator.cdi");
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION);
final ModuleLoader moduleLoader = Module.getBootModuleLoader();
final CapabilityServiceSupport support = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT);
final WeldCapability weldCapability;
try {
weldCapability = support.getCapabilityRuntimeAPI(WELD_CAPABILITY_NAME, WeldCapability.class);
} catch (CapabilityServiceSupport.NoSuchCapabilityException ignored) {
return;
}
if (!weldCapability.isPartOfWeldDeployment(deploymentUnit)) {
return; // Skip if there are no beans.xml files in the deployment
}
ModuleDependency cdiBeanValidationDep = new ModuleDependency(moduleLoader, CDI_BEAN_VALIDATION_ID, false, false, true, false);
moduleSpecification.addSystemDependency(cdiBeanValidationDep);
}
}
| 3,203 | 44.771429 | 134 | java |
null | wildfly-main/weld/bean-validation/src/main/java/org/jboss/as/weld/deployment/processor/CdiBeanValidationFactoryProcessor.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.weld.deployment.processor;
import static org.jboss.as.weld.Capabilities.WELD_CAPABILITY_NAME;
import java.util.function.Supplier;
import jakarta.enterprise.inject.spi.BeanManager;
import org.jboss.as.controller.capability.CapabilityServiceSupport;
import org.jboss.as.ee.beanvalidation.BeanValidationAttachments;
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.DeploymentUnitProcessor;
import org.jboss.as.weld.CdiValidatorFactoryService;
import org.jboss.as.weld.ServiceNames;
import org.jboss.as.weld.WeldCapability;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
/**
* Deployment processor that replaces the delegate of LazyValidatorFactory with a CDI-enabled ValidatorFactory.
*
* @author Farah Juma
* @author Martin Kouba
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public class CdiBeanValidationFactoryProcessor implements DeploymentUnitProcessor {
@Override
public void deploy(DeploymentPhaseContext phaseContext) {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final DeploymentUnit topLevelDeployment = deploymentUnit.getParent() == null ? deploymentUnit : deploymentUnit.getParent();
final ServiceName weldStartService = topLevelDeployment.getServiceName().append(ServiceNames.WELD_START_SERVICE_NAME);
final CapabilityServiceSupport support = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT);
final WeldCapability weldCapability;
try {
weldCapability = support.getCapabilityRuntimeAPI(WELD_CAPABILITY_NAME, WeldCapability.class);
} catch (CapabilityServiceSupport.NoSuchCapabilityException ignored) {
return;
}
if (!weldCapability.isPartOfWeldDeployment(deploymentUnit)) {
return;
}
if (!deploymentUnit.hasAttachment(BeanValidationAttachments.VALIDATOR_FACTORY)) {
return;
}
final ServiceTarget serviceTarget = phaseContext.getServiceTarget();
final ServiceName serviceName = deploymentUnit.getServiceName().append(CdiValidatorFactoryService.SERVICE_NAME);
final ServiceBuilder<?> sb = serviceTarget.addService(serviceName);
final Supplier<BeanManager> beanManagerSupplier = weldCapability.addBeanManagerService(deploymentUnit, sb);
sb.requires(weldStartService);
sb.setInstance(new CdiValidatorFactoryService(deploymentUnit, beanManagerSupplier));
sb.install();
}
}
| 3,760 | 44.313253 | 131 | java |
null | wildfly-main/weld/subsystem/src/test/java/org/jboss/as/weld/WeldSubsystemTestCase.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld;
import java.io.IOException;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.model.test.FailedOperationTransformationConfig;
import org.jboss.as.model.test.ModelTestControllerVersion;
import org.jboss.as.model.test.ModelTestUtils;
import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest;
import org.jboss.as.subsystem.test.AdditionalInitialization;
import org.jboss.as.subsystem.test.KernelServices;
import org.jboss.as.subsystem.test.KernelServicesBuilder;
import org.jboss.as.subsystem.test.LegacyKernelServicesInitializer;
import org.jboss.dmr.ModelNode;
import org.junit.Assert;
import org.junit.Test;
/**
* @author <a href="[email protected]">Kabir Khan</a>
*/
public class WeldSubsystemTestCase extends AbstractSubsystemBaseTest {
public WeldSubsystemTestCase() {
super(WeldExtension.SUBSYSTEM_NAME, new WeldExtension());
}
@Override
protected String getSubsystemXml() throws IOException {
return readResource("subsystem.xml");
}
@Override
protected String getSubsystemXsdPath() throws Exception {
return "schema/jboss-as-weld_5_0.xsd";
}
@Test
public void testSubsystem10() throws Exception {
standardSubsystemTest("subsystem_1_0.xml", false);
}
@Test
public void testSubsystem20() throws Exception {
standardSubsystemTest("subsystem_2_0.xml", false);
}
@Test
public void testSubsystem30() throws Exception {
standardSubsystemTest("subsystem_3_0.xml", false);
}
@Test
public void testSubsystem40() throws Exception {
standardSubsystemTest("subsystem_4_0.xml", false);
}
@Test
public void testExpressions() throws Exception {
standardSubsystemTest("subsystem_with_expression.xml");
}
@Test
public void testTransformerEAP740() throws Exception {
testTransformer(ModelTestControllerVersion.EAP_7_4_0, true);
}
@Test
public void testTransformersRejectionEAP740() throws Exception {
testTransformersRejection(ModelTestControllerVersion.EAP_7_4_0);
}
private void testTransformersRejection(ModelTestControllerVersion controllerVersion) throws Exception {
ModelVersion modelVersion = controllerVersion.getSubsystemModelVersion(getMainSubsystemName());
KernelServices mainServices = buildKernelServices(controllerVersion, null, false);
Assert.assertTrue(mainServices.isSuccessfulBoot());
Assert.assertTrue(mainServices.getLegacyServices(modelVersion).isSuccessfulBoot());
ModelTestUtils.checkFailedTransformedBootOperations(mainServices, modelVersion, parse(getSubsystemXml("subsystem-reject.xml")),
new FailedOperationTransformationConfig().addFailedAttribute(PathAddress.pathAddress(WeldExtension.PATH_SUBSYSTEM),
new FailedOperationTransformationConfig.NewAttributesConfig(WeldResourceDefinition.LEGACY_EMPTY_BEANS_XML_TREATMENT_ATTRIBUTE) {
@Override
protected boolean checkValue(String attrName, ModelNode attribute, boolean isGeneratedWriteAttribute) {
return !attribute.equals(ModelNode.TRUE);
}
@Override
protected ModelNode correctValue(ModelNode attribute, boolean isGeneratedWriteAttribute) {
// if it's 'false' change it to undefined to test handling of undefined as well
return attribute.isDefined() ? ModelNode.TRUE : new ModelNode();
}
}));
}
private void testTransformer(ModelTestControllerVersion controllerVersion, boolean fixLegacyEmptyXmlTreatment) throws Exception {
KernelServices mainServices = buildKernelServices(controllerVersion, getSubsystemXml(), fixLegacyEmptyXmlTreatment);
ModelVersion modelVersion = controllerVersion.getSubsystemModelVersion(getMainSubsystemName());
// check that both versions of the legacy model are the same and valid
checkSubsystemModelTransformation(mainServices, modelVersion, null, false);
ModelNode transformed = mainServices.readTransformedModel(modelVersion);
Assert.assertTrue(transformed.isDefined());
}
private KernelServices buildKernelServices(ModelTestControllerVersion legacyVersion, String subsystemXml, boolean fixLegacyEmptyXmlTreatment) throws Exception {
ModelVersion modelVersion = legacyVersion.getSubsystemModelVersion(getMainSubsystemName());
KernelServicesBuilder builder = createKernelServicesBuilder(AdditionalInitialization.MANAGEMENT);
if (subsystemXml != null) {
builder.setSubsystemXml(subsystemXml);
}
LegacyKernelServicesInitializer legacyInitializer =
builder.createLegacyKernelServicesBuilder(AdditionalInitialization.MANAGEMENT, ModelTestControllerVersion.EAP_7_4_0, modelVersion)
.addMavenResourceURL("org.jboss.eap:wildfly-weld:" + ModelTestControllerVersion.EAP_7_4_0.getMavenGavVersion())
.addParentFirstClassPattern("org.jboss.msc.*")
.addParentFirstClassPattern("org.jboss.msc.service.*")
.dontPersistXml();
if (fixLegacyEmptyXmlTreatment) {
// The legacy host won't configure "legacy-empty-beans-xml-treatment=true" as that is
// the hard coded, unconfigurable behavior. So when we try and boot the current version
// with the boot ops from the legacy host, fix that up
legacyInitializer.configureReverseControllerCheck(AdditionalInitialization.MANAGEMENT,
null,
WeldSubsystemTestCase::fixLegacyAddOp);
}
KernelServices mainServices = builder.build();
Assert.assertTrue(mainServices.isSuccessfulBoot());
Assert.assertTrue(mainServices.getLegacyServices(modelVersion).isSuccessfulBoot());
return mainServices;
}
private static ModelNode fixLegacyAddOp(ModelNode op) {
ModelNode addr = op.get("address");
if (addr.asInt() == 1 && addr.get(0).asProperty().getName().equals("subsystem")) {
op.get("legacy-empty-beans-xml-treatment").set(true);
}
return op;
}
}
| 7,437 | 45.4875 | 164 | java |
null | wildfly-main/weld/subsystem/src/test/java/org/jboss/as/weld/discovery/IndexUtils.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.discovery;
import java.io.IOException;
import java.util.Collections;
import org.jboss.as.server.deployment.annotation.CompositeIndex;
import org.jboss.jandex.Index;
import org.jboss.jandex.Indexer;
class IndexUtils {
static CompositeIndex createIndex(Object... resources) throws IOException {
final ClassLoader classLoader = IndexUtils.class.getClassLoader();
final Indexer indexer = new Indexer();
for (Object resource : resources) {
addResource(resource, indexer, classLoader);
}
final Index index = indexer.complete();
return new CompositeIndex(Collections.singleton(index));
}
private static void addResource(Object resource, Indexer indexer, ClassLoader classLoader) throws IOException {
final String resourceName;
if (resource instanceof Class<?>) {
resourceName = ((Class<?>) resource).getName().replace(".", "/") + ".class";
} else if (resource instanceof String) {
resourceName = resource.toString();
} else {
throw new IllegalArgumentException("Unsupported resource type");
}
indexer.index(classLoader.getResourceAsStream(resourceName));
if (resource instanceof Class<?>) {
for (Class<?> innerClass : ((Class<?>) resource).getDeclaredClasses()) {
addResource(innerClass, indexer, classLoader);
}
}
}
}
| 2,475 | 40.266667 | 115 | java |
null | wildfly-main/weld/subsystem/src/test/java/org/jboss/as/weld/discovery/AlphaImpl.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.discovery;
public class AlphaImpl extends AbstractAlpha {
}
| 1,104 | 39.925926 | 73 | java |
null | wildfly-main/weld/subsystem/src/test/java/org/jboss/as/weld/discovery/Alpha.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.discovery;
import jakarta.enterprise.inject.Vetoed;
@Vetoed
public interface Alpha {
}
| 1,132 | 36.766667 | 73 | java |
null | wildfly-main/weld/subsystem/src/test/java/org/jboss/as/weld/discovery/Charlie.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.discovery;
public class Charlie {
@AnnotationNotInIndex
public void foo() {
}
}
| 1,137 | 35.709677 | 73 | java |
null | wildfly-main/weld/subsystem/src/test/java/org/jboss/as/weld/discovery/AbstractAlpha.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.discovery;
public abstract class AbstractAlpha implements Alpha {
}
| 1,112 | 40.222222 | 73 | java |
null | wildfly-main/weld/subsystem/src/test/java/org/jboss/as/weld/discovery/InnerClasses.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.discovery;
import jakarta.inject.Named;
public class InnerClasses {
@Named
public interface InnerInterface {
}
}
| 1,170 | 35.59375 | 73 | java |
null | wildfly-main/weld/subsystem/src/test/java/org/jboss/as/weld/discovery/WeldClassFileServicesTest.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.discovery;
import java.io.IOException;
import java.lang.annotation.Target;
import java.lang.reflect.Modifier;
import jakarta.enterprise.inject.Vetoed;
import jakarta.inject.Inject;
import jakarta.inject.Named;
import org.jboss.as.weld.discovery.InnerClasses.InnerInterface;
import org.jboss.as.weld.discovery.vetoed.Bravo;
import org.jboss.weld.resources.spi.ClassFileInfo;
import org.jboss.weld.resources.spi.ClassFileServices;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
public class WeldClassFileServicesTest {
private static ClassFileInfo alpha;
private static ClassFileInfo abstractAlpha;
private static ClassFileInfo alphaImpl;
private static ClassFileInfo innerInterface;
private static ClassFileInfo bravo;
private static ClassFileInfo charlie;
@BeforeClass
public static void init() throws IOException {
ClassFileServices service = new WeldClassFileServices(IndexUtils.createIndex(Alpha.class, AlphaImpl.class, AbstractAlpha.class, InnerClasses.class,
Bravo.class, "org/jboss/as/weld/discovery/vetoed/package-info.class", Inject.class, Named.class, Charlie.class), Thread.currentThread()
.getContextClassLoader());
alpha = service.getClassFileInfo(Alpha.class.getName());
abstractAlpha = service.getClassFileInfo(AbstractAlpha.class.getName());
alphaImpl = service.getClassFileInfo(AlphaImpl.class.getName());
innerInterface = service.getClassFileInfo(InnerClasses.InnerInterface.class.getName());
bravo = service.getClassFileInfo(Bravo.class.getName());
charlie = service.getClassFileInfo(Charlie.class.getName());
}
@Test
public void testModifiers() throws IOException {
Assert.assertTrue(Modifier.isAbstract(alpha.getModifiers()));
Assert.assertTrue(Modifier.isAbstract(abstractAlpha.getModifiers()));
Assert.assertFalse(Modifier.isAbstract(alphaImpl.getModifiers()));
Assert.assertFalse(Modifier.isStatic(alpha.getModifiers()));
Assert.assertFalse(Modifier.isStatic(abstractAlpha.getModifiers()));
Assert.assertFalse(Modifier.isStatic(alphaImpl.getModifiers()));
}
@Test
public void testVeto() throws IOException {
Assert.assertTrue(alpha.isVetoed());
Assert.assertFalse(abstractAlpha.isVetoed());
Assert.assertFalse(alphaImpl.isVetoed());
Assert.assertTrue(bravo.isVetoed());
}
@Test
public void testSuperclassName() {
Assert.assertEquals(Object.class.getName(), alpha.getSuperclassName());
Assert.assertEquals(Object.class.getName(), abstractAlpha.getSuperclassName());
Assert.assertEquals(AbstractAlpha.class.getName(), alphaImpl.getSuperclassName());
}
@Test
public void testIsAssignableFrom() {
Assert.assertTrue(alpha.isAssignableFrom(AlphaImpl.class));
Assert.assertTrue(abstractAlpha.isAssignableFrom(AlphaImpl.class));
Assert.assertFalse(abstractAlpha.isAssignableFrom(Alpha.class));
Assert.assertTrue(innerInterface.isAssignableFrom(Bravo.class));
Assert.assertTrue(alphaImpl.isAssignableFrom(Bravo.class));
}
@Test
public void testIsAssignableTo() {
Assert.assertTrue(alphaImpl.isAssignableTo(Alpha.class));
Assert.assertTrue(abstractAlpha.isAssignableTo(Alpha.class));
Assert.assertFalse(abstractAlpha.isAssignableTo(AlphaImpl.class));
Assert.assertTrue(bravo.isAssignableTo(InnerInterface.class));
Assert.assertTrue(bravo.isAssignableTo(AbstractAlpha.class));
Assert.assertFalse(bravo.isAssignableTo(InnerClasses.class));
}
@Test
public void testIsAssignableToObject() {
Assert.assertTrue(alpha.isAssignableTo(Object.class));
Assert.assertTrue(abstractAlpha.isAssignableTo(Object.class));
Assert.assertTrue(alphaImpl.isAssignableTo(Object.class));
Assert.assertTrue(bravo.isAssignableTo(Object.class));
}
@Test
public void testIsAssignableFromObject() {
Assert.assertFalse(alpha.isAssignableFrom(Object.class));
Assert.assertFalse(abstractAlpha.isAssignableFrom(Object.class));
Assert.assertFalse(alphaImpl.isAssignableFrom(Object.class));
Assert.assertFalse(bravo.isAssignableFrom(Object.class));
}
@Test
public void testIsAnnotationDeclared() {
Assert.assertTrue(alpha.isAnnotationDeclared(Vetoed.class));
Assert.assertTrue(innerInterface.isAnnotationDeclared(Named.class));
Assert.assertFalse(bravo.isAnnotationDeclared(Vetoed.class));
Assert.assertFalse(bravo.isAnnotationDeclared(Named.class));
Assert.assertFalse(bravo.isAnnotationDeclared(Inject.class));
}
@Test
public void testContainsAnnotation() {
Assert.assertTrue(alpha.containsAnnotation(Vetoed.class));
Assert.assertTrue(innerInterface.containsAnnotation(Named.class));
Assert.assertFalse(bravo.containsAnnotation(Vetoed.class));
Assert.assertFalse(bravo.containsAnnotation(Named.class));
Assert.assertTrue(bravo.containsAnnotation(Inject.class));
}
@Test
public void testContainsAnnotationReflectionFallback() {
Assert.assertTrue(charlie.containsAnnotation(Target.class));
Assert.assertTrue(bravo.containsAnnotation(Target.class));
}
}
| 6,417 | 42.659864 | 155 | java |
null | wildfly-main/weld/subsystem/src/test/java/org/jboss/as/weld/discovery/AnnotationNotInIndex.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.discovery;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Target({ TYPE, METHOD, PARAMETER, FIELD })
@Retention(RUNTIME)
public @interface AnnotationNotInIndex {
}
| 1,519 | 39 | 73 | java |
null | wildfly-main/weld/subsystem/src/test/java/org/jboss/as/weld/discovery/vetoed/package-info.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
@jakarta.enterprise.inject.Vetoed
package org.jboss.as.weld.discovery.vetoed;
| 1,094 | 44.625 | 73 | java |
null | wildfly-main/weld/subsystem/src/test/java/org/jboss/as/weld/discovery/vetoed/Bravo.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.discovery.vetoed;
import jakarta.inject.Inject;
import org.jboss.as.weld.discovery.AlphaImpl;
import org.jboss.as.weld.discovery.InnerClasses.InnerInterface;
public class Bravo extends AlphaImpl implements InnerInterface {
@Inject
Long charlie;
}
| 1,302 | 36.228571 | 73 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/WeldSubsystem20Parser.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld;
import org.jboss.as.controller.PersistentResourceXMLDescription;
import org.jboss.as.controller.PersistentResourceXMLParser;
class WeldSubsystem20Parser extends PersistentResourceXMLParser {
public static final String NAMESPACE = "urn:jboss:domain:weld:2.0";
static final WeldSubsystem20Parser INSTANCE = new WeldSubsystem20Parser();
private static final PersistentResourceXMLDescription xmlDescription;
static {
xmlDescription = PersistentResourceXMLDescription.builder(WeldExtension.PATH_SUBSYSTEM, NAMESPACE)
.addAttributes(WeldResourceDefinition.NON_PORTABLE_MODE_ATTRIBUTE, WeldResourceDefinition.REQUIRE_BEAN_DESCRIPTOR_ATTRIBUTE)
.build();
}
private WeldSubsystem20Parser() {
}
@Override
public PersistentResourceXMLDescription getParserDescription() {
return xmlDescription;
}
}
| 1,925 | 39.125 | 140 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/WeldSubsystem50Parser.java | package org.jboss.as.weld;
import org.jboss.as.controller.PersistentResourceXMLDescription;
import org.jboss.as.controller.PersistentResourceXMLParser;
public class WeldSubsystem50Parser extends PersistentResourceXMLParser {
public static final String NAMESPACE = "urn:jboss:domain:weld:5.0";
static final WeldSubsystem50Parser INSTANCE = new WeldSubsystem50Parser();
private static final PersistentResourceXMLDescription xmlDescription;
static {
xmlDescription = PersistentResourceXMLDescription.builder(WeldExtension.PATH_SUBSYSTEM, NAMESPACE)
.addAttributes(WeldResourceDefinition.NON_PORTABLE_MODE_ATTRIBUTE, WeldResourceDefinition.REQUIRE_BEAN_DESCRIPTOR_ATTRIBUTE,
WeldResourceDefinition.DEVELOPMENT_MODE_ATTRIBUTE, WeldResourceDefinition.THREAD_POOL_SIZE_ATTRIBUTE,
WeldResourceDefinition.LEGACY_EMPTY_BEANS_XML_TREATMENT_ATTRIBUTE)
.build();
}
private WeldSubsystem50Parser() {
}
@Override
public PersistentResourceXMLDescription getParserDescription() {
return xmlDescription;
}
}
| 1,132 | 39.464286 | 140 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/WeldResourceDefinition.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld;
import static org.jboss.as.weld.Capabilities.WELD_CAPABILITY_NAME;
import java.util.Arrays;
import java.util.Collection;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.PersistentResourceDefinition;
import org.jboss.as.controller.ReloadRequiredRemoveStepHandler;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.capability.RuntimeCapability;
import org.jboss.as.controller.operations.validation.IntRangeValidator;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.RuntimePackageDependency;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
/**
* Resource definition for Weld subsystem
*
* @author Jozef Hartinger
*
*/
class WeldResourceDefinition extends PersistentResourceDefinition {
static final RuntimeCapability<WeldCapability> WELD_CAPABILITY = RuntimeCapability.Builder
.of(WELD_CAPABILITY_NAME, WeldCapabilityImpl.INSTANCE)
.build();
static final String REQUIRE_BEAN_DESCRIPTOR_ATTRIBUTE_NAME = "require-bean-descriptor";
static final String LEGACY_EMPTY_BEANS_XML_TREATMENT_ATTRIBUTE_NAME = "legacy-empty-beans-xml-treatment";
static final String NON_PORTABLE_MODE_ATTRIBUTE_NAME = "non-portable-mode";
static final String DEVELOPMENT_MODE_ATTRIBUTE_NAME = "development-mode";
static final String THREAD_POOL_SIZE = "thread-pool-size";
static final SimpleAttributeDefinition REQUIRE_BEAN_DESCRIPTOR_ATTRIBUTE =
new SimpleAttributeDefinitionBuilder(REQUIRE_BEAN_DESCRIPTOR_ATTRIBUTE_NAME, ModelType.BOOLEAN, true)
.setAllowExpression(true)
.setDefaultValue(ModelNode.FALSE)
.setRestartAllServices()
.build();
static final SimpleAttributeDefinition LEGACY_EMPTY_BEANS_XML_TREATMENT_ATTRIBUTE =
new SimpleAttributeDefinitionBuilder(LEGACY_EMPTY_BEANS_XML_TREATMENT_ATTRIBUTE_NAME, ModelType.BOOLEAN, true)
.setAllowExpression(true)
.setDefaultValue(ModelNode.FALSE)
.setRestartAllServices()
.build();
static final SimpleAttributeDefinition NON_PORTABLE_MODE_ATTRIBUTE =
new SimpleAttributeDefinitionBuilder(NON_PORTABLE_MODE_ATTRIBUTE_NAME, ModelType.BOOLEAN, true)
.setAllowExpression(true)
.setDefaultValue(ModelNode.FALSE)
.setRestartAllServices()
.build();
static final SimpleAttributeDefinition DEVELOPMENT_MODE_ATTRIBUTE =
new SimpleAttributeDefinitionBuilder(DEVELOPMENT_MODE_ATTRIBUTE_NAME, ModelType.BOOLEAN, true)
.setAllowExpression(true)
.setDefaultValue(ModelNode.FALSE)
.setRestartAllServices()
.setDeprecated(ModelVersion.create(5, 0))
.build();
static final SimpleAttributeDefinition THREAD_POOL_SIZE_ATTRIBUTE =
new SimpleAttributeDefinitionBuilder(THREAD_POOL_SIZE, ModelType.INT, true)
.setAllowExpression(true)
.setValidator(new IntRangeValidator(1))
.setRestartAllServices()
.build();
private static final AttributeDefinition[] ATTRIBUTES = new AttributeDefinition[] { REQUIRE_BEAN_DESCRIPTOR_ATTRIBUTE, LEGACY_EMPTY_BEANS_XML_TREATMENT_ATTRIBUTE, NON_PORTABLE_MODE_ATTRIBUTE, DEVELOPMENT_MODE_ATTRIBUTE, THREAD_POOL_SIZE_ATTRIBUTE };
WeldResourceDefinition() {
super(new SimpleResourceDefinition.Parameters(WeldExtension.PATH_SUBSYSTEM, WeldExtension.getResourceDescriptionResolver())
.setAddHandler(new WeldSubsystemAdd(ATTRIBUTES))
.setRemoveHandler(ReloadRequiredRemoveStepHandler.INSTANCE)
.setCapabilities(WELD_CAPABILITY)
);
}
@Override
public Collection<AttributeDefinition> getAttributes() {
return Arrays.asList(ATTRIBUTES);
}
@Override
public void registerAdditionalRuntimePackages(ManagementResourceRegistration resourceRegistration) {
resourceRegistration.registerAdditionalRuntimePackages(RuntimePackageDependency.passive("org.jboss.as.weld.ejb"),
RuntimePackageDependency.passive("org.jboss.as.weld.jpa"),
RuntimePackageDependency.passive("org.jboss.as.weld.beanvalidation"),
RuntimePackageDependency.passive("org.jboss.as.weld.webservices"),
RuntimePackageDependency.passive("org.jboss.as.weld.transactions"),
RuntimePackageDependency.required("jakarta.inject.api"),
RuntimePackageDependency.required("jakarta.persistence.api"),
RuntimePackageDependency.required("org.hibernate.validator.cdi"));
}
}
| 5,991 | 47.715447 | 253 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/WeldJBossAll11Parser.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld;
import static org.jboss.as.weld.WeldResourceDefinition.DEVELOPMENT_MODE_ATTRIBUTE_NAME;
import static org.jboss.as.weld.WeldResourceDefinition.LEGACY_EMPTY_BEANS_XML_TREATMENT_ATTRIBUTE_NAME;
import static org.jboss.as.weld.WeldResourceDefinition.NON_PORTABLE_MODE_ATTRIBUTE_NAME;
import static org.jboss.as.weld.WeldResourceDefinition.REQUIRE_BEAN_DESCRIPTOR_ATTRIBUTE_NAME;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.jbossallxml.JBossAllXMLParser;
import org.jboss.staxmapper.XMLExtendedStreamReader;
/**
* Parses <code>jboss-all.xml</code> and creates {@link WeldJBossAllConfiguration} holding the parsed configuration.
*
* @author Jozef Hartinger
*
*/
class WeldJBossAll11Parser extends AbstractWeldJBossAllParser implements JBossAllXMLParser<WeldJBossAllConfiguration> {
public static final String NAMESPACE = "urn:jboss:weld:1.1";
public static final QName ROOT_ELEMENT = new QName(NAMESPACE, "weld");
public static final WeldJBossAll11Parser INSTANCE = new WeldJBossAll11Parser();
private WeldJBossAll11Parser() {
}
@Override
public WeldJBossAllConfiguration parse(XMLExtendedStreamReader reader, DeploymentUnit deploymentUnit) throws XMLStreamException {
Boolean requireBeanDescriptor = getAttributeAsBoolean(reader, REQUIRE_BEAN_DESCRIPTOR_ATTRIBUTE_NAME);
Boolean nonPortableMode = getAttributeAsBoolean(reader, NON_PORTABLE_MODE_ATTRIBUTE_NAME);
Boolean developmentMode = getAttributeAsBoolean(reader, DEVELOPMENT_MODE_ATTRIBUTE_NAME);
Boolean legacyEmptyBeansXmlTreatment = getAttributeAsBoolean(reader, LEGACY_EMPTY_BEANS_XML_TREATMENT_ATTRIBUTE_NAME);
super.parseWeldElement(reader);
return new WeldJBossAllConfiguration(requireBeanDescriptor, nonPortableMode, developmentMode, legacyEmptyBeansXmlTreatment); }
}
| 2,989 | 48.016393 | 137 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/WeldSubsystem40Parser.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2017, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld;
import org.jboss.as.controller.PersistentResourceXMLDescription;
import org.jboss.as.controller.PersistentResourceXMLParser;
class WeldSubsystem40Parser extends PersistentResourceXMLParser {
public static final String NAMESPACE = "urn:jboss:domain:weld:4.0";
static final WeldSubsystem40Parser INSTANCE = new WeldSubsystem40Parser();
private static final PersistentResourceXMLDescription xmlDescription;
static {
xmlDescription = PersistentResourceXMLDescription.builder(WeldExtension.PATH_SUBSYSTEM, NAMESPACE)
.addAttributes(WeldResourceDefinition.NON_PORTABLE_MODE_ATTRIBUTE, WeldResourceDefinition.REQUIRE_BEAN_DESCRIPTOR_ATTRIBUTE,
WeldResourceDefinition.DEVELOPMENT_MODE_ATTRIBUTE, WeldResourceDefinition.THREAD_POOL_SIZE_ATTRIBUTE)
.build();
}
private WeldSubsystem40Parser() {
}
@Override
public PersistentResourceXMLDescription getParserDescription() {
return xmlDescription;
}
}
| 2,050 | 41.729167 | 140 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/WeldBootstrapService.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld;
import org.jboss.as.weld.deployment.BeanDeploymentArchiveImpl;
import org.jboss.as.weld.deployment.WeldDeployment;
import org.jboss.as.weld.logging.WeldLogger;
import org.jboss.as.weld.services.ModuleGroupSingletonProvider;
import org.jboss.msc.Service;
import org.jboss.msc.service.LifecycleEvent;
import org.jboss.msc.service.LifecycleListener;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.weld.Container;
import org.jboss.weld.ContainerState;
import org.jboss.weld.bootstrap.WeldBootstrap;
import org.jboss.weld.bootstrap.api.Environment;
import org.jboss.weld.bootstrap.spi.BeanDeploymentArchive;
import org.jboss.weld.manager.BeanManagerImpl;
import org.jboss.weld.manager.api.ExecutorServices;
import org.jboss.weld.security.spi.SecurityServices;
import org.jboss.weld.transaction.spi.TransactionServices;
import org.wildfly.security.manager.WildFlySecurityManager;
import jakarta.enterprise.inject.spi.BeanManager;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Supplier;
/**
* Provides the initial bootstrap of the Weld container. This does not actually finish starting the container, merely gets it to
* the point that the bean manager is available.
*
* @author Stuart Douglas
* @author <a href="mailto:[email protected]">Richard Opalka</a>
*/
public class WeldBootstrapService implements Service {
/**
* The service name that external services depend on
*/
public static final ServiceName SERVICE_NAME = ServiceName.of("WeldBootstrapService");
/**
* The actual service name the bootstrap service is installed under.
* <p>
* The reasons for this dual service name setup is kinda complex, and relates to https://issues.redhat.com/browse/JBEAP-18634
* Because Weld cannot be restarted if an attempt is made to restart the service then we need to bail out and restart
* the whole deployment.
* <p>
* If we just do a check in the start method that looks like:
* if (restartRequired) {
* doRestart();
* return;
* }
* Then the service startup will technically complete successfully, and dependent services can still start before
* the restart actually takes effect (as MSC is directional, it keep starting services that have all their dependencies
* met before it start to take services down).
* <p>
* To get around this we use two different service names, with the service that other services depend on only being
* installed at the end of the start() method. This means that in the case of a restart this will not be installed,
* so no dependent services will be started as they are missing their dependency.
*/
public static final ServiceName INTERNAL_SERVICE_NAME = ServiceName.of("WeldBootstrapServiceInternal");
private final WeldBootstrap bootstrap;
private final WeldDeployment deployment;
private final Environment environment;
private final Map<String, BeanDeploymentArchive> beanDeploymentArchives;
private final BeanDeploymentArchiveImpl rootBeanDeploymentArchive;
private final String deploymentName;
private final Consumer<WeldBootstrapService> weldBootstrapServiceConsumer;
private final Supplier<ExecutorServices> executorServicesSupplier;
private final Supplier<ExecutorService> serverExecutorSupplier;
private final Supplier<SecurityServices> securityServicesSupplier;
private final Supplier<TransactionServices> weldTransactionServicesSupplier;
private final ServiceName deploymentServiceName;
private final ServiceName weldBootstrapServiceName;
private volatile boolean started;
private volatile ServiceController<?> controller;
private final AtomicBoolean runOnce = new AtomicBoolean();
public WeldBootstrapService(final WeldDeployment deployment, final Environment environment, final String deploymentName,
final Consumer<WeldBootstrapService> weldBootstrapServiceConsumer,
final Supplier<ExecutorServices> executorServicesSupplier,
final Supplier<ExecutorService> serverExecutorSupplier,
final Supplier<SecurityServices> securityServicesSupplier,
final Supplier<TransactionServices> weldTransactionServicesSupplier,
ServiceName deploymentServiceName, ServiceName weldBootstrapServiceName) {
this.deployment = deployment;
this.environment = environment;
this.deploymentName = deploymentName;
this.weldBootstrapServiceConsumer = weldBootstrapServiceConsumer;
this.executorServicesSupplier = executorServicesSupplier;
this.serverExecutorSupplier = serverExecutorSupplier;
this.securityServicesSupplier = securityServicesSupplier;
this.weldTransactionServicesSupplier = weldTransactionServicesSupplier;
this.deploymentServiceName = deploymentServiceName;
this.weldBootstrapServiceName = weldBootstrapServiceName;
this.bootstrap = new WeldBootstrap();
Map<String, BeanDeploymentArchive> bdas = new HashMap<String, BeanDeploymentArchive>();
BeanDeploymentArchiveImpl rootBeanDeploymentArchive = null;
for (BeanDeploymentArchive archive : deployment.getBeanDeploymentArchives()) {
bdas.put(archive.getId(), archive);
if (archive instanceof BeanDeploymentArchiveImpl) {
BeanDeploymentArchiveImpl bda = (BeanDeploymentArchiveImpl) archive;
if (bda.isRoot()) {
rootBeanDeploymentArchive = bda;
}
}
}
this.rootBeanDeploymentArchive = rootBeanDeploymentArchive;
this.beanDeploymentArchives = Collections.unmodifiableMap(bdas);
}
/**
* Starts the weld container
*
* @throws IllegalStateException if the container is already running
*/
public synchronized void start(final StartContext context) {
if (!runOnce.compareAndSet(false, true)) {
ServiceController<?> controller = context.getController().getServiceContainer().getService(deploymentServiceName);
controller.addListener(new LifecycleListener() {
@Override
public void handleEvent(final ServiceController<?> controller, final LifecycleEvent event) {
if (event == LifecycleEvent.DOWN) {
controller.setMode(ServiceController.Mode.ACTIVE);
controller.removeListener(this);
}
}
});
controller.setMode(ServiceController.Mode.NEVER);
return;
}
if (started) {
throw WeldLogger.ROOT_LOGGER.alreadyRunning("WeldContainer");
}
started = true;
WeldLogger.DEPLOYMENT_LOGGER.startingWeldService(deploymentName);
// set up injected services
addWeldService(SecurityServices.class, securityServicesSupplier.get());
TransactionServices transactionServices = weldTransactionServicesSupplier != null ? weldTransactionServicesSupplier.get() : null;
if (transactionServices != null) {
addWeldService(TransactionServices.class, transactionServices);
}
if (!deployment.getServices().contains(ExecutorServices.class)) {
addWeldService(ExecutorServices.class, executorServicesSupplier.get());
}
ModuleGroupSingletonProvider.addClassLoaders(deployment.getModule().getClassLoader(),
deployment.getSubDeploymentClassLoaders());
ClassLoader oldTccl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
try {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(deployment.getModule().getClassLoader());
bootstrap.startContainer(deploymentName, environment, deployment);
WeldProvider.containerInitialized(Container.instance(deploymentName), getBeanManager(), deployment);
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTccl);
}
weldBootstrapServiceConsumer.accept(this);
//this is the actual service that clients depend on
//we install it here so that if a restart needs to happen all our dependants won't be able to start
final ServiceBuilder<?> weldBootstrapServiceBuilder = context.getChildTarget().addService(weldBootstrapServiceName);
Consumer<WeldBootstrapService> provider = weldBootstrapServiceBuilder.provides(weldBootstrapServiceName);
weldBootstrapServiceBuilder.setInstance(new Service() {
@Override
public void start(StartContext context) throws StartException {
provider.accept(WeldBootstrapService.this);
}
@Override
public void stop(StopContext context) {
context.getController().setMode(ServiceController.Mode.REMOVE);
}
});
weldBootstrapServiceBuilder.install();
controller = context.getController();
}
/**
* This is a no-op if {@link WeldStartService#start(StartContext)} completes normally and the shutdown is performed in
* {@link WeldStartService#stop(org.jboss.msc.service.StopContext)}.
*/
public synchronized void stop(final StopContext context) {
weldBootstrapServiceConsumer.accept(null);
if (started) {
// WeldStartService#stop() not completed - attempt to perform the container cleanup
final Container container = Container.instance(deploymentName);
if (container != null && !ContainerState.SHUTDOWN.equals(container.getState())) {
context.asynchronous();
final ExecutorService executorService = serverExecutorSupplier.get();
final Runnable task = new Runnable() {
@Override
public void run() {
WeldLogger.DEPLOYMENT_LOGGER.debugf("Weld container cleanup for deployment %s", deploymentName);
ClassLoader oldTccl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
try {
WildFlySecurityManager
.setCurrentContextClassLoaderPrivileged(deployment.getModule().getClassLoader());
WeldProvider.containerShutDown(container);
container.setState(ContainerState.SHUTDOWN);
container.cleanup();
startServiceShutdown();
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTccl);
ModuleGroupSingletonProvider.removeClassLoader(deployment.getModule().getClassLoader());
context.complete();
}
}
};
try {
executorService.execute(task);
} catch (RejectedExecutionException e) {
task.run();
}
}
}
}
/**
* Gets the {@link BeanManager} for a given bean deployment archive id.
*
* @throws IllegalStateException if the container is not running
* @throws IllegalArgumentException if the bean deployment archive id is not found
*/
public BeanManagerImpl getBeanManager(String beanArchiveId) {
if (!started) {
throw WeldLogger.ROOT_LOGGER.notStarted("WeldContainer");
}
BeanDeploymentArchive beanDeploymentArchive = beanDeploymentArchives.get(beanArchiveId);
if (beanDeploymentArchive == null) {
throw WeldLogger.ROOT_LOGGER.beanDeploymentNotFound(beanArchiveId);
}
return bootstrap.getManager(beanDeploymentArchive);
}
/**
* Adds a {@link Service} to the deployment. This method must not be called after the container has started
*/
public <T extends org.jboss.weld.bootstrap.api.Service> void addWeldService(Class<T> type, T service) {
deployment.addWeldService(type, service);
}
/**
* Gets the {@link BeanManager} linked to the root bean deployment archive. This BeanManager has access to all beans in a
* deployment
*
* @throws IllegalStateException if the container is not running
*/
public BeanManagerImpl getBeanManager() {
if (!started) {
throw WeldLogger.ROOT_LOGGER.notStarted("WeldContainer");
}
return bootstrap.getManager(rootBeanDeploymentArchive);
}
/**
* get all beans deployment archives in the deployment
*/
public Set<BeanDeploymentArchive> getBeanDeploymentArchives() {
return new HashSet<BeanDeploymentArchive>(beanDeploymentArchives.values());
}
public boolean isStarted() {
return started;
}
void startServiceShutdown() {
//the start service has been shutdown, which means either we are being shutdown/undeployed
//or we are going to need to bounce the whole deployment
this.started = false;
if (controller.getServiceContainer().isShutdown()) {
//container is being shutdown, no action required
return;
}
ServiceController<?> deploymentController = controller.getServiceContainer().getService(deploymentServiceName);
if (deploymentController.getMode() != ServiceController.Mode.ACTIVE) {
//deployment is not active, no action required
return;
}
//add a listener to tentatively 'bounce' this service
//if the service does actually restart then this will trigger a full deployment restart
//we do it this way as we don't have visibility into MSC in the general sense
//so we don't really know if this service is supposed to go away
//this 'potential bounce' is hard to do in a non-racey manner
//we need to add the listener first, but the listener may be invoked before the CAS to never
CompletableFuture<Boolean> attemptingBounce = new CompletableFuture();
try {
CompletableFuture<Boolean> listenerDone = new CompletableFuture<>();
LifecycleListener listener = new LifecycleListener() {
@Override
public void handleEvent(final ServiceController<?> controller, final LifecycleEvent event) {
try {
try {
if (controller.getServiceContainer().isShutdown() || !attemptingBounce.get()) {
controller.removeListener(this);
return;
}
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
if (deploymentController.getMode() != ServiceController.Mode.ACTIVE ||
controller.getMode() == ServiceController.Mode.REMOVE) {
return;
}
if (event == LifecycleEvent.DOWN) {
controller.removeListener(this);
do {
if (controller.getMode() != ServiceController.Mode.NEVER) {
return;
}
} while (!controller.compareAndSetMode(ServiceController.Mode.NEVER, ServiceController.Mode.ACTIVE));
}
} finally {
listenerDone.complete(true);
}
}
};
//
controller.getServiceContainer().addService(controller.getName().append("fakeStabilityService")).setInstance(new Service() {
@Override
public void start(StartContext context) throws StartException {
context.asynchronous();
listenerDone.handle(new BiFunction<Boolean, Throwable, Object>() {
@Override
public Object apply(Boolean aBoolean, Throwable throwable) {
context.getController().setMode(ServiceController.Mode.REMOVE);
context.complete();
return null;
}
});
}
@Override
public void stop(StopContext context) {
}
}).install();
controller.addListener(listener);
if (!controller.compareAndSetMode(ServiceController.Mode.ACTIVE, ServiceController.Mode.NEVER)) {
controller.removeListener(listener);
attemptingBounce.complete(false);
listenerDone.complete(false);
} else {
attemptingBounce.complete(true);
}
} catch (Throwable t) {
//should never happen
//but lets be safe
attemptingBounce.completeExceptionally(t);
throw new RuntimeException(t);
}
}
WeldDeployment getDeployment() {
return deployment;
}
String getDeploymentName() {
return deploymentName;
}
WeldBootstrap getBootstrap() {
return bootstrap;
}
}
| 19,272 | 46.237745 | 137 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/WeldSubsystemAdd.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld;
import static org.jboss.as.weld.WeldResourceDefinition.LEGACY_EMPTY_BEANS_XML_TREATMENT_ATTRIBUTE;
import static org.jboss.as.weld.WeldResourceDefinition.REQUIRE_BEAN_DESCRIPTOR_ATTRIBUTE;
import java.util.ServiceLoader;
import java.util.function.Consumer;
import org.jboss.as.controller.AbstractBoottimeAddStepHandler;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.controller.registry.Resource.NoSuchResourceException;
import org.jboss.as.server.AbstractDeploymentChainStep;
import org.jboss.as.server.DeploymentProcessorTarget;
import org.jboss.as.server.deployment.Phase;
import org.jboss.as.server.deployment.jbossallxml.JBossAllXmlParserRegisteringProcessor;
import org.jboss.as.weld.deployment.CdiAnnotationProcessor;
import org.jboss.as.weld.deployment.processors.BeanArchiveProcessor;
import org.jboss.as.weld.deployment.processors.BeanDefiningAnnotationProcessor;
import org.jboss.as.weld.deployment.processors.BeansXmlProcessor;
import org.jboss.as.weld.deployment.processors.EarApplicationScopedObserverMethodProcessor;
import org.jboss.as.weld.deployment.processors.ExternalBeanArchiveProcessor;
import org.jboss.as.weld.deployment.processors.SimpleEnvEntryCdiResourceInjectionProcessor;
import org.jboss.as.weld.deployment.processors.WebIntegrationProcessor;
import org.jboss.as.weld.deployment.processors.WeldBeanManagerServiceProcessor;
import org.jboss.as.weld.deployment.processors.WeldComponentIntegrationProcessor;
import org.jboss.as.weld.deployment.processors.WeldConfigurationProcessor;
import org.jboss.as.weld.deployment.processors.WeldDependencyProcessor;
import org.jboss.as.weld.deployment.processors.WeldDeploymentCleanupProcessor;
import org.jboss.as.weld.deployment.processors.WeldDeploymentProcessor;
import org.jboss.as.weld.deployment.processors.WeldImplicitDeploymentProcessor;
import org.jboss.as.weld.deployment.processors.WeldPortableExtensionProcessor;
import org.jboss.as.weld.services.TCCLSingletonService;
import org.jboss.as.weld.services.bootstrap.WeldExecutorServices;
import org.jboss.as.weld.spi.DeploymentUnitProcessorProvider;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceController.Mode;
import org.jboss.weld.manager.api.ExecutorServices;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* The weld subsystem add update handler.
*
* @author Stuart Douglas
* @author Emanuel Muckenhuber
* @author <a href="mailto:[email protected]">Tomasz Adamski</a>
*/
class WeldSubsystemAdd extends AbstractBoottimeAddStepHandler {
WeldSubsystemAdd(AttributeDefinition... attributes) {
super(attributes);
}
@Override
protected void performBoottime(final OperationContext context, ModelNode operation,Resource resource) throws OperationFailedException {
final ModelNode model = resource.getModel();
final boolean requireBeanDescriptor = REQUIRE_BEAN_DESCRIPTOR_ATTRIBUTE.resolveModelAttribute(context, model).asBoolean();
final boolean legacyEmptyBeansXmlTreatment = LEGACY_EMPTY_BEANS_XML_TREATMENT_ATTRIBUTE.resolveModelAttribute(context, model).asBoolean();
final boolean nonPortableMode = WeldResourceDefinition.NON_PORTABLE_MODE_ATTRIBUTE.resolveModelAttribute(context, model).asBoolean();
final boolean developmentMode = WeldResourceDefinition.DEVELOPMENT_MODE_ATTRIBUTE.resolveModelAttribute(context, model).asBoolean();
final int threadPoolSize = WeldResourceDefinition.THREAD_POOL_SIZE_ATTRIBUTE.resolveModelAttribute(context, model)
.asInt(WeldExecutorServices.DEFAULT_BOUND);
context.addStep(new AbstractDeploymentChainStep() {
@Override
protected void execute(DeploymentProcessorTarget processorTarget) {
final JBossAllXmlParserRegisteringProcessor<?> jbossAllParsers = JBossAllXmlParserRegisteringProcessor.builder()
.addParser(WeldJBossAll10Parser.ROOT_ELEMENT, WeldJBossAllConfiguration.ATTACHMENT_KEY, WeldJBossAll10Parser.INSTANCE)
.addParser(WeldJBossAll11Parser.ROOT_ELEMENT, WeldJBossAllConfiguration.ATTACHMENT_KEY, WeldJBossAll11Parser.INSTANCE)
.build();
processorTarget.addDeploymentProcessor(WeldExtension.SUBSYSTEM_NAME, Phase.STRUCTURE, Phase.STRUCTURE_REGISTER_JBOSS_ALL_WELD, jbossAllParsers);
processorTarget.addDeploymentProcessor(WeldExtension.SUBSYSTEM_NAME, Phase.PARSE, Phase.PARSE_WELD_CONFIGURATION, new WeldConfigurationProcessor(requireBeanDescriptor, nonPortableMode, developmentMode, legacyEmptyBeansXmlTreatment));
processorTarget.addDeploymentProcessor(WeldExtension.SUBSYSTEM_NAME, Phase.PARSE, Phase.PARSE_CDI_ANNOTATIONS, new CdiAnnotationProcessor());
processorTarget.addDeploymentProcessor(WeldExtension.SUBSYSTEM_NAME, Phase.PARSE, Phase.PARSE_CDI_BEAN_DEFINING_ANNOTATIONS, new BeanDefiningAnnotationProcessor());
processorTarget.addDeploymentProcessor(WeldExtension.SUBSYSTEM_NAME, Phase.PARSE, Phase.PARSE_WELD_DEPLOYMENT, new BeansXmlProcessor());
processorTarget.addDeploymentProcessor(WeldExtension.SUBSYSTEM_NAME, Phase.PARSE, Phase.PARSE_WELD_IMPLICIT_DEPLOYMENT_DETECTION, new WeldImplicitDeploymentProcessor());
processorTarget.addDeploymentProcessor(WeldExtension.SUBSYSTEM_NAME, Phase.DEPENDENCIES, Phase.DEPENDENCIES_WELD, new WeldDependencyProcessor());
processorTarget.addDeploymentProcessor(WeldExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_WELD_WEB_INTEGRATION, new WebIntegrationProcessor());
processorTarget.addDeploymentProcessor(WeldExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_WELD_BEAN_ARCHIVE, new BeanArchiveProcessor());
processorTarget.addDeploymentProcessor(WeldExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_WELD_EXTERNAL_BEAN_ARCHIVE, new ExternalBeanArchiveProcessor());
processorTarget.addDeploymentProcessor(WeldExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_WELD_PORTABLE_EXTENSIONS, new WeldPortableExtensionProcessor());
// TODO add processor priority to Phase
processorTarget.addDeploymentProcessor(WeldExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, 0x0F10, new EarApplicationScopedObserverMethodProcessor());
processorTarget.addDeploymentProcessor(WeldExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_WELD_COMPONENT_INTEGRATION, new WeldComponentIntegrationProcessor());
// TODO add processor priority to Phase
processorTarget.addDeploymentProcessor(WeldExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_ENV_ENTRY + 1, new SimpleEnvEntryCdiResourceInjectionProcessor());
processorTarget.addDeploymentProcessor(WeldExtension.SUBSYSTEM_NAME, Phase.INSTALL, Phase.INSTALL_WELD_DEPLOYMENT, new WeldDeploymentProcessor(checkJtsEnabled(context)));
processorTarget.addDeploymentProcessor(WeldExtension.SUBSYSTEM_NAME, Phase.INSTALL, Phase.INSTALL_WELD_BEAN_MANAGER, new WeldBeanManagerServiceProcessor());
// note that we want to go one step before Phase.CLEANUP_EE because we use metadata that it then cleans up
processorTarget.addDeploymentProcessor(WeldExtension.SUBSYSTEM_NAME, Phase.CLEANUP, Phase.CLEANUP_EE - 1, new WeldDeploymentCleanupProcessor());
// Add additional deployment processors
ServiceLoader<DeploymentUnitProcessorProvider> processorProviders = ServiceLoader.load(DeploymentUnitProcessorProvider.class,
WildFlySecurityManager.getClassLoaderPrivileged(WeldSubsystemAdd.class));
for (DeploymentUnitProcessorProvider provider : processorProviders) {
processorTarget.addDeploymentProcessor(WeldExtension.SUBSYSTEM_NAME, provider.getPhase(), provider.getPriority(), provider.getProcessor());
}
}
}, OperationContext.Stage.RUNTIME);
context.getServiceTarget().addService(TCCLSingletonService.SERVICE_NAME).setInstance(new TCCLSingletonService()).setInitialMode(Mode.ON_DEMAND).install();
ServiceBuilder<?> builder = context.getServiceTarget().addService(WeldExecutorServices.SERVICE_NAME);
final Consumer<ExecutorServices> executorServicesConsumer = builder.provides(WeldExecutorServices.SERVICE_NAME);
builder.setInstance(new WeldExecutorServices(executorServicesConsumer, threadPoolSize));
builder.setInitialMode(Mode.ON_DEMAND);
builder.install();
}
// Synchronization objects created by iiop Jakarta Enterprise Beans beans require wrapping by JTSSychronizationWrapper to work correctly
// (WFLY-3538). This hack is used obtain jts configuration in order to avoid doing this in non-jts environments when it is
// not necessary.
private boolean checkJtsEnabled(final OperationContext context) {
try {
final ModelNode jtsNode = context.readResourceFromRoot(PathAddress.pathAddress("subsystem", "transactions"), false)
.getModel().get("jts");
return jtsNode.isDefined() ? jtsNode.asBoolean() : false;
} catch (NoSuchResourceException ex) {
return false;
}
}
}
| 10,657 | 70.053333 | 249 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/WeldSubsystem10Parser.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoAttributes;
import static org.jboss.as.controller.parsing.ParseUtils.requireNoContent;
import java.util.List;
import javax.xml.stream.XMLStreamException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.XMLElementReader;
import org.jboss.staxmapper.XMLExtendedStreamReader;
class WeldSubsystem10Parser implements XMLElementReader<List<ModelNode>> {
public static final String NAMESPACE = "urn:jboss:domain:weld:1.0";
static final WeldSubsystem10Parser INSTANCE = new WeldSubsystem10Parser();
private WeldSubsystem10Parser() {
}
/** {@inheritDoc} */
@Override
public void readElement(final XMLExtendedStreamReader reader, final List<ModelNode> list) throws XMLStreamException {
// Require no attributes or content
requireNoAttributes(reader);
requireNoContent(reader);
list.add(Util.createAddOperation(PathAddress.pathAddress(WeldExtension.PATH_SUBSYSTEM)));
}
} | 2,152 | 39.622642 | 121 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/WeldProvider.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import jakarta.enterprise.inject.spi.BeanManager;
import jakarta.enterprise.inject.spi.CDI;
import jakarta.enterprise.inject.spi.CDIProvider;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.jboss.as.weld.deployment.WeldDeployment;
import org.jboss.as.weld.logging.WeldLogger;
import org.jboss.as.weld.services.ModuleGroupSingletonProvider;
import org.jboss.as.weld.util.Reflections;
import org.jboss.weld.AbstractCDI;
import org.jboss.weld.Container;
import org.jboss.weld.ContainerState;
import org.jboss.weld.bean.builtin.BeanManagerProxy;
import org.jboss.weld.bootstrap.spi.BeanDeploymentArchive;
import org.jboss.weld.logging.BeanManagerLogger;
import org.jboss.weld.manager.BeanManagerImpl;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* Service provider for {@link CDI}.
*
* @author Jozef Hartinger
*
*/
public class WeldProvider implements CDIProvider {
private static final ConcurrentMap<Container, CdiImpl> containers = new ConcurrentHashMap<>();
static void containerInitialized(Container container, BeanManagerImpl rootBeanManager, WeldDeployment deployment) {
containers.put(container, new WeldProvider.CdiImpl(container, new BeanManagerProxy(rootBeanManager), deployment));
}
static void containerShutDown(Container container) {
containers.remove(container);
}
@Override
public CDI<Object> getCDI() {
if (ModuleGroupSingletonProvider.deploymentClassLoaders.isEmpty()) {
throw WeldLogger.ROOT_LOGGER.weldNotInitialized();
}
final Container container = Container.instance();
checkContainerState(container);
return containers.get(container);
}
private static void checkContainerState(Container container) {
ContainerState state = container.getState();
if (state.equals(ContainerState.STOPPED) || state.equals(ContainerState.SHUTDOWN)) {
throw BeanManagerLogger.LOG.beanManagerNotAvailable();
}
}
private static class CdiImpl extends AbstractCDI<Object> {
private final Container container;
private final BeanManagerProxy rootBeanManager;
private final WeldDeployment deployment;
public CdiImpl(Container container, BeanManagerProxy rootBeanManager, WeldDeployment deployment) {
this.container = container;
this.rootBeanManager = rootBeanManager;
this.deployment = deployment;
}
@Override
public BeanManager getBeanManager() {
checkContainerState(container);
final String callerName = getCallingClassName();
if(callerName.startsWith("org.glassfish.soteria")) {
//the Jakarta EE Security RI uses CDI.current() to perform bean lookup, however
//as it is part of the container its bean archive does not have visibility to deployment beans
//we use this code path to enable it to get the bean manager of the current module
//so it can look up the deployment beans it needs to work
try {
BeanManager bm = (BeanManager) new InitialContext().lookup("java:comp/BeanManager");
if(bm != null) {
return bm;
}
} catch (NamingException e) {
//ignore
}
}
final ClassLoader tccl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
final Class<?> callerClass = Reflections.loadClass(callerName, tccl);
if (callerClass != null) {
final BeanDeploymentArchive bda = deployment.getBeanDeploymentArchive(callerClass);
if (bda != null) {
return new BeanManagerProxy(container.beanDeploymentArchives().get(bda));
}
}
// fallback for cases when we are unable to load the class or no BeanManager exists yet for the given BDA
return rootBeanManager;
}
@Override
public String toString() {
return "Weld instance for deployment " + BeanManagerProxy.unwrap(rootBeanManager).getContextId();
}
}
}
| 5,401 | 39.924242 | 122 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/CdiAnnotations.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld;
import java.util.Set;
import org.jboss.as.weld.discovery.AnnotationType;
import org.jboss.jandex.DotName;
import org.jboss.weld.util.collections.ImmutableSet;
import jakarta.enterprise.inject.spi.BeanManager;
/**
* Class that stores the {@link DotName}s of CDI annotations.
*
*/
public enum CdiAnnotations {
/**
* jakarta.decorator.Decorator CDI annotation.
*/
DECORATOR(Constants.JAVAX_DECORATOR, "Decorator"),
/**
* jakarta.decorator.Delegate CDI annotation.
*/
DELEGATE(Constants.JAVAX_DECORATOR, "Delegate"),
/**
* jakarta.enterprise.context.ApplicationScoped CDI annotation.
*/
APP_SCOPED(Constants.JAVAX_ENT_CONTEXT, "ApplicationScoped"),
/**
* jakarta.enterprise.context.ConversationScoped CDI annotation.
*/
CONV_SCOPED(Constants.JAVAX_ENT_CONTEXT, "ConversationScoped"),
/**
* jakarta.enterprise.context.RequestScoped CDI annotation.
*/
REQ_SCOPED(Constants.JAVAX_ENT_CONTEXT, "RequestScoped"),
/**
* jakarta.enterprise.context.SessionScoped CDI annotation.
*/
SESS_SCOPED(Constants.JAVAX_ENT_CONTEXT, "SessionScoped"),
/**
* jakarta.enterprise.context.NormalScope CDI annotation.
*/
NORM_SCOPE(Constants.JAVAX_ENT_CONTEXT, "NormalScope"),
/**
* jakarta.enterprise.context.Dependent CDI annotation.
*/
DEPENDENT(Constants.JAVAX_ENT_CONTEXT, "Dependent"),
/**
* jakarta.inject.Singleton annotation.
*/
SINGLETON(Constants.JAVAX_INJ, "Singleton"),
/**
* jakarta.enterprise.event.Observes CDI annotation.
*/
OBSERVES(Constants.JAVAX_ENT_EVT, "Observes"),
/**
* jakarta.enterprise.inject.Alternative CDI annotation.
*/
ALTERNATIVE(Constants.JAVAX_ENT_INJ, "Alternative"),
/**
* jakarta.enterprise.inject.Any CDI annotation.
*/
ANY(Constants.JAVAX_ENT_INJ, "Any"),
/**
* jakarta.enterprise.inject.Default CDI annotation.
*/
DEFAULT(Constants.JAVAX_ENT_INJ, "Default"),
/**
* jakarta.enterprise.inject.Disposes CDI annotation.
*/
DISPOSES(Constants.JAVAX_ENT_INJ, "Disposes"),
/**
* jakarta.enterprise.inject.Model CDI annotation.
*/
MODEL(Constants.JAVAX_ENT_INJ, "Model"),
/**
* jakarta.enterprise.inject.New CDI annotation.
*/
NEW(Constants.JAVAX_ENT_INJ, "New"),
/**
* jakarta.enterprise.inject.Produces CDI annotation.
*/
PRODUCES(Constants.JAVAX_ENT_INJ, "Produces"),
/**
* jakarta.enterprise.inject.Specializes CDI annotation.
*/
SPECIALIZES(Constants.JAVAX_ENT_INJ, "Specializes"),
/**
* jakarta.enterprise.inject.Stereotype CDI annotation.
*/
STEREOTYPE(Constants.JAVAX_ENT_INJ, "Stereotype"),
/**
* jakarta.enterprise.inject.Typed CDI annotation.
*/
TYPED(Constants.JAVAX_ENT_INJ, "Typed");
/**
* CDI annotation name.
*/
private final String simpleName;
/**
* CDI annotation fully qualified name.
*/
private final DotName dotName;
/**
* Constructor.
*
* @param prefix qualified name part
* @param simpleName simple class name
*/
private CdiAnnotations(final DotName prefix, final String simpleName) {
this.simpleName = simpleName;
this.dotName = DotName.createComponentized(prefix, simpleName);
}
/**
* this can't go on the enum itself.
*/
private static class Constants {
private static final String EE_NAMESPACE = BeanManager.class.getName().substring(0, BeanManager.class.getName().indexOf("."));
/**
* javax package.
*/
public static final DotName JAVAX = DotName.createComponentized(null, EE_NAMESPACE);
/**
* jakarta.interceptor package.
*/
public static final DotName JAVAX_INTERCEPTOR = DotName.createComponentized(JAVAX, "interceptor");
/**
* jakarta.decorator package.
*/
public static final DotName JAVAX_DECORATOR = DotName.createComponentized(JAVAX, "decorator");
/**
* javax.enterprise package.
*/
public static final DotName JAVAX_ENT = DotName.createComponentized(JAVAX, "enterprise");
/**
* jakarta.enterprise.context package.
*/
public static final DotName JAVAX_ENT_CONTEXT = DotName.createComponentized(JAVAX_ENT, "context");
/**
* jakarta.enterprise.event package.
*/
public static final DotName JAVAX_ENT_EVT = DotName.createComponentized(JAVAX_ENT, "event");
/**
* jakarta.enterprise.inject package.
*/
public static final DotName JAVAX_ENT_INJ = DotName.createComponentized(JAVAX_ENT, "inject");
/**
* jakarta.inject package.
*/
public static final DotName JAVAX_INJ = DotName.createComponentized(JAVAX, "inject");
}
/**
* @return fully qualified name
*/
public DotName getDotName() {
return dotName;
}
/**
* @return simple name
*/
public String getSimpleName() {
return simpleName;
}
public static final DotName SCOPE = DotName.createComponentized(Constants.JAVAX_INJ, "Scope");
public static final Set<DotName> BUILT_IN_SCOPE_NAMES = ImmutableSet.<DotName>of(DEPENDENT.getDotName(), REQ_SCOPED.getDotName(), CONV_SCOPED.getDotName(), SESS_SCOPED.getDotName(), APP_SCOPED.getDotName(), SINGLETON.getDotName());
public static final Set<AnnotationType> BUILT_IN_SCOPES = BUILT_IN_SCOPE_NAMES.stream().map(dotName -> new AnnotationType(dotName, true)).collect(ImmutableSet.collector());
public static final Set<AnnotationType> BEAN_DEFINING_ANNOTATIONS = ImmutableSet.of(
new AnnotationType(DotName.createComponentized(Constants.JAVAX_INTERCEPTOR, "Interceptor"), false), asAnnotationType(DECORATOR, false),
asAnnotationType(DEPENDENT), asAnnotationType(REQ_SCOPED), asAnnotationType(CONV_SCOPED), asAnnotationType(SESS_SCOPED),
asAnnotationType(APP_SCOPED));
public static final Set<AnnotationType> BEAN_DEFINING_META_ANNOTATIONS = ImmutableSet.of(asAnnotationType(NORM_SCOPE, false),
asAnnotationType(STEREOTYPE, false));
private static AnnotationType asAnnotationType(CdiAnnotations annotation) {
return new AnnotationType(annotation.getDotName(), true);
}
private static AnnotationType asAnnotationType(CdiAnnotations annotation, boolean inherited) {
return new AnnotationType(annotation.getDotName(), inherited);
}
}
| 7,640 | 33.111607 | 235 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/WeldJBossAllConfiguration.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld;
import org.jboss.as.server.deployment.AttachmentKey;
/**
* Immutable representation of Weld configuration in <code>jboss-all.xml<code>.
* This configuration is processed by {@link org.jboss.as.weld.deployment.processors.WeldConfigurationProcessor}.
*
* @author Jozef Hartinger
*
*/
public class WeldJBossAllConfiguration {
public static final AttachmentKey<WeldJBossAllConfiguration> ATTACHMENT_KEY = AttachmentKey.create(WeldJBossAllConfiguration.class);
private final Boolean requireBeanDescriptor;
private final Boolean nonPortableMode;
private final Boolean developmentMode;
private final Boolean legacyEmptyBeansXmlTreatment;
WeldJBossAllConfiguration(Boolean requireBeanDescriptor, Boolean nonPortableMode, Boolean developmentMode, Boolean legacyEmptyBeansXmlTreatment) {
this.requireBeanDescriptor = requireBeanDescriptor;
this.nonPortableMode = nonPortableMode;
this.developmentMode = developmentMode;
this.legacyEmptyBeansXmlTreatment = legacyEmptyBeansXmlTreatment;
}
public Boolean getNonPortableMode() {
return nonPortableMode;
}
public Boolean getRequireBeanDescriptor() {
return requireBeanDescriptor;
}
public Boolean getDevelopmentMode() {
return developmentMode;
}
public Boolean getLegacyEmptyBeansXmlTreatment() {
return legacyEmptyBeansXmlTreatment;
}
}
| 2,456 | 36.8 | 150 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/WeldStartCompletionService.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2018, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Supplier;
import org.jboss.as.server.deployment.SetupAction;
import org.jboss.as.weld.logging.WeldLogger;
import org.jboss.msc.Service;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StopContext;
import org.jboss.weld.bootstrap.api.Bootstrap;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* This service calls {@link Bootstrap#endInitialization()}, i.e. places the container into a state where it can service
* requests.
*
* Its start is delayed after all EE components are installed which allows Weld to perform efficient cleanup and further
* optimizations after bootstrap.
*
* @author Martin Kouba
* @author Matej Novotny
* @author <a href="mailto:[email protected]">Richard Opalka</a>
* @see WeldStartService
*/
public class WeldStartCompletionService implements Service {
public static final ServiceName SERVICE_NAME = ServiceNames.WELD_START_COMPLETION_SERVICE_NAME;
private final Supplier<WeldBootstrapService> bootstrapSupplier;
private final List<SetupAction> setupActions;
private final ClassLoader classLoader;
private final AtomicBoolean runOnce = new AtomicBoolean();
public WeldStartCompletionService(final Supplier<WeldBootstrapService> bootstrapSupplier,
final List<SetupAction> setupActions,
final ClassLoader classLoader) {
this.bootstrapSupplier = bootstrapSupplier;
this.setupActions = setupActions;
this.classLoader = classLoader;
}
@Override
public void start(final StartContext context) {
if (!runOnce.compareAndSet(false, true)) {
// we only execute this once, if there is a restart, WeldStartService initiates re-deploy hence we do nothing here
return;
}
ClassLoader oldTccl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
try {
for (SetupAction action : setupActions) {
action.setup(null);
}
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader);
bootstrapSupplier.get().getBootstrap().endInitialization();
} finally {
for (SetupAction action : setupActions) {try {
action.teardown(null);
} catch (Exception e) {
WeldLogger.DEPLOYMENT_LOGGER.exceptionClearingThreadState(e);
}
}
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTccl);
}
}
@Override
public void stop(StopContext context) {
// No-op
}
}
| 3,821 | 38.402062 | 126 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/WeldSubsystem30Parser.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld;
import org.jboss.as.controller.PersistentResourceXMLDescription;
import org.jboss.as.controller.PersistentResourceXMLParser;
class WeldSubsystem30Parser extends PersistentResourceXMLParser {
public static final String NAMESPACE = "urn:jboss:domain:weld:3.0";
static final WeldSubsystem30Parser INSTANCE = new WeldSubsystem30Parser();
private static final PersistentResourceXMLDescription xmlDescription;
static {
xmlDescription = PersistentResourceXMLDescription.builder(WeldExtension.PATH_SUBSYSTEM, NAMESPACE)
.addAttributes(WeldResourceDefinition.NON_PORTABLE_MODE_ATTRIBUTE, WeldResourceDefinition.REQUIRE_BEAN_DESCRIPTOR_ATTRIBUTE, WeldResourceDefinition.DEVELOPMENT_MODE_ATTRIBUTE)
.build();
}
private WeldSubsystem30Parser() {
}
@Override
public PersistentResourceXMLDescription getParserDescription() {
return xmlDescription;
}
}
| 1,976 | 40.1875 | 191 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/WeldExtension.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import org.jboss.as.controller.Extension;
import org.jboss.as.controller.ExtensionContext;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.SubsystemRegistration;
import org.jboss.as.controller.descriptions.StandardResourceDescriptionResolver;
import org.jboss.as.controller.operations.common.GenericSubsystemDescribeHandler;
import org.jboss.as.controller.parsing.ExtensionParsingContext;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.weld.logging.WeldLogger;
/**
* Domain extension used to initialize the weld subsystem.
*
* @author Stuart Douglas
* @author Emanuel Muckenhuber
* @author Jozef Hartinger
*/
public class WeldExtension implements Extension {
public static final String SUBSYSTEM_NAME = "weld";
static final PathElement PATH_SUBSYSTEM = PathElement.pathElement(SUBSYSTEM, SUBSYSTEM_NAME);
private static final String RESOURCE_NAME = WeldExtension.class.getPackage().getName() + ".LocalDescriptions";
private static final ModelVersion CURRENT_MODEL_VERSION = ModelVersion.create(5, 0, 0);
static StandardResourceDescriptionResolver getResourceDescriptionResolver(final String... keyPrefix) {
StringBuilder prefix = new StringBuilder(SUBSYSTEM_NAME);
for (String kp : keyPrefix) {
prefix.append('.').append(kp);
}
return new StandardResourceDescriptionResolver(prefix.toString(), RESOURCE_NAME, WeldExtension.class.getClassLoader(), true, false);
}
/** {@inheritDoc} */
@Override
public void initialize(final ExtensionContext context) {
WeldLogger.ROOT_LOGGER.debug("Activating Weld Extension");
final SubsystemRegistration subsystem = context.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL_VERSION);
final ManagementResourceRegistration registration = subsystem.registerSubsystemModel(new WeldResourceDefinition());
registration.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE);
subsystem.registerXMLElementWriter(WeldSubsystem50Parser.INSTANCE);
}
/** {@inheritDoc} */
@Override
public void initializeParsers(final ExtensionParsingContext context) {
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, WeldSubsystem10Parser.NAMESPACE, () -> WeldSubsystem10Parser.INSTANCE);
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, WeldSubsystem20Parser.NAMESPACE, () -> WeldSubsystem20Parser.INSTANCE);
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, WeldSubsystem30Parser.NAMESPACE, () -> WeldSubsystem30Parser.INSTANCE);
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, WeldSubsystem40Parser.NAMESPACE, () -> WeldSubsystem40Parser.INSTANCE);
context.setSubsystemXmlMapping(SUBSYSTEM_NAME, WeldSubsystem50Parser.NAMESPACE, () -> WeldSubsystem50Parser.INSTANCE);
}
}
| 4,084 | 45.954023 | 140 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/WeldCapabilityImpl.java | /*
* JBoss, Home of Professional Open Source
*
* Copyright 2018 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.weld;
import java.util.function.Supplier;
import jakarta.enterprise.inject.spi.BeanManager;
import jakarta.enterprise.inject.spi.Extension;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.weld._private.WeldDeploymentMarker;
import org.jboss.as.weld.deployment.WeldPortableExtensions;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.ServiceBuilder;
/**
* The implementation of WeldCapability.
*
* @author Yeray Borges
*/
public class WeldCapabilityImpl implements WeldCapability {
static final WeldCapability INSTANCE = new WeldCapabilityImpl();
private WeldCapabilityImpl() {}
@Override
public void registerExtensionInstance(final Extension extension, final DeploymentUnit unit) {
if (isPartOfWeldDeployment(unit)) {
WeldPortableExtensions extensions = WeldPortableExtensions.getPortableExtensions(unit);
extensions.registerExtensionInstance(extension, unit);
}
}
@Override
public Supplier<BeanManager> addBeanManagerService(final DeploymentUnit unit, final ServiceBuilder<?> serviceBuilder) {
if (isPartOfWeldDeployment(unit)) {
return serviceBuilder.requires(ServiceNames.beanManagerServiceName(unit));
}
return null;
}
@Override
public ServiceBuilder<?> addBeanManagerService(final DeploymentUnit unit, final ServiceBuilder<?> serviceBuilder, final Injector<BeanManager> targetInjector) {
if (isPartOfWeldDeployment(unit)) {
return serviceBuilder.addDependency(ServiceNames.beanManagerServiceName(unit), BeanManager.class, targetInjector);
}
return serviceBuilder;
}
public boolean isPartOfWeldDeployment(final DeploymentUnit unit) {
return WeldDeploymentMarker.isPartOfWeldDeployment(unit);
}
public boolean isWeldDeployment(final DeploymentUnit unit) {
return WeldDeploymentMarker.isWeldDeployment(unit);
}
public void markAsWeldDeployment(DeploymentUnit unit) {
WeldDeploymentMarker.mark(unit);
}
}
| 2,759 | 33.5 | 163 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/WeldStartService.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Supplier;
import org.jboss.as.server.deployment.SetupAction;
import org.jboss.as.weld.logging.WeldLogger;
import org.jboss.as.weld.services.ModuleGroupSingletonProvider;
import org.jboss.msc.service.LifecycleEvent;
import org.jboss.msc.service.LifecycleListener;
import org.jboss.msc.Service;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceController.Mode;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.weld.Container;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* Service that actually finishes starting the weld container, after it has been bootstrapped by
* {@link WeldBootstrapService}
*
* @author Stuart Douglas
* @author <a href="mailto:[email protected]">Richard Opalka</a>
* @see WeldStartCompletionService
*/
public class WeldStartService implements Service {
public static final ServiceName SERVICE_NAME = ServiceNames.WELD_START_SERVICE_NAME;
private final Supplier<WeldBootstrapService> bootstrapSupplier;
private final List<SetupAction> setupActions;
private final ClassLoader classLoader;
private final ServiceName deploymentServiceName;
private final AtomicBoolean runOnce = new AtomicBoolean();
public WeldStartService(final Supplier<WeldBootstrapService> bootstrapSupplier, final List<SetupAction> setupActions, final ClassLoader classLoader, final ServiceName deploymentServiceName) {
this.bootstrapSupplier = bootstrapSupplier;
this.setupActions = setupActions;
this.classLoader = classLoader;
this.deploymentServiceName = deploymentServiceName;
}
@Override
public void start(final StartContext context) throws StartException {
/*
* Weld service restarts are not supported. Therefore, if we detect that Weld is being restarted we
* trigger restart of the entire deployment.
*/
if (!runOnce.compareAndSet(false,true)) {
ServiceController<?> controller = context.getController().getServiceContainer().getService(deploymentServiceName);
controller.addListener(new LifecycleListener() {
@Override
public void handleEvent(final ServiceController<?> controller, final LifecycleEvent event) {
if (event == LifecycleEvent.DOWN) {
controller.setMode(Mode.ACTIVE);
controller.removeListener(this);
}
}
});
controller.setMode(Mode.NEVER);
return;
}
ClassLoader oldTccl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
try {
for (SetupAction action : setupActions) {
action.setup(null);
}
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader);
bootstrapSupplier.get().getBootstrap().startInitialization();
bootstrapSupplier.get().getBootstrap().deployBeans();
bootstrapSupplier.get().getBootstrap().validateBeans();
} finally {
for (SetupAction action : setupActions) {
try {
action.teardown(null);
} catch (Exception e) {
WeldLogger.DEPLOYMENT_LOGGER.exceptionClearingThreadState(e);
}
}
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTccl);
}
}
/**
* Stops the container
* Executed in WeldStartService to shutdown the runtime before NamingService is closed.
*
* @throws IllegalStateException if the container is not running
*/
@Override
public void stop(final StopContext context) {
final WeldBootstrapService bootstrapService = bootstrapSupplier.get();
if (!bootstrapService.isStarted()) {
//this happens when the 'runOnce' code in start has been triggered
return;
}
WeldLogger.DEPLOYMENT_LOGGER.stoppingWeldService(bootstrapService.getDeploymentName());
ClassLoader oldTccl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
try {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(bootstrapService.getDeployment().getModule().getClassLoader());
WeldProvider.containerShutDown(Container.instance(bootstrapService.getDeploymentName()));
bootstrapService.getBootstrap().shutdown();
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTccl);
ModuleGroupSingletonProvider.removeClassLoader(bootstrapService.getDeployment().getModule().getClassLoader());
}
bootstrapService.startServiceShutdown();
}
}
| 6,043 | 42.482014 | 195 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/WeldJBossAll10Parser.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld;
import static org.jboss.as.weld.WeldResourceDefinition.NON_PORTABLE_MODE_ATTRIBUTE_NAME;
import static org.jboss.as.weld.WeldResourceDefinition.REQUIRE_BEAN_DESCRIPTOR_ATTRIBUTE_NAME;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.jbossallxml.JBossAllXMLParser;
import org.jboss.staxmapper.XMLExtendedStreamReader;
/**
* Parses <code>jboss-all.xml</code> and creates {@link WeldJBossAllConfiguration} holding the parsed configuration.
*
* @author Jozef Hartinger
*
*/
class WeldJBossAll10Parser extends AbstractWeldJBossAllParser implements JBossAllXMLParser<WeldJBossAllConfiguration> {
public static final String NAMESPACE = "urn:jboss:weld:1.0";
public static final QName ROOT_ELEMENT = new QName(NAMESPACE, "weld");
public static final WeldJBossAll10Parser INSTANCE = new WeldJBossAll10Parser();
private WeldJBossAll10Parser() {
}
@Override
public WeldJBossAllConfiguration parse(XMLExtendedStreamReader reader, DeploymentUnit deploymentUnit) throws XMLStreamException {
Boolean requireBeanDescriptor = getAttributeAsBoolean(reader, REQUIRE_BEAN_DESCRIPTOR_ATTRIBUTE_NAME);
Boolean nonPortableMode = getAttributeAsBoolean(reader, NON_PORTABLE_MODE_ATTRIBUTE_NAME);
super.parseWeldElement(reader);
return new WeldJBossAllConfiguration(requireBeanDescriptor, nonPortableMode, false, false);
}
}
| 2,540 | 42.810345 | 133 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/AbstractWeldJBossAllParser.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2015, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld;
import javax.xml.stream.XMLStreamException;
import org.jboss.staxmapper.XMLExtendedStreamReader;
abstract class AbstractWeldJBossAllParser {
protected Boolean getAttributeAsBoolean(XMLExtendedStreamReader reader, String attributeName) {
for (int i = 0; i < reader.getAttributeCount(); i++) {
final String name = reader.getAttributeLocalName(i);
final String value = reader.getAttributeValue(i);
if (attributeName.equals(name)) {
return Boolean.valueOf(value);
}
}
return null;
}
protected void parseWeldElement(final XMLExtendedStreamReader reader) throws XMLStreamException {
while (reader.hasNext() && reader.nextTag() != javax.xml.stream.XMLStreamConstants.END_ELEMENT) {
}
}
}
| 1,849 | 39.217391 | 105 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/WeldTransformers.java | package org.jboss.as.weld;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.controller.transform.ExtensionTransformerRegistration;
import org.jboss.as.controller.transform.SubsystemTransformerRegistration;
import org.jboss.as.controller.transform.description.ChainedTransformationDescriptionBuilder;
import org.jboss.as.controller.transform.description.DiscardAttributeChecker;
import org.jboss.as.controller.transform.description.RejectAttributeChecker;
import org.jboss.as.controller.transform.description.ResourceTransformationDescriptionBuilder;
import org.jboss.as.controller.transform.description.TransformationDescriptionBuilder;
import org.jboss.dmr.ModelNode;
public class WeldTransformers implements ExtensionTransformerRegistration {
@Override
public String getSubsystemName() {
return WeldExtension.SUBSYSTEM_NAME;
}
@Override
public void registerTransformers(SubsystemTransformerRegistration subsystem) {
ModelVersion version4_0_0 = ModelVersion.create(4, 0, 0);
ChainedTransformationDescriptionBuilder chainedBuilder = TransformationDescriptionBuilder.Factory
.createChainedSubystemInstance(subsystem.getCurrentSubsystemVersion());
// Differences between the current version and 4.0.0
ResourceTransformationDescriptionBuilder builder400 = chainedBuilder.createBuilder(subsystem.getCurrentSubsystemVersion(), version4_0_0);
builder400.getAttributeBuilder()
// Discard an explicit 'true' as that's the legacy behavior. Reject otherwise.
.setDiscard(new DiscardAttributeChecker.DiscardAttributeValueChecker(false, false, ModelNode.TRUE),
WeldResourceDefinition.LEGACY_EMPTY_BEANS_XML_TREATMENT_ATTRIBUTE)
.addRejectCheck(RejectAttributeChecker.ALL, WeldResourceDefinition.LEGACY_EMPTY_BEANS_XML_TREATMENT_ATTRIBUTE)
.end();
chainedBuilder.buildAndRegister(subsystem, new ModelVersion[]{version4_0_0});
}
}
| 2,024 | 50.923077 | 145 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/WeldModuleResourceLoader.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld;
import org.jboss.modules.Module;
import org.jboss.weld.resources.spi.ResourceLoader;
import org.jboss.weld.resources.spi.ResourceLoadingException;
import java.net.URL;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* A {@link ResourceLoader} that can load classes from a {@link Module}
* <p>
* Thread Safety: This class is thread safe, and does not require a happens before even between construction and usage
*
* @author Stuart Douglas
*
*/
public class WeldModuleResourceLoader implements ResourceLoader {
private final Module module;
/**
* Additional classes that have been added to the bean archive by the container or by a portable extension
*/
private final Map<String, Class<?>> classes;
public WeldModuleResourceLoader(Module module) {
this.module = module;
this.classes = new ConcurrentHashMap<String, Class<?>>();
}
/**
* If the class name is found in additionalClasses then return it.
*
* Otherwise the class will be loaded from the module ClassLoader
*/
@Override
public Class<?> classForName(String name) {
try {
if (classes.containsKey(name)) {
return classes.get(name);
}
final Class<?> clazz = module.getClassLoader().loadClass(name);
classes.put(name, clazz);
return clazz;
} catch (ClassNotFoundException | LinkageError e) {
throw new ResourceLoadingException(e);
}
}
public void addAdditionalClass(Class<?> clazz) {
this.classes.put(clazz.getName(), clazz);
}
/**
* Loads a resource from the module class loader
*/
@Override
public URL getResource(String name) {
try {
return module.getClassLoader().getResource(name);
} catch (Exception e) {
throw new ResourceLoadingException(e);
}
}
/**
* Loads resources from the module class loader
*/
@Override
public Collection<URL> getResources(String name) {
try {
final HashSet<URL> resources = new HashSet<URL>();
Enumeration<URL> urls = module.getClassLoader().getResources(name);
while (urls.hasMoreElements()) {
resources.add(urls.nextElement());
}
return resources;
} catch (Exception e) {
throw new ResourceLoadingException(e);
}
}
@Override
public void cleanup() {
// nop
}
}
| 3,661 | 30.568966 | 118 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/_private/WeldDeploymentMarker.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld._private;
import org.jboss.as.server.deployment.AttachmentKey;
import org.jboss.as.server.deployment.DeploymentUnit;
/**
* Marker for top level deployments that contain a beans.xml file
*
* @author Stuart Douglas
*/
public class WeldDeploymentMarker {
private static final AttachmentKey<Boolean> MARKER = AttachmentKey.create(Boolean.class);
/**
* Mark this deployment and the top level deployment as being a weld deployment.
*
*/
public static void mark(DeploymentUnit unit) {
unit.putAttachment(MARKER, Boolean.TRUE);
if (unit.getParent() != null) {
mark(unit.getParent());
}
}
/**
* returns true if the {@link DeploymentUnit} is part of a weld deployment
*/
public static boolean isPartOfWeldDeployment(DeploymentUnit unit) {
if (unit.getParent() == null) {
return unit.getAttachment(MARKER) != null;
} else {
return unit.getParent().getAttachment(MARKER) != null;
}
}
/**
* returns true if the {@link DeploymentUnit} has a beans.xml in any of it's resource roots,
* or is a top level deployment that contains sub-deployments that are weld deployments.
*/
public static boolean isWeldDeployment(DeploymentUnit unit) {
return unit.getAttachment(MARKER) != null;
}
private WeldDeploymentMarker() {
}
}
| 2,438 | 33.352113 | 96 | java |
null | wildfly-main/weld/subsystem/src/main/java/org/jboss/as/weld/arquillian/WeldContextSetup.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.weld.arquillian;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import jakarta.enterprise.context.spi.CreationalContext;
import jakarta.enterprise.inject.spi.Bean;
import jakarta.enterprise.inject.spi.BeanManager;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.jboss.as.server.deployment.SetupAction;
import org.jboss.as.weld.logging.WeldLogger;
import org.jboss.msc.service.ServiceName;
import org.jboss.weld.Container;
import org.jboss.weld.context.bound.BoundConversationContext;
import org.jboss.weld.context.bound.BoundLiteral;
import org.jboss.weld.context.bound.BoundRequest;
import org.jboss.weld.context.bound.BoundRequestContext;
import org.jboss.weld.context.bound.BoundSessionContext;
import org.jboss.weld.context.bound.MutableBoundRequest;
/**
* Sets up the session, request and conversation contexts for a weld deployment
*
* @author Stuart Douglas
*
*/
public class WeldContextSetup implements SetupAction {
private static class ContextMapThreadLocal extends ThreadLocal<Map<String, Object>> {
@Override
protected Map<String, Object> initialValue() {
return new ConcurrentHashMap<String, Object>();
}
}
private static final String STANDARD_BEAN_MANAGER_JNDI_NAME = "java:comp/BeanManager";
private final ThreadLocal<Map<String, Object>> sessionContexts = new ContextMapThreadLocal();
private final ThreadLocal<Map<String, Object>> requestContexts = new ContextMapThreadLocal();
private final ThreadLocal<BoundRequest> boundRequests = new ThreadLocal<BoundRequest>();
@SuppressWarnings("unchecked")
public void setup(Map<String, Object> properties) {
try {
final BeanManager manager = (BeanManager) new InitialContext().lookup(STANDARD_BEAN_MANAGER_JNDI_NAME);
if (manager != null && Container.available()) {
final Bean<BoundSessionContext> sessionContextBean = (Bean<BoundSessionContext>) manager.resolve(manager
.getBeans(BoundSessionContext.class, BoundLiteral.INSTANCE));
CreationalContext<?> ctx = manager.createCreationalContext(sessionContextBean);
final BoundSessionContext sessionContext = (BoundSessionContext) manager.getReference(sessionContextBean,
BoundSessionContext.class, ctx);
sessionContext.associate(sessionContexts.get());
sessionContext.activate();
final Bean<BoundRequestContext> requestContextBean = (Bean<BoundRequestContext>) manager.resolve(manager
.getBeans(BoundRequestContext.class, BoundLiteral.INSTANCE));
ctx = manager.createCreationalContext(requestContextBean);
final BoundRequestContext requestContext = (BoundRequestContext) manager.getReference(requestContextBean,
BoundRequestContext.class, ctx);
requestContext.associate(requestContexts.get());
requestContext.activate();
final Bean<BoundConversationContext> conversationContextBean = (Bean<BoundConversationContext>) manager
.resolve(manager.getBeans(BoundConversationContext.class, BoundLiteral.INSTANCE));
ctx = manager.createCreationalContext(conversationContextBean);
final BoundConversationContext conversationContext = (BoundConversationContext) manager.getReference(
conversationContextBean, BoundConversationContext.class, ctx);
BoundRequest request = new MutableBoundRequest(requestContexts.get(), sessionContexts.get());
boundRequests.set(request);
conversationContext.associate(request);
conversationContext.activate();
}
} catch (NamingException e) {
WeldLogger.ROOT_LOGGER.failedToSetupWeldContexts(e);
}
}
@SuppressWarnings("unchecked")
public void teardown(Map<String, Object> properties) {
try {
final BeanManager manager = (BeanManager) new InitialContext().lookup("java:comp/BeanManager");
if (manager != null && Container.available()) {
final Bean<BoundSessionContext> sessionContextBean = (Bean<BoundSessionContext>) manager.resolve(manager.getBeans(
BoundSessionContext.class, BoundLiteral.INSTANCE));
CreationalContext<?> ctx = manager.createCreationalContext(sessionContextBean);
final BoundSessionContext sessionContext = (BoundSessionContext) manager.getReference(sessionContextBean,
BoundSessionContext.class, ctx);
sessionContext.invalidate();
sessionContext.deactivate();
sessionContext.dissociate(sessionContexts.get());
final Bean<BoundRequestContext> requestContextBean = (Bean<BoundRequestContext>) manager.resolve(manager.getBeans(
BoundRequestContext.class, BoundLiteral.INSTANCE));
ctx = manager.createCreationalContext(requestContextBean);
final BoundRequestContext requestContext = (BoundRequestContext) manager.getReference(requestContextBean,
BoundRequestContext.class, ctx);
requestContext.invalidate();
requestContext.deactivate();
requestContext.dissociate(requestContexts.get());
final Bean<BoundConversationContext> conversationContextBean = (Bean<BoundConversationContext>) manager
.resolve(manager.getBeans(BoundConversationContext.class, BoundLiteral.INSTANCE));
ctx = manager.createCreationalContext(conversationContextBean);
final BoundConversationContext conversationContext = (BoundConversationContext) manager.getReference(
conversationContextBean, BoundConversationContext.class, ctx);
conversationContext.invalidate();
conversationContext.deactivate();
conversationContext.dissociate(boundRequests.get());
}
} catch (NamingException e) {
WeldLogger.ROOT_LOGGER.failedToTearDownWeldContexts(e);
} finally {
sessionContexts.remove();
requestContexts.remove();
boundRequests.remove();
}
}
@Override
public Set<ServiceName> dependencies() {
return Collections.emptySet();
}
@Override
public int priority() {
return 100;
}
}
| 7,711 | 48.121019 | 130 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.