/** {@inheritDoc} */ public Object processInvocation(final InterceptorContext context) throws Exception { Object target = targetReference.get().getInstance(); if (target == null) { throw new IllegalStateException("No injection target found"); } // if it's an optional injection and the injection source isn't available, then just proceed by // skipping the injection if (this.factory == null && this.optionalInjection) { return context.proceed(); } ManagedReference reference = factory.getReference(); boolean ok = false; try { valueReference.set(reference); method.invoke(target, reference.getInstance()); Object result = context.proceed(); ok = true; return result; } finally { if (!ok) { valueReference.set(null); reference.release(); } } }
public ComponentViewInstance createInstance(Map<Object, Object> contextData) { final SimpleInterceptorFactoryContext factoryContext = new SimpleInterceptorFactoryContext(); final Map<Method, InterceptorFactory> viewInterceptorFactories = ViewService.this.viewInterceptorFactories; final Map<Method, Interceptor> viewEntryPoints = new IdentityHashMap<Method, Interceptor>(viewInterceptorFactories.size()); factoryContext.getContextData().put(Component.class, component); factoryContext.getContextData().putAll(contextData); // the post construct interceptors currently MUST be created first // and in some cases the instance is attached in this create process // TODO: this is probably not a good thing. {@see ManagedBeanCreateInterceptorFactory} final Interceptor postConstructInterceptor = viewPostConstruct.create(factoryContext); for (Method method : viewInterceptorFactories.keySet()) { viewEntryPoints.put(method, viewInterceptorFactories.get(method).create(factoryContext)); } final Interceptor preDestroyInterceptor = viewPreDestroy.create(factoryContext); final ComponentViewInstance instance = new ViewInstance(viewEntryPoints, preDestroyInterceptor); try { InterceptorContext context = new InterceptorContext(); context.putPrivateData(ComponentView.class, this); context.putPrivateData(Component.class, component); postConstructInterceptor.processInvocation(context); } catch (Exception e) { // TODO: What is the best exception type to throw here? throw new RuntimeException("Failed to instantiate component view", e); } return instance; }
@Override public void callTimeout(final TimerImpl timer, final Method timeoutMethod) throws Exception { final Interceptor interceptor; synchronized (this) { if (!started) { // this can happen if an invocation has been triggered as the deployment is shutting down throw EjbLogger.ROOT_LOGGER.timerInvocationFailedDueToInvokerNotBeingStarted(); } interceptor = timeoutInterceptors.get(timeoutMethod); } if (interceptor == null) { throw EjbLogger.ROOT_LOGGER.failToInvokeTimeout(timeoutMethod); } final InterceptorContext context = new InterceptorContext(); context.setContextData(new HashMap<String, Object>()); context.setMethod(timeoutMethod); if (timeoutMethod.getParameterTypes().length == 0) { context.setParameters(new Object[0]); } else { final Object[] params = new Object[1]; params[0] = timer; context.setParameters(params); } context.setTimer(timer); if (timer.getPrimaryKey() != null) { context.putPrivateData(EntityBeanComponent.PRIMARY_KEY_CONTEXT_KEY, timer.getPrimaryKey()); } context.putPrivateData(Component.class, ejbComponent.getValue()); context.putPrivateData(MethodIntf.class, MethodIntf.TIMER); context.putPrivateData(InvocationType.class, InvocationType.TIMER); interceptor.processInvocation(context); }
/** * Processes an incoming invocation and checks for the presence of a remote transaction associated * with the invocation context. * * @param context The invocation context * @return * @throws Exception */ @Override public Object processInvocation(InterceptorContext context) throws Exception { final RemotingAttachments remotingAttachments = context.getPrivateData(RemotingAttachments.class); final TransactionManager transactionManager = this.ejbRemoteTransactionsRepository.getTransactionManager(); Transaction originatingRemoteTx = null; if (remotingAttachments != null) { // get the transaction attachment final byte[] transactionIDBytes = remotingAttachments.getPayloadAttachment(0x0001); // A (remote) tx is associated with the invocation, so propogate it appropriately if (transactionIDBytes != null) { final TransactionID transactionID = TransactionID.createTransactionID(transactionIDBytes); // if it's UserTransaction then create or resume the UserTransaction corresponding to the ID if (transactionID instanceof UserTransactionID) { this.createOrResumeUserTransaction((UserTransactionID) transactionID); } else if (transactionID instanceof XidTransactionID) { this.createOrResumeXidTransaction((XidTransactionID) transactionID); } // the invocation was associated with a remote tx, so keep a flag so that we can // suspend (on this thread) the originating tx when returning from the invocation originatingRemoteTx = transactionManager.getTransaction(); } } try { // we are done with any tx propogation setup, let's move on return context.proceed(); } finally { // suspend the originating remote tx on this thread now that the invocation has been done if (originatingRemoteTx != null) { transactionManager.suspend(); } } }
@Override public Object processInvocation(InterceptorContext interceptorContext) throws Exception { try { return interceptorContext.proceed(); } finally { StatefulSessionComponentInstance sfsb = (StatefulSessionComponentInstance) interceptorContext.getPrivateData(ComponentInstance.class); SFSBContextHandleImpl sfsbContextHandle = new SFSBContextHandleImpl(sfsb); List<EntityManager> readyToClose = SFSBXPCMap.getINSTANCE().remove(sfsbContextHandle); if (readyToClose != null && readyToClose.size() > 0) { for (EntityManager entityManager : readyToClose) { if (entityManager instanceof ExtendedEntityManager) { // TODO: continue iterating through remaining entity managers and chain any exceptions ((ExtendedEntityManager) entityManager).containerClose(); } else { throw new RuntimeException( "can only close SFSB XPC entity manager that are instances of ExtendedEntityManager" + entityManager.getClass().getName()); } } } } }
@Override public Object processInvocation(final InterceptorContext context) throws Exception { final Object instance = context.getPrivateData(ComponentInstance.class).getInstance(); try { return method.invoke(instance, context.getPrivateData(PARAMETERS_KEY)); } catch (InvocationTargetException e) { throw Interceptors.rethrow(e.getCause()); } }
/** @return The primary key of the current EJB, or null if not applicable */ private Object currentPrimaryKey() { final InterceptorContext context = CurrentInvocationContext.get(); if (context == null) { return null; } return context.getPrivateData(EntityBeanComponent.PRIMARY_KEY_CONTEXT_KEY); }
@Override public Object getInstance() { // get the current invocation context and the EJBComponent out of it final InterceptorContext currentInvocationContext = CurrentInvocationContext.get(); final EJBComponent ejbComponent = (EJBComponent) currentInvocationContext.getPrivateData(Component.class); if (ejbComponent == null) { throw MESSAGES.failToGetEjbComponent(currentInvocationContext); } return ejbComponent.getTimerService(); }
protected TransactionAttributeType getCurrentTransactionAttribute() { final InterceptorContext currentInvocationContext = CurrentInvocationContext.get(); if (currentInvocationContext == null) { return null; } final Method invokedMethod = currentInvocationContext.getMethod(); // if method is null, then it's a lifecycle invocation if (invokedMethod == null) { return null; } // get the tx attribute of the invoked method return this.getTransactionAttributeType(invokedMethod); }
public void destroy() { try { InterceptorContext interceptorContext = new InterceptorContext(); interceptorContext.putPrivateData(ComponentView.class, View.this); interceptorContext.putPrivateData(ComponentViewInstance.class, this); interceptorContext.putPrivateData(Component.class, component); preDestroyInterceptor.processInvocation(interceptorContext); } catch (Exception e) { logger.warn( "Exception while invoking pre-destroy interceptor for component class: " + this.getComponent().getComponentClass(), e); } }
/** * Returns true if the {@link CurrentInvocationContext} represents a lifecycle callback * invocation. Else returns false. * * <p>This method internally relies on {@link CurrentInvocationContext#get()} to obtain the * current invocation context. * * <ul> * <li>If the context is available then it looks for the method that was invoked. The absence of * a method indicates a lifecycle callback. * <li>If the context is <i>not</i> available, then this method returns false (i.e. it doesn't * consider the current invocation as a lifecycle callback). This is for convenience, to * allow the invocation of {@link javax.ejb.TimerService} methods in the absence of {@link * CurrentInvocationContext} * </ul> * * <p> * * @return */ protected boolean isLifecycleCallbackInvocation() { final InterceptorContext currentInvocationContext = CurrentInvocationContext.get(); if (currentInvocationContext == null) { return false; } // If the method in current invocation context is null, // then it represents a lifecycle callback invocation Method invokedMethod = currentInvocationContext.getMethod(); if (invokedMethod == null) { // it's a lifecycle callback return true; } // not a lifecycle callback return false; }
public boolean wasCancelCalled() throws IllegalStateException { final CancellationFlag flag = context.getPrivateData(CancellationFlag.class); if (flag != null) { return flag.get(); } return super.wasCancelCalled(); }
public Object createProxy() { final SimpleInterceptorFactoryContext factoryContext = new SimpleInterceptorFactoryContext(); factoryContext.getContextData().put(Component.class, component); factoryContext.getContextData().put(ComponentView.class, View.this); factoryContext.getContextData().put(ComponentViewInstance.class, this); final Map<Method, InterceptorFactory> clientInterceptorFactories = ViewService.this.clientInterceptorFactories; final Map<Method, Interceptor> clientEntryPoints = new IdentityHashMap<Method, Interceptor>(clientInterceptorFactories.size()); for (Method method : clientInterceptorFactories.keySet()) { clientEntryPoints.put( method, clientInterceptorFactories.get(method).create(factoryContext)); } final Interceptor postConstructInterceptor = clientPostConstruct.create(factoryContext); try { Object object = proxyFactory.newInstance( new ProxyInvocationHandler(clientEntryPoints, component, View.this, this)); InterceptorContext interceptorContext = new InterceptorContext(); interceptorContext.putPrivateData(ComponentView.class, View.this); interceptorContext.putPrivateData(ComponentViewInstance.class, this); interceptorContext.putPrivateData(Component.class, component); try { postConstructInterceptor.processInvocation(interceptorContext); } catch (Exception e) { InstantiationException exception = new InstantiationException("Post-construct lifecycle failed"); exception.initCause(e); throw exception; } return object; } catch (InstantiationException e) { InstantiationError error = new InstantiationError(e.getMessage()); Throwable cause = e.getCause(); if (cause != null) error.initCause(cause); throw error; } catch (IllegalAccessException e) { IllegalAccessError error = new IllegalAccessError(e.getMessage()); Throwable cause = e.getCause(); if (cause != null) error.initCause(cause); throw error; } }
@Override public Object processInvocation(InterceptorContext context) throws Exception { final Component component = context.getPrivateData(Component.class); // if a session bean is participating in a transaction, it // is an error for a client to invoke the remove method // on the session object's home or component interface. final ComponentView view = context.getPrivateData(ComponentView.class); if (view != null) { Ejb2xViewType viewType = view.getPrivateData(Ejb2xViewType.class); if (viewType != null) { // this means it is an EJB 2.x view // which is not allowed to remove while enrolled in a TX final StatefulTransactionMarker marker = context.getPrivateData(StatefulTransactionMarker.class); if (marker != null && !marker.isFirstInvocation()) { throw EjbLogger.ROOT_LOGGER.cannotRemoveWhileParticipatingInTransaction(); } } } // just log a WARN and throw back the original exception if (component instanceof StatefulSessionComponent == false) { throw EjbLogger.ROOT_LOGGER.unexpectedComponent(component, StatefulSessionComponent.class); } final StatefulSessionComponent statefulComponent = (StatefulSessionComponent) component; Object invocationResult = null; try { // proceed invocationResult = context.proceed(); } catch (Exception e) { // Exception caught during call to @Remove method. Handle it appropriately // If it's an application exception and if the @Remove method has set "retainIfException" to // true // then just throw back the exception and don't remove the session instance. if (this.isApplicationException(statefulComponent, e.getClass(), context.getMethod()) && this.retainIfException) { throw e; } // otherwise, just remove it and throw back the original exception final StatefulSessionComponentInstance statefulComponentInstance = (StatefulSessionComponentInstance) context.getPrivateData(ComponentInstance.class); final SessionID sessionId = statefulComponentInstance.getId(); statefulComponent.removeSession(sessionId); throw e; } final StatefulSessionComponentInstance statefulComponentInstance = (StatefulSessionComponentInstance) context.getPrivateData(ComponentInstance.class); final SessionID sessionId = statefulComponentInstance.getId(); // just remove the session because of a call to @Remove method statefulComponent.removeSession(sessionId); // return the invocation result return invocationResult; }
public void invokeTimeoutMethod(final Method method, final Timer timer) { final Interceptor interceptor = timeoutInterceptors.get(method); if (interceptor == null) { throw MESSAGES.failToCallTimeOutMethod(method); } try { InterceptorContext context = prepareInterceptorContext(); context.setMethod(method); context.setTimer(timer); context.setTarget(getInstance()); final Object[] params; if (method.getParameterTypes().length == 1) { params = new Object[1]; params[0] = timer; } else { params = EMPTY_OBJECT_ARRAY; } context.setParameters(params); interceptor.processInvocation(context); } catch (Exception e) { throw new RuntimeException(e); } }
private void prepareInterceptorContext( final SkeletonStrategy op, final Object[] params, final InterceptorContext interceptorContext) throws IOException, ClassNotFoundException { if (!home) { if (componentView.getComponent() instanceof StatefulSessionComponent) { final SessionID sessionID = (SessionID) unmarshalIdentifier(); interceptorContext.putPrivateData(SessionID.class, sessionID); } else if (componentView.getComponent() instanceof EntityBeanComponent) { final Object pk = unmarshalIdentifier(); interceptorContext.putPrivateData(EntityBeanComponent.PRIMARY_KEY_CONTEXT_KEY, pk); } } interceptorContext.setContextData(new HashMap<String, Object>()); interceptorContext.setParameters(params); interceptorContext.setMethod(op.getMethod()); interceptorContext.putPrivateData(ComponentView.class, componentView); interceptorContext.putPrivateData(Component.class, componentView.getComponent()); }
/** * Invokes WS endpoint. * * @param endpoint WS endpoint * @param wsInvocation web service invocation * @throws Exception if any error occurs */ public void invoke(final Endpoint endpoint, final Invocation wsInvocation) throws Exception { try { // prepare for invocation onBeforeInvocation(wsInvocation); // prepare invocation data final ComponentView componentView = getComponentView(); Component component = componentView.getComponent(); // for spring integration and @FactoryType is annotated we don't need to go into ee's // interceptors if (wsInvocation.getInvocationContext().getTargetBean() != null && (endpoint.getProperty("SpringBus") != null) || wsInvocation.getInvocationContext().getProperty("forceTargetBean") != null) { this.reference = new ManagedReference() { public void release() {} public Object getInstance() { return wsInvocation.getInvocationContext().getTargetBean(); } }; if (component instanceof WSComponent) { ((WSComponent) component).setReference(reference); } } final Method method = getComponentViewMethod(wsInvocation.getJavaMethod(), componentView.getViewMethods()); final InterceptorContext context = new InterceptorContext(); prepareForInvocation(context, wsInvocation); context.setMethod(method); context.setParameters(wsInvocation.getArgs()); context.putPrivateData(Component.class, component); context.putPrivateData(ComponentView.class, componentView); if (wsInvocation.getInvocationContext().getProperty("forceTargetBean") != null) { context.putPrivateData(ManagedReference.class, reference); } // invoke method final Object retObj = componentView.invoke(context); // set return value wsInvocation.setReturnValue(retObj); } catch (Throwable t) { handleInvocationException(t); } finally { onAfterInvocation(wsInvocation); } }
@Override public Object processInvocation(InterceptorContext context) throws Exception { final Method invokedMethod = context.getMethod(); final ComponentViewInstance componentViewInstance = context.getPrivateData(ComponentViewInstance.class); // For a lifecycle interception, the ComponentViewInstance (and the invoked business interface) // will be null. // On a normal method invocation, the invoked business interface will be obtained from the // ComponentViewInstance final Class<?> invokedBusinessInterface = componentViewInstance == null ? null : componentViewInstance.getViewClass(); Object[] parameters = context.getParameters(); SessionInvocationContext sessionInvocationContext = new CustomSessionInvocationContext( lifecycleCallback, context, invokedBusinessInterface, invokedMethod, parameters); context.putPrivateData(InvocationContext.class, sessionInvocationContext); CurrentInvocationContext.push(sessionInvocationContext); try { return context.proceed(); } finally { CurrentInvocationContext.pop(); context.putPrivateData(InvocationContext.class, null); } }
/** * Receives IIOP requests to this servant's <code>EJBObject</code>s and forwards them to the bean * container, through the JBoss <code>MBean</code> server. */ public OutputStream _invoke( final String opName, final InputStream in, final ResponseHandler handler) { if (logger.isTraceEnabled()) { logger.trace("EJBObject invocation: " + opName); } SkeletonStrategy op = methodInvokerMap.get(opName); if (op == null) { logger.debugf( "Unable to find opname '%s' valid operations:%s", opName, methodInvokerMap.keySet()); throw new BAD_OPERATION(opName); } final NamespaceContextSelector selector = componentView.getComponent().getNamespaceContextSelector(); final ClassLoader oldCl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged(); NamespaceContextSelector.pushCurrentSelector(selector); try { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader); SecurityContext sc = null; org.omg.CORBA_2_3.portable.OutputStream out; try { Object retVal; if (!home && opName.equals("_get_handle")) { retVal = new HandleImplIIOP(orb.object_to_string(_this_object())); } else if (home && opName.equals("_get_homeHandle")) { retVal = homeHandle; } else if (home && opName.equals("_get_EJBMetaData")) { retVal = ejbMetaData; } else { Transaction tx = null; if (inboundTxCurrent != null) tx = inboundTxCurrent.getCurrentTransaction(); if (tx != null) { transactionManager.resume(tx); } try { SimplePrincipal principal = null; Object credential = null; if (sasCurrent != null) { final byte[] incomingName = sasCurrent.get_incoming_principal_name(); if (incomingName != null && incomingName.length > 0) { // we have an identity token, which is a trust based mechanism if (incomingName.length > 0) { String name = new String(incomingName, StandardCharsets.UTF_8); int domainIndex = name.indexOf('@'); if (domainIndex > 0) name = name.substring(0, domainIndex); principal = new SimplePrincipal(name); // we don't have any real way to establish trust here // we just use the SASCurrent as a credential, and a custom login // module can make a decision for us. credential = sasCurrent; } } else { // the client has just sent a username and password final byte[] username = sasCurrent.get_incoming_username(); final byte[] incomingPassword = sasCurrent.get_incoming_password(); if (username.length > 0) { String name = new String(username, StandardCharsets.UTF_8); int domainIndex = name.indexOf('@'); if (domainIndex > 0) { name = name.substring(0, domainIndex); } principal = new SimplePrincipal(name); credential = new String(incomingPassword, StandardCharsets.UTF_8).toCharArray(); } } if (securityDomain != null) { sc = SecurityContextFactory.createSecurityContext(securityDomain); sc.getUtil().createSubjectInfo(principal, credential, null); } } final Object[] params = op.readParams((org.omg.CORBA_2_3.portable.InputStream) in); if (!home && opName.equals("isIdentical") && params.length == 1) { // handle isIdentical specially Object val = params[0]; if (val instanceof org.omg.CORBA.Object) { retVal = handleIsIdentical((org.omg.CORBA.Object) val); } else { retVal = false; } } else { if (sc != null) { setSecurityContextOnAssociation(sc); } try { final InterceptorContext interceptorContext = new InterceptorContext(); if (sc != null) { interceptorContext.putPrivateData(SecurityContext.class, sc); } prepareInterceptorContext(op, params, interceptorContext); retVal = componentView.invoke(interceptorContext); } finally { if (sc != null) { clearSecurityContextOnAssociation(); } } } } finally { if (tx != null) { if (transactionManager.getStatus() != Status.STATUS_NO_TRANSACTION) { transactionManager.suspend(); } } } } out = (org.omg.CORBA_2_3.portable.OutputStream) handler.createReply(); if (op.isNonVoid()) { op.writeRetval(out, retVal); } } catch (Exception e) { if (logger.isTraceEnabled()) { logger.trace("Exception in EJBObject invocation", e); } if (e instanceof MBeanException) { e = ((MBeanException) e).getTargetException(); } RmiIdlUtil.rethrowIfCorbaSystemException(e); out = (org.omg.CORBA_2_3.portable.OutputStream) handler.createExceptionReply(); op.writeException(out, e); } return out; } finally { NamespaceContextSelector.popCurrentSelector(); WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldCl); } }
@Override public SessionBeanComponent getComponent() { // return (SessionBeanComponent) super.getComponent(); // this is faster return (SessionBeanComponent) context.getPrivateData(Component.class); }
public Object processInvocation(final InterceptorContext context) throws Exception { ComponentView view = context.getPrivateData(ComponentView.class); return view.invoke(context); }
@Override public Map<String, Object> getContextData() { return context.getContextData(); }
@Override public SessionContext getEJBContext() { return ((SessionBeanComponentInstance) context.getPrivateData(ComponentInstance.class)) .getSessionContext(); }
@Override public Object proceed() throws Exception { return context.proceed(); }
protected TransactionAttributeType getCurrentTransactionAttribute() { final InterceptorContext invocation = CurrentInvocationContext.get(); final MethodIntf methodIntf = MethodIntfHelper.of(invocation); return getTransactionAttributeType(methodIntf, invocation.getMethod()); }
@Override public void setParameters(Object[] params) throws IllegalArgumentException, IllegalStateException { context.setParameters(params); }
protected SessionID getSessionIdOf(final InterceptorContext ctx) { final StatefulSessionComponentInstance instance = (StatefulSessionComponentInstance) ctx.getPrivateData(ComponentInstance.class); return instance.getId(); }
public Object processInvocation(final InterceptorContext context) throws Exception { context.getPrivateData(ComponentViewInstance.class).destroy(); return null; }
@Override public Object processInvocation(InterceptorContext context) throws Exception { return super.invoke( (TransactionalInvocationContext) context.getPrivateData(InvocationContext.class)); }