Search in sources :

Example 16 with Duration

use of org.apache.openejb.util.Duration in project tomee by apache.

the class ReconnectDelayListSelfTest method test.

@Test
public void test() throws Exception {
    // To run in an IDE, uncomment and update this line
    System.setProperty("version", OpenEjbVersion.get().getVersion());
    final Duration reconnectDelay = new Duration("1 second");
    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();
    System.setProperty("openejb.client.requestretry", "true");
    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.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");
        multipoint.set("discoveryName", name);
        multipoint.set("reconnectDelay", reconnectDelay.toString());
        servers.put(name, server);
    }
    final StandaloneServer red = servers.get("red");
    // Set all the initialServers to point to RED
    for (final Map.Entry<String, StandaloneServer> entry : servers.entrySet()) {
        final StandaloneServer server = entry.getValue();
        final StandaloneServer.ServerService multipoint = server.getServerService(MULTIPOINT);
        final String value = "localhost:" + red.getServerService(MULTIPOINT).getPort() + ",localhost:" + multipoint.getPort();
        multipoint.set("initialServers", value);
    }
    // Start all the servers except RED
    for (final Map.Entry<String, StandaloneServer> entry : servers.entrySet()) {
        if (entry.getKey().equals("red"))
            continue;
        entry.getValue().start(1, TimeUnit.MINUTES);
    }
    // Verify Failover is not yet functional
    {
        // RED was never started so BLUE never found any peers
        // Lets invoke BLUE then shut it down and verify we have
        // no other peers to invoke
        final StandaloneServer blue = servers.get("blue");
        final Properties environment = new Properties();
        environment.put(Context.INITIAL_CONTEXT_FACTORY, RemoteInitialContextFactory.class.getName());
        environment.put(Context.PROVIDER_URL, "ejbd://localhost:" + blue.getServerService("ejbd").getPort());
        final InitialContext context = new InitialContext(environment);
        final Calculator bean = (Calculator) context.lookup("CalculatorBeanRemote");
        // Invoke BLUE a few times
        invoke(bean, 10, "blue");
        // Kill BLUE
        blue.kill();
        // Invocations should now fail (and not failover)
        try {
            bean.name();
            Assert.fail("Server should be down and failover not hooked up");
        } catch (final Exception e) {
        // pass
        }
    }
    // Now we start RED
    red.start(1, TimeUnit.MINUTES);
    // Wait for the reconnectDelay so GREEN can find RED
    Thread.sleep((long) (reconnectDelay.getTime(TimeUnit.MILLISECONDS) * 1.5));
    // Verify Failover is now functional
    {
        // RED was never started so GREEN never found any peers
        // Lets invoke GREEN then shut it down and verify we have
        // no other peers to invoke
        final StandaloneServer green = servers.get("green");
        final Properties environment = new Properties();
        environment.put(Context.INITIAL_CONTEXT_FACTORY, RemoteInitialContextFactory.class.getName());
        environment.put(Context.PROVIDER_URL, "ejbd://localhost:" + green.getServerService("ejbd").getPort());
        final InitialContext context = new InitialContext(environment);
        final Calculator bean = (Calculator) context.lookup("CalculatorBeanRemote");
        // Invoke GREEN a few times
        invoke(bean, 10, "green");
        // Kill GREEN
        green.kill();
        // Invocations should now failover to RED
        invoke(bean, 10, "red");
    }
}
Also used : HashMap(java.util.HashMap) Duration(org.apache.openejb.util.Duration) Properties(java.util.Properties) InitialContext(javax.naming.InitialContext) StandaloneServer(org.apache.openejb.server.control.StandaloneServer) Calculator(org.apache.openejb.itest.failover.ejb.Calculator) File(java.io.File) HashMap(java.util.HashMap) Map(java.util.Map) Test(org.junit.Test)

Example 17 with Duration

use of org.apache.openejb.util.Duration in project tomee by apache.

the class ReconnectDelayTest method test.

@Test
public void test() throws Exception {
    // To run in an IDE, uncomment and update this line
    System.setProperty("version", OpenEjbVersion.get().getVersion());
    final Duration reconnectDelay = new Duration("1 second");
    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();
    System.setProperty("openejb.client.requestretry", "true");
    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.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");
        multipoint.set("discoveryName", name);
        multipoint.set("reconnectDelay", reconnectDelay.toString());
        servers.put(name, server);
    }
    final StandaloneServer red = servers.get("red");
    // Set all the initialServers to point to RED
    for (final Map.Entry<String, StandaloneServer> entry : servers.entrySet()) {
        final StandaloneServer server = entry.getValue();
        final StandaloneServer.ServerService multipoint = server.getServerService(MULTIPOINT);
        multipoint.set("initialServers", "localhost:" + red.getServerService(MULTIPOINT).getPort());
    }
    // Start all the servers except RED
    for (final Map.Entry<String, StandaloneServer> entry : servers.entrySet()) {
        if (entry.getKey().equals("red"))
            continue;
        entry.getValue().start(1, TimeUnit.MINUTES);
    }
    // Verify Failover is not yet functional
    {
        // RED was never started so BLUE never found any peers
        // Lets invoke BLUE then shut it down and verify we have
        // no other peers to invoke
        final StandaloneServer blue = servers.get("blue");
        final Properties environment = new Properties();
        environment.put(Context.INITIAL_CONTEXT_FACTORY, RemoteInitialContextFactory.class.getName());
        environment.put(Context.PROVIDER_URL, "ejbd://localhost:" + blue.getServerService("ejbd").getPort());
        final InitialContext context = new InitialContext(environment);
        final Calculator bean = (Calculator) context.lookup("CalculatorBeanRemote");
        // Invoke BLUE a few times
        invoke(bean, 10, "blue");
        // Kill BLUE
        blue.kill();
        // Invocations should now fail (and not failover)
        try {
            bean.name();
            Assert.fail("Server should be down and failover not hooked up");
        } catch (final Exception e) {
        // pass
        }
    }
    // Now we start RED
    red.start(1, TimeUnit.MINUTES);
    // Wait for the reconnectDelay so GREEN can find RED
    Thread.sleep((long) (reconnectDelay.getTime(TimeUnit.MILLISECONDS) * 1.5));
    // Verify Failover is now functional
    {
        // RED was never started so GREEN never found any peers
        // Lets invoke GREEN then shut it down and verify we have
        // no other peers to invoke
        final StandaloneServer green = servers.get("green");
        final Properties environment = new Properties();
        environment.put(Context.INITIAL_CONTEXT_FACTORY, RemoteInitialContextFactory.class.getName());
        environment.put(Context.PROVIDER_URL, "ejbd://localhost:" + green.getServerService("ejbd").getPort());
        final InitialContext context = new InitialContext(environment);
        final Calculator bean = (Calculator) context.lookup("CalculatorBeanRemote");
        // Invoke GREEN a few times
        invoke(bean, 10, "green");
        // Kill GREEN
        green.kill();
        // Invocations should now failover to RED
        invoke(bean, 10, "red");
    }
}
Also used : HashMap(java.util.HashMap) Duration(org.apache.openejb.util.Duration) Properties(java.util.Properties) InitialContext(javax.naming.InitialContext) StandaloneServer(org.apache.openejb.server.control.StandaloneServer) Calculator(org.apache.openejb.itest.failover.ejb.Calculator) File(java.io.File) HashMap(java.util.HashMap) Map(java.util.Map) Test(org.junit.Test)

Example 18 with Duration

use of org.apache.openejb.util.Duration in project tomee by apache.

the class ReconnectDelayCaseInsensitiveTest method test.

@Test
public void test() throws Exception {
    // To run in an IDE, uncomment and update this line
    System.setProperty("version", OpenEjbVersion.get().getVersion());
    final Duration reconnectDelay = new Duration("1 second");
    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();
    System.setProperty("openejb.client.requestretry", "true");
    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.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");
        multipoint.set("discoveryName", name);
        multipoint.set("reconnectDelay", reconnectDelay.toString());
        servers.put(name, server);
    }
    final StandaloneServer red = servers.get("red");
    // Set all the initialServers to point to RED
    for (final Map.Entry<String, StandaloneServer> entry : servers.entrySet()) {
        final StandaloneServer server = entry.getValue();
        final StandaloneServer.ServerService multipoint = server.getServerService(MULTIPOINT);
        final String value = "lOcAlHosT:" + red.getServerService(MULTIPOINT).getPort() + ",locALHost:" + multipoint.getPort();
        multipoint.set("initialServers", value);
    }
    // Start all the servers except RED
    for (final Map.Entry<String, StandaloneServer> entry : servers.entrySet()) {
        if (entry.getKey().equals("red"))
            continue;
        entry.getValue().start(1, TimeUnit.MINUTES);
    }
    // Verify Failover is not yet functional
    {
        // RED was never started so BLUE never found any peers
        // Lets invoke BLUE then shut it down and verify we have
        // no other peers to invoke
        final StandaloneServer blue = servers.get("blue");
        final Properties environment = new Properties();
        environment.put(Context.INITIAL_CONTEXT_FACTORY, RemoteInitialContextFactory.class.getName());
        environment.put(Context.PROVIDER_URL, "ejbd://localhost:" + blue.getServerService("ejbd").getPort());
        final InitialContext context = new InitialContext(environment);
        final Calculator bean = (Calculator) context.lookup("CalculatorBeanRemote");
        // Invoke BLUE a few times
        invoke(bean, 10, "blue");
        // Kill BLUE
        blue.kill();
        // Invocations should now fail (and not failover)
        try {
            bean.name();
            Assert.fail("Server should be down and failover not hooked up");
        } catch (final Exception e) {
        // pass
        }
    }
    // Now we start RED
    red.start(1, TimeUnit.MINUTES);
    // Wait for the reconnectDelay so GREEN can find RED
    Thread.sleep((long) (reconnectDelay.getTime(TimeUnit.MILLISECONDS) * 1.5));
    // Verify Failover is now functional
    {
        // RED was never started so GREEN never found any peers
        // Lets invoke GREEN then shut it down and verify we have
        // no other peers to invoke
        final StandaloneServer green = servers.get("green");
        final Properties environment = new Properties();
        environment.put(Context.INITIAL_CONTEXT_FACTORY, RemoteInitialContextFactory.class.getName());
        environment.put(Context.PROVIDER_URL, "ejbd://localhost:" + green.getServerService("ejbd").getPort());
        final InitialContext context = new InitialContext(environment);
        final Calculator bean = (Calculator) context.lookup("CalculatorBeanRemote");
        // Invoke GREEN a few times
        invoke(bean, 10, "green");
        // Kill GREEN
        green.kill();
        // Invocations should now failover to RED
        invoke(bean, 10, "red");
    }
}
Also used : HashMap(java.util.HashMap) Duration(org.apache.openejb.util.Duration) Properties(java.util.Properties) InitialContext(javax.naming.InitialContext) StandaloneServer(org.apache.openejb.server.control.StandaloneServer) Calculator(org.apache.openejb.itest.failover.ejb.Calculator) File(java.io.File) HashMap(java.util.HashMap) Map(java.util.Map) Test(org.junit.Test)

Example 19 with Duration

use of org.apache.openejb.util.Duration in project tomee by apache.

the class StatelessInstanceManager method deploy.

@SuppressWarnings("unchecked")
public void deploy(final BeanContext beanContext) throws OpenEJBException {
    final Options options = new Options(beanContext.getProperties());
    final Duration accessTimeout = getDuration(options, "AccessTimeout", // default timeout
    getDuration(options, "Timeout", this.accessTimeout, TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS);
    final Duration closeTimeout = getDuration(options, "CloseTimeout", this.closeTimeout, TimeUnit.MINUTES);
    final ObjectRecipe recipe = PassthroughFactory.recipe(new Pool.Builder(poolBuilder));
    recipe.allow(Option.CASE_INSENSITIVE_FACTORY);
    recipe.allow(Option.CASE_INSENSITIVE_PROPERTIES);
    recipe.allow(Option.IGNORE_MISSING_PROPERTIES);
    recipe.setAllProperties(beanContext.getProperties());
    final Pool.Builder builder = (Pool.Builder) recipe.create();
    setDefault(builder.getMaxAge(), TimeUnit.HOURS);
    setDefault(builder.getIdleTimeout(), TimeUnit.MINUTES);
    setDefault(builder.getInterval(), TimeUnit.MINUTES);
    final StatelessSupplier supplier = new StatelessSupplier(beanContext);
    builder.setSupplier(supplier);
    builder.setExecutor(executor);
    builder.setScheduledExecutor(scheduledExecutor);
    final Data data = new Data(builder.build(), accessTimeout, closeTimeout);
    beanContext.setContainerData(data);
    beanContext.set(EJBContext.class, data.sessionContext);
    try {
        final Context context = beanContext.getJndiEnc();
        context.bind("comp/EJBContext", data.sessionContext);
        context.bind("comp/WebServiceContext", new EjbWsContext(data.sessionContext));
        context.bind("comp/TimerService", new TimerServiceWrapper());
    } catch (final NamingException e) {
        throw new OpenEJBException("Failed to bind EJBContext/WebServiceContext/TimerService", e);
    }
    final int min = builder.getMin();
    final long maxAge = builder.getMaxAge().getTime(TimeUnit.MILLISECONDS);
    final double maxAgeOffset = builder.getMaxAgeOffset();
    final ObjectNameBuilder jmxName = new ObjectNameBuilder("openejb.management");
    jmxName.set("J2EEServer", "openejb");
    jmxName.set("J2EEApplication", null);
    jmxName.set("EJBModule", beanContext.getModuleID());
    jmxName.set("StatelessSessionBean", beanContext.getEjbName());
    jmxName.set("name", beanContext.getEjbName());
    final MBeanServer server = LocalMBeanServer.get();
    // Create stats interceptor
    if (StatsInterceptor.isStatsActivated()) {
        StatsInterceptor stats = null;
        for (final InterceptorInstance interceptor : beanContext.getUserAndSystemInterceptors()) {
            if (interceptor.getInterceptor() instanceof StatsInterceptor) {
                stats = (StatsInterceptor) interceptor.getInterceptor();
            }
        }
        if (stats == null) {
            // normally useless
            stats = new StatsInterceptor(beanContext.getBeanClass());
            beanContext.addFirstSystemInterceptor(stats);
        }
        // register the invocation stats interceptor
        try {
            final ObjectName objectName = jmxName.set("j2eeType", "Invocations").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);
        }
    }
    // register the pool
    try {
        final ObjectName objectName = jmxName.set("j2eeType", "Pool").build();
        if (server.isRegistered(objectName)) {
            server.unregisterMBean(objectName);
        }
        server.registerMBean(new ManagedMBean(data.pool), objectName);
        data.add(objectName);
    } catch (final Exception e) {
        logger.error("Unable to register MBean ", e);
    }
    // Finally, fill the pool and start it
    if (!options.get("BackgroundStartup", false) && min > 0) {
        final ExecutorService es = Executors.newFixedThreadPool(min);
        for (int i = 0; i < min; i++) {
            es.submit(new InstanceCreatorRunnable(maxAge, i, min, maxAgeOffset, data, supplier));
        }
        es.shutdown();
        try {
            es.awaitTermination(5, TimeUnit.MINUTES);
        } catch (final InterruptedException e) {
            logger.error("can't fill the stateless pool", e);
        }
    }
    data.getPool().start();
}
Also used : Options(org.apache.openejb.loader.Options) OpenEJBException(org.apache.openejb.OpenEJBException) ObjectNameBuilder(org.apache.openejb.monitoring.ObjectNameBuilder) TimerServiceWrapper(org.apache.openejb.core.timer.TimerServiceWrapper) ObjectRecipe(org.apache.xbean.recipe.ObjectRecipe) Pool(org.apache.openejb.util.Pool) NamingException(javax.naming.NamingException) MBeanServer(javax.management.MBeanServer) LocalMBeanServer(org.apache.openejb.monitoring.LocalMBeanServer) SessionContext(javax.ejb.SessionContext) BeanContext(org.apache.openejb.BeanContext) Context(javax.naming.Context) EJBContext(javax.ejb.EJBContext) InstanceContext(org.apache.openejb.core.InstanceContext) ThreadContext(org.apache.openejb.core.ThreadContext) StatsInterceptor(org.apache.openejb.monitoring.StatsInterceptor) Duration(org.apache.openejb.util.Duration) InterceptorData(org.apache.openejb.core.interceptor.InterceptorData) InterceptorInstance(org.apache.openejb.core.interceptor.InterceptorInstance) TimeoutException(java.util.concurrent.TimeoutException) NamingException(javax.naming.NamingException) ConcurrentAccessTimeoutException(javax.ejb.ConcurrentAccessTimeoutException) OpenEJBException(org.apache.openejb.OpenEJBException) InvocationTargetException(java.lang.reflect.InvocationTargetException) RemoteException(java.rmi.RemoteException) SystemException(org.apache.openejb.SystemException) ApplicationException(org.apache.openejb.ApplicationException) IOException(java.io.IOException) ObjectName(javax.management.ObjectName) ObjectNameBuilder(org.apache.openejb.monitoring.ObjectNameBuilder) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ExecutorService(java.util.concurrent.ExecutorService) ManagedMBean(org.apache.openejb.monitoring.ManagedMBean)

Example 20 with Duration

use of org.apache.openejb.util.Duration in project tomee by apache.

the class SessionManager method initEviction.

public void initEviction() {
    if (!"true".equalsIgnoreCase(SystemInstance.get().getProperty("openejb.http.eviction", "true"))) {
        return;
    }
    final Duration duration = new Duration(SystemInstance.get().getProperty("openejb.http.eviction.duration", "1 minute"));
    es = Executors.newScheduledThreadPool(1, new DaemonThreadFactory(SessionManager.class));
    es.scheduleWithFixedDelay(new Runnable() {

        @Override
        public void run() {
            for (final SessionWrapper data : new ArrayList<>(sessions.values())) {
                final HttpSession session = data.session;
                if (session.getMaxInactiveInterval() > 0 && session.getLastAccessedTime() + TimeUnit.SECONDS.toMillis(session.getMaxInactiveInterval()) < System.currentTimeMillis()) {
                    doDestroy(data);
                    sessions.remove(data.session.getId());
                }
            }
        }
    }, duration.getTime(), duration.getTime(), duration.getUnit());
}
Also used : DaemonThreadFactory(org.apache.openejb.util.DaemonThreadFactory) HttpSession(org.apache.openejb.server.httpd.HttpSession) Duration(org.apache.openejb.util.Duration)

Aggregations

Duration (org.apache.openejb.util.Duration)20 HashMap (java.util.HashMap)6 Map (java.util.Map)5 File (java.io.File)4 NamingException (javax.naming.NamingException)4 OpenEJBException (org.apache.openejb.OpenEJBException)4 Test (org.junit.Test)4 Method (java.lang.reflect.Method)3 Properties (java.util.Properties)3 InitialContext (javax.naming.InitialContext)3 BeanContext (org.apache.openejb.BeanContext)3 Calculator (org.apache.openejb.itest.failover.ejb.Calculator)3 StandaloneServer (org.apache.openejb.server.control.StandaloneServer)3 PrintStream (java.io.PrintStream)2 RemoteException (java.rmi.RemoteException)2 ArrayList (java.util.ArrayList)2 HashSet (java.util.HashSet)2 ExecutorService (java.util.concurrent.ExecutorService)2 TimeoutException (java.util.concurrent.TimeoutException)2 ConcurrentAccessTimeoutException (javax.ejb.ConcurrentAccessTimeoutException)2