Search in sources :

Example 71 with OpenEJBException

use of org.apache.openejb.OpenEJBException in project tomee by apache.

the class StatefulContainer method registerEntityManagers.

private void registerEntityManagers(final Instance instance, final ThreadContext callContext) throws OpenEJBException {
    if (entityManagerRegistry == null) {
        return;
    }
    final BeanContext beanContext = callContext.getBeanContext();
    // get the factories
    final Index<EntityManagerFactory, BeanContext.EntityManagerConfiguration> factories = beanContext.getExtendedEntityManagerFactories();
    if (factories == null) {
        return;
    }
    // get the managers for the factories
    final Map<EntityManagerFactory, JtaEntityManagerRegistry.EntityManagerTracker> entityManagers = instance.getEntityManagers(factories);
    if (entityManagers == null) {
        return;
    }
    // register them
    try {
        entityManagerRegistry.addEntityManagers((String) beanContext.getDeploymentID(), instance.primaryKey, entityManagers);
    } catch (final EntityManagerAlreadyRegisteredException e) {
        throw new EJBException(e);
    }
}
Also used : EntityManagerAlreadyRegisteredException(org.apache.openejb.persistence.EntityManagerAlreadyRegisteredException) BeanContext(org.apache.openejb.BeanContext) EntityManagerFactory(javax.persistence.EntityManagerFactory) OpenEJBException(org.apache.openejb.OpenEJBException) EJBException(javax.ejb.EJBException)

Example 72 with OpenEJBException

use of org.apache.openejb.OpenEJBException in project tomee by apache.

the class EjbTimerServiceImpl method ejbTimeout.

/**
 * This method calls the ejbTimeout method and starts a transaction if the timeout is transacted.
 * <p/>
 * This method will retry failed ejbTimeout calls until retryAttempts is exceeded.
 *
 * @param timerData the timer to call.
 */
@SuppressWarnings("ReturnInsideFinallyBlock")
public void ejbTimeout(final TimerData timerData) {
    final Thread thread = Thread.currentThread();
    // container loader
    final ClassLoader loader = thread.getContextClassLoader();
    try {
        Timer timer = getTimer(timerData.getId());
        // quartz can be backed by some advanced config (jdbc for instance)
        if (timer == null && timerStore instanceof MemoryTimerStore && timerData.getTimer() != null) {
            try {
                timerStore.addTimerData(timerData);
                // TODO: replace memoryjobstore by the db one?
                timer = timerData.getTimer();
            } catch (final TimerStoreException e) {
            // shouldn't occur
            }
        // return;
        }
        for (int tries = 0; tries < 1 + retryAttempts; tries++) {
            boolean retry = false;
            // if transacted, begin the transaction
            if (transacted) {
                try {
                    transactionManager.begin();
                } catch (final Exception e) {
                    log.warning("Exception occured while starting container transaction", e);
                    return;
                }
            }
            // call the timeout method
            try {
                final RpcContainer container = (RpcContainer) deployment.getContainer();
                if (container == null) {
                    return;
                }
                final Method ejbTimeout = timerData.getTimeoutMethod();
                if (ejbTimeout == null) {
                    return;
                }
                // if app registered Synchronization we need it for commit()/rollback()
                // so forcing it and not relying on container for it
                thread.setContextClassLoader(deployment.getClassLoader() != null ? deployment.getClassLoader() : loader);
                SetAccessible.on(ejbTimeout);
                container.invoke(deployment.getDeploymentID(), InterfaceType.TIMEOUT, ejbTimeout.getDeclaringClass(), ejbTimeout, new Object[] { timer }, timerData.getPrimaryKey());
            } catch (final RuntimeException e) {
                retry = true;
                // exception from a timer does not necessairly mean failure
                log.warning("RuntimeException from ejbTimeout on " + deployment.getDeploymentID(), e);
                try {
                    transactionManager.setRollbackOnly();
                } catch (final SystemException e1) {
                    log.warning("Exception occured while setting RollbackOnly for container transaction", e1);
                }
            } catch (final OpenEJBException e) {
                retry = true;
                if (ApplicationException.class.isInstance(e)) {
                    // we don't want to pollute logs
                    log.debug("Exception from ejbTimeout on " + deployment.getDeploymentID(), e);
                } else {
                    log.warning("Exception from ejbTimeout on " + deployment.getDeploymentID(), e);
                }
                if (transacted) {
                    try {
                        transactionManager.setRollbackOnly();
                    } catch (final SystemException e1) {
                        log.warning("Exception occured while setting RollbackOnly for container transaction", e1);
                    }
                }
            } finally {
                try {
                    if (!transacted) {
                        if (!retry) {
                            return;
                        }
                    } else if (transactionManager.getStatus() == Status.STATUS_ACTIVE) {
                        transactionManager.commit();
                        return;
                    } else {
                        // tx was marked rollback, so roll it back and retry.
                        transactionManager.rollback();
                    }
                } catch (final Exception e) {
                    log.warning("Exception occured while completing container transaction", e);
                }
            }
        }
        log.warning("Failed to execute ejbTimeout on " + timerData.getDeploymentId() + " successfully within " + retryAttempts + " attempts");
    } catch (final RuntimeException e) {
        log.warning("RuntimeException occured while calling ejbTimeout", e);
        throw e;
    } catch (final Error e) {
        log.warning("Error occured while calling ejbTimeout", e);
        throw e;
    } finally {
        thread.setContextClassLoader(loader);
        // TODO shall we do all this via Quartz listener ???
        if (timerData.getType() == TimerType.SingleAction) {
            timerStore.removeTimer(timerData.getId());
            timerData.setExpired(true);
        } else if (timerData.getType() == TimerType.Calendar && timerData.getNextTimeout() == null) {
            timerStore.removeTimer(timerData.getId());
            timerData.setExpired(true);
        } else {
            timerStore.updateIntervalTimer(timerData);
        }
    }
}
Also used : OpenEJBException(org.apache.openejb.OpenEJBException) Method(java.lang.reflect.Method) OpenEJBException(org.apache.openejb.OpenEJBException) EJBException(javax.ejb.EJBException) SchedulerException(org.apache.openejb.quartz.SchedulerException) ApplicationException(org.apache.openejb.ApplicationException) IOException(java.io.IOException) SystemException(javax.transaction.SystemException) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) RpcContainer(org.apache.openejb.RpcContainer) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) ApplicationException(org.apache.openejb.ApplicationException) Timer(javax.ejb.Timer) SystemException(javax.transaction.SystemException)

Example 73 with OpenEJBException

use of org.apache.openejb.OpenEJBException in project tomee by apache.

the class SingletonContainer method invoke.

@Override
public Object invoke(final Object deployID, InterfaceType type, final Class callInterface, final Method callMethod, final Object[] args, final Object primKey) throws OpenEJBException {
    final BeanContext beanContext = this.getBeanContext(deployID);
    if (beanContext == null) {
        throw new OpenEJBException("Deployment does not exist in this container. Deployment(id='" + deployID + "'), Container(id='" + containerID + "')");
    }
    // Use the backup way to determine call type if null was supplied.
    if (type == null) {
        type = beanContext.getInterfaceType(callInterface);
    }
    final Method runMethod = beanContext.getMatchingBeanMethod(callMethod);
    final ThreadContext callContext = new ThreadContext(beanContext, primKey);
    final ThreadContext oldCallContext = ThreadContext.enter(callContext);
    final CurrentCreationalContext currentCreationalContext = beanContext.get(CurrentCreationalContext.class);
    Object runAs = null;
    try {
        if (oldCallContext != null) {
            final BeanContext oldBc = oldCallContext.getBeanContext();
            if (oldBc.getRunAsUser() != null || oldBc.getRunAs() != null) {
                runAs = AbstractSecurityService.class.cast(securityService).overrideWithRunAsContext(callContext, beanContext, oldBc);
            }
        }
        final boolean authorized = type == InterfaceType.TIMEOUT || getSecurityService().isCallerAuthorized(callMethod, type);
        if (!authorized) {
            throw new org.apache.openejb.ApplicationException(new EJBAccessException("Unauthorized Access by Principal Denied"));
        }
        final Class declaringClass = callMethod.getDeclaringClass();
        if (EJBHome.class.isAssignableFrom(declaringClass) || EJBLocalHome.class.isAssignableFrom(declaringClass)) {
            if (callMethod.getName().startsWith("create")) {
                return createEJBObject(beanContext, callMethod);
            } else {
                // EJBHome.remove( ) and other EJBHome methods are not process by the container
                return null;
            }
        } else if (EJBObject.class == declaringClass || EJBLocalObject.class == declaringClass) {
            // EJBObject.remove( ) and other EJBObject methods are not process by the container
            return null;
        }
        final Instance instance = instanceManager.getInstance(callContext);
        callContext.setCurrentOperation(type == InterfaceType.TIMEOUT ? Operation.TIMEOUT : Operation.BUSINESS);
        callContext.setCurrentAllowedStates(null);
        callContext.set(Method.class, runMethod);
        callContext.setInvokedInterface(callInterface);
        if (currentCreationalContext != null) {
            // noinspection unchecked
            currentCreationalContext.set(instance.creationalContext);
        }
        return _invoke(callMethod, runMethod, args, instance, callContext, type);
    } finally {
        if (runAs != null) {
            try {
                securityService.associate(runAs);
            } catch (final LoginException e) {
            // no-op
            }
        }
        ThreadContext.exit(oldCallContext);
        if (currentCreationalContext != null) {
            currentCreationalContext.remove();
        }
    }
}
Also used : OpenEJBException(org.apache.openejb.OpenEJBException) EJBHome(javax.ejb.EJBHome) ThreadContext(org.apache.openejb.core.ThreadContext) Method(java.lang.reflect.Method) EJBAccessException(javax.ejb.EJBAccessException) EJBLocalHome(javax.ejb.EJBLocalHome) CurrentCreationalContext(org.apache.openejb.cdi.CurrentCreationalContext) BeanContext(org.apache.openejb.BeanContext) EjbTransactionUtil.handleApplicationException(org.apache.openejb.core.transaction.EjbTransactionUtil.handleApplicationException) LoginException(javax.security.auth.login.LoginException) EJBObject(javax.ejb.EJBObject) EJBLocalObject(javax.ejb.EJBLocalObject)

Example 74 with OpenEJBException

use of org.apache.openejb.OpenEJBException in project tomee by apache.

the class SingletonInstanceManager method deploy.

public void deploy(final BeanContext beanContext) throws OpenEJBException {
    final Data data = new Data(beanContext);
    beanContext.setContainerData(data);
    beanContext.set(EJBContext.class, this.sessionContext);
    // Create stats interceptor
    if (StatsInterceptor.isStatsActivated()) {
        final StatsInterceptor stats = new StatsInterceptor(beanContext.getBeanClass());
        beanContext.addFirstSystemInterceptor(stats);
        final ObjectNameBuilder jmxName = new ObjectNameBuilder("openejb.management");
        jmxName.set("J2EEServer", "openejb");
        jmxName.set("J2EEApplication", null);
        jmxName.set("EJBModule", beanContext.getModuleID());
        jmxName.set("SingletonSessionBean", beanContext.getEjbName());
        jmxName.set("name", beanContext.getEjbName());
        jmxName.set("j2eeType", "Invocations");
        // register the invocation stats interceptor
        final MBeanServer server = LocalMBeanServer.get();
        try {
            final ObjectName objectName = jmxName.build();
            if (server.isRegistered(objectName)) {
                server.unregisterMBean(objectName);
            }
            server.registerMBean(new ManagedMBean(stats), objectName);
            data.add(objectName);
        } catch (final Exception e) {
            logger.error("Unable to register MBean ", e);
        }
    }
    try {
        final Context context = beanContext.getJndiEnc();
        context.bind("comp/EJBContext", sessionContext);
        context.bind("comp/WebServiceContext", webServiceContext);
        context.bind("comp/TimerService", new TimerServiceWrapper());
    } catch (final NamingException e) {
        throw new OpenEJBException("Failed to bind EJBContext/WebServiceContext/TimerService", e);
    }
}
Also used : BeanContext(org.apache.openejb.BeanContext) WebServiceContext(javax.xml.ws.WebServiceContext) Context(javax.naming.Context) EJBContext(javax.ejb.EJBContext) InstanceContext(org.apache.openejb.core.InstanceContext) ThreadContext(org.apache.openejb.core.ThreadContext) ObjectNameBuilder(org.apache.openejb.monitoring.ObjectNameBuilder) TimerServiceWrapper(org.apache.openejb.core.timer.TimerServiceWrapper) OpenEJBException(org.apache.openejb.OpenEJBException) StatsInterceptor(org.apache.openejb.monitoring.StatsInterceptor) InterceptorData(org.apache.openejb.core.interceptor.InterceptorData) NamingException(javax.naming.NamingException) ManagedMBean(org.apache.openejb.monitoring.ManagedMBean) NoSuchEJBException(javax.ejb.NoSuchEJBException) NamingException(javax.naming.NamingException) ApplicationException(org.apache.openejb.ApplicationException) OpenEJBException(org.apache.openejb.OpenEJBException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ExecutionException(java.util.concurrent.ExecutionException) MBeanServer(javax.management.MBeanServer) LocalMBeanServer(org.apache.openejb.monitoring.LocalMBeanServer) ObjectName(javax.management.ObjectName)

Example 75 with OpenEJBException

use of org.apache.openejb.OpenEJBException in project tomee by apache.

the class JmsTest method setUp.

@Override
protected void setUp() throws Exception {
    super.setUp();
    // create a transaction manager
    final GeronimoTransactionManager transactionManager = new GeronimoTransactionManager();
    // create the ActiveMQ resource adapter instance
    ra = new ActiveMQResourceAdapter();
    // initialize properties
    ra.setServerUrl(brokerAddress);
    ra.setBrokerXmlConfig(brokerXmlConfig);
    ra.setStartupTimeout(new Duration(10, TimeUnit.SECONDS));
    // create a thead pool for ActiveMQ
    final Executor threadPool = Executors.newFixedThreadPool(30);
    // create a work manager which ActiveMQ uses to dispatch message delivery jobs
    final TransactionContextHandler txWorkContextHandler = new TransactionContextHandler(transactionManager);
    final GeronimoWorkManager workManager = new GeronimoWorkManager(threadPool, threadPool, threadPool, Collections.<WorkContextHandler>singletonList(txWorkContextHandler));
    // wrap the work mananger and transaction manager in a bootstrap context (connector spec thing)
    final BootstrapContext bootstrapContext = new GeronimoBootstrapContext(workManager, transactionManager, transactionManager);
    // Create a ConnectionFactory
    connectionFactory = new ActiveMQConnectionFactory(brokerAddress);
    ra.setConnectionFactory(connectionFactory);
    // start the resource adapter
    try {
        ra.start(bootstrapContext);
    } catch (final ResourceAdapterInternalException e) {
        throw new OpenEJBException(e);
    }
}
Also used : ActiveMQConnectionFactory(org.apache.activemq.ActiveMQConnectionFactory) OpenEJBException(org.apache.openejb.OpenEJBException) Executor(java.util.concurrent.Executor) GeronimoBootstrapContext(org.apache.geronimo.connector.GeronimoBootstrapContext) TransactionContextHandler(org.apache.geronimo.connector.work.TransactionContextHandler) GeronimoWorkManager(org.apache.geronimo.connector.work.GeronimoWorkManager) ActiveMQResourceAdapter(org.apache.openejb.resource.activemq.ActiveMQResourceAdapter) Duration(org.apache.openejb.util.Duration) GeronimoBootstrapContext(org.apache.geronimo.connector.GeronimoBootstrapContext) BootstrapContext(javax.resource.spi.BootstrapContext) GeronimoTransactionManager(org.apache.geronimo.transaction.manager.GeronimoTransactionManager) ResourceAdapterInternalException(javax.resource.spi.ResourceAdapterInternalException)

Aggregations

OpenEJBException (org.apache.openejb.OpenEJBException)187 IOException (java.io.IOException)55 NamingException (javax.naming.NamingException)34 URL (java.net.URL)31 MalformedURLException (java.net.MalformedURLException)30 ApplicationException (org.apache.openejb.ApplicationException)29 BeanContext (org.apache.openejb.BeanContext)29 File (java.io.File)26 ArrayList (java.util.ArrayList)26 OpenEJBRuntimeException (org.apache.openejb.OpenEJBRuntimeException)23 SystemException (org.apache.openejb.SystemException)22 Method (java.lang.reflect.Method)20 HashMap (java.util.HashMap)18 ThreadContext (org.apache.openejb.core.ThreadContext)17 InterceptorData (org.apache.openejb.core.interceptor.InterceptorData)15 RemoteException (java.rmi.RemoteException)14 EJBException (javax.ejb.EJBException)14 EjbTransactionUtil.handleApplicationException (org.apache.openejb.core.transaction.EjbTransactionUtil.handleApplicationException)14 HashSet (java.util.HashSet)13 Properties (java.util.Properties)13