http://git-wip-us.apache.org/repos/asf/tomee-site-generator/blob/efed31f4/src/main/jbake/content/examples/interceptors.adoc ---------------------------------------------------------------------- diff --git a/src/main/jbake/content/examples/interceptors.adoc b/src/main/jbake/content/examples/interceptors.adoc deleted file mode 100755 index d59fc72..0000000 --- a/src/main/jbake/content/examples/interceptors.adoc +++ /dev/null @@ -1,888 +0,0 @@ -= Interceptors -:jbake-date: 2016-09-06 -:jbake-type: page -:jbake-tomeepdf: -:jbake-status: published - -Example interceptors can be browsed at https://github.com/apache/tomee/tree/master/examples/interceptors - - -*Help us document this example! Click the blue pencil icon in the upper right to edit this page.* - -== ClassLevelInterceptorOne - - -[source,java] ----- -package org.superbiz.interceptors; - -import javax.interceptor.AroundInvoke; -import javax.interceptor.InvocationContext; - -/** - * @version $Rev: 607077 $ $Date: 2007-12-27 06:55:23 -0800 (Thu, 27 Dec 2007) $ - */ -public class ClassLevelInterceptorOne { - - @AroundInvoke - protected Object businessMethodInterceptor(InvocationContext ic) throws Exception { - return Utils.addClassSimpleName(ic, this.getClass().getSimpleName()); - } -} ----- - - -== ClassLevelInterceptorSuperClassOne - - -[source,java] ----- -package org.superbiz.interceptors; - -import javax.interceptor.AroundInvoke; -import javax.interceptor.InvocationContext; - -/** - * @version $Rev: 607077 $ $Date: 2007-12-27 06:55:23 -0800 (Thu, 27 Dec 2007) $ - */ -public class ClassLevelInterceptorSuperClassOne { - - @AroundInvoke - protected Object businessMethodInterceptor(InvocationContext ic) throws Exception { - return Utils.addClassSimpleName(ic, this.getClass().getSimpleName()); - } -} ----- - - -== ClassLevelInterceptorSuperClassTwo - - -[source,java] ----- -package org.superbiz.interceptors; - -import javax.interceptor.AroundInvoke; -import javax.interceptor.InvocationContext; - -/** - * @version $Rev: 607077 $ $Date: 2007-12-27 06:55:23 -0800 (Thu, 27 Dec 2007) $ - */ -public class ClassLevelInterceptorSuperClassTwo extends SuperClassOfClassLevelInterceptor { - - @AroundInvoke - protected Object businessMethodInterceptor(InvocationContext ic) throws Exception { - return Utils.addClassSimpleName(ic, this.getClass().getSimpleName()); - } -} ----- - - -== ClassLevelInterceptorTwo - - -[source,java] ----- -package org.superbiz.interceptors; - -import javax.interceptor.AroundInvoke; -import javax.interceptor.InvocationContext; - -/** - * @version $Rev: 607077 $ $Date: 2007-12-27 06:55:23 -0800 (Thu, 27 Dec 2007) $ - */ -public class ClassLevelInterceptorTwo { - - @AroundInvoke - protected Object businessMethodInterceptor(InvocationContext ic) throws Exception { - return Utils.addClassSimpleName(ic, this.getClass().getSimpleName()); - } -} ----- - - -== DefaultInterceptorOne - - -[source,java] ----- -package org.superbiz.interceptors; - -import javax.annotation.PostConstruct; -import javax.interceptor.AroundInvoke; -import javax.interceptor.InvocationContext; - -/** - * @version $Rev: 607077 $ $Date: 2007-12-27 06:55:23 -0800 (Thu, 27 Dec 2007) $ - */ -public class DefaultInterceptorOne { - - @AroundInvoke - protected Object businessMethodInterceptor(InvocationContext ic) throws Exception { - return Utils.addClassSimpleName(ic, this.getClass().getSimpleName()); - } - - @PostConstruct - protected void postConstructInterceptor(InvocationContext ic) throws Exception { - Utils.addClassSimpleName(ic, this.getClass().getSimpleName()); - } -} ----- - - -== DefaultInterceptorTwo - - -[source,java] ----- -package org.superbiz.interceptors; - -import javax.interceptor.AroundInvoke; -import javax.interceptor.InvocationContext; - -/** - * @version $Rev: 607077 $ $Date: 2007-12-27 06:55:23 -0800 (Thu, 27 Dec 2007) $ - */ -public class DefaultInterceptorTwo { - - @AroundInvoke - protected Object businessMethodInterceptor(InvocationContext ic) throws Exception { - return Utils.addClassSimpleName(ic, this.getClass().getSimpleName()); - } -} ----- - - -== FullyIntercepted - - -[source,java] ----- -package org.superbiz.interceptors; - -import java.util.List; - -/** - * @version $Rev: 607077 $ $Date: 2007-12-27 06:55:23 -0800 (Thu, 27 Dec 2007) $ - */ -public interface FullyIntercepted { - - List<String> businessMethod(); - - List<String> methodWithDefaultInterceptorsExcluded(); -} ----- - - -== FullyInterceptedBean - - -[source,java] ----- -package org.superbiz.interceptors; - -import javax.ejb.Local; -import javax.ejb.Stateless; -import javax.interceptor.AroundInvoke; -import javax.interceptor.Interceptors; -import javax.interceptor.InvocationContext; -import java.util.ArrayList; -import java.util.List; - -/** - * @version $Rev: 607077 $ $Date: 2007-12-27 06:55:23 -0800 (Thu, 27 Dec 2007) $ - */ -@Stateless -@Local -@Interceptors({ClassLevelInterceptorOne.class, ClassLevelInterceptorTwo.class}) -public class FullyInterceptedBean extends FullyInterceptedSuperClass implements FullyIntercepted { - - @Interceptors({MethodLevelInterceptorOne.class, MethodLevelInterceptorTwo.class}) - public List<String> businessMethod() { - List<String> list = new ArrayList<String>(); - list.add("businessMethod"); - return list; - } - - @Interceptors({MethodLevelInterceptorOne.class, MethodLevelInterceptorTwo.class}) - public List<String> methodWithDefaultInterceptorsExcluded() { - List<String> list = new ArrayList<String>(); - list.add("methodWithDefaultInterceptorsExcluded"); - return list; - } - - @AroundInvoke - protected Object beanClassBusinessMethodInterceptor(InvocationContext ic) throws Exception { - return Utils.addClassSimpleName(ic, "beanClassBusinessMethodInterceptor"); - } -} ----- - - -== FullyInterceptedSuperClass - - -[source,java] ----- -package org.superbiz.interceptors; - -import javax.interceptor.Interceptors; - -/** - * @version $Rev: 607077 $ $Date: 2007-12-27 06:55:23 -0800 (Thu, 27 Dec 2007) $ - */ -@Interceptors({ClassLevelInterceptorSuperClassOne.class, ClassLevelInterceptorSuperClassTwo.class}) -public class FullyInterceptedSuperClass { -} ----- - - -== MethodLevelInterceptorOne - - -[source,java] ----- -package org.superbiz.interceptors; - -import javax.interceptor.AroundInvoke; -import javax.interceptor.InvocationContext; - -/** - * @version $Rev: 607077 $ $Date: 2007-12-27 06:55:23 -0800 (Thu, 27 Dec 2007) $ - */ -public class MethodLevelInterceptorOne { - - @AroundInvoke - protected Object businessMethodInterceptor(InvocationContext ic) throws Exception { - return Utils.addClassSimpleName(ic, this.getClass().getSimpleName()); - } -} ----- - - -== MethodLevelInterceptorOnlyIntf - - -[source,java] ----- -package org.superbiz.interceptors; - -import java.io.Serializable; -import java.util.List; - -public interface MethodLevelInterceptorOnlyIntf<T extends Serializable> { - public List<T> makePersistent(T entity); -} ----- - - -== MethodLevelInterceptorOnlyParent - - -[source,java] ----- -package org.superbiz.interceptors; - -import java.util.List; - -public interface MethodLevelInterceptorOnlyParent extends MethodLevelInterceptorOnlyIntf<String> { - - public List<String> makePersistent(String entity); -} ----- - - -== MethodLevelInterceptorOnlySLSBean - - -[source,java] ----- -package org.superbiz.interceptors; - -import javax.ejb.Local; -import javax.ejb.Stateless; -import javax.interceptor.Interceptors; -import java.util.ArrayList; -import java.util.List; - -@Local(MethodLevelInterceptorOnlyParent.class) -@Stateless -public class MethodLevelInterceptorOnlySLSBean implements MethodLevelInterceptorOnlyParent { - - @Interceptors(MethodLevelInterceptorOne.class) - public List<String> makePersistent(String entity) { - List<String> list = new ArrayList<String>(); - list.add("makePersistent"); - return list; - } -} ----- - - -== MethodLevelInterceptorTwo - - -[source,java] ----- -package org.superbiz.interceptors; - -import javax.interceptor.AroundInvoke; -import javax.interceptor.InvocationContext; - -/** - * @version $Rev: 607077 $ $Date: 2007-12-27 06:55:23 -0800 (Thu, 27 Dec 2007) $ - */ -public class MethodLevelInterceptorTwo { - - @AroundInvoke - protected Object businessMethodInterceptor(InvocationContext ic) throws Exception { - return Utils.addClassSimpleName(ic, this.getClass().getSimpleName()); - } -} ----- - - -== SecondStatelessInterceptedBean - - -[source,java] ----- -package org.superbiz.interceptors; - -import javax.ejb.Stateless; -import javax.interceptor.AroundInvoke; -import javax.interceptor.Interceptors; -import javax.interceptor.InvocationContext; -import java.util.ArrayList; -import java.util.List; - -/** - * @version $Rev: 808273 $ $Date: 2009-08-26 20:42:06 -0700 (Wed, 26 Aug 2009) $ - */ -@Stateless -@Interceptors({ClassLevelInterceptorOne.class, ClassLevelInterceptorTwo.class}) -public class SecondStatelessInterceptedBean implements SecondStatelessInterceptedLocal { - - @Interceptors({MethodLevelInterceptorOne.class, MethodLevelInterceptorTwo.class}) - public List<String> methodWithDefaultInterceptorsExcluded() { - List<String> list = new ArrayList<String>(); - list.add("methodWithDefaultInterceptorsExcluded"); - return list; - } - - @AroundInvoke - protected Object beanClassBusinessMethodInterceptor(InvocationContext ic) throws Exception { - return Utils.addClassSimpleName(ic, this.getClass().getSimpleName()); - } -} ----- - - -== SecondStatelessInterceptedLocal - - -[source,java] ----- -package org.superbiz.interceptors; - -import java.util.List; - -/** - * @version $Rev: 808273 $ $Date: 2009-08-26 20:42:06 -0700 (Wed, 26 Aug 2009) $ - */ -public interface SecondStatelessInterceptedLocal { - List<String> methodWithDefaultInterceptorsExcluded(); -} ----- - - -== SuperClassOfClassLevelInterceptor - - -[source,java] ----- -package org.superbiz.interceptors; - -import javax.annotation.PostConstruct; -import javax.interceptor.AroundInvoke; -import javax.interceptor.InvocationContext; - -/** - * @version $Rev: 607077 $ $Date: 2007-12-27 06:55:23 -0800 (Thu, 27 Dec 2007) $ - */ -public class SuperClassOfClassLevelInterceptor { - - @AroundInvoke - protected Object businessMethodInterceptor(InvocationContext ic) throws Exception { - return Utils.addClassSimpleName(ic, this.getClass().getSimpleName()); - } - - @PostConstruct - protected void postConstructInterceptor(InvocationContext ic) throws Exception { - Utils.addClassSimpleName(ic, this.getClass().getSimpleName()); - } -} ----- - - -== ThirdSLSBean - - -[source,java] ----- -package org.superbiz.interceptors; - -import javax.ejb.Stateless; -import javax.interceptor.AroundInvoke; -import javax.interceptor.ExcludeClassInterceptors; -import javax.interceptor.ExcludeDefaultInterceptors; -import javax.interceptor.Interceptors; -import javax.interceptor.InvocationContext; -import java.util.ArrayList; -import java.util.List; - -/** - * @version $Rev: 1090810 $ $Date: 2011-04-10 07:49:26 -0700 (Sun, 10 Apr 2011) $ - */ -@Stateless -@Interceptors({ClassLevelInterceptorOne.class, ClassLevelInterceptorTwo.class}) -@ExcludeDefaultInterceptors -public class ThirdSLSBean implements ThirdSLSBeanLocal { - - @Interceptors({MethodLevelInterceptorOne.class, MethodLevelInterceptorTwo.class}) - public List<String> businessMethod() { - List<String> list = new ArrayList<String>(); - list.add("businessMethod"); - return list; - } - - @Interceptors({MethodLevelInterceptorOne.class, MethodLevelInterceptorTwo.class}) - @ExcludeClassInterceptors - public List<String> anotherBusinessMethod() { - List<String> list = new ArrayList<String>(); - list.add("anotherBusinessMethod"); - return list; - } - - - @AroundInvoke - protected Object beanClassBusinessMethodInterceptor(InvocationContext ic) throws Exception { - return Utils.addClassSimpleName(ic, this.getClass().getSimpleName()); - } -} ----- - - -== ThirdSLSBeanLocal - - -[source,java] ----- -package org.superbiz.interceptors; - -import java.util.List; - -/** - * @version $Rev: 607320 $ $Date: 2007-12-28 12:15:06 -0800 (Fri, 28 Dec 2007) $ - */ -public interface ThirdSLSBeanLocal { - List<String> businessMethod(); - - List<String> anotherBusinessMethod(); -} ----- - - -== Utils - - -[source,java] ----- -package org.superbiz.interceptors; - -import javax.interceptor.InvocationContext; -import java.util.ArrayList; -import java.util.List; - -/** - * @version $Rev: 808273 $ $Date: 2009-08-26 20:42:06 -0700 (Wed, 26 Aug 2009) $ - */ -public class Utils { - - public static List<String> addClassSimpleName(InvocationContext ic, String classSimpleName) throws Exception { - List<String> list = new ArrayList<String>(); - list.add(classSimpleName); - List<String> listOfStrings = (List<String>) ic.proceed(); - if (listOfStrings != null) { - list.addAll(listOfStrings); - } - return list; - } -} ----- - - -== ejb-jar.xml - - -[source,xml] ----- -<ejb-jar xmlns="http://java.sun.com/xml/ns/javaee" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd" - version="3.0"> - <interceptors> - <interceptor> - <interceptor-class>org.superbiz.interceptors.DefaultInterceptorOne</interceptor-class> - </interceptor> - <interceptor> - <interceptor-class>org.superbiz.interceptors.DefaultInterceptorTwo</interceptor-class> - </interceptor> - </interceptors> - <assembly-descriptor> - <interceptor-binding> - <ejb-name>*</ejb-name> - <interceptor-class>org.superbiz.interceptors.DefaultInterceptorOne</interceptor-class> - </interceptor-binding> - <interceptor-binding> - <ejb-name>*</ejb-name> - <interceptor-class>org.superbiz.interceptors.DefaultInterceptorTwo</interceptor-class> - </interceptor-binding> - <interceptor-binding> - <ejb-name>FullyInterceptedBean</ejb-name> - <exclude-default-interceptors>true</exclude-default-interceptors> - <method> - <method-name>methodWithDefaultInterceptorsExcluded</method-name> - </method> - </interceptor-binding> - <interceptor-binding> - <ejb-name>SecondStatelessInterceptedBean</ejb-name> - <exclude-default-interceptors>true</exclude-default-interceptors> - </interceptor-binding> - <interceptor-binding> - <ejb-name>MethodLevelInterceptorOnlySLSBean</ejb-name> - <exclude-default-interceptors>true</exclude-default-interceptors> - </interceptor-binding> - </assembly-descriptor> -</ejb-jar> ----- - - -== FullyInterceptedTest - - -[source,java] ----- -package org.superbiz.interceptors; - -import junit.framework.TestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import javax.naming.Context; -import javax.naming.InitialContext; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -/** - * @version $Rev: 1090810 $ $Date: 2011-04-10 07:49:26 -0700 (Sun, 10 Apr 2011) $ - */ -public class FullyInterceptedTest extends TestCase { - - private InitialContext initCtx; - - @Before - public void setUp() throws Exception { - Properties properties = new Properties(); - properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.core.LocalInitialContextFactory"); - properties.setProperty("openejb.deployments.classpath.include", ".*interceptors/target/classes.*"); - - initCtx = new InitialContext(properties); - } - - @Test - public void testBusinessMethod() throws Exception { - - FullyIntercepted fullyIntercepted = (FullyIntercepted) initCtx.lookup("FullyInterceptedBeanLocal"); - - assert fullyIntercepted != null; - - List<String> expected = new ArrayList<String>(); - expected.add("DefaultInterceptorOne"); - expected.add("DefaultInterceptorTwo"); - expected.add("ClassLevelInterceptorSuperClassOne"); - expected.add("ClassLevelInterceptorSuperClassTwo"); - expected.add("ClassLevelInterceptorOne"); - expected.add("ClassLevelInterceptorTwo"); - expected.add("MethodLevelInterceptorOne"); - expected.add("MethodLevelInterceptorTwo"); - expected.add("beanClassBusinessMethodInterceptor"); - expected.add("businessMethod"); - - List<String> actual = fullyIntercepted.businessMethod(); - assert expected.equals(actual) : "Expected " + expected + ", but got " + actual; - } - - @Test - public void testMethodWithDefaultInterceptorsExcluded() throws Exception { - - FullyIntercepted fullyIntercepted = (FullyIntercepted) initCtx.lookup("FullyInterceptedBeanLocal"); - - assert fullyIntercepted != null; - - List<String> expected = new ArrayList<String>(); - expected.add("ClassLevelInterceptorSuperClassOne"); - expected.add("ClassLevelInterceptorSuperClassTwo"); - expected.add("ClassLevelInterceptorOne"); - expected.add("ClassLevelInterceptorTwo"); - expected.add("MethodLevelInterceptorOne"); - expected.add("MethodLevelInterceptorTwo"); - expected.add("beanClassBusinessMethodInterceptor"); - expected.add("methodWithDefaultInterceptorsExcluded"); - - List<String> actual = fullyIntercepted.methodWithDefaultInterceptorsExcluded(); - assert expected.equals(actual) : "Expected " + expected + ", but got " + actual; - } - - @After - public void tearDown() throws Exception { - initCtx.close(); - } -} ----- - - -== MethodLevelInterceptorOnlyTest - - -[source,java] ----- -package org.superbiz.interceptors; - -import junit.framework.TestCase; -import org.junit.Before; -import org.junit.Test; - -import javax.naming.Context; -import javax.naming.InitialContext; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -/** - * @version $Rev: 895825 $ $Date: 2010-01-04 15:35:22 -0800 (Mon, 04 Jan 2010) $ - */ -public class MethodLevelInterceptorOnlyTest extends TestCase { - private InitialContext initCtx; - - @Before - public void setUp() throws Exception { - Properties properties = new Properties(); - properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.core.LocalInitialContextFactory"); - properties.setProperty("openejb.deployments.classpath.include", ".*interceptors/target/classes.*"); - - initCtx = new InitialContext(properties); - } - - @Test - public void testInterceptedGenerifiedBusinessIntfMethod() throws Exception { - MethodLevelInterceptorOnlyParent bean = (MethodLevelInterceptorOnlyParent) initCtx.lookup("MethodLevelInterceptorOnlySLSBeanLocal"); - - assert bean != null; - - List<String> expected = new ArrayList<String>(); - expected.add("MethodLevelInterceptorOne"); - expected.add("makePersistent"); - - List<String> actual = bean.makePersistent(null); - assert expected.equals(actual) : "Expected " + expected + ", but got " + actual; - } -} ----- - - -== SecondStatelessInterceptedTest - - -[source,java] ----- -package org.superbiz.interceptors; - -import junit.framework.TestCase; -import org.junit.Before; -import org.junit.Test; - -import javax.naming.Context; -import javax.naming.InitialContext; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -/** - * @version $Rev: 1090810 $ $Date: 2011-04-10 07:49:26 -0700 (Sun, 10 Apr 2011) $ - */ -public class SecondStatelessInterceptedTest extends TestCase { - - private InitialContext initCtx; - - @Before - public void setUp() throws Exception { - Properties properties = new Properties(); - properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.core.LocalInitialContextFactory"); - properties.setProperty("openejb.deployments.classpath.include", ".*interceptors/target/classes.*"); - - initCtx = new InitialContext(properties); - } - - @Test - public void testMethodWithDefaultInterceptorsExcluded() throws Exception { - SecondStatelessInterceptedLocal bean = - (SecondStatelessInterceptedLocal) initCtx.lookup("SecondStatelessInterceptedBeanLocal"); - - assert bean != null; - - List<String> expected = new ArrayList<String>(); - expected.add("ClassLevelInterceptorOne"); - expected.add("ClassLevelInterceptorTwo"); - expected.add("MethodLevelInterceptorOne"); - expected.add("MethodLevelInterceptorTwo"); - expected.add("SecondStatelessInterceptedBean"); - expected.add("methodWithDefaultInterceptorsExcluded"); - - List<String> actual = bean.methodWithDefaultInterceptorsExcluded(); - assert expected.equals(actual) : "Expected " + expected + ", but got " + actual; - } -} ----- - - -== ThirdSLSBeanTest - - -[source,java] ----- -package org.superbiz.interceptors; - -import junit.framework.TestCase; -import org.junit.Before; -import org.junit.Test; - -import javax.naming.Context; -import javax.naming.InitialContext; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -/** - * @version $Rev: 1090810 $ $Date: 2011-04-10 07:49:26 -0700 (Sun, 10 Apr 2011) $ - */ -public class ThirdSLSBeanTest extends TestCase { - private InitialContext initCtx; - - @Before - public void setUp() throws Exception { - Properties properties = new Properties(); - properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.core.LocalInitialContextFactory"); - properties.setProperty("openejb.deployments.classpath.include", ".*interceptors/target/classes.*"); - - initCtx = new InitialContext(properties); - } - - @Test - public void testMethodWithDefaultInterceptorsExcluded() throws Exception { - ThirdSLSBeanLocal bean = (ThirdSLSBeanLocal) initCtx.lookup("ThirdSLSBeanLocal"); - - assert bean != null; - - List<String> expected = new ArrayList<String>(); - expected.add("ClassLevelInterceptorOne"); - expected.add("ClassLevelInterceptorTwo"); - expected.add("MethodLevelInterceptorOne"); - expected.add("MethodLevelInterceptorTwo"); - expected.add("ThirdSLSBean"); - expected.add("businessMethod"); - - List<String> actual = bean.businessMethod(); - assert expected.equals(actual) : "Expected " + expected + ", but got " + actual; - } - - @Test - public void testMethodWithDefaultAndClassInterceptorsExcluded() throws Exception { - ThirdSLSBeanLocal bean = (ThirdSLSBeanLocal) initCtx.lookup("ThirdSLSBeanLocal"); - - assert bean != null; - - List<String> expected = new ArrayList<String>(); - expected.add("MethodLevelInterceptorOne"); - expected.add("MethodLevelInterceptorTwo"); - expected.add("ThirdSLSBean"); - expected.add("anotherBusinessMethod"); - - List<String> actual = bean.anotherBusinessMethod(); - assert expected.equals(actual) : "Expected " + expected + ", but got " + actual; - } -} ----- - - -= Running - - - -[source] ----- -------------------------------------------------------- - T E S T S -------------------------------------------------------- -Running org.superbiz.interceptors.FullyInterceptedTest -Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06 -http://tomee.apache.org/ -INFO - openejb.home = /Users/dblevins/examples/interceptors -INFO - openejb.base = /Users/dblevins/examples/interceptors -INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service) -INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager) -INFO - Using 'openejb.deployments.classpath.include=.*interceptors/target/classes.*' -INFO - Found EjbModule in classpath: /Users/dblevins/examples/interceptors/target/classes -INFO - Beginning load: /Users/dblevins/examples/interceptors/target/classes -INFO - Configuring enterprise application: /Users/dblevins/examples/interceptors/classpath.ear -INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container) -INFO - Auto-creating a container for bean FullyInterceptedBean: Container(type=STATELESS, id=Default Stateless Container) -INFO - Enterprise application "/Users/dblevins/examples/interceptors/classpath.ear" loaded. -INFO - Assembling app: /Users/dblevins/examples/interceptors/classpath.ear -INFO - Jndi(name=FullyInterceptedBeanLocal) --> Ejb(deployment-id=FullyInterceptedBean) -INFO - Jndi(name=global/classpath.ear/interceptors/FullyInterceptedBean!org.superbiz.interceptors.FullyIntercepted) --> Ejb(deployment-id=FullyInterceptedBean) -INFO - Jndi(name=global/classpath.ear/interceptors/FullyInterceptedBean) --> Ejb(deployment-id=FullyInterceptedBean) -INFO - Jndi(name=ThirdSLSBeanLocal) --> Ejb(deployment-id=ThirdSLSBean) -INFO - Jndi(name=global/classpath.ear/interceptors/ThirdSLSBean!org.superbiz.interceptors.ThirdSLSBeanLocal) --> Ejb(deployment-id=ThirdSLSBean) -INFO - Jndi(name=global/classpath.ear/interceptors/ThirdSLSBean) --> Ejb(deployment-id=ThirdSLSBean) -INFO - Jndi(name=SecondStatelessInterceptedBeanLocal) --> Ejb(deployment-id=SecondStatelessInterceptedBean) -INFO - Jndi(name=global/classpath.ear/interceptors/SecondStatelessInterceptedBean!org.superbiz.interceptors.SecondStatelessInterceptedLocal) --> Ejb(deployment-id=SecondStatelessInterceptedBean) -INFO - Jndi(name=global/classpath.ear/interceptors/SecondStatelessInterceptedBean) --> Ejb(deployment-id=SecondStatelessInterceptedBean) -INFO - Jndi(name=MethodLevelInterceptorOnlySLSBeanLocal) --> Ejb(deployment-id=MethodLevelInterceptorOnlySLSBean) -INFO - Jndi(name=global/classpath.ear/interceptors/MethodLevelInterceptorOnlySLSBean!org.superbiz.interceptors.MethodLevelInterceptorOnlyParent) --> Ejb(deployment-id=MethodLevelInterceptorOnlySLSBean) -INFO - Jndi(name=global/classpath.ear/interceptors/MethodLevelInterceptorOnlySLSBean) --> Ejb(deployment-id=MethodLevelInterceptorOnlySLSBean) -INFO - Created Ejb(deployment-id=ThirdSLSBean, ejb-name=ThirdSLSBean, container=Default Stateless Container) -INFO - Created Ejb(deployment-id=SecondStatelessInterceptedBean, ejb-name=SecondStatelessInterceptedBean, container=Default Stateless Container) -INFO - Created Ejb(deployment-id=FullyInterceptedBean, ejb-name=FullyInterceptedBean, container=Default Stateless Container) -INFO - Created Ejb(deployment-id=MethodLevelInterceptorOnlySLSBean, ejb-name=MethodLevelInterceptorOnlySLSBean, container=Default Stateless Container) -INFO - Started Ejb(deployment-id=ThirdSLSBean, ejb-name=ThirdSLSBean, container=Default Stateless Container) -INFO - Started Ejb(deployment-id=SecondStatelessInterceptedBean, ejb-name=SecondStatelessInterceptedBean, container=Default Stateless Container) -INFO - Started Ejb(deployment-id=FullyInterceptedBean, ejb-name=FullyInterceptedBean, container=Default Stateless Container) -INFO - Started Ejb(deployment-id=MethodLevelInterceptorOnlySLSBean, ejb-name=MethodLevelInterceptorOnlySLSBean, container=Default Stateless Container) -INFO - Deployed Application(path=/Users/dblevins/examples/interceptors/classpath.ear) -Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.564 sec -Running org.superbiz.interceptors.MethodLevelInterceptorOnlyTest -Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.004 sec -Running org.superbiz.interceptors.SecondStatelessInterceptedTest -Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.003 sec -Running org.superbiz.interceptors.ThirdSLSBeanTest -Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.004 sec - -Results : - -Tests run: 6, Failures: 0, Errors: 0, Skipped: 0 ----- - -
http://git-wip-us.apache.org/repos/asf/tomee-site-generator/blob/efed31f4/src/main/jbake/content/examples/javamail.adoc ---------------------------------------------------------------------- diff --git a/src/main/jbake/content/examples/javamail.adoc b/src/main/jbake/content/examples/javamail.adoc deleted file mode 100755 index 77141dd..0000000 --- a/src/main/jbake/content/examples/javamail.adoc +++ /dev/null @@ -1,201 +0,0 @@ -= Javamail API -:jbake-date: 2016-09-06 -:jbake-type: page -:jbake-tomeepdf: -:jbake-status: published - -Example javamail can be browsed at https://github.com/apache/tomee/tree/master/examples/javamail - - -This is just a simple example to demonstrate a very basic usage of the API. It should be enough to get you started using the java mail packages. - -= The Code - -== A simple REST service using the Javamail API - -Here we see a very simple RESTful endpoint that can be called with a message to send by Email. It would not be hard to modify the application to provide -more useful configuration options. As is, this will not send anything, but if you change the parameters to match your mail server then you'll see the message being sent. -You can find much more detailed information on the link:https://java.net/projects/javamail/pages/Home#Samples[Javamail API here] - - -[source,java] ----- -package org.superbiz.rest; - -import javax.mail.Authenticator; -import javax.mail.Message; -import javax.mail.MessagingException; -import javax.mail.PasswordAuthentication; -import javax.mail.Session; -import javax.mail.Transport; -import javax.mail.internet.InternetAddress; -import javax.mail.internet.MimeMessage; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import java.util.Date; -import java.util.Properties; - -@Path("/email") -public class EmailService { - - @POST - public String lowerCase(final String message) { - - try { - - //Create some properties and get the default Session - final Properties props = new Properties(); - props.put("mail.smtp.host", "your.mailserver.host"); - props.put("mail.debug", "true"); - - final Session session = Session.getInstance(props, new Authenticator() { - @Override - protected PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication("MyUsername", "MyPassword"); - } - }); - - //Set this just to see some internal logging - session.setDebug(true); - - //Create a message - final MimeMessage msg = new MimeMessage(session); - msg.setFrom(new InternetAddress("[email protected]")); - final InternetAddress[] address = {new InternetAddress("[email protected]")}; - msg.setRecipients(Message.RecipientType.TO, address); - msg.setSubject("JavaMail API test"); - msg.setSentDate(new Date()); - msg.setText(message, "UTF-8"); - - - Transport.send(msg); - } catch (MessagingException e) { - return "Failed to send message: " + e.getMessage(); - } - - return "Sent"; - } -} ----- - - -= Testing - -== Test for the JAXRS service - -The test uses the OpenEJB ApplicationComposer to make it trivial. - -The idea is first to activate the jaxrs services. This is done using @EnableServices annotation. - -Then we create on the fly the application simply returning an object representing the web.xml. Here we simply -use it to define the context root but you can use it to define your REST Application too. And to complete the -application definition we add @Classes annotation to define the set of classes to use in this app. - -Finally to test it we use cxf client API to call the REST service post() method. - - -[source,java] ----- -package org.superbiz.rest; - -import org.apache.cxf.jaxrs.client.WebClient; -import org.apache.openejb.jee.WebApp; -import org.apache.openejb.junit.ApplicationComposer; -import org.apache.openejb.testing.Classes; -import org.apache.openejb.testing.EnableServices; -import org.apache.openejb.testing.Module; -import org.junit.Test; -import org.junit.runner.RunWith; - -import java.io.IOException; - -import static org.junit.Assert.assertEquals; - -@EnableServices(value = "jaxrs") -@RunWith(ApplicationComposer.class) -public class EmailServiceTest { - - @Module - @Classes(EmailService.class) - public WebApp app() { - return new WebApp().contextRoot("test"); - } - - @Test - public void post() throws IOException { - final String message = WebClient.create("http://localhost:4204").path("/test/email/").post("Hello Tomitribe", String.class); - assertEquals("Failed to send message: Unknown SMTP host: your.mailserver.host", message); - } -} ----- - - -= Running - -Running the example is fairly simple. In the "javamail-api" directory run: - - $ mvn clean install - -Which should create output like the following. - - INFO - Cannot find the configuration file [conf/openejb.xml]. Will attempt to create one for the beans deployed. - INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service) - INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager) - INFO - Creating TransactionManager(id=Default Transaction Manager) - INFO - Creating SecurityService(id=Default Security Service) - INFO - Initializing network services - INFO - Creating ServerService(id=cxf-rs) - INFO - Creating ServerService(id=httpejbd) - INFO - Created ServicePool 'httpejbd' with (10) core threads, limited to (200) threads with a queue of (9) - INFO - Initializing network services - INFO - ** Bound Services ** - INFO - NAME IP PORT - INFO - httpejbd 127.0.0.1 4204 - INFO - ------- - INFO - Ready! - INFO - Configuring enterprise application: D:\github\tomee\examples\javamail\EmailServiceTest - INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container) - INFO - Auto-creating a container for bean org.superbiz.rest.EmailServiceTest: Container(type=MANAGED, id=Default Managed Container) - INFO - Creating Container(id=Default Managed Container) - INFO - Using directory D:\windows\tmp for stateful session passivation - INFO - Configuring Service(id=comp/DefaultManagedExecutorService, type=Resource, provider-id=Default Executor Service) - INFO - Auto-creating a Resource with id 'comp/DefaultManagedExecutorService' of type 'javax.enterprise.concurrent.ManagedExecutorService for 'test'. - INFO - Configuring Service(id=comp/DefaultManagedScheduledExecutorService, type=Resource, provider-id=Default Scheduled Executor Service) - INFO - Auto-creating a Resource with id 'comp/DefaultManagedScheduledExecutorService' of type 'javax.enterprise.concurrent.ManagedScheduledExecutorService for 'test'. - INFO - Configuring Service(id=comp/DefaultManagedThreadFactory, type=Resource, provider-id=Default Managed Thread Factory) - INFO - Auto-creating a Resource with id 'comp/DefaultManagedThreadFactory' of type 'javax.enterprise.concurrent.ManagedThreadFactory for 'test'. - INFO - Enterprise application "D:\github\tomee\examples\javamail\EmailServiceTest" loaded. - INFO - Creating dedicated application classloader for EmailServiceTest - INFO - Assembling app: D:\github\tomee\examples\javamail\EmailServiceTest - INFO - Using providers: - INFO - org.apache.johnzon.jaxrs.JohnzonProvider@2687f956 - INFO - org.apache.cxf.jaxrs.provider.JAXBElementProvider@1ded7b14 - INFO - org.apache.johnzon.jaxrs.JsrProvider@29be7749 - INFO - org.apache.johnzon.jaxrs.WadlDocumentMessageBodyWriter@5f84abe8 - INFO - org.apache.openejb.server.cxf.rs.EJBAccessExceptionMapper@4650a407 - INFO - org.apache.cxf.jaxrs.validation.ValidationExceptionMapper@30135202 - INFO - REST Application: http://127.0.0.1:4204/test/ -> org.apache.openejb.server.rest.InternalApplication - INFO - Service URI: http://127.0.0.1:4204/test/email -> Pojo org.superbiz.rest.EmailService - INFO - POST http://127.0.0.1:4204/test/email/ -> String lowerCase(String) - INFO - Deployed Application(path=D:\github\tomee\examples\javamail\EmailServiceTest) - DEBUG: JavaMail version 1.4ea - DEBUG: java.io.FileNotFoundException: D:\java\jdk8\jre\lib\javamail.providers (The system cannot find the file specified) - DEBUG: !anyLoaded - DEBUG: not loading resource: /META-INF/javamail.providers - DEBUG: successfully loaded resource: /META-INF/javamail.default.providers - DEBUG: Tables of loaded providers - DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc]} - DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]} - DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map - DEBUG: !anyLoaded - DEBUG: not loading resource: /META-INF/javamail.address.map - DEBUG: java.io.FileNotFoundException: D:\java\jdk8\jre\lib\javamail.address.map (The system cannot find the file specified) - DEBUG: setDebug: JavaMail version 1.4ea - DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc] - DEBUG SMTP: useEhlo true, useAuth false - DEBUG SMTP: trying to connect to host "your.mailserver.host", port 25, isSSL false - INFO - Undeploying app: D:\github\tomee\examples\javamail\EmailServiceTest - INFO - Stopping network services - INFO - Stopping server services - - http://git-wip-us.apache.org/repos/asf/tomee-site-generator/blob/efed31f4/src/main/jbake/content/examples/jpa-eclipselink.adoc ---------------------------------------------------------------------- diff --git a/src/main/jbake/content/examples/jpa-eclipselink.adoc b/src/main/jbake/content/examples/jpa-eclipselink.adoc deleted file mode 100755 index 21f9321..0000000 --- a/src/main/jbake/content/examples/jpa-eclipselink.adoc +++ /dev/null @@ -1,239 +0,0 @@ -= JPA Eclipselink -:jbake-date: 2016-09-06 -:jbake-type: page -:jbake-tomeepdf: -:jbake-status: published - -Example jpa-eclipselink can be browsed at https://github.com/apache/tomee/tree/master/examples/jpa-eclipselink - - -This example shows how to configure `persistence.xml` to work with Eclipselink. It uses an `@Entity` class and a `@Stateful` bean to add and delete entities from a database. - -== Creating the JPA Entity - -The entity itself is simply a pojo annotated with `@Entity`. We create one pojo called `Movie` which we can use to hold movie records. - - -[source,java] ----- -package org.superbiz.eclipselink; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - -@Entity -public class Movie { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private long id; - - private String director; - private String title; - private int year; - - public Movie() { - } - - public Movie(String director, String title, int year) { - this.director = director; - this.title = title; - this.year = year; - } - - public String getDirector() { - return director; - } - - public void setDirector(String director) { - this.director = director; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public int getYear() { - return year; - } - - public void setYear(int year) { - this.year = year; - } - -} ----- - - -== Database Operations - -This is the bean responsible for database operations; it allows us to persist or delete entities. -For more information we recommend you to see link:http://tomee.apache.org/examples-trunk/injection-of-entitymanager/README.html[injection-of-entitymanager] - - - -[source,java] ----- -package org.superbiz.eclipselink; - -import javax.ejb.Stateful; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.PersistenceContextType; -import javax.persistence.Query; -import java.util.List; - -@Stateful -public class Movies { - - @PersistenceContext(unitName = "movie-unit", type = PersistenceContextType.EXTENDED) - private EntityManager entityManager; - - public void addMovie(Movie movie) throws Exception { - entityManager.persist(movie); - } - - public void deleteMovie(Movie movie) throws Exception { - entityManager.remove(movie); - } - - public List<Movie> getMovies() throws Exception { - Query query = entityManager.createQuery("SELECT m from Movie as m"); - return query.getResultList(); - } -} ----- - - -== Persistence.xml with EclipseLink configuration - -This operation is too easy, just set the `provider` to `org.eclipse.persistence.jpa.PersistenceProvider` and add additional properties to the persistence unit. -The example has followed a strategy that allows the creation of tables in a HSQL database. -For a complete list of persistence unit properties see link:http://www.eclipse.org/eclipselink/api/2.4/org/eclipse/persistence/config/PersistenceUnitProperties.html[here] - - -[source,xml] ----- -<persistence version="1.0" - xmlns="http://java.sun.com/xml/ns/persistence" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"> - <persistence-unit name="movie-unit"> - <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> - <jta-data-source>movieDatabase</jta-data-source> - <non-jta-data-source>movieDatabaseUnmanaged</non-jta-data-source> - <properties> - <property name="eclipselink.target-database" value="org.eclipse.persistence.platform.database.HSQLPlatform"/> - <property name="eclipselink.ddl-generation" value="create-tables"/> - <property name="eclipselink.ddl-generation.output-mode" value="database"/> - </properties> - </persistence-unit> -</persistence> ----- - - - -== MoviesTest - -Testing JPA is quite easy, we can simply use the `EJBContainer` API to create a container in our test case. - - -[source,java] ----- -package org.superbiz.eclipselink; - -import junit.framework.TestCase; - -import javax.ejb.embeddable.EJBContainer; -import javax.naming.Context; -import java.util.List; -import java.util.Properties; - -/** - * @version $Revision: 607077 $ $Date: 2007-12-27 06:55:23 -0800 (Thu, 27 Dec 2007) $ - */ -public class MoviesTest extends TestCase { - - public void test() throws Exception { - Properties p = new Properties(); - p.put("movieDatabase", "new://Resource?type=DataSource"); - p.put("movieDatabase.JdbcDriver", "org.hsqldb.jdbcDriver"); - p.put("movieDatabase.JdbcUrl", "jdbc:hsqldb:mem:moviedb"); - - final Context context = EJBContainer.createEJBContainer(p).getContext(); - - Movies movies = (Movies) context.lookup("java:global/jpa-eclipselink/Movies"); - - movies.addMovie(new Movie("Quentin Tarantino", "Reservoir Dogs", 1992)); - movies.addMovie(new Movie("Joel Coen", "Fargo", 1996)); - movies.addMovie(new Movie("Joel Coen", "The Big Lebowski", 1998)); - - List<Movie> list = movies.getMovies(); - assertEquals("List.size()", 3, list.size()); - - for (Movie movie : list) { - movies.deleteMovie(movie); - } - - assertEquals("Movies.getMovies()", 0, movies.getMovies().size()); - } -} ----- - - -= Running - -When we run our test case we should see output similar to the following. - - -[source] ----- -------------------------------------------------------- - T E S T S -------------------------------------------------------- -Running org.superbiz.eclipselink.MoviesTest -Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06 -http://tomee.apache.org/ -INFO - openejb.home = /Users/dblevins/examples/jpa-eclipselink -INFO - openejb.base = /Users/dblevins/examples/jpa-eclipselink -INFO - Using 'javax.ejb.embeddable.EJBContainer=true' -INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service) -INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager) -INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database) -INFO - Found EjbModule in classpath: /Users/dblevins/examples/jpa-eclipselink/target/classes -INFO - Beginning load: /Users/dblevins/examples/jpa-eclipselink/target/classes -INFO - Configuring enterprise application: /Users/dblevins/examples/jpa-eclipselink -INFO - Configuring Service(id=Default Stateful Container, type=Container, provider-id=Default Stateful Container) -INFO - Auto-creating a container for bean Movies: Container(type=STATEFUL, id=Default Stateful Container) -INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container) -INFO - Auto-creating a container for bean org.superbiz.eclipselink.MoviesTest: Container(type=MANAGED, id=Default Managed Container) -INFO - Configuring PersistenceUnit(name=movie-unit, provider=org.eclipse.persistence.jpa.PersistenceProvider) -INFO - Auto-creating a Resource with id 'movieDatabaseNonJta' of type 'DataSource for 'movie-unit'. -INFO - Configuring Service(id=movieDatabaseNonJta, type=Resource, provider-id=movieDatabase) -INFO - Adjusting PersistenceUnit movie-unit <non-jta-data-source> to Resource ID 'movieDatabaseNonJta' from 'movieDatabaseUnmanaged' -INFO - Enterprise application "/Users/dblevins/examples/jpa-eclipselink" loaded. -INFO - Assembling app: /Users/dblevins/examples/jpa-eclipselink -INFO - PersistenceUnit(name=movie-unit, provider=org.eclipse.persistence.jpa.PersistenceProvider) - provider time 511ms -INFO - Jndi(name="java:global/jpa-eclipselink/Movies!org.superbiz.eclipselink.Movies") -INFO - Jndi(name="java:global/jpa-eclipselink/Movies") -INFO - Jndi(name="java:global/EjbModule225280863/org.superbiz.eclipselink.MoviesTest!org.superbiz.eclipselink.MoviesTest") -INFO - Jndi(name="java:global/EjbModule225280863/org.superbiz.eclipselink.MoviesTest") -INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container) -INFO - Created Ejb(deployment-id=org.superbiz.eclipselink.MoviesTest, ejb-name=org.superbiz.eclipselink.MoviesTest, container=Default Managed Container) -INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container) -INFO - Started Ejb(deployment-id=org.superbiz.eclipselink.MoviesTest, ejb-name=org.superbiz.eclipselink.MoviesTest, container=Default Managed Container) -INFO - Deployed Application(path=/Users/dblevins/examples/jpa-eclipselink) -Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.188 sec - -Results : - -Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 ----- - - http://git-wip-us.apache.org/repos/asf/tomee-site-generator/blob/efed31f4/src/main/jbake/content/examples/jpa-enumerated.adoc ---------------------------------------------------------------------- diff --git a/src/main/jbake/content/examples/jpa-enumerated.adoc b/src/main/jbake/content/examples/jpa-enumerated.adoc deleted file mode 100755 index 38ec6ec..0000000 --- a/src/main/jbake/content/examples/jpa-enumerated.adoc +++ /dev/null @@ -1,295 +0,0 @@ -= JPA and Enums via @Enumerated -:jbake-date: 2016-09-06 -:jbake-type: page -:jbake-tomeepdf: -:jbake-status: published - -Example jpa-enumerated can be browsed at https://github.com/apache/tomee/tree/master/examples/jpa-enumerated - - -It can sometimes be desirable to have a Java `enum` type to represent a particular column in a database. JPA supports converting database data to and from Java `enum` types via the `@javax.persistence.Enumerated` annotation. - -This example will show basic `@Enumerated` usage in a field of an `@Entity` as well as `enum`s as the parameter of a `Query`. We'll also see that the actual database representation can be effectively `String` or `int`. - -== Enum - -For our example we will leverage the familiar `Movie` entity and add a new field to represent the MPAA.org rating of the movie. This is defined via a simple `enum` that requires no JPA specific annotations. - - -[source,java] ----- -public enum Rating { - UNRATED, - G, - PG, - PG13, - R, - NC17 -} ----- - - -== @Enumerated - -In our `Movie` entity, we add a `rating` field of the enum type `Rating` and annotate it with `@Enumerated(EnumType.STRING)` to declare that its value should be converted from what is effectively a `String` in the database to the `Rating` type. - - -[source,java] ----- -@Entity -public class Movie { - - @Id - @GeneratedValue - private int id; - private String director; - private String title; - private int year; - - @Enumerated(EnumType.STRING) - private Rating rating; - - public Movie() { - } - - public Movie(String director, String title, int year, Rating rating) { - this.director = director; - this.title = title; - this.year = year; - this.rating = rating; - } - - public String getDirector() { - return director; - } - - public void setDirector(String director) { - this.director = director; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public int getYear() { - return year; - } - - public void setYear(int year) { - this.year = year; - } - - public Rating getRating() { - return rating; - } - - public void setRating(Rating rating) { - this.rating = rating; - } -} ----- - - -The above is enough and we are effectively done. For the sake of completeness we'll show a sample `Query` - -== Enum in JPQL Query - -Note the `findByRating` method which creates a `Query` with a `rating` named parameter. The key thing to notice is that the `rating` enum instance itself is passed into the - `query.setParameter` method, **not** `rating.name()` or `rating.ordinal()`. - -Regardless if you use `EnumType.STRING` or `EnumType.ORDINAL`, you still always pass the enum itself in calls to `query.setParameter`. - - -[source,java] ----- -@Stateful -public class Movies { - - @PersistenceContext(unitName = "movie-unit", type = PersistenceContextType.EXTENDED) - private EntityManager entityManager; - - public void addMovie(Movie movie) { - entityManager.persist(movie); - } - - public void deleteMovie(Movie movie) { - entityManager.remove(movie); - } - - public List<Movie> findByRating(Rating rating) { - final Query query = entityManager.createQuery("SELECT m FROM Movie as m WHERE m.rating = :rating"); - query.setParameter("rating", rating); - return query.getResultList(); - } - - public List<Movie> getMovies() throws Exception { - Query query = entityManager.createQuery("SELECT m from Movie as m"); - return query.getResultList(); - } - -} ----- - - -== EnumType.STRING vs EnumType.ORDINAL - -It is a matter of style how you would like your `enum` data represented in the database. Either `name()` or `ordinal()` are supported: - - - `@Enumerated(EnumType.STRING) Rating rating` the value of `rating.name()` is written and read from the corresponding database column; e.g. `G`, `PG`, `PG13` - - `@Enumerated(EnumType.ORDINAL) Rating rating` the value of `rating.ordinal()` is written and read from the corresponding database column; e.g. `0`, `1`, `2` - -The default is `EnumType.ORDINAL` - -There are advantages and disadvantages to each. - -=== Disadvantage of EnumType.ORDINAL - -A disadvantage of `EnumType.ORDINAL` is the effect of time and the desire to keep `enums` in a logical order. With `EnumType.ORDINAL` any new enum elements must be added to the -**end** of the list or you will accidentally change the meaning of all your records. - -Let's use our `Rating` enum and see how it would have had to evolve over time to keep up with changes in the MPAA.org ratings system. - -**1980** - - -[source,java] ----- -public enum Rating { - G, - PG, - R, - UNRATED -} ----- - - -**1984** PG-13 is added - - -[source,java] ----- -public enum Rating { - G, - PG, - R, - UNRATED, - PG13 -} ----- - - -**1990** NC-17 is added - - -[source,java] ----- -public enum Rating { - G, - PG, - R, - UNRATED, - PG13, - NC17 -} ----- - - -If `EnumType.STRING` was used, then the enum could be reordered at anytime and would instead look as we have defined it originally with ratings starting at `G` and increasing in severity to `NC17` and eventually `UNRATED`. With `EnumType.ORDINAL` the logical ordering would not have withstood the test of time as new values were added. - -If the order of the enum values is significant to your code, avoid `EnumType.ORDINAL` - -== Unit Testing the JPA @Enumerated - - -[source,java] ----- -public class MoviesTest extends TestCase { - - public void test() throws Exception { - - final Properties p = new Properties(); - p.put("movieDatabase", "new://Resource?type=DataSource"); - p.put("movieDatabase.JdbcDriver", "org.hsqldb.jdbcDriver"); - p.put("movieDatabase.JdbcUrl", "jdbc:hsqldb:mem:moviedb"); - - EJBContainer container = EJBContainer.createEJBContainer(p); - final Context context = container.getContext(); - - final Movies movies = (Movies) context.lookup("java:global/jpa-scratch/Movies"); - - movies.addMovie(new Movie("James Frawley", "The Muppet Movie", 1979, Rating.G)); - movies.addMovie(new Movie("Jim Henson", "The Great Muppet Caper", 1981, Rating.G)); - movies.addMovie(new Movie("Frank Oz", "The Muppets Take Manhattan", 1984, Rating.G)); - movies.addMovie(new Movie("James Bobin", "The Muppets", 2011, Rating.PG)); - - assertEquals("List.size()", 4, movies.getMovies().size()); - - assertEquals("List.size()", 3, movies.findByRating(Rating.G).size()); - - assertEquals("List.size()", 1, movies.findByRating(Rating.PG).size()); - - assertEquals("List.size()", 0, movies.findByRating(Rating.R).size()); - - container.close(); - } -} ----- - - -= Running - -To run the example via maven: - - cd jpa-enumerated - mvn clean install - -Which will generate output similar to the following: - - -[source] ----- -------------------------------------------------------- - T E S T S -------------------------------------------------------- -Running org.superbiz.jpa.enums.MoviesTest -Apache OpenEJB 4.0.0-beta-2 build: 20120115-08:26 -http://tomee.apache.org/ -INFO - openejb.home = /Users/dblevins/openejb/examples/jpa-enumerated -INFO - openejb.base = /Users/dblevins/openejb/examples/jpa-enumerated -INFO - Using 'javax.ejb.embeddable.EJBContainer=true' -INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service) -INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager) -INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database) -INFO - Found EjbModule in classpath: /Users/dblevins/openejb/examples/jpa-enumerated/target/classes -INFO - Beginning load: /Users/dblevins/openejb/examples/jpa-enumerated/target/classes -INFO - Configuring enterprise application: /Users/dblevins/openejb/examples/jpa-enumerated -INFO - Configuring Service(id=Default Stateful Container, type=Container, provider-id=Default Stateful Container) -INFO - Auto-creating a container for bean Movies: Container(type=STATEFUL, id=Default Stateful Container) -INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container) -INFO - Auto-creating a container for bean org.superbiz.jpa.enums.MoviesTest: Container(type=MANAGED, id=Default Managed Container) -INFO - Configuring PersistenceUnit(name=movie-unit) -INFO - Auto-creating a Resource with id 'movieDatabaseNonJta' of type 'DataSource for 'movie-unit'. -INFO - Configuring Service(id=movieDatabaseNonJta, type=Resource, provider-id=movieDatabase) -INFO - Adjusting PersistenceUnit movie-unit <non-jta-data-source> to Resource ID 'movieDatabaseNonJta' from 'movieDatabaseUnmanaged' -INFO - Enterprise application "/Users/dblevins/openejb/examples/jpa-enumerated" loaded. -INFO - Assembling app: /Users/dblevins/openejb/examples/jpa-enumerated -INFO - PersistenceUnit(name=movie-unit, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 406ms -INFO - Jndi(name="java:global/jpa-enumerated/Movies!org.superbiz.jpa.enums.Movies") -INFO - Jndi(name="java:global/jpa-enumerated/Movies") -INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container) -INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container) -INFO - Deployed Application(path=/Users/dblevins/openejb/examples/jpa-enumerated) -INFO - Undeploying app: /Users/dblevins/openejb/examples/jpa-enumerated -INFO - Closing DataSource: movieDatabase -INFO - Closing DataSource: movieDatabaseNonJta -Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.831 sec - -Results : - -Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 ----- - http://git-wip-us.apache.org/repos/asf/tomee-site-generator/blob/efed31f4/src/main/jbake/content/examples/jpa-hibernate.adoc ---------------------------------------------------------------------- diff --git a/src/main/jbake/content/examples/jpa-hibernate.adoc b/src/main/jbake/content/examples/jpa-hibernate.adoc deleted file mode 100755 index f57ff1b..0000000 --- a/src/main/jbake/content/examples/jpa-hibernate.adoc +++ /dev/null @@ -1,224 +0,0 @@ -= JPA Hibernate -:jbake-date: 2016-09-06 -:jbake-type: page -:jbake-tomeepdf: -:jbake-status: published - -Example jpa-hibernate can be browsed at https://github.com/apache/tomee/tree/master/examples/jpa-hibernate - - -*Help us document this example! Click the blue pencil icon in the upper right to edit this page.* - -== Movie - - -[source,java] ----- -package org.superbiz.injection.h3jpa; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - -@Entity -public class Movie { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private long id; - - private String director; - private String title; - private int year; - - public Movie() { - } - - public Movie(String director, String title, int year) { - this.director = director; - this.title = title; - this.year = year; - } - - public String getDirector() { - return director; - } - - public void setDirector(String director) { - this.director = director; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public int getYear() { - return year; - } - - public void setYear(int year) { - this.year = year; - } - -} ----- - - -== Movies - - -[source,java] ----- -package org.superbiz.injection.h3jpa; - -import javax.ejb.Stateful; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.PersistenceContextType; -import javax.persistence.Query; -import java.util.List; - -@Stateful -public class Movies { - - @PersistenceContext(unitName = "movie-unit", type = PersistenceContextType.EXTENDED) - private EntityManager entityManager; - - public void addMovie(Movie movie) throws Exception { - entityManager.persist(movie); - } - - public void deleteMovie(Movie movie) throws Exception { - entityManager.remove(movie); - } - - public List<Movie> getMovies() throws Exception { - Query query = entityManager.createQuery("SELECT m from Movie as m"); - return query.getResultList(); - } -} ----- - - -== persistence.xml - - -[source,xml] ----- -<persistence version="1.0" - xmlns="http://java.sun.com/xml/ns/persistence" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"> - <persistence-unit name="movie-unit"> - <provider>org.hibernate.ejb.HibernatePersistence</provider> - <jta-data-source>movieDatabase</jta-data-source> - <non-jta-data-source>movieDatabaseUnmanaged</non-jta-data-source> - <properties> - <property name="hibernate.hbm2ddl.auto" value="create-drop"/> - <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/> - </properties> - </persistence-unit> -</persistence> ----- - - - -== MoviesTest - - -[source,java] ----- -package org.superbiz.injection.h3jpa; - -import junit.framework.TestCase; - -import javax.ejb.embeddable.EJBContainer; -import javax.naming.Context; -import java.util.List; -import java.util.Properties; - -/** - * @version $Revision: 607077 $ $Date: 2007-12-27 06:55:23 -0800 (Thu, 27 Dec 2007) $ - */ -public class MoviesTest extends TestCase { - - public void test() throws Exception { - final Properties p = new Properties(); - p.put("movieDatabase", "new://Resource?type=DataSource"); - p.put("movieDatabase.JdbcDriver", "org.hsqldb.jdbcDriver"); - p.put("movieDatabase.JdbcUrl", "jdbc:hsqldb:mem:moviedb"); - - final Context context = EJBContainer.createEJBContainer(p).getContext(); - Movies movies = (Movies) context.lookup("java:global/jpa-hibernate/Movies"); - - movies.addMovie(new Movie("Quentin Tarantino", "Reservoir Dogs", 1992)); - movies.addMovie(new Movie("Joel Coen", "Fargo", 1996)); - movies.addMovie(new Movie("Joel Coen", "The Big Lebowski", 1998)); - - List<Movie> list = movies.getMovies(); - assertEquals("List.size()", 3, list.size()); - - for (Movie movie : list) { - movies.deleteMovie(movie); - } - - assertEquals("Movies.getMovies()", 0, movies.getMovies().size()); - } -} ----- - - -= Running - - - -[source] ----- -------------------------------------------------------- - T E S T S -------------------------------------------------------- -Running org.superbiz.injection.h3jpa.MoviesTest -Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06 -http://tomee.apache.org/ -INFO - openejb.home = /Users/dblevins/examples/jpa-hibernate -INFO - openejb.base = /Users/dblevins/examples/jpa-hibernate -INFO - Using 'javax.ejb.embeddable.EJBContainer=true' -INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service) -INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager) -INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database) -INFO - Found EjbModule in classpath: /Users/dblevins/examples/jpa-hibernate/target/classes -INFO - Beginning load: /Users/dblevins/examples/jpa-hibernate/target/classes -INFO - Configuring enterprise application: /Users/dblevins/examples/jpa-hibernate -INFO - Configuring Service(id=Default Stateful Container, type=Container, provider-id=Default Stateful Container) -INFO - Auto-creating a container for bean Movies: Container(type=STATEFUL, id=Default Stateful Container) -INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container) -INFO - Auto-creating a container for bean org.superbiz.injection.h3jpa.MoviesTest: Container(type=MANAGED, id=Default Managed Container) -INFO - Configuring PersistenceUnit(name=movie-unit, provider=org.hibernate.ejb.HibernatePersistence) -INFO - Auto-creating a Resource with id 'movieDatabaseNonJta' of type 'DataSource for 'movie-unit'. -INFO - Configuring Service(id=movieDatabaseNonJta, type=Resource, provider-id=movieDatabase) -INFO - Adjusting PersistenceUnit movie-unit <non-jta-data-source> to Resource ID 'movieDatabaseNonJta' from 'movieDatabaseUnmanaged' -INFO - Enterprise application "/Users/dblevins/examples/jpa-hibernate" loaded. -INFO - Assembling app: /Users/dblevins/examples/jpa-hibernate -INFO - PersistenceUnit(name=movie-unit, provider=org.hibernate.ejb.HibernatePersistence) - provider time 631ms -INFO - Jndi(name="java:global/jpa-hibernate/Movies!org.superbiz.injection.h3jpa.Movies") -INFO - Jndi(name="java:global/jpa-hibernate/Movies") -INFO - Jndi(name="java:global/EjbModule1235930463/org.superbiz.injection.h3jpa.MoviesTest!org.superbiz.injection.h3jpa.MoviesTest") -INFO - Jndi(name="java:global/EjbModule1235930463/org.superbiz.injection.h3jpa.MoviesTest") -INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container) -INFO - Created Ejb(deployment-id=org.superbiz.injection.h3jpa.MoviesTest, ejb-name=org.superbiz.injection.h3jpa.MoviesTest, container=Default Managed Container) -INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container) -INFO - Started Ejb(deployment-id=org.superbiz.injection.h3jpa.MoviesTest, ejb-name=org.superbiz.injection.h3jpa.MoviesTest, container=Default Managed Container) -INFO - Deployed Application(path=/Users/dblevins/examples/jpa-hibernate) -Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.22 sec - -Results : - -Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 ----- - - http://git-wip-us.apache.org/repos/asf/tomee-site-generator/blob/efed31f4/src/main/jbake/content/examples/jsf-cdi-and-ejb.adoc ---------------------------------------------------------------------- diff --git a/src/main/jbake/content/examples/jsf-cdi-and-ejb.adoc b/src/main/jbake/content/examples/jsf-cdi-and-ejb.adoc deleted file mode 100755 index 1d31e0a..0000000 --- a/src/main/jbake/content/examples/jsf-cdi-and-ejb.adoc +++ /dev/null @@ -1,273 +0,0 @@ -= JSF-CDI-EJB -:jbake-date: 2016-09-06 -:jbake-type: page -:jbake-tomeepdf: -:jbake-status: published - -Example jsf-cdi-and-ejb can be browsed at https://github.com/apache/tomee/tree/master/examples/jsf-cdi-and-ejb - - -The simple application contains a CDI managed bean `CalculatorBean`, which uses the `Calculator` EJB to add two numbers -and display the results to the user. The EJB is injected in the managed bean using @Inject annotation. - -You could run this in the latest Apache TomEE link:https://repository.apache.org/content/repositories/snapshots/org/apache/openejb/apache-tomee/[snapshot] - -The complete source code is below but lets break down to look at some smaller snippets and see how it works. - - -A little note on the setup: - -As for the libraries, myfaces-api and myfaces-impl are provided in tomee/lib and hence they should not be a part of the -war. In maven terms, they would be with scope 'provided' - -Also note that we use servlet 2.5 declaration in web.xml -<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xmlns="http://java.sun.com/xml/ns/javaee" - xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" - xsi:schemaLocation="http://java.sun.com/xml/ns/javaee - http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" - version="2.5"> - -And we use 2.0 version of faces-config - - <faces-config xmlns="http://java.sun.com/xml/ns/javaee" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://java.sun.com/xml/ns/javaee - http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd" - version="2.0"> - -To make this a cdi-aware-archive (i.e bean archive) an empty beans.xml is added in WEB-INF - - <?xml version="1.0" encoding="UTF-8"?> - - <beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://java.sun.com/xml/ns/javaee - http://java.sun.com/xml/ns/javaee/beans_1_0.xsd"> - </beans> - -We'll first declare the FacesServlet in the web.xml - - <servlet> - <servlet-name>Faces Servlet</servlet-name> - <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> - <load-on-startup>1</load-on-startup> - </servlet> - -FacesServlet acts as the master controller. - -We'll then create the calculator.xhtml file. - - <h:outputText value='Enter first number'/> - <h:inputText value='#{calculatorBean.x}'/> - <h:outputText value='Enter second number'/> - <h:inputText value='#{calculatorBean.y}'/> - <h:commandButton action="#{calculatorBean.add}" value="Add"/> - -Notice how we've used the bean here. By default, the bean name would be the simple name of the bean -class with the first letter in lower case. - -We've annotated the `CalculatorBean` with `@RequestScoped`. -So when a request comes in, the bean is instantiated and placed in the request scope. - -<h:inputText value='#{calculatorBean.x}'/> - -Here, getX() method of calculatorBean is invoked and the resulting value is displayed. -x being a Double, we rightly should see 0.0 displayed. - -When you change the value and submit the form, these entered values are bound using the setters -in the bean and then the commandButton-action method is invoked. - -In this case, CalculatorBean#add() is invoked. - -Calculator#add() delegates the work to the ejb, gets the result, stores it -and then returns what view is to be rendered. - -The return value "success" is checked up in faces-config navigation-rules -and the respective page is rendered. - -In our case, 'result.xhtml' page is rendered where -use EL and display the result from the request-scoped `calculatorBean`. - -= Source Code - -== CalculatorBean - - -[source,java] ----- -import javax.enterprise.context.RequestScoped; -import javax.inject.Named; -import javax.inject.Inject; - -@RequestScoped -@Named -public class CalculatorBean { - @Inject - Calculator calculator; - private double x; - private double y; - private double result; - - public double getX() { - return x; - } - - public void setX(double x) { - this.x = x; - } - - public double getY() { - return y; - } - - public void setY(double y) { - this.y = y; - } - - public double getResult() { - return result; - } - - public void setResult(double result) { - this.result = result; - } - - public String add() { - result = calculator.add(x, y); - return "success"; - } -} ----- - - -== Calculator - - -[source,java] ----- -package org.superbiz.jsf; - -import javax.ejb.Stateless; - -@Stateless -public class Calculator{ - - public double add(double x, double y) { - return x + y; - } -} ----- - - - -= web.xml - -<?xml version="1.0"?> - -<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xmlns="http://java.sun.com/xml/ns/javaee" - xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" - xsi:schemaLocation="http://java.sun.com/xml/ns/javaee - http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" - version="2.5"> - - <description>MyProject web.xml</description> - - <!-- Faces Servlet --> - <servlet> - -[source,xml] ----- -<servlet-name>Faces Servlet</servlet-name> -<servlet-class>javax.faces.webapp.FacesServlet</servlet-class> -<load-on-startup>1</load-on-startup> - </servlet> - - <!-- Faces Servlet Mapping --> - <servlet-mapping> -<servlet-name>Faces Servlet</servlet-name> -<url-pattern>*.jsf</url-pattern> - </servlet-mapping> - - <!-- Welcome files --> - <welcome-file-list> -<welcome-file>index.jsp</welcome-file> -<welcome-file>index.html</welcome-file> - </welcome-file-list> - -</web-app> - - -#Calculator.xhtml - -<?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" -"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml" - xmlns:f="http://java.sun.com/jsf/core" - xmlns:h="http://java.sun.com/jsf/html"> - - -<h:body bgcolor="white"> -<f:view> - <h:form> - <h:panelGrid columns="2"> - <h:outputText value='Enter first number'/> - <h:inputText value='#{calculatorBean.x}'/> - <h:outputText value='Enter second number'/> - <h:inputText value='#{calculatorBean.y}'/> - <h:commandButton action="#{calculatorBean.add}" value="Add"/> - </h:panelGrid> - </h:form> -</f:view> -</h:body> -</html> - - - #Result.xhtml - -<?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" - "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml" - xmlns:f="http://java.sun.com/jsf/core" - xmlns:h="http://java.sun.com/jsf/html"> - -<h:body> -<f:view> -<h:form id="mainForm"> - <h2><h:outputText value="Result of adding #{calculatorBean.x} and #{calculatorBean.y} is #{calculatorBean.result }"/></h2> - <h:commandLink action="back"> - <h:outputText value="Home"/> - </h:commandLink> -</h:form> -</f:view> -</h:body> -</html> - - #faces-config.xml - - <?xml version="1.0"?> - <faces-config xmlns="http://java.sun.com/xml/ns/javaee" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://java.sun.com/xml/ns/javaee - http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd" - version="2.0"> - - <navigation-rule> - <from-view-id>/calculator.xhtml</from-view-id> - <navigation-case> - <from-outcome>success</from-outcome> - <to-view-id>/result.xhtml</to-view-id> - </navigation-case> - </navigation-rule> - - <navigation-rule> - <from-view-id>/result.xhtml</from-view-id> - <navigation-case> - <from-outcome>back</from-outcome> - <to-view-id>/calculator.xhtml</to-view-id> - </navigation-case> - </navigation-rule> - </faces-config> - http://git-wip-us.apache.org/repos/asf/tomee-site-generator/blob/efed31f4/src/main/jbake/content/examples/jsf-managedBean-and-ejb.adoc ---------------------------------------------------------------------- diff --git a/src/main/jbake/content/examples/jsf-managedBean-and-ejb.adoc b/src/main/jbake/content/examples/jsf-managedBean-and-ejb.adoc deleted file mode 100755 index cea24ba..0000000 --- a/src/main/jbake/content/examples/jsf-managedBean-and-ejb.adoc +++ /dev/null @@ -1,277 +0,0 @@ -= JSF Application that uses managed-bean and ejb -:jbake-date: 2016-09-06 -:jbake-type: page -:jbake-tomeepdf: -:jbake-status: published - -Example jsf-managedBean-and-ejb can be browsed at https://github.com/apache/tomee/tree/master/examples/jsf-managedBean-and-ejb - - -This is a simple web-app showing how to use dependency injection in JSF managed beans using TomEE. - -It contains a Local Stateless session bean `CalculatorImpl` which adds two numbers and returns the result. -The application also contains a JSF managed bean `CalculatorBean`, which uses the EJB to add two numbers -and display the results to the user. The EJB is injected in the managed bean using `@EJB` annotation. - - -== A little note on the setup: - -You could run this in the latest Apache TomEE link:https://repository.apache.org/content/repositories/snapshots/org/apache/openejb/apache-tomee/[snapshot] - -As for the libraries, myfaces-api and myfaces-impl are provided in tomee/lib and hence they should not be a part of the -war. In maven terms, they would be with scope 'provided' - -Also note that we use servlet 2.5 declaration in web.xml - - -[source,xml] ----- -<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" -xmlns="http://java.sun.com/xml/ns/javaee" -xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" -xsi:schemaLocation="http://java.sun.com/xml/ns/javaee -http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" -version="2.5"> - -And we use 2.0 version of faces-config - - <faces-config xmlns="http://java.sun.com/xml/ns/javaee" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://java.sun.com/xml/ns/javaee - http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd" - version="2.0"> - - -The complete source code is provided below but let's break down to look at some smaller snippets and see how it works. - -We'll first declare the `FacesServlet` in the `web.xml` - - <servlet> - <servlet-name>Faces Servlet</servlet-name> - <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> - <load-on-startup>1</load-on-startup> - </servlet> - -`FacesServlet` acts as the master controller. - -We'll then create the `calculator.xhtml` file. - - <h:outputText value='Enter first number'/> - <h:inputText value='#{calculatorBean.x}'/> - <h:outputText value='Enter second number'/> - <h:inputText value='#{calculatorBean.y}'/> - <h:commandButton action="#{calculatorBean.add}" value="Add"/> - - -Notice how we've use the bean here. -By default it is the simple class name of the managed bean. - -When a request comes in, the bean is instantiated and placed in the appropriate scope. -By default, the bean is placed in the request scope. - - <h:inputText value='#{calculatorBean.x}'/> - -Here, getX() method of calculatorBean is invoked and the resulting value is displayed. -x being a Double, we rightly should see 0.0 displayed. - -When you change the value and submit the form, these entered values are bound using the setters -in the bean and then the commandButton-action method is invoked. - -In this case, `CalculatorBean#add()` is invoked. - -`Calculator#add()` delegates the work to the ejb, gets the result, stores it -and then instructs what view is to be rendered. - -You're right. The return value "success" is checked up in faces-config navigation-rules -and the respective page is rendered. - -In our case, `result.xhtml` page is rendered. - -The request scoped `calculatorBean` is available here, and we use EL to display the values. - -## Source - -## Calculator - -package org.superbiz.jsf; - -import javax.ejb.Local; - -@Local -public interface Calculator { - public double add(double x, double y); -} - - -## CalculatorBean - -package org.superbiz.jsf; - -import javax.ejb.EJB; -import javax.faces.bean.ManagedBean; - -@ManagedBean -public class CalculatorBean { - @EJB - Calculator calculator; - private double x; - private double y; - private double result; - - public double getX() { - return x; - } - - public void setX(double x) { - this.x = x; - } - - public double getY() { - return y; - } - - public void setY(double y) { - this.y = y; - } - - public double getResult() { - return result; - } - - public void setResult(double result) { - this.result = result; - } - - public String add() { - result = calculator.add(x, y); - return "success"; - } -} - -## CalculatorImpl - -package org.superbiz.jsf; - -import javax.ejb.Stateless; - -@Stateless -public class CalculatorImpl implements Calculator { - - public double add(double x, double y) { - return x + y; - } -} - - -# web.xml - -<?xml version="1.0"?> - - <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xmlns="http://java.sun.com/xml/ns/javaee" - xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" - xsi:schemaLocation="http://java.sun.com/xml/ns/javaee - http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" - version="2.5"> - - <description>MyProject web.xml</description> - - <!-- Faces Servlet --> - <servlet> - <servlet-name>Faces Servlet</servlet-name> - <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> - <load-on-startup>1</load-on-startup> - </servlet> - - <!-- Faces Servlet Mapping --> - <servlet-mapping> - <servlet-name>Faces Servlet</servlet-name> - <url-pattern>*.jsf</url-pattern> - </servlet-mapping> - - <!-- Welcome files --> - <welcome-file-list> - <welcome-file>index.jsp</welcome-file> - <welcome-file>index.html</welcome-file> - </welcome-file-list> - </web-app> ----- - - - -== Calculator.xhtml - - -[source,xml] ----- -<?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" -"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml" -xmlns:f="http://java.sun.com/jsf/core" -xmlns:h="http://java.sun.com/jsf/html"> - - -<h:body bgcolor="white"> - <f:view> - <h:form> - <h:panelGrid columns="2"> - <h:outputText value='Enter first number'/> - <h:inputText value='#{calculatorBean.x}'/> - <h:outputText value='Enter second number'/> - <h:inputText value='#{calculatorBean.y}'/> - <h:commandButton action="#{calculatorBean.add}" value="Add"/> - </h:panelGrid> - </h:form> - </f:view> -</h:body> -</html> - - -##Result.xhtml - -<?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" -"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml" -xmlns:f="http://java.sun.com/jsf/core" -xmlns:h="http://java.sun.com/jsf/html"> - -<h:body> - <f:view> - <h:form id="mainForm"> - <h2><h:outputText value="Result of adding #{calculatorBean.x} and #{calculatorBean.y} is #{calculatorBean.result }"/></h2> - <h:commandLink action="back"> - <h:outputText value="Home"/> - </h:commandLink> - </h:form> - </f:view> -</h:body> -</html> - -#faces-config.xml - -<?xml version="1.0"?> -<faces-config xmlns="http://java.sun.com/xml/ns/javaee" -xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" -xsi:schemaLocation="http://java.sun.com/xml/ns/javaee -http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd" -version="2.0"> - -<navigation-rule> - <from-view-id>/calculator.xhtml</from-view-id> - <navigation-case> - <from-outcome>success</from-outcome> - <to-view-id>/result.xhtml</to-view-id> - </navigation-case> -</navigation-rule> - -<navigation-rule> - <from-view-id>/result.xhtml</from-view-id> - <navigation-case> - <from-outcome>back</from-outcome> - <to-view-id>/calculator.xhtml</to-view-id> - </navigation-case> -</navigation-rule> -</faces-config> -
