@Override protected void destroyStatefulSessionBeanInstance(final T proxyInstance, final Object unused) { if (proxyInstance instanceof BeanContext.Removable) { try { ((BeanContext.Removable) proxyInstance).$$remove(); } catch (final NoSuchEJBException nsee) { // no-op } catch (final UndeclaredThrowableException nsoe) { if (!(nsoe.getCause() instanceof NoSuchObjectException)) { throw nsoe; } } catch (final Exception e) { if (!(e instanceof NoSuchObjectException)) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } throw new OpenEJBRuntimeException(e); } } } }
private void destroyScopedStateful(final T instance, final CreationalContext<T> cc) { try { instance.hashCode(); // force the instance to be created - otherwise we'll miss @PreDestroy for instance } catch (final NoSuchEJBException e) { InvocationHandler handler = null; if (LocalBeanProxyFactory.isProxy(instance.getClass())) { handler = LocalBeanProxyFactory.getInvocationHandler(instance); } else if (ProxyManager.isProxyClass(instance.getClass())) { handler = ProxyManager.getInvocationHandler(instance); } if (BaseEjbProxyHandler.class.isInstance(handler) && !BaseEjbProxyHandler.class.cast(handler).isValid()) { return; // already destroyed } // else log error logger.log(Level.FINE, "The stateful instance " + instance + " can't be removed since it was invalidated", e); return; } final Object ejbInstance = dependentSFSBToBeRemoved.remove(System.identityHashCode(instance)); if (ejbInstance != null) { destroyStatefulSessionBeanInstance((T) ejbInstance, cc); } else { destroyStatefulSessionBeanInstance(instance, cc); } }
private void isValidReference(final Method method) throws NoSuchObjectException { if (isInvalidReference) { if (interfaceType.isComponent() && interfaceType.isLocal()) { throw new NoSuchObjectLocalException("reference is invalid"); } else if (interfaceType.isComponent() || Remote.class.isAssignableFrom(method.getDeclaringClass())) { throw new NoSuchObjectException("reference is invalid"); } else { throw new NoSuchEJBException("reference is invalid for " + deploymentID); } } if (!(Object.class.equals(method.getDeclaringClass()) && method.getName().equals("finalize") && method.getExceptionTypes().length == 1 && Throwable.class.equals(method.getExceptionTypes()[0]))) { getBeanContext(); // will throw an exception if app has been undeployed. } }
public void testZeroTimeout() throws Exception { final InitialContext ctx = new InitialContext(); final MyLocalBean bean; // cache is cleared ever 3 seconds and bean timeout is 0 seconds bean = (MyLocalBean) ctx.lookup("BeanZeroLocal"); bean.doNothing(0); // cache should be cleared by now and the bean should be removed Thread.sleep(5 * 1000); try { bean.doNothing(0); fail("Did not throw expected exception"); } catch (final NoSuchEJBException e) { // that's what we expect } }
public void testTimeout() throws Exception { final InitialContext ctx = new InitialContext(); final MyLocalBean bean; // cache is cleared ever 3 seconds and bean timeout is 5 seconds bean = (MyLocalBean) ctx.lookup("BeanLocal"); bean.doNothing(0); // cache should be cleared once by now but the bean is not expired yet Thread.sleep(5 * 1000); bean.doNothing(0); // cache should be cleared again and our bean should be removed // since the bean was idle for more than 5 seconds. Thread.sleep(10 * 1000); try { bean.doNothing(0); fail("Did not throw expected exception"); } catch (final NoSuchEJBException e) { // that's what we expect } }
@Test public void testStatefulTimeout() throws InterruptedException { logger.info("start test stateful timeout"); assertFalse("The stateful session is not registered", user.isRegistered()); user.register(); assertTrue("The stateful session is registered", user.isRegistered()); sleep(160); try { user.isRegistered(); fail(); } catch (NoSuchEJBException e) { logger.info("The ejb is expired"); } logger.info("Timeout end."); }
@Override public Object invoke(final Object proxy, final Method method, final Object... args) throws Throwable { if (isInvalidReference.get()) { if (remote || java.rmi.Remote.class.isAssignableFrom(method.getDeclaringClass())) { throw new NoSuchObjectException("reference is invalid"); } else { throw new NoSuchEJBException("reference is invalid"); } } return _invoke(proxy, method, args); }
private Instance createInstance(final ThreadContext callContext, final BeanContext beanContext) throws ApplicationException { try { initializeDependencies(beanContext); final InstanceContext context = beanContext.newInstance(); if (context.getBean() instanceof SessionBean) { final Operation originalOperation = callContext.getCurrentOperation(); try { callContext.setCurrentOperation(Operation.CREATE); final Method create = beanContext.getCreateMethod(); final InterceptorStack ejbCreate = new InterceptorStack(context.getBean(), create, Operation.CREATE, new ArrayList<InterceptorData>(), new HashMap()); ejbCreate.invoke(); } finally { callContext.setCurrentOperation(originalOperation); } } final ReadWriteLock lock; if (beanContext.isBeanManagedConcurrency()) { // Bean-Managed Concurrency lock = new BeanManagedLock(); } else { // Container-Managed Concurrency lock = new ReentrantReadWriteLock(); } return new Instance(context.getBean(), context.getInterceptors(), context.getCreationalContext(), lock); } catch (Throwable e) { if (e instanceof InvocationTargetException) { e = ((InvocationTargetException) e).getTargetException(); } final String t = "The bean instance " + beanContext.getDeploymentID() + " threw a system exception:" + e; logger.error(t, e); throw new ApplicationException(new NoSuchEJBException("Singleton failed to initialize").initCause(e)); } }
@Test public void checkBeanIsCleaned() throws Exception { assertNotNull(context); final TimedOutStateful stateful = (TimedOutStateful) context.lookup("global/StatefulStatefulTimeoutTest/stateful/TimedOutStateful"); stateful.foo(); Thread.sleep(6000); try { stateful.foo(); fail(); } catch (final NoSuchEJBException e) { // ok } }
/** * Test that the extended persistence context can * survive the removal of the parent * * @throws Exception */ public void _testExtendedRemove() throws Exception { final InitialContext ctx = new InitialContext(); Node node = (Node) ctx.lookup("ExtendedLocalBean"); // This bean should still be attached // when the transaction commits final Color attached = node.create(2, "Blue"); while (node.getChild() != null) { assertTrue(node.contains(attached)); final Node next = node.getChild(); node.remove(); try { node.contains(attached); fail("The Stateful bean should have been removed"); } catch (final NoSuchEJBException e) { // good } node = next; } }
@Test public void testBusinessLocalInterface() throws Exception { Widget.lifecycle.clear(); final WidgetLocal widgetLocal = (WidgetLocal) new InitialContext().lookup("WidgetLocal"); widgetLocal.widget(); final BeanContext.Removable removable = (BeanContext.Removable) widgetLocal; removable.$$remove(); try { widgetLocal.widget(); fail("The bean should have been removed"); } catch (final NoSuchEJBException e) { // pass } // Check the lifecycle of the bean final Lifecycle[] expected = { Lifecycle.CONSTRUCTOR, Lifecycle.POST_CONSTRUCT, Lifecycle.BUSINESS_METHOD, Lifecycle.PRE_DESTROY}; assertEquals(join("\n", Arrays.asList(expected)), join("\n", Widget.lifecycle)); }
public void testFailure() throws Throwable { final Exception exception1 = new Exception("Inner exception"); exception1.fillInStackTrace(); exception.set(true); final Context context = new InitialContext(); final int threads = 200; final CyclicBarrier start = new CyclicBarrier(threads + 1); final CountDownLatch finish = new CountDownLatch(threads); for (int i = threads; i > 0; i--) { final Thread thread = new Thread(new Client(context, start, finish)); thread.setDaemon(true); thread.start(); } start.await(30, TimeUnit.SECONDS); assertFalse("All threads did not start", start.isBroken()); assertTrue("Client threads did not complete", finish.await(30, TimeUnit.SECONDS)); assertEquals("incorrect number of instances", 1, MySingleton.instances.get()); // Invoke a business method just to be sure final MySingletonLocal singletonLocal = (MySingletonLocal) context.lookup("MySingletonLocal"); try { assertEquals(1, singletonLocal.getId()); fail("Expected NoSuchEJBException"); } catch (final NoSuchEJBException e) { // pass } }
/** * Renamed method so it shows up with a much more understandable purpose as it * will be the top element in the stacktrace * * @param e Throwable * @param method Method */ protected Throwable convertException(final Throwable e, final Method method) { if (!remote && e instanceof RemoteException) { if (e instanceof TransactionRequiredException) { return new TransactionRequiredLocalException(e.getMessage()).initCause(getCause(e)); } if (e instanceof TransactionRolledbackException) { return new TransactionRolledbackLocalException(e.getMessage()).initCause(getCause(e)); } /** * If a client attempts to invoke a method on a removed bean's business interface, * we must throw a javax.ejb.NoSuchEJBException. If the business interface is a * remote business interface that extends java.rmi.Remote, the * java.rmi.NoSuchObjectException is thrown to the client instead. * See EJB 3.0, section 4.4 */ if (e instanceof NoSuchObjectException) { if (java.rmi.Remote.class.isAssignableFrom(method.getDeclaringClass())) { return e; } else { return new NoSuchEJBException(e.getMessage()).initCause(getCause(e)); } } if (e instanceof AccessException) { return new AccessLocalException(e.getMessage()).initCause(getCause(e)); } return new EJBException(e.getMessage()).initCause(getCause(e)); } if (remote && e instanceof EJBAccessException) { if (e.getCause() instanceof Exception) { return new AccessException(e.getMessage(), (Exception) e.getCause()); } else { return new AccessException(e.getMessage()); } } if (!remote && e instanceof EJBTransactionRolledbackException) { return new TransactionRolledbackLocalException(e.getMessage()).initCause(getCause(e)); } return e; }
/** * Renamed method so it shows up with a much more understandable purpose as it * will be the top element in the stacktrace * * @param e Throwable * @param method Method * @param interfce Class */ protected Throwable convertException(Throwable e, final Method method, final Class interfce) { final boolean rmiRemote = Remote.class.isAssignableFrom(interfce); if (e instanceof TransactionRequiredException) { if (!rmiRemote && interfaceType.isBusiness()) { return new EJBTransactionRequiredException(e.getMessage()).initCause(getCause(e)); } else if (interfaceType.isLocal()) { return new TransactionRequiredLocalException(e.getMessage()).initCause(getCause(e)); } else { return e; } } if (e instanceof TransactionRolledbackException) { if (!rmiRemote && interfaceType.isBusiness()) { return new EJBTransactionRolledbackException(e.getMessage()).initCause(getCause(e)); } else if (interfaceType.isLocal()) { return new TransactionRolledbackLocalException(e.getMessage()).initCause(getCause(e)); } else { return e; } } if (e instanceof NoSuchObjectException) { if (!rmiRemote && interfaceType.isBusiness()) { return new NoSuchEJBException(e.getMessage()).initCause(getCause(e)); } else if (interfaceType.isLocal()) { return new NoSuchObjectLocalException(e.getMessage()).initCause(getCause(e)); } else { return e; } } if (e instanceof AccessException) { if (!rmiRemote && interfaceType.isBusiness()) { return new AccessLocalException(e.getMessage()).initCause(getCause(e)); } else if (interfaceType.isLocal()) { return new AccessLocalException(e.getMessage()).initCause(getCause(e)); } else { return e; } } if (e instanceof RemoteException) { if (!rmiRemote && interfaceType.isBusiness()) { return new EJBException(e.getMessage()).initCause(getCause(e)); } else if (interfaceType.isLocal()) { return new EJBException(e.getMessage()).initCause(getCause(e)); } else { return e; } } for (final Class<?> type : method.getExceptionTypes()) { if (type.isAssignableFrom(e.getClass())) { return e; } } // Exception is undeclared // Try and find a runtime exception in there while (e.getCause() != null && !(e instanceof RuntimeException)) { e = e.getCause(); } return e; }
public static void main(String[] args) throws NamingException { // Create the JNDI InitialContext, configuring it for use with JBoss EJB Hashtable<String, String> jndiProperties = new Hashtable<String, String>(); jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming"); final Context context = new InitialContext(jndiProperties); /* * The app name is the application name of the deployed EJBs. This is typically the ear name without the .ear suffix. * However, the application name could be overridden in the application.xml of the EJB deployment on the server. Since * we haven't deployed the application as a .ear, the app name for us will be an empty string */ final String appName = ""; /* * This is the module name of the deployed EJBs on the server. This is typically the jar name of the EJB deployment, * without the .jar suffix, but can be overridden via the ejb-jar.xml. In this example, we have deployed the EJBs in a * jboss-as-shoppingcart-server.jar, so the module name is jboss-as-shopping-cart-server */ final String moduleName = "jboss-as-shoppingcart-server"; /* * AS7 allows each deployment to have an (optional) distinct name. We haven't specified a distinct name for our EJB * deployment, so this is an empty string */ final String distinctName = ""; /* * The EJB name which by default is the simple class name of the bean implementation class */ final String beanName = ShoppingCartBean.class.getSimpleName(); /* The remote view fully qualified class name */ final String viewClassName = ShoppingCart.class.getName(); /* Lookup the remote interface of the shopping cart */ String lookupName = "ejb:" + appName + "/" + moduleName + "/" + distinctName + "/" + beanName + "!" + viewClassName + "?stateful"; final ShoppingCart cart = (ShoppingCart) context.lookup(lookupName); System.out.println("\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"); System.out.println("Obtained the remote interface to the shopping cart"); /* invoke on the remote interface */ System.out.println("Buying a \"" + EAP + "\""); cart.buy(EAP, 1); System.out.println("Buying another \"" + EAP + "\""); cart.buy(EAP, 1); System.out.println("Buying a \"" + SOAP + "\""); cart.buy(SOAP, 1); System.out.println("\nPrint cart:"); HashMap<String, Integer> cartContents = cart.getCartContents(); for (String product : cartContents.keySet()) { System.out.println(cartContents.get(product) + " " + product); } System.out.println("\nCheckout"); cart.checkout(); /* Try to access the cart after checkout*/ try { cart.getCartContents(); } catch (NoSuchEJBException e) { System.out.println("ERROR: Cannot access cart after Checkout!"); } System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n"); }
public static void main(String[] args) throws NamingException { // Create the JNDI InitialContext, configuring it for use with JBoss EJB Hashtable<String, String> jndiProperties = new Hashtable<String, String>(); jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming"); final Context context = new InitialContext(jndiProperties); /* * The app name is the application name of the deployed EJBs. This is typically the ear name without the .ear suffix. * However, the application name could be overridden in the application.xml of the EJB deployment on the server. Since * we haven't deployed the application as a .ear, the app name for us will be an empty string */ final String appName = ""; /* * This is the module name of the deployed EJBs on the server. This is typically the jar name of the EJB deployment, * without the .jar suffix, but can be overridden via the ejb-jar.xml. In this example, we have deployed the EJBs in a * jboss-shopping-cart-server.jar, so the module name is jboss-shopping-cart-server */ final String moduleName = "jboss-shopping-cart-server"; /* * AS7 allows each deployment to have an (optional) distinct name. We haven't specified a distinct name for our EJB * deployment, so this is an empty string */ final String distinctName = ""; /* * The EJB name which by default is the simple class name of the bean implementation class */ final String beanName = ShoppingCartBean.class.getSimpleName(); /* The remote view fully qualified class name */ final String viewClassName = ShoppingCart.class.getName(); /* Lookup the remote interface of the shopping cart */ String lookupName = "ejb:" + appName + "/" + moduleName + "/" + distinctName + "/" + beanName + "!" + viewClassName + "?stateful"; final ShoppingCart cart = (ShoppingCart) context.lookup(lookupName); System.out.println("\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"); System.out.println("Obtained the remote interface to the shopping cart"); /* invoke on the remote interface */ System.out.println("Buying a \"" + EAP + "\""); cart.buy(EAP, 1); System.out.println("Buying another \"" + EAP + "\""); cart.buy(EAP, 1); System.out.println("Buying a \"" + SOAP + "\""); cart.buy(SOAP, 1); System.out.println("\nPrint cart:"); HashMap<String, Integer> cartContents = cart.getCartContents(); for (String product : cartContents.keySet()) { System.out.println(cartContents.get(product) + " " + product); } System.out.println("\nCheckout"); cart.checkout(); /* Try to access the cart after checkout */ try { cart.getCartContents(); } catch (NoSuchEJBException e) { System.out.println("ERROR: Cannot access cart after Checkout!"); } System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n"); }