Search in sources :

Example 26 with EJBException

use of javax.ejb.EJBException in project tomee by apache.

the class EntityManagerPropogationTest method _testSFEx2SLTr2SFEx.

public void _testSFEx2SLTr2SFEx() throws Exception {
    final InitialContext ctx = new InitialContext();
    final Node node = (Node) ctx.lookup("ExtendedToTransactionLocalBean");
    try {
        //	    System.out.println("SFSB+EPC --> SLSB+TPC --> SFSB+EPC");
        node.createUntilLeaf(6, "red");
    } catch (final EJBException e) {
        e.printStackTrace();
        fail("5.6.3.1 Requirements for Persistence Context Propagation (persistence spec)" + "\n\t--> the SFSB+EPC is the one who starts the transaction and then calls the " + "SLSB+TPC who then calls back to the SFSB+EPC \n\t--> IT SHOULD WORK ...");
    }
}
Also used : NoSuchEJBException(javax.ejb.NoSuchEJBException) OpenEJBException(org.apache.openejb.OpenEJBException) EJBException(javax.ejb.EJBException) InitialContext(javax.naming.InitialContext)

Example 27 with EJBException

use of javax.ejb.EJBException in project tomee by apache.

the class StatefulContainer method createEJBObject.

protected ProxyInfo createEJBObject(final BeanContext beanContext, final Method callMethod, final Object[] args, final InterfaceType interfaceType) throws OpenEJBException {
    // generate a new primary key
    final Object primaryKey = newPrimaryKey();
    final ThreadContext createContext = new ThreadContext(beanContext, primaryKey);
    final ThreadContext oldCallContext = ThreadContext.enter(createContext);
    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(createContext, beanContext, oldBc);
            }
        }
        // Security check
        checkAuthorization(callMethod, interfaceType);
        // Create the extended entity managers for this instance
        final Index<EntityManagerFactory, JtaEntityManagerRegistry.EntityManagerTracker> entityManagers = createEntityManagers(beanContext);
        // Register the newly created entity managers
        if (entityManagers != null) {
            try {
                entityManagerRegistry.addEntityManagers((String) beanContext.getDeploymentID(), primaryKey, entityManagers);
            } catch (final EntityManagerAlreadyRegisteredException e) {
                throw new EJBException(e);
            }
        }
        createContext.setCurrentOperation(Operation.CREATE);
        createContext.setCurrentAllowedStates(null);
        // Start transaction
        final TransactionPolicy txPolicy = EjbTransactionUtil.createTransactionPolicy(createContext.getBeanContext().getTransactionType(callMethod, interfaceType), createContext);
        Instance instance = null;
        try {
            try {
                final InstanceContext context = beanContext.newInstance();
                // Wrap-up everthing into a object
                instance = new Instance(beanContext, primaryKey, containerID, context.getBean(), context.getCreationalContext(), context.getInterceptors(), entityManagers, lockFactory.newLock(primaryKey.toString()));
            } catch (final Throwable throwable) {
                final ThreadContext callContext = ThreadContext.getThreadContext();
                EjbTransactionUtil.handleSystemException(callContext.getTransactionPolicy(), throwable, callContext);
                // should never be reached
                throw new IllegalStateException(throwable);
            }
            // add to cache
            if (isPassivable(beanContext)) {
                // no need to cache it it will never expires
                cache.add(primaryKey, instance);
            }
            // instance starts checked-out
            checkedOutInstances.put(primaryKey, instance);
            // Register for synchronization callbacks
            registerSessionSynchronization(instance, createContext);
            // Invoke create for legacy beans
            if (!callMethod.getDeclaringClass().equals(BeanContext.BusinessLocalHome.class) && !callMethod.getDeclaringClass().equals(BeanContext.BusinessRemoteHome.class) && !callMethod.getDeclaringClass().equals(BeanContext.BusinessLocalBeanHome.class)) {
                // Setup for business invocation
                final Method createOrInit = beanContext.getMatchingBeanMethod(callMethod);
                createContext.set(Method.class, createOrInit);
                // Initialize interceptor stack
                final InterceptorStack interceptorStack = new InterceptorStack(instance.bean, createOrInit, Operation.CREATE, new ArrayList<InterceptorData>(), new HashMap<String, Object>());
                // Invoke
                if (args == null) {
                    interceptorStack.invoke();
                } else {
                    interceptorStack.invoke(args);
                }
            }
        } catch (final Throwable e) {
            handleException(createContext, txPolicy, e);
        } finally {
            // un register EntityManager
            unregisterEntityManagers(instance, createContext);
            afterInvoke(createContext, txPolicy, instance);
        }
        return new ProxyInfo(beanContext, primaryKey);
    } finally {
        if (runAs != null) {
            try {
                securityService.associate(runAs);
            } catch (final LoginException e) {
            // no-op
            }
        }
        ThreadContext.exit(oldCallContext);
    }
}
Also used : EntityManagerAlreadyRegisteredException(org.apache.openejb.persistence.EntityManagerAlreadyRegisteredException) SystemInstance(org.apache.openejb.loader.SystemInstance) ThreadContext(org.apache.openejb.core.ThreadContext) JtaTransactionPolicy(org.apache.openejb.core.transaction.JtaTransactionPolicy) TransactionPolicy(org.apache.openejb.core.transaction.TransactionPolicy) BeanTransactionPolicy(org.apache.openejb.core.transaction.BeanTransactionPolicy) Method(java.lang.reflect.Method) BeanContext(org.apache.openejb.BeanContext) ProxyInfo(org.apache.openejb.ProxyInfo) InstanceContext(org.apache.openejb.core.InstanceContext) EntityManagerFactory(javax.persistence.EntityManagerFactory) InterceptorStack(org.apache.openejb.core.interceptor.InterceptorStack) InterceptorData(org.apache.openejb.core.interceptor.InterceptorData) LoginException(javax.security.auth.login.LoginException) OpenEJBException(org.apache.openejb.OpenEJBException) EJBException(javax.ejb.EJBException)

Example 28 with EJBException

use of javax.ejb.EJBException 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 29 with EJBException

use of javax.ejb.EJBException in project tomee by apache.

the class DiscoveryHostTest method test.

@Ignore
@Test
public void test() throws Exception {
    // To run in an IDE, uncomment and update this line
    //System.setProperty("version", OpenEjbVersion.get().getVersion());
    final File zip = Repository.getArtifact("org.apache.tomee", "openejb-standalone", "zip");
    final File app = Repository.getArtifact("org.apache.openejb.itests", "failover-ejb", "jar");
    final File dir = Files.tmpdir();
    final List<StandaloneServer> servers = new ArrayList<StandaloneServer>();
    final List<String> initialServers = new ArrayList<String>();
    for (final String name : new String[] { "red", "green", "blue" }) {
        final File home = new File(dir, name);
        Files.mkdir(home);
        Zips.unzip(zip, home, true);
        final StandaloneServer server = new StandaloneServer(home, home);
        server.killOnExit();
        server.ignoreOut();
        server.getJvmOpts().add("-Dopenejb.classloader.forced-load=org.apache.openejb");
        server.getProperties().put("name", name);
        server.getProperties().put("openejb.extract.configuration", "false");
        IO.copy(app, Files.path(home, "apps", "itest.jar"));
        IO.copy(IO.read("<openejb><Deployments dir=\"apps/\"/></openejb>"), Files.path(home, "conf", "openejb.xml"));
        final StandaloneServer.ServerService ejbd = server.getServerService("ejbd");
        ejbd.setDisabled(false);
        ejbd.setBind("0.0.0.0");
        ejbd.setPort(getAvailablePort());
        ejbd.setThreads(5);
        ejbd.set("discoveryHost", "localhost");
        ejbd.set("discovery", "ejb:ejbd://{discoveryHost}:{port}/" + name);
        final StandaloneServer.ServerService multipoint = server.getServerService("multipoint");
        multipoint.setBind("0.0.0.0");
        multipoint.setPort(getAvailablePort());
        multipoint.setDisabled(false);
        multipoint.set("discoveryHost", "localhost");
        initialServers.add("localhost:" + multipoint.getPort());
        servers.add(server);
    }
    servers.get(0).setOut(System.out);
    for (final StandaloneServer server : servers) {
        final StandaloneServer.ServerService multipoint = server.getServerService("multipoint");
        multipoint.set("initialServers", Join.join(",", initialServers));
    }
    for (final StandaloneServer server : servers) {
        server.start(1, TimeUnit.MINUTES);
    }
    Collections.reverse(servers);
    System.setProperty("openejb.client.requestretry", "true");
    final Properties environment = new Properties();
    environment.put(Context.INITIAL_CONTEXT_FACTORY, RemoteInitialContextFactory.class.getName());
    environment.put(Context.PROVIDER_URL, "failover:ejbd://localhost:" + servers.get(0).getServerService("ejbd").getPort());
    final InitialContext context = new InitialContext(environment);
    final Calculator bean = (Calculator) context.lookup("CalculatorBeanRemote");
    for (final StandaloneServer server : servers) {
        System.out.println(String.format("Average invocation time %s microseconds", invoke(bean, 10000)));
        server.kill();
    }
    System.out.println("All servers destroyed");
    try {
        System.out.println(String.format("Average invocation time %s microseconds", invoke(bean, 10000)));
        Assert.fail("Server should be destroyed");
    } catch (final EJBException e) {
    // good
    }
    for (final StandaloneServer server : servers) {
        server.start(1, TimeUnit.MINUTES);
        System.out.println(String.format("Average invocation time %s microseconds", invoke(bean, 10000)));
    }
    System.out.println("DONE");
}
Also used : StandaloneServer(org.apache.openejb.server.control.StandaloneServer) Calculator(org.apache.openejb.itest.failover.ejb.Calculator) ArrayList(java.util.ArrayList) RemoteInitialContextFactory(org.apache.openejb.client.RemoteInitialContextFactory) Properties(java.util.Properties) EJBException(javax.ejb.EJBException) File(java.io.File) InitialContext(javax.naming.InitialContext) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 30 with EJBException

use of javax.ejb.EJBException in project tomee by apache.

the class RandomConnectionStrategyTest method test.

@Test
public void test() throws Exception {
    //        To run in an IDE, uncomment and update this line
    //        System.setProperty("version", OpenEjbVersion.get().getVersion());
    System.setProperty("openejb.client.connection.strategy", "roundrobin");
    final File zip = Repository.getArtifact("org.apache.tomee", "openejb-standalone", "zip");
    final File app = Repository.getArtifact("org.apache.openejb.itests", "failover-ejb", "jar");
    final File dir = Files.tmpdir();
    final StandaloneServer root;
    {
        final String name = "root";
        final File home = new File(dir, name);
        Files.mkdir(home);
        Zips.unzip(zip, home, true);
        root = new StandaloneServer(home, home);
        root.killOnExit();
        root.getJvmOpts().add("-Dopenejb.classloader.forced-load=org.apache.openejb");
        root.ignoreOut();
        root.setProperty("name", name);
        root.setProperty("openejb.extract.configuration", "false");
        final StandaloneServer.ServerService multipoint = root.getServerService("multipoint");
        multipoint.setBind("localhost");
        multipoint.setPort(getNextAvailablePort());
        multipoint.setDisabled(false);
        multipoint.set("discoveryName", name);
        logger.info("Starting Root server");
        // Wait for it to start before continuing, otherwise test may fail in slower machines.
        root.start(1, TimeUnit.MINUTES);
    }
    final Services services = new Services();
    Client.addEventObserver(services);
    final Map<String, StandaloneServer> servers = new HashMap<String, StandaloneServer>();
    for (final String name : new String[] { "red", "green", "blue" }) {
        final File home = new File(dir, name);
        Files.mkdir(home);
        Zips.unzip(zip, home, true);
        final StandaloneServer server = new StandaloneServer(home, home);
        server.killOnExit();
        server.ignoreOut();
        server.setProperty("name", name);
        server.setProperty("openejb.extract.configuration", "false");
        server.getJvmOpts().add("-Dopenejb.classloader.forced-load=org.apache.openejb");
        IO.copy(app, Files.path(home, "apps", "itest.jar"));
        IO.copy(IO.read("<openejb><Deployments dir=\"apps/\"/></openejb>"), Files.path(home, "conf", "openejb.xml"));
        final StandaloneServer.ServerService ejbd = server.getServerService("ejbd");
        ejbd.setBind("localhost");
        ejbd.setDisabled(false);
        ejbd.setPort(getNextAvailablePort());
        ejbd.setThreads(5);
        final URI uri = URI.create(String.format("ejbd://%s:%s/%s", ejbd.getBind(), ejbd.getPort(), name));
        ejbd.set("discovery", "ejb:" + uri);
        services.add(uri);
        server.getContext().set(URI.class, uri);
        final StandaloneServer.ServerService multipoint = server.getServerService("multipoint");
        multipoint.setPort(getNextAvailablePort());
        multipoint.setDisabled(false);
        multipoint.set("discoveryName", name);
        multipoint.set("initialServers", "localhost:" + root.getServerService("multipoint").getPort());
        servers.put(name, server);
        logger.info(String.format("Starting %s server", name));
        server.start(1, TimeUnit.MINUTES);
    }
    System.setProperty("openejb.client.requestretry", "true");
    System.setProperty("openejb.client.connection.strategy", "random");
    logger.info("Beginning Test");
    final Properties environment = new Properties();
    environment.put(Context.INITIAL_CONTEXT_FACTORY, RemoteInitialContextFactory.class.getName());
    environment.put(Context.PROVIDER_URL, "ejbd://localhost:" + servers.values().iterator().next().getServerService("ejbd").getPort() + "/provider");
    final InitialContext context = new InitialContext(environment);
    final Calculator bean = (Calculator) context.lookup("CalculatorBeanRemote");
    for (final Map.Entry<String, StandaloneServer> entry : servers.entrySet()) {
        final String name = entry.getKey();
        final StandaloneServer server = entry.getValue();
        final URI serverURI = server.getContext().get(URI.class);
        logger.info("Waiting for updated list");
        services.assertServices(CLIENT_DELAY, TimeUnit.SECONDS, new CalculatorCallable(bean), 500);
        logger.info("Asserting balance");
        assertBalance(bean, services.get().size());
        logger.info("Shutting down " + name);
        server.kill();
        services.remove(serverURI);
    }
    logger.info("All Servers Shutdown");
    try {
        logger.info("Making one last request, expecting complete failover");
        final String name = bean.name();
        Assert.fail("Server should be destroyed: " + name);
    } catch (final EJBException e) {
        logger.info(String.format("Pass.  Request resulted in %s: %s", e.getCause().getClass().getSimpleName(), e.getMessage()));
    // good
    }
    for (final Map.Entry<String, StandaloneServer> entry : servers.entrySet()) {
        final String name = entry.getKey();
        final StandaloneServer server = entry.getValue();
        final URI serverURI = server.getContext().get(URI.class);
        logger.info(String.format("Starting %s server", name));
        server.start(1, TimeUnit.MINUTES);
        services.add(serverURI);
        logger.info("Waiting for updated list");
        services.assertServices(CLIENT_DELAY, TimeUnit.SECONDS, new CalculatorCallable(bean), 500);
        logger.info("Asserting balance");
        assertBalance(bean, services.get().size());
    }
}
Also used : HashMap(java.util.HashMap) Properties(java.util.Properties) URI(java.net.URI) InitialContext(javax.naming.InitialContext) StandaloneServer(org.apache.openejb.server.control.StandaloneServer) Calculator(org.apache.openejb.itest.failover.ejb.Calculator) RemoteInitialContextFactory(org.apache.openejb.client.RemoteInitialContextFactory) EJBException(javax.ejb.EJBException) File(java.io.File) HashMap(java.util.HashMap) Map(java.util.Map) Test(org.junit.Test)

Aggregations

EJBException (javax.ejb.EJBException)86 InitialContext (javax.naming.InitialContext)40 OpenEJBException (org.apache.openejb.OpenEJBException)24 Test (org.junit.Test)16 RemoteException (java.rmi.RemoteException)13 CreateException (javax.ejb.CreateException)12 NamingException (javax.naming.NamingException)11 Connection (java.sql.Connection)10 PreparedStatement (java.sql.PreparedStatement)10 DataSource (javax.sql.DataSource)10 Properties (java.util.Properties)9 ThreadContext (org.apache.openejb.core.ThreadContext)9 FinderException (javax.ejb.FinderException)7 HashMap (java.util.HashMap)6 RemoveException (javax.ejb.RemoveException)6 BeanContext (org.apache.openejb.BeanContext)6 File (java.io.File)5 NoSuchObjectLocalException (javax.ejb.NoSuchObjectLocalException)5 JMSException (javax.jms.JMSException)5 Assembler (org.apache.openejb.assembler.classic.Assembler)5