use of java.lang.reflect.InvocationHandler in project cxf by apache.
the class JaxWsClientThreadTest method testRequestContextThreadSafety.
@Test
public void testRequestContextThreadSafety() throws Throwable {
URL url = getClass().getResource("/wsdl/hello_world.wsdl");
javax.xml.ws.Service s = javax.xml.ws.Service.create(url, serviceName);
final Greeter greeter = s.getPort(portName, Greeter.class);
final InvocationHandler handler = Proxy.getInvocationHandler(greeter);
((BindingProvider) handler).getRequestContext().put(JaxWsClientProxy.THREAD_LOCAL_REQUEST_CONTEXT, Boolean.TRUE);
Map<String, Object> requestContext = ((BindingProvider) handler).getRequestContext();
String address = (String) requestContext.get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY);
final Throwable[] errorHolder = new Throwable[1];
Runnable r = new Runnable() {
public void run() {
try {
final String protocol = "http-" + Thread.currentThread().getId();
for (int i = 0; i < 10; i++) {
String threadSpecificaddress = protocol + "://localhost:80/" + i;
Map<String, Object> requestContext = ((BindingProvider) handler).getRequestContext();
requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, threadSpecificaddress);
assertEquals("we get what we set", threadSpecificaddress, requestContext.get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY));
try {
greeter.greetMe("Hi");
} catch (WebServiceException expected) {
// expected.getCause().printStackTrace();
MalformedURLException mue = (MalformedURLException) expected.getCause();
if (mue == null || mue.getMessage() == null) {
throw expected;
}
assertTrue("protocol contains thread id from context", mue.getMessage().indexOf(protocol) != 0);
}
requestContext.remove(BindingProvider.ENDPOINT_ADDRESS_PROPERTY);
assertTrue("property is null", requestContext.get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY) == null);
}
} catch (Throwable t) {
// capture assert failures
errorHolder[0] = t;
}
}
};
final int numThreads = 5;
Thread[] threads = new Thread[numThreads];
for (int i = 0; i < numThreads; i++) {
threads[i] = new Thread(r);
}
for (int i = 0; i < numThreads; i++) {
threads[i].start();
}
for (int i = 0; i < numThreads; i++) {
threads[i].join();
}
if (errorHolder[0] != null) {
throw errorHolder[0];
}
// main thread contextValues are un changed
assertTrue("address from existing context has not changed", address.equals(requestContext.get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY)));
// get the latest values
((ClientImpl.EchoContext) ((WrappedMessageContext) requestContext).getWrappedMap()).reload();
assertTrue("address is different", !address.equals(requestContext.get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY)));
// verify value reflects what other threads were doing
assertTrue("property is null from last thread execution", requestContext.get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY) == null);
}
use of java.lang.reflect.InvocationHandler in project tomee by apache.
the class CdiPlugin method getSessionBeanProxy.
@Override
public Object getSessionBeanProxy(final Bean<?> inBean, final Class<?> interfce, final CreationalContext<?> creationalContext) {
Object instance = cacheProxies.get(inBean);
if (instance != null) {
return instance;
}
synchronized (inBean) {
// singleton for the app so safe to sync on it
instance = cacheProxies.get(inBean);
if (instance != null) {
return instance;
}
final Class<? extends Annotation> scopeClass = inBean.getScope();
final CdiEjbBean<Object> cdiEjbBean = (CdiEjbBean<Object>) inBean;
final CreationalContext<Object> cc = (CreationalContext<Object>) creationalContext;
if (scopeClass == null || Dependent.class == scopeClass) {
// no need to add any layer, null = @New
return cdiEjbBean.createEjb(cc);
}
// only stateful normally
final InstanceBean<Object> bean = new InstanceBean<Object>(cdiEjbBean);
if (webBeansContext.getBeanManagerImpl().isNormalScope(scopeClass)) {
final BeanContext beanContext = cdiEjbBean.getBeanContext();
final Provider provider = webBeansContext.getNormalScopeProxyFactory().getInstanceProvider(beanContext.getClassLoader(), cdiEjbBean);
if (!beanContext.isLocalbean()) {
final List<Class> interfaces = new ArrayList<Class>();
final InterfaceType type = beanContext.getInterfaceType(interfce);
if (type != null) {
interfaces.addAll(beanContext.getInterfaces(type));
} else {
// can happen when looked up from impl instead of API in OWB -> default to business local
interfaces.addAll(beanContext.getInterfaces(InterfaceType.BUSINESS_LOCAL));
}
interfaces.add(Serializable.class);
interfaces.add(IntraVmProxy.class);
if (BeanType.STATEFUL.equals(beanContext.getComponentType()) || BeanType.MANAGED.equals(beanContext.getComponentType())) {
interfaces.add(BeanContext.Removable.class);
}
try {
instance = ProxyManager.newProxyInstance(interfaces.toArray(new Class<?>[interfaces.size()]), new InvocationHandler() {
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
try {
return method.invoke(provider.get(), args);
} catch (final InvocationTargetException ite) {
throw ite.getCause();
}
}
});
} catch (final IllegalAccessException e) {
throw new OpenEJBRuntimeException(e);
}
} else {
final NormalScopeProxyFactory normalScopeProxyFactory = webBeansContext.getNormalScopeProxyFactory();
final Class<?> proxyClass = normalScopeProxyFactory.createProxyClass(beanContext.getClassLoader(), beanContext.getBeanClass());
instance = normalScopeProxyFactory.createProxyInstance(proxyClass, provider);
}
cacheProxies.put(inBean, instance);
} else {
final Context context = webBeansContext.getBeanManagerImpl().getContext(scopeClass);
instance = context.get(bean, cc);
}
bean.setOwbProxy(instance);
return instance;
}
}
use of java.lang.reflect.InvocationHandler in project tomee by apache.
the class BeanContext method newInstance.
@SuppressWarnings("unchecked")
public InstanceContext newInstance() throws Exception {
final ThreadContext callContext = new ThreadContext(this, null, Operation.INJECTION);
final ThreadContext oldContext = ThreadContext.enter(callContext);
final boolean dynamicallyImplemented = isDynamicallyImplemented();
final WebBeansContext webBeansContext = getWebBeansContext();
if (dynamicallyImplemented) {
if (!InvocationHandler.class.isAssignableFrom(getProxyClass())) {
throw new OpenEJBException("proxy class can only be InvocationHandler");
}
}
try {
final Context ctx = getJndiEnc();
final Class beanClass = getBeanClass();
final CurrentCreationalContext<Object> currentCreationalContext = get(CurrentCreationalContext.class);
CreationalContext<Object> creationalContext = currentCreationalContext != null ? currentCreationalContext.get() : null;
final CdiEjbBean cdiEjbBean = get(CdiEjbBean.class);
if (!CreationalContextImpl.class.isInstance(creationalContext) && webBeansContext != null) {
if (creationalContext == null) {
creationalContext = webBeansContext.getCreationalContextFactory().getCreationalContext(cdiEjbBean);
} else {
creationalContext = webBeansContext.getCreationalContextFactory().wrappedCreationalContext(creationalContext, cdiEjbBean);
}
}
final Object rootInstance;
if (cdiEjbBean != null && !dynamicallyImplemented && CdiEjbBean.EjbInjectionTargetImpl.class.isInstance(cdiEjbBean.getInjectionTarget())) {
rootInstance = CdiEjbBean.EjbInjectionTargetImpl.class.cast(cdiEjbBean.getInjectionTarget()).createNewPojo(creationalContext);
} else {
// not a cdi bean
rootInstance = getManagedClass().newInstance();
}
// Create bean instance
Object beanInstance;
final InjectionProcessor injectionProcessor;
if (!dynamicallyImplemented) {
injectionProcessor = new InjectionProcessor(rootInstance, getInjections(), InjectionProcessor.unwrap(ctx));
beanInstance = injectionProcessor.createInstance();
inject(beanInstance, creationalContext);
} else {
// update target
final List<Injection> newInjections = new ArrayList<Injection>();
for (final Injection injection : getInjections()) {
if (beanClass.equals(injection.getTarget())) {
final Injection updated = new Injection(injection.getJndiName(), injection.getName(), proxyClass);
newInjections.add(updated);
} else {
newInjections.add(injection);
}
}
injections.clear();
injections.addAll(newInjections);
injectionProcessor = new InjectionProcessor(rootInstance, injections, InjectionProcessor.unwrap(ctx));
final InvocationHandler handler = (InvocationHandler) injectionProcessor.createInstance();
beanInstance = DynamicProxyImplFactory.newProxy(this, handler);
inject(handler, creationalContext);
}
// Create interceptors
final Map<String, Object> interceptorInstances = new LinkedHashMap<String, Object>();
// Add the stats interceptor instance and other already created interceptor instances
for (final InterceptorInstance interceptorInstance : this.getUserAndSystemInterceptors()) {
final Class clazz = interceptorInstance.getData().getInterceptorClass();
interceptorInstances.put(clazz.getName(), interceptorInstance.getInterceptor());
}
final Collection<DependentCreationalContext<?>> createdDependents = getDependents(creationalContext);
for (final InterceptorData interceptorData : this.getInstanceScopedInterceptors()) {
if (interceptorData.getInterceptorClass().equals(beanClass)) {
continue;
}
final Class clazz = interceptorData.getInterceptorClass();
final Object iInstance;
if (webBeansContext != null) {
Object preInstantiated = null;
if (createdDependents != null) {
for (final DependentCreationalContext<?> dcc : createdDependents) {
if (clazz.isInstance(dcc.getInstance())) {
// is that enough? do we have more to match?
preInstantiated = dcc.getInstance();
break;
}
}
}
if (preInstantiated != null) {
iInstance = preInstantiated;
} else {
ConstructorInjectionBean interceptorConstructor = interceptorData.get(ConstructorInjectionBean.class);
if (interceptorConstructor == null) {
synchronized (this) {
interceptorConstructor = interceptorData.get(ConstructorInjectionBean.class);
if (interceptorConstructor == null) {
interceptorConstructor = new ConstructorInjectionBean(webBeansContext, clazz, webBeansContext.getAnnotatedElementFactory().newAnnotatedType(clazz));
interceptorData.set(ConstructorInjectionBean.class, interceptorConstructor);
}
}
}
iInstance = interceptorConstructor.create(creationalContext);
}
} else {
iInstance = clazz.newInstance();
}
final InjectionProcessor interceptorInjector = new InjectionProcessor(iInstance, this.getInjections(), InjectionProcessor.unwrap(ctx));
try {
final Object interceptorInstance = interceptorInjector.createInstance();
if (webBeansContext != null) {
try {
OWBInjector.inject(webBeansContext.getBeanManagerImpl(), interceptorInstance, creationalContext);
} catch (final Throwable t) {
// TODO handle this differently
// this is temporary till the injector can be rewritten
}
}
interceptorInstances.put(clazz.getName(), interceptorInstance);
} catch (final ConstructionException e) {
throw new Exception("Failed to create interceptor: " + clazz.getName(), e);
}
}
interceptorInstances.put(beanClass.getName(), beanInstance);
// Invoke post construct method
callContext.setCurrentOperation(Operation.POST_CONSTRUCT);
final List<InterceptorData> callbackInterceptors = this.getCallbackInterceptors();
final InterceptorStack postConstruct = new InterceptorStack(beanInstance, null, Operation.POST_CONSTRUCT, callbackInterceptors, interceptorInstances);
// Transaction Demarcation for Singleton PostConstruct method
TransactionType transactionType;
if (componentType == BeanType.SINGLETON || componentType == BeanType.STATEFUL) {
final Set<Method> callbacks = callbackInterceptors.get(callbackInterceptors.size() - 1).getPostConstruct();
if (callbacks.isEmpty()) {
transactionType = TransactionType.RequiresNew;
} else {
// TODO: we should take the last one I think
transactionType = getTransactionType(callbacks.iterator().next());
if (transactionType == TransactionType.Required) {
transactionType = TransactionType.RequiresNew;
}
}
} else {
transactionType = isBeanManagedTransaction() ? TransactionType.BeanManaged : TransactionType.NotSupported;
}
final TransactionPolicy transactionPolicy = EjbTransactionUtil.createTransactionPolicy(transactionType, callContext);
try {
// Call the chain
if (cdiEjbBean != null) {
// call it, it has no postconstruct but extensions can add stuff here, TODO: see if it should be called before or after effective postconstruct
cdiEjbBean.getInjectionTarget().postConstruct(beanInstance);
}
postConstruct.invoke();
} catch (final Throwable e) {
// RollBack Transaction
EjbTransactionUtil.handleSystemException(transactionPolicy, e, callContext);
} finally {
EjbTransactionUtil.afterInvoke(transactionPolicy, callContext);
}
// handle cdi decorators
if (cdiEjbBean != null) {
final Class<?> proxyClass = Class.class.cast(Reflections.get(cdiEjbBean.getInjectionTarget(), "proxyClass"));
if (proxyClass != null) {
// means interception
final InterceptorResolutionService.BeanInterceptorInfo interceptorInfo = cdiEjbBean.getBeanContext().get(InterceptorResolutionService.BeanInterceptorInfo.class);
if (interceptorInfo.getDecorators() != null && !interceptorInfo.getDecorators().isEmpty()) {
final InterceptorDecoratorProxyFactory pf = webBeansContext.getInterceptorDecoratorProxyFactory();
// decorators
final Object instance = beanInstance;
final List<Decorator<?>> decorators = interceptorInfo.getDecorators();
final Map<Decorator<?>, Object> instances = new HashMap<Decorator<?>, Object>();
for (int i = decorators.size(); i > 0; i--) {
final Decorator<?> decorator = decorators.get(i - 1);
CreationalContextImpl.class.cast(creationalContext).putDelegate(beanInstance);
final Object decoratorInstance = decorator.create(CreationalContext.class.cast(creationalContext));
instances.put(decorator, decoratorInstance);
beanInstance = pf.createProxyInstance(proxyClass, instance, new DecoratorHandler(interceptorInfo, decorators, instances, i - 1, instance, cdiEjbBean.getId()));
}
}
}
}
return new InstanceContext(this, beanInstance, interceptorInstances, creationalContext);
} finally {
ThreadContext.exit(oldContext);
}
}
use of java.lang.reflect.InvocationHandler in project tomee by apache.
the class ManagedConnection method invoke.
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
// first some Object method management
final String mtdName = method.getName();
if ("toString".equals(mtdName)) {
return "ManagedConnection{" + delegate + "}";
}
if ("hashCode".equals(mtdName)) {
return hashCode();
}
if ("equals".equals(mtdName)) {
InvocationHandler handler;
return args[0] == this || ((handler = unwrapHandler(args[0])) == this) || (delegate != null && delegate.equals(unwrapDelegate(args[0], handler)));
}
// allow to get delegate if needed by the underlying program
if (Wrapper.class == method.getDeclaringClass() && args.length == 1 && Connection.class == args[0]) {
if ("isWrapperFor".equals(mtdName)) {
return true;
}
if ("unwrap".equals(mtdName)) {
return delegate;
}
}
// here the real logic starts
try {
final Transaction transaction = transactionManager.getTransaction();
// shouldn't be used without a transaction but if so just delegate to the actual connection
if (transaction == null) {
if ("close".equals(mtdName)) {
if (delegate == null) {
// no need to get a connection
return close();
}
closeConnection(true);
return null;
}
if ("isClosed".equals(mtdName) && closed) {
return true;
}
if (delegate == null) {
newConnection();
}
return invoke(method, delegate, args);
}
// if we have a tx check it is the same this connection is linked to
if (currentTransaction != null && isUnderTransaction(currentTransaction.getStatus())) {
if (!currentTransaction.equals(transaction)) {
throw new SQLException("Connection can not be used while enlisted in another transaction");
}
return invokeUnderTransaction(method, args);
}
// get the already bound connection to the current transaction or enlist this one in the tx
final int transactionStatus = transaction.getStatus();
if (isUnderTransaction(transactionStatus)) {
Connection connection = Connection.class.cast(registry.getResource(key));
if (connection == null && delegate == null) {
newConnection();
currentTransaction = transaction;
try {
if (!transaction.enlistResource(getXAResource())) {
closeConnection(true);
throw new SQLException("Unable to enlist connection in transaction: enlistResource returns 'false'.");
}
} catch (final RollbackException ignored) {
// no-op
} catch (final SystemException e) {
throw new SQLException("Unable to enlist connection the transaction", e);
}
registry.putResource(key, delegate);
transaction.registerSynchronization(new ClosingSynchronization());
if (xaConnection == null) {
try {
setAutoCommit(false);
} catch (final SQLException xae) {
// we are alreay in a transaction so this can't be called from a user perspective - some XA DataSource prevents it in their code
final String message = "Can't set auto commit to false cause the XA datasource doesn't support it, this is likely an issue";
final Logger logger = Logger.getInstance(LogCategory.OPENEJB_RESOURCE_JDBC, ManagedConnection.class);
if (logger.isDebugEnabled()) {
// we don't want to print the exception by default
logger.warning(message, xae);
} else {
logger.warning(message);
}
}
}
} else if (delegate == null) {
// shouldn't happen
delegate = connection;
}
return invokeUnderTransaction(method, args);
}
if ("isClosed".equals(mtdName) && closed) {
return true;
}
if ("close".equals(mtdName)) {
// let it be handled by the ClosingSynchronisation since we have a tx there
return close();
}
// we shouldn't come here, tempted to just throw an exception
if (delegate == null) {
newConnection();
}
return invoke(method, delegate, args);
} catch (final InvocationTargetException ite) {
throw ite.getTargetException();
}
}
use of java.lang.reflect.InvocationHandler in project tomee by apache.
the class MdbProxy method destroyProxy.
public static void destroyProxy(final Object proxy) {
final InvocationHandler handler = Proxy.getInvocationHandler(proxy);
if (handler instanceof MdbProxy) {
final MdbInvocationHandler mdbInvocationHandler = (MdbInvocationHandler) handler;
mdbInvocationHandler.destroy();
}
}
Aggregations