blob: ba5ccce934f1f4fe6bb59abae69a21ca381cf8fe [file] [log] [blame]
{
"all":{
"adapters":[
{
"name":"multiple-arquillian-adapters",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/multiple-arquillian-adapters"
}
],
"alternate":[
{
"name":"alternate-descriptors",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/alternate-descriptors"
}
],
"alternative":[
{
"name":"cdi-alternative-and-stereotypes",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/cdi-alternative-and-stereotypes"
}
],
"applet":[
{
"name":"applet",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/applet"
}
],
"applicationcomposer":[
{
"name":"applicationcomposer-jaxws-cdi",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/applicationcomposer-jaxws-cdi"
},
{
"name":"rest-applicationcomposer",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/rest-applicationcomposer"
},
{
"name":"application-composer",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/application-composer"
},
{
"name":"rest-applicationcomposer-mockito",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/rest-applicationcomposer-mockito"
}
],
"applicationexception":[
{
"name":"applicationexception",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/applicationexception"
}
],
"arquillian":[
{
"name":"arquillian-jpa",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/arquillian-jpa"
},
{
"name":"multiple-tomee-arquillian",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/multiple-tomee-arquillian"
},
{
"name":"multiple-arquillian-adapters",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/multiple-arquillian-adapters"
}
],
"async":[
{
"name":"async-postconstruct",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/async-postconstruct"
},
{
"name":"async-methods",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/async-methods"
}
],
"attachments":[
{
"name":"webservice-attachments",
"readme":"Title: Webservice Attachments\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## AttachmentImpl\n\n package org.superbiz.attachment;\n \n import javax.activation.DataHandler;\n import javax.activation.DataSource;\n import javax.ejb.Stateless;\n import javax.jws.WebService;\n import javax.xml.ws.BindingType;\n import javax.xml.ws.soap.SOAPBinding;\n import java.io.IOException;\n import java.io.InputStream;\n \n /**\n * This is an EJB 3 style pojo stateless session bean\n * Every stateless session bean implementation must be annotated\n * using the annotation @Stateless\n * This EJB has a single interface: {@link AttachmentWs} a webservice interface.\n */\n @Stateless\n @WebService(\n portName = \"AttachmentPort\",\n serviceName = \"AttachmentWsService\",\n targetNamespace = \"http://superbiz.org/wsdl\",\n endpointInterface = \"org.superbiz.attachment.AttachmentWs\")\n @BindingType(value = SOAPBinding.SOAP12HTTP_MTOM_BINDING)\n public class AttachmentImpl implements AttachmentWs {\n \n public String stringFromBytes(byte[] data) {\n return new String(data);\n }\n \n public String stringFromDataSource(DataSource source) {\n \n try {\n InputStream inStr = source.getInputStream();\n int size = inStr.available();\n byte[] data = new byte[size];\n inStr.read(data);\n inStr.close();\n return new String(data);\n } catch (IOException e) {\n e.printStackTrace();\n }\n return \"\";\n }\n \n public String stringFromDataHandler(DataHandler handler) {\n \n try {\n return (String) handler.getContent();\n } catch (IOException e) {\n e.printStackTrace();\n }\n return \"\";\n }\n }\n\n## AttachmentWs\n\n package org.superbiz.attachment;\n \n import javax.activation.DataHandler;\n import javax.jws.WebService;\n \n /**\n * This is an EJB 3 webservice interface to send attachments throughout SAOP.\n */\n @WebService(targetNamespace = \"http://superbiz.org/wsdl\")\n public interface AttachmentWs {\n \n public String stringFromBytes(byte[] data);\n \n // Not working at the moment with SUN saaj provider and CXF\n //public String stringFromDataSource(DataSource source);\n \n public String stringFromDataHandler(DataHandler handler);\n }\n\n## ejb-jar.xml\n\n <ejb-jar/>\n\n## AttachmentTest\n\n package org.superbiz.attachment;\n \n import junit.framework.TestCase;\n \n import javax.activation.DataHandler;\n import javax.activation.DataSource;\n import javax.mail.util.ByteArrayDataSource;\n import javax.naming.Context;\n import javax.naming.InitialContext;\n import javax.xml.namespace.QName;\n import javax.xml.ws.BindingProvider;\n import javax.xml.ws.Service;\n import javax.xml.ws.soap.SOAPBinding;\n import java.net.URL;\n import java.util.Properties;\n \n public class AttachmentTest extends TestCase {\n \n //START SNIPPET: setup\t\n private InitialContext initialContext;\n \n protected void setUp() throws Exception {\n \n Properties properties = new Properties();\n properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, \"org.apache.openejb.core.LocalInitialContextFactory\");\n properties.setProperty(\"openejb.embedded.remotable\", \"true\");\n \n initialContext = new InitialContext(properties);\n }\n //END SNIPPET: setup \n \n /**\n * Create a webservice client using wsdl url\n *\n * @throws Exception\n */\n //START SNIPPET: webservice\n public void testAttachmentViaWsInterface() throws Exception {\n Service service = Service.create(\n new URL(\"http://127.0.0.1:4204/AttachmentImpl?wsdl\"),\n new QName(\"http://superbiz.org/wsdl\", \"AttachmentWsService\"));\n assertNotNull(service);\n \n AttachmentWs ws = service.getPort(AttachmentWs.class);\n \n // retrieve the SOAPBinding\n SOAPBinding binding = (SOAPBinding) ((BindingProvider) ws).getBinding();\n binding.setMTOMEnabled(true);\n \n String request = \"tsztelak@gmail.com\";\n \n // Byte array\n String response = ws.stringFromBytes(request.getBytes());\n assertEquals(request, response);\n \n // Data Source\n DataSource source = new ByteArrayDataSource(request.getBytes(), \"text/plain; charset=UTF-8\");\n \n // not yet supported !\n // response = ws.stringFromDataSource(source);\n // assertEquals(request, response);\n \n // Data Handler\n response = ws.stringFromDataHandler(new DataHandler(source));\n assertEquals(request, response);\n }\n //END SNIPPET: webservice\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.attachment.AttachmentTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/webservice-attachments\n INFO - openejb.base = /Users/dblevins/examples/webservice-attachments\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/webservice-attachments/target/classes\n INFO - Beginning load: /Users/dblevins/examples/webservice-attachments/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/webservice-attachments/classpath.ear\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean AttachmentImpl: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Enterprise application \"/Users/dblevins/examples/webservice-attachments/classpath.ear\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/webservice-attachments/classpath.ear\n INFO - Created Ejb(deployment-id=AttachmentImpl, ejb-name=AttachmentImpl, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=AttachmentImpl, ejb-name=AttachmentImpl, container=Default Stateless Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/webservice-attachments/classpath.ear)\n INFO - Initializing network services\n INFO - Creating ServerService(id=httpejbd)\n INFO - Creating ServerService(id=cxf)\n INFO - Creating ServerService(id=admin)\n INFO - Creating ServerService(id=ejbd)\n INFO - Creating ServerService(id=ejbds)\n INFO - Initializing network services\n ** Starting Services **\n NAME IP PORT \n httpejbd 127.0.0.1 4204 \n admin thread 127.0.0.1 4200 \n ejbd 127.0.0.1 4201 \n ejbd 127.0.0.1 4203 \n -------\n Ready!\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.034 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/webservice-attachments"
}
],
"bmt":[
{
"name":"testing-transactions-bmt",
"readme":"Title: Testing Transactions BMT\n\nShows how to begin, commit and rollback transactions using a UserTransaction via a Stateful Bean.\n\n## Movie\n\n package org.superbiz.injection.tx;\n\n import javax.persistence.Entity;\n import javax.persistence.GeneratedValue;\n import javax.persistence.Id;\n\n @Entity\n public class Movie {\n\n @Id\n @GeneratedValue\n private Long id;\n private String director;\n private String title;\n private int year;\n\n public Movie(String director, String title, int year) {\n this.director = director;\n this.title = title;\n this.year = year;\n }\n\n public Movie() {\n\n }\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getDirector() {\n return director;\n }\n\n public void setDirector(String director) {\n this.director = director;\n }\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public int getYear() {\n return year;\n }\n\n public void setYear(int year) {\n this.year = year;\n }\n }\n\n## Movies\n\n package org.superbiz.injection.tx;\n\n import javax.annotation.Resource;\n import javax.ejb.Stateful;\n import javax.ejb.TransactionManagement;\n import javax.ejb.TransactionManagementType;\n import javax.persistence.EntityManager;\n import javax.persistence.PersistenceContext;\n import javax.persistence.PersistenceContextType;\n import javax.persistence.Query;\n import javax.transaction.UserTransaction;\n\n @Stateful(name = \"Movies\")\n @TransactionManagement(TransactionManagementType.BEAN)\n public class Movies {\n\n @PersistenceContext(unitName = \"movie-unit\", type = PersistenceContextType.TRANSACTION)\n private EntityManager entityManager;\n\n @Resource\n private UserTransaction userTransaction;\n\n public void addMovie(Movie movie) throws Exception {\n try {\n userTransaction.begin();\n entityManager.persist(movie);\n\n //For some dummy reason, this db can have only 5 titles. :O)\n if (countMovies() > 5) {\n userTransaction.rollback();\n } else {\n userTransaction.commit();\n }\n\n\n } catch (Exception e) {\n e.printStackTrace();\n userTransaction.rollback();\n }\n }\n\n public Long countMovies() throws Exception {\n Query query = entityManager.createQuery(\"SELECT COUNT(m) FROM Movie m\");\n return Long.class.cast(query.getSingleResult());\n }\n }\n\n\n## persistence.xml\n\n <persistence xmlns=\"http://java.sun.com/xml/ns/persistence\" version=\"1.0\">\n\n <persistence-unit name=\"movie-unit\">\n <jta-data-source>movieDatabase</jta-data-source>\n <non-jta-data-source>movieDatabaseUnmanaged</non-jta-data-source>\n <class>org.superbiz.injection.tx.Movie</class>\n\n <properties>\n <property name=\"openjpa.jdbc.SynchronizeMappings\" value=\"buildSchema(ForeignKeys=true)\"/>\n </properties>\n </persistence-unit>\n </persistence>\n\n## MoviesTest\n\n package org.superbiz.injection.tx;\n\n import org.junit.Assert;\n import org.junit.Test;\n\n import javax.ejb.EJB;\n import javax.ejb.embeddable.EJBContainer;\n import java.util.Properties;\n\n public class MoviesTest {\n\n @EJB\n private Movies movies;\n\n @Test\n public void testMe() throws Exception {\n final Properties p = new Properties();\n p.put(\"movieDatabase\", \"new://Resource?type=DataSource\");\n p.put(\"movieDatabase.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"movieDatabase.JdbcUrl\", \"jdbc:hsqldb:mem:moviedb\");\n\n EJBContainer.createEJBContainer(p).getContext().bind(\"inject\", this);\n\n movies.addMovie(new Movie(\"Asif Kapadia\", \"Senna\", 2010));\n movies.addMovie(new Movie(\"José Padilha\", \"Tropa de Elite\", 2007));\n movies.addMovie(new Movie(\"Andy Wachowski/Lana Wachowski\", \"The Matrix\", 1999));\n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n movies.addMovie(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n movies.addMovie(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n\n Assert.assertEquals(5L, movies.countMovies().longValue());\n }\n\n }\n\n\n# Running\n\n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.injection.tx.MoviesTest\n INFO - ********************************************************************************\n INFO - OpenEJB http://tomee.apache.org/\n INFO - Startup: Sat Jul 21 16:39:28 EDT 2012\n INFO - Copyright 1999-2012 (C) Apache OpenEJB Project, All Rights Reserved.\n INFO - Version: 4.1.0\n INFO - Build date: 20120721\n INFO - Build time: 12:06\n INFO - ********************************************************************************\n INFO - openejb.home = /home/boto/dev/ws/openejb_trunk/openejb/examples/testing-transactions-bmt\n INFO - openejb.base = /home/boto/dev/ws/openejb_trunk/openejb/examples/testing-transactions-bmt\n INFO - Created new singletonService org.apache.openejb.cdi.ThreadSingletonServiceImpl@3f3f210f\n INFO - Succeeded in installing singleton service\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Cannot find the configuration file [conf/openejb.xml]. Will attempt to create one for the beans deployed.\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Creating TransactionManager(id=Default Transaction Manager)\n INFO - Creating SecurityService(id=Default Security Service)\n INFO - Creating Resource(id=movieDatabase)\n INFO - Beginning load: /home/boto/dev/ws/openejb_trunk/openejb/examples/testing-transactions-bmt/target/classes\n INFO - Configuring enterprise application: /home/boto/dev/ws/openejb_trunk/openejb/examples/testing-transactions-bmt\n WARNING - Method 'lookup' is not available for 'javax.annotation.Resource'. Probably using an older Runtime.\n INFO - Auto-deploying ejb Movies: EjbDeployment(deployment-id=Movies)\n INFO - Configuring Service(id=Default Stateful Container, type=Container, provider-id=Default Stateful Container)\n INFO - Auto-creating a container for bean Movies: Container(type=STATEFUL, id=Default Stateful Container)\n INFO - Creating Container(id=Default Stateful Container)\n INFO - Using directory /tmp for stateful session passivation\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.injection.tx.MoviesTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Creating Container(id=Default Managed Container)\n INFO - Using directory /tmp for stateful session passivation\n INFO - Configuring PersistenceUnit(name=movie-unit)\n INFO - Auto-creating a Resource with id 'movieDatabaseNonJta' of type 'DataSource for 'movie-unit'.\n INFO - Configuring Service(id=movieDatabaseNonJta, type=Resource, provider-id=movieDatabase)\n INFO - Creating Resource(id=movieDatabaseNonJta)\n INFO - Adjusting PersistenceUnit movie-unit <non-jta-data-source> to Resource ID 'movieDatabaseNonJta' from 'movieDatabaseUnmanaged'\n INFO - Enterprise application \"/home/boto/dev/ws/openejb_trunk/openejb/examples/testing-transactions-bmt\" loaded.\n INFO - Assembling app: /home/boto/dev/ws/openejb_trunk/openejb/examples/testing-transactions-bmt\n SEVERE - JAVA AGENT NOT INSTALLED. The JPA Persistence Provider requested installation of a ClassFileTransformer which requires a JavaAgent. See http://tomee.apache.org/3.0/javaagent.html\n INFO - PersistenceUnit(name=movie-unit, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 399ms\n INFO - Jndi(name=\"java:global/testing-transactions-bmt/Movies!org.superbiz.injection.tx.Movies\")\n INFO - Jndi(name=\"java:global/testing-transactions-bmt/Movies\")\n INFO - Existing thread singleton service in SystemInstance() org.apache.openejb.cdi.ThreadSingletonServiceImpl@3f3f210f\n INFO - OpenWebBeans Container is starting...\n INFO - Adding OpenWebBeansPlugin : [CdiPlugin]\n INFO - All injection points are validated successfully.\n INFO - OpenWebBeans Container has started, it took 157 ms.\n INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Deployed Application(path=/home/boto/dev/ws/openejb_trunk/openejb/examples/testing-transactions-bmt)\n INFO - Started user transaction org.apache.geronimo.transaction.manager.TransactionImpl@709a1411\n 21-Jul-2012 4:39:32 PM null openjpa.Runtime\n INFO: Starting OpenJPA 2.2.0\n 21-Jul-2012 4:39:32 PM null openjpa.jdbc.JDBC\n INFO: Using dictionary class \"org.apache.openjpa.jdbc.sql.HSQLDictionary\" (HSQL Database Engine 2.2.8 ,HSQL Database Engine Driver 2.2.8).\n 21-Jul-2012 4:39:33 PM null openjpa.Enhance\n INFO: Creating subclass and redefining methods for \"[class org.superbiz.injection.tx.Movie]\". This means that your application will be less efficient than it would if you ran the OpenJPA enhancer.\n INFO - Committing user transaction org.apache.geronimo.transaction.manager.TransactionImpl@709a1411\n INFO - Started user transaction org.apache.geronimo.transaction.manager.TransactionImpl@2bb64b70\n INFO - Committing user transaction org.apache.geronimo.transaction.manager.TransactionImpl@2bb64b70\n INFO - Started user transaction org.apache.geronimo.transaction.manager.TransactionImpl@627b5c\n INFO - Committing user transaction org.apache.geronimo.transaction.manager.TransactionImpl@627b5c\n INFO - Started user transaction org.apache.geronimo.transaction.manager.TransactionImpl@2f031310\n INFO - Committing user transaction org.apache.geronimo.transaction.manager.TransactionImpl@2f031310\n INFO - Started user transaction org.apache.geronimo.transaction.manager.TransactionImpl@4df2a9da\n INFO - Committing user transaction org.apache.geronimo.transaction.manager.TransactionImpl@4df2a9da\n INFO - Started user transaction org.apache.geronimo.transaction.manager.TransactionImpl@3fa9b4a4\n INFO - Rolling back user transaction org.apache.geronimo.transaction.manager.TransactionImpl@3fa9b4a4\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 7.471 sec\n\n Results :\n\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n",
"url":"https://github.com/apache/tomee/tree/master/examples/testing-transactions-bmt"
}
],
"bval":[
{
"name":"bval-evaluation-redeployment",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/bval-evaluation-redeployment"
}
],
"callbacks":[
{
"name":"simple-stateful-callbacks",
"readme":"Title: Simple Stateful with callback methods\n\nThis example shows how to create a stateful session bean that uses the @PrePassivate, @PostActivate, @PostConstruct, @PreDestroy and @AroundInvoke annotations.\n\n## CallbackCounter\n\n package org.superbiz.counter;\n\n import javax.annotation.PostConstruct;\n import javax.annotation.PreDestroy;\n import javax.ejb.PostActivate;\n import javax.ejb.PrePassivate;\n import javax.ejb.Stateful;\n import javax.ejb.StatefulTimeout;\n import javax.interceptor.AroundInvoke;\n import javax.interceptor.InvocationContext;\n import java.io.Serializable;\n import java.util.concurrent.TimeUnit;\n\n @Stateful\n @StatefulTimeout(value = 1, unit = TimeUnit.SECONDS)\n public class CallbackCounter implements Serializable {\n\n private int count = 0;\n\n @PrePassivate\n public void prePassivate() {\n ExecutionChannel.getInstance().notifyObservers(\"prePassivate\");\n }\n\n @PostActivate\n public void postActivate() {\n ExecutionChannel.getInstance().notifyObservers(\"postActivate\");\n }\n\n @PostConstruct\n public void postConstruct() {\n ExecutionChannel.getInstance().notifyObservers(\"postConstruct\");\n }\n\n @PreDestroy\n public void preDestroy() {\n ExecutionChannel.getInstance().notifyObservers(\"preDestroy\");\n }\n\n @AroundInvoke\n public Object intercept(InvocationContext ctx) throws Exception {\n ExecutionChannel.getInstance().notifyObservers(ctx.getMethod().getName());\n return ctx.proceed();\n }\n\n public int count() {\n return count;\n }\n\n public int increment() {\n return ++count;\n }\n\n public int reset() {\n return (count = 0);\n }\n }\n\n## ExecutionChannel\n\n package org.superbiz.counter;\n\n import java.util.ArrayList;\n import java.util.List;\n\n public class ExecutionChannel {\n private static final ExecutionChannel INSTANCE = new ExecutionChannel();\n\n private final List<ExecutionObserver> observers = new ArrayList<ExecutionObserver>();\n\n public static ExecutionChannel getInstance() {\n return INSTANCE;\n }\n\n public void addObserver(ExecutionObserver observer) {\n this.observers.add(observer);\n }\n\n public void notifyObservers(Object value) {\n for (ExecutionObserver observer : this.observers) {\n observer.onExecution(value);\n }\n }\n }\n\n## ExecutionObserver\n\n package org.superbiz.counter;\n\n public interface ExecutionObserver {\n\n void onExecution(Object value);\n\n }\n\n## CounterCallbacksTest\n\n package org.superbiz.counter;\n\n import junit.framework.Assert;\n import org.junit.Test;\n\n import javax.ejb.embeddable.EJBContainer;\n import javax.naming.Context;\n import javax.naming.InitialContext;\n import javax.naming.NamingException;\n import java.util.*;\n\n public class CounterCallbacksTest implements ExecutionObserver {\n private static List<Object> received = new ArrayList<Object>();\n\n public Context getContext() throws NamingException {\n final Properties p = new Properties();\n p.put(Context.INITIAL_CONTEXT_FACTORY, \"org.apache.openejb.core.LocalInitialContextFactory\");\n return new InitialContext(p);\n\n }\n\n @Test\n public void test() throws Exception {\n final Map<String, Object> p = new HashMap<String, Object>();\n p.put(\"MySTATEFUL\", \"new://Container?type=STATEFUL\");\n p.put(\"MySTATEFUL.Capacity\", \"2\"); //How many instances of Stateful beans can our server hold in memory?\n p.put(\"MySTATEFUL.Frequency\", \"1\"); //Interval in seconds between checks\n p.put(\"MySTATEFUL.BulkPassivate\", \"0\"); //No bulkPassivate - just passivate entities whenever it is needed\n final EJBContainer container = EJBContainer.createEJBContainer(p);\n\n //this is going to track the execution\n ExecutionChannel.getInstance().addObserver(this);\n\n {\n final Context context = getContext();\n\n CallbackCounter counterA = (CallbackCounter) context.lookup(\"java:global/simple-stateful-callbacks/CallbackCounter\");\n Assert.assertNotNull(counterA);\n Assert.assertEquals(\"postConstruct\", received.remove(0));\n\n Assert.assertEquals(0, counterA.count());\n Assert.assertEquals(\"count\", received.remove(0));\n\n Assert.assertEquals(1, counterA.increment());\n Assert.assertEquals(\"increment\", received.remove(0));\n\n Assert.assertEquals(0, counterA.reset());\n Assert.assertEquals(\"reset\", received.remove(0));\n\n Assert.assertEquals(1, counterA.increment());\n Assert.assertEquals(\"increment\", received.remove(0));\n\n System.out.println(\"Waiting 2 seconds...\");\n Thread.sleep(2000);\n\n Assert.assertEquals(\"preDestroy\", received.remove(0));\n\n try {\n counterA.increment();\n Assert.fail(\"The ejb is not supposed to be there.\");\n } catch (javax.ejb.NoSuchEJBException e) {\n //excepted\n }\n\n context.close();\n }\n\n {\n final Context context = getContext();\n\n CallbackCounter counterA = (CallbackCounter) context.lookup(\"java:global/simple-stateful-callbacks/CallbackCounter\");\n Assert.assertEquals(\"postConstruct\", received.remove(0));\n\n Assert.assertEquals(1, counterA.increment());\n Assert.assertEquals(\"increment\", received.remove(0));\n\n ((CallbackCounter) context.lookup(\"java:global/simple-stateful-callbacks/CallbackCounter\")).count();\n Assert.assertEquals(\"postConstruct\", received.remove(0));\n Assert.assertEquals(\"count\", received.remove(0));\n\n ((CallbackCounter) context.lookup(\"java:global/simple-stateful-callbacks/CallbackCounter\")).count();\n Assert.assertEquals(\"postConstruct\", received.remove(0));\n Assert.assertEquals(\"count\", received.remove(0));\n\n System.out.println(\"Waiting 2 seconds...\");\n Thread.sleep(2000);\n Assert.assertEquals(\"prePassivate\", received.remove(0));\n\n context.close();\n }\n container.close();\n\n Assert.assertEquals(\"preDestroy\", received.remove(0));\n Assert.assertEquals(\"preDestroy\", received.remove(0));\n\n Assert.assertTrue(received.toString(), received.isEmpty());\n }\n\n @Override\n public void onExecution(Object value) {\n System.out.println(\"Test step -> \" + value);\n received.add(value);\n }\n }\n\n# Running\n\n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.counter.CounterCallbacksTest\n INFO - ********************************************************************************\n INFO - OpenEJB http://tomee.apache.org/\n INFO - Startup: Sat Jul 21 08:18:28 EDT 2012\n INFO - Copyright 1999-2012 (C) Apache OpenEJB Project, All Rights Reserved.\n INFO - Version: 4.1.0\n INFO - Build date: 20120721\n INFO - Build time: 04:06\n INFO - ********************************************************************************\n INFO - openejb.home = /home/boto/dev/ws/openejb_trunk/openejb/examples/simple-stateful-callbacks\n INFO - openejb.base = /home/boto/dev/ws/openejb_trunk/openejb/examples/simple-stateful-callbacks\n INFO - Created new singletonService org.apache.openejb.cdi.ThreadSingletonServiceImpl@527736bd\n INFO - Succeeded in installing singleton service\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Cannot find the configuration file [conf/openejb.xml]. Will attempt to create one for the beans deployed.\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=MySTATEFUL, type=Container, provider-id=Default Stateful Container)\n INFO - Creating TransactionManager(id=Default Transaction Manager)\n INFO - Creating SecurityService(id=Default Security Service)\n INFO - Creating Container(id=MySTATEFUL)\n INFO - Using directory /tmp for stateful session passivation\n INFO - Beginning load: /home/boto/dev/ws/openejb_trunk/openejb/examples/simple-stateful-callbacks/target/classes\n INFO - Configuring enterprise application: /home/boto/dev/ws/openejb_trunk/openejb/examples/simple-stateful-callbacks\n INFO - Auto-deploying ejb CallbackCounter: EjbDeployment(deployment-id=CallbackCounter)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.counter.CounterCallbacksTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Creating Container(id=Default Managed Container)\n INFO - Using directory /tmp for stateful session passivation\n INFO - Enterprise application \"/home/boto/dev/ws/openejb_trunk/openejb/examples/simple-stateful-callbacks\" loaded.\n INFO - Assembling app: /home/boto/dev/ws/openejb_trunk/openejb/examples/simple-stateful-callbacks\n INFO - Jndi(name=\"java:global/simple-stateful-callbacks/CallbackCounter!org.superbiz.counter.CallbackCounter\")\n INFO - Jndi(name=\"java:global/simple-stateful-callbacks/CallbackCounter\")\n INFO - Existing thread singleton service in SystemInstance() org.apache.openejb.cdi.ThreadSingletonServiceImpl@527736bd\n INFO - OpenWebBeans Container is starting...\n INFO - Adding OpenWebBeansPlugin : [CdiPlugin]\n INFO - All injection points are validated successfully.\n INFO - OpenWebBeans Container has started, it took 225 ms.\n INFO - Created Ejb(deployment-id=CallbackCounter, ejb-name=CallbackCounter, container=MySTATEFUL)\n INFO - Started Ejb(deployment-id=CallbackCounter, ejb-name=CallbackCounter, container=MySTATEFUL)\n INFO - Deployed Application(path=/home/boto/dev/ws/openejb_trunk/openejb/examples/simple-stateful-callbacks)\n Test step -> postConstruct\n Test step -> count\n Test step -> increment\n Test step -> reset\n Test step -> increment\n Waiting 2 seconds...\n Test step -> preDestroy\n INFO - Removing the timed-out stateful session bean instance 583c10bfdbd326ba:57f94a9b:138a9798adf:-8000\n INFO - Activation failed: file not found /tmp/583c10bfdbd326ba=57f94a9b=138a9798adf=-8000\n Test step -> postConstruct\n Test step -> increment\n Test step -> postConstruct\n Test step -> count\n Test step -> postConstruct\n Test step -> count\n Waiting 2 seconds...\n Test step -> prePassivate\n INFO - Passivating to file /tmp/583c10bfdbd326ba=57f94a9b=138a9798adf=-7fff\n Test step -> preDestroy\n INFO - Removing the timed-out stateful session bean instance 583c10bfdbd326ba:57f94a9b:138a9798adf:-7ffe\n Test step -> preDestroy\n INFO - Removing the timed-out stateful session bean instance 583c10bfdbd326ba:57f94a9b:138a9798adf:-7ffd\n INFO - Undeploying app: /home/boto/dev/ws/openejb_trunk/openejb/examples/simple-stateful-callbacks\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 7.487 sec\n\n Results :\n\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n\n [INFO] ------------------------------------------------------------------------\n [INFO] BUILD SUCCESS\n [INFO] ------------------------------------------------------------------------\n [INFO] Total time: 15.803s\n [INFO] Finished at: Sat Jul 21 08:18:35 EDT 2012\n [INFO] Final Memory: 11M/247M\n [INFO] ------------------------------------------------------------------------\n\n\n",
"url":"https://github.com/apache/tomee/tree/master/examples/simple-stateful-callbacks"
},
{
"name":"simple-stateless-callbacks",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/simple-stateless-callbacks"
}
],
"cdi":[
{
"name":"applicationcomposer-jaxws-cdi",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/applicationcomposer-jaxws-cdi"
},
{
"name":"cdi-basic",
"readme":"Title: CDI @Inject\n\nTo use `@Inject`, the first thing you need is a `META-INF/beans.xml` file in the module\nor jar. This effectively turns on CDI and allows the `@Inject` references to work.\nNo `META-INF/beans.xml` no injection, period. This may seem overly strict,\nbut it is not without reason. The CDI API is a bit greedy and does consume a fair\nabout of resources by design.\n\nWhen the container constructs a bean with an `@Inject` reference,\nit will first find or create the object that will be injected. For the sake of\nsimplicity, the is example has a basic `Faculty` pojo with a no-arg constructor. Anyone\nreferencing `@Inject Faculty` will get their own instance of `Faculty`. If the desire\nis to share the same instance of `Faculty`, see the concept of `scopes` -- this is\nexactly what scopes are for.\n\n# Example\n\nIn this example we have an `@Stateless` bean `Course` with an `@Inject` reference to an\nobject of type `Faculty`. When `Course` is created, the container will also create an\ninstance of `Faculty`. The `@PostConstruct` will be called on the `Faculty`,\nthen the `Faculty` instance will be injected into the `Course` bean. Finally, the\n`@PostConstruct` will be invoked on `Course` and then we're done. All instances will\nhave been created.\n\nThe `CourseTest` test case drives this creation process by having `Course` injected\ninto it in its `@Setup` method. By the time our `@Test` method is invoked,\nall the real work should be done and we should be ready to go. In the test case we do\nsome basic asserts to ensure everything was constructed, all `@PostConstruct` methods\ncalled and everyting injected.\n\n## Faculty <small>a basic injectable pojo</small>\n\n public class Faculty {\n\n private List<String> facultyMembers;\n\n private String facultyName;\n\n @PostConstruct\n public void initialize() {\n this.facultyMembers = new ArrayList<String>();\n facultyMembers.add(\"Ian Schultz\");\n facultyMembers.add(\"Diane Reyes\");\n facultyName = \"Computer Science\";\n }\n\n public List<String> getFacultyMembers() {\n return facultyMembers;\n }\n\n public String getFacultyName() {\n return facultyName;\n }\n\n }\n\n## Course <small>a simple session bean</small>\n\n @Stateless\n public class Course {\n\n @Inject\n private Faculty faculty;\n\n private String courseName;\n\n private int capacity;\n\n @PostConstruct\n private void init() {\n assert faculty != null;\n\n // These strings can be externalized\n // We'll see how to do that later\n this.courseName = \"CDI 101 - Introduction to CDI\";\n this.capacity = 100;\n }\n\n public String getCourseName() {\n return courseName;\n }\n\n public int getCapacity() {\n return capacity;\n }\n\n public Faculty getFaculty() {\n return faculty;\n }\n }\n\n# Test Case\n\n public class CourseTest extends TestCase {\n\n @EJB\n private Course course;\n\n @Before\n public void setUp() throws Exception {\n EJBContainer.createEJBContainer().getContext().bind(\"inject\", this);\n }\n\n @Test\n public void test() {\n\n // Was the EJB injected?\n assertTrue(course != null);\n\n // Was the Course @PostConstruct called?\n assertNotNull(course.getCourseName());\n assertTrue(course.getCapacity() > 0);\n\n // Was a Faculty instance injected into Course?\n final Faculty faculty = course.getFaculty();\n assertTrue(faculty != null);\n\n // Was the @PostConstruct called on Faculty?\n assertEquals(faculty.getFacultyName(), \"Computer Science\");\n assertEquals(faculty.getFacultyMembers().size(), 2);\n }\n }\n\n# Running\n\n\n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.cdi.basic.CourseTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/cdi-basic\n INFO - openejb.base = /Users/dblevins/examples/cdi-basic\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/cdi-basic/target/classes\n INFO - Beginning load: /Users/dblevins/examples/cdi-basic/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/cdi-basic\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean cdi-basic.Comp: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean Course: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Enterprise application \"/Users/dblevins/examples/cdi-basic\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/cdi-basic\n INFO - Jndi(name=\"java:global/cdi-basic/cdi-basic.Comp!org.apache.openejb.BeanContext$Comp\")\n INFO - Jndi(name=\"java:global/cdi-basic/cdi-basic.Comp\")\n INFO - Jndi(name=\"java:global/cdi-basic/Course!org.superbiz.cdi.basic.Course\")\n INFO - Jndi(name=\"java:global/cdi-basic/Course\")\n INFO - Jndi(name=\"java:global/EjbModule1833350875/org.superbiz.cdi.basic.CourseTest!org.superbiz.cdi.basic.CourseTest\")\n INFO - Jndi(name=\"java:global/EjbModule1833350875/org.superbiz.cdi.basic.CourseTest\")\n INFO - Created Ejb(deployment-id=Course, ejb-name=Course, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=cdi-basic.Comp, ejb-name=cdi-basic.Comp, container=Default Managed Container)\n INFO - Created Ejb(deployment-id=org.superbiz.cdi.basic.CourseTest, ejb-name=org.superbiz.cdi.basic.CourseTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=Course, ejb-name=Course, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=cdi-basic.Comp, ejb-name=cdi-basic.Comp, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=org.superbiz.cdi.basic.CourseTest, ejb-name=org.superbiz.cdi.basic.CourseTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/cdi-basic)\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.126 sec\n\n Results :\n\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n",
"url":"https://github.com/apache/tomee/tree/master/examples/cdi-basic"
},
{
"name":"simple-mdb-and-cdi",
"readme":"Title: Simple MDB and CDI\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## ChatBean\n\n package org.superbiz.mdb;\n \n import javax.annotation.Resource;\n import javax.ejb.MessageDriven;\n import javax.inject.Inject;\n import javax.jms.Connection;\n import javax.jms.ConnectionFactory;\n import javax.jms.DeliveryMode;\n import javax.jms.JMSException;\n import javax.jms.Message;\n import javax.jms.MessageListener;\n import javax.jms.MessageProducer;\n import javax.jms.Queue;\n import javax.jms.Session;\n import javax.jms.TextMessage;\n \n @MessageDriven\n public class ChatBean implements MessageListener {\n \n @Resource\n private ConnectionFactory connectionFactory;\n \n @Resource(name = \"AnswerQueue\")\n private Queue answerQueue;\n \n @Inject\n private ChatRespondCreator responder;\n \n public void onMessage(Message message) {\n try {\n \n final TextMessage textMessage = (TextMessage) message;\n final String question = textMessage.getText();\n final String response = responder.respond(question);\n \n if (response != null) {\n respond(response);\n }\n } catch (JMSException e) {\n throw new IllegalStateException(e);\n }\n }\n \n private void respond(String text) throws JMSException {\n \n Connection connection = null;\n Session session = null;\n \n try {\n connection = connectionFactory.createConnection();\n connection.start();\n \n // Create a Session\n session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);\n \n // Create a MessageProducer from the Session to the Topic or Queue\n MessageProducer producer = session.createProducer(answerQueue);\n producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);\n \n // Create a message\n TextMessage message = session.createTextMessage(text);\n \n // Tell the producer to send the message\n producer.send(message);\n } finally {\n // Clean up\n if (session != null) session.close();\n if (connection != null) connection.close();\n }\n }\n }\n\n## ChatRespondCreator\n\n package org.superbiz.mdb;\n \n public class ChatRespondCreator {\n public String respond(String question) {\n if (\"Hello World!\".equals(question)) {\n return \"Hello, Test Case!\";\n } else if (\"How are you?\".equals(question)) {\n return \"I'm doing well.\";\n } else if (\"Still spinning?\".equals(question)) {\n return \"Once every day, as usual.\";\n }\n return null;\n }\n }\n\n## beans.xml\n\n <!--\n \n Licensed to the Apache Software Foundation (ASF) under one or more\n contributor license agreements. See the NOTICE file distributed with\n this work for additional information regarding copyright ownership.\n The ASF licenses this file to You under the Apache License, Version 2.0\n (the \"License\"); you may not use this file except in compliance with\n the License. You may obtain a copy of the License at\n \n http://www.apache.org/licenses/LICENSE-2.0\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n -->\n \n <beans/>\n \n\n## ChatBeanTest\n\n package org.superbiz.mdb;\n \n import junit.framework.TestCase;\n \n import javax.annotation.Resource;\n import javax.ejb.embeddable.EJBContainer;\n import javax.jms.Connection;\n import javax.jms.ConnectionFactory;\n import javax.jms.JMSException;\n import javax.jms.MessageConsumer;\n import javax.jms.MessageProducer;\n import javax.jms.Queue;\n import javax.jms.Session;\n import javax.jms.TextMessage;\n \n public class ChatBeanTest extends TestCase {\n \n @Resource\n private ConnectionFactory connectionFactory;\n \n @Resource(name = \"ChatBean\")\n private Queue questionQueue;\n \n @Resource(name = \"AnswerQueue\")\n private Queue answerQueue;\n \n public void test() throws Exception {\n EJBContainer.createEJBContainer().getContext().bind(\"inject\", this);\n \n \n final Connection connection = connectionFactory.createConnection();\n \n connection.start();\n \n final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);\n \n final MessageProducer questions = session.createProducer(questionQueue);\n \n final MessageConsumer answers = session.createConsumer(answerQueue);\n \n \n sendText(\"Hello World!\", questions, session);\n \n assertEquals(\"Hello, Test Case!\", receiveText(answers));\n \n \n sendText(\"How are you?\", questions, session);\n \n assertEquals(\"I'm doing well.\", receiveText(answers));\n \n \n sendText(\"Still spinning?\", questions, session);\n \n assertEquals(\"Once every day, as usual.\", receiveText(answers));\n }\n \n private void sendText(String text, MessageProducer questions, Session session) throws JMSException {\n \n questions.send(session.createTextMessage(text));\n }\n \n private String receiveText(MessageConsumer answers) throws JMSException {\n \n return ((TextMessage) answers.receive(1000)).getText();\n }\n }\n",
"url":"https://github.com/apache/tomee/tree/master/examples/simple-mdb-and-cdi"
},
{
"name":"jsf-cdi-and-ejb",
"readme":"Title: JSF-CDI-EJB\n\nThe simple application contains a CDI managed bean `CalculatorBean`, which uses the `Calculator` EJB to add two numbers\nand display the results to the user. The EJB is injected in the managed bean using @Inject annotation.\n\nYou could run this in the latest Apache TomEE [snapshot](https://repository.apache.org/content/repositories/snapshots/org/apache/openejb/apache-tomee/)\n\nThe complete source code is below but lets break down to look at some smaller snippets and see how it works.\n\n\nA little note on the setup:\n\nAs for the libraries, myfaces-api and myfaces-impl are provided in tomee/lib and hence they should not be a part of the\nwar. In maven terms, they would be with scope 'provided'\n\nAlso note that we use servlet 2.5 declaration in web.xml\n<web-app xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns=\"http://java.sun.com/xml/ns/javaee\"\n xmlns:web=\"http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee\n http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n version=\"2.5\">\n\nAnd we use 2.0 version of faces-config\n\n <faces-config xmlns=\"http://java.sun.com/xml/ns/javaee\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee\n http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd\"\n version=\"2.0\">\n\nTo make this a cdi-aware-archive (i.e bean archive) an empty beans.xml is added in WEB-INF\n\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n <beans xmlns=\"http://java.sun.com/xml/ns/javaee\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee\n http://java.sun.com/xml/ns/javaee/beans_1_0.xsd\">\n </beans>\n\nWe'll first declare the FacesServlet in the web.xml\n\n <servlet>\n <servlet-name>Faces Servlet</servlet-name>\n <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>\n <load-on-startup>1</load-on-startup>\n </servlet>\n\nFacesServlet acts as the master controller.\n\nWe'll then create the calculator.xhtml file.\n\n <h:outputText value='Enter first number'/>\n <h:inputText value='#{calculatorBean.x}'/>\n <h:outputText value='Enter second number'/>\n <h:inputText value='#{calculatorBean.y}'/>\n <h:commandButton action=\"#{calculatorBean.add}\" value=\"Add\"/>\n\nNotice how we've used the bean here. By default, the bean name would be the simple name of the bean\nclass with the first letter in lower case.\n\nWe've annotated the `CalculatorBean` with `@RequestScoped`.\nSo when a request comes in, the bean is instantiated and placed in the request scope.\n\n<h:inputText value='#{calculatorBean.x}'/>\n\nHere, getX() method of calculatorBean is invoked and the resulting value is displayed.\nx being a Double, we rightly should see 0.0 displayed.\n\nWhen you change the value and submit the form, these entered values are bound using the setters\nin the bean and then the commandButton-action method is invoked.\n\nIn this case, CalculatorBean#add() is invoked.\n\nCalculator#add() delegates the work to the ejb, gets the result, stores it\nand then returns what view is to be rendered.\n\nThe return value \"success\" is checked up in faces-config navigation-rules\nand the respective page is rendered.\n\nIn our case, 'result.xhtml' page is rendered where\nuse EL and display the result from the request-scoped `calculatorBean`.\n\n#Source Code\n\n## CalculatorBean\n\n import javax.enterprise.context.RequestScoped;\n import javax.inject.Named;\n import javax.inject.Inject;\n\n @RequestScoped\n @Named\n public class CalculatorBean {\n @Inject\n Calculator calculator;\n private double x;\n private double y;\n private double result;\n \n public double getX() {\n return x;\n }\n \n public void setX(double x) {\n this.x = x;\n }\n \n public double getY() {\n return y;\n }\n \n public void setY(double y) {\n this.y = y;\n }\n \n public double getResult() {\n return result;\n }\n \n public void setResult(double result) {\n this.result = result;\n }\n \n public String add() {\n result = calculator.add(x, y);\n return \"success\";\n }\n }\n\n## Calculator\n\n package org.superbiz.jsf;\n \n import javax.ejb.Stateless;\n \n @Stateless\n public class Calculator{\n \n public double add(double x, double y) {\n return x + y;\n }\n }\n\n\n#web.xml\n\n<?xml version=\"1.0\"?>\n\n<web-app xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns=\"http://java.sun.com/xml/ns/javaee\"\n xmlns:web=\"http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee\n http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n version=\"2.5\">\n\n <description>MyProject web.xml</description>\n\n <!-- Faces Servlet -->\n <servlet>\n <servlet-name>Faces Servlet</servlet-name>\n <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>\n <load-on-startup>1</load-on-startup>\n </servlet>\n\n <!-- Faces Servlet Mapping -->\n <servlet-mapping>\n <servlet-name>Faces Servlet</servlet-name>\n <url-pattern>*.jsf</url-pattern>\n </servlet-mapping>\n\n <!-- Welcome files -->\n <welcome-file-list>\n <welcome-file>index.jsp</welcome-file>\n <welcome-file>index.html</welcome-file>\n </welcome-file-list>\n\n</web-app>\n\n\n#Calculator.xhtml\n\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\"\n xmlns:f=\"http://java.sun.com/jsf/core\"\n xmlns:h=\"http://java.sun.com/jsf/html\">\n\n\n<h:body bgcolor=\"white\">\n <f:view>\n <h:form>\n <h:panelGrid columns=\"2\">\n <h:outputText value='Enter first number'/>\n <h:inputText value='#{calculatorBean.x}'/>\n <h:outputText value='Enter second number'/>\n <h:inputText value='#{calculatorBean.y}'/>\n <h:commandButton action=\"#{calculatorBean.add}\" value=\"Add\"/>\n </h:panelGrid>\n </h:form>\n </f:view>\n</h:body>\n</html>\n\n\n #Result.xhtml\n\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\"\n xmlns:f=\"http://java.sun.com/jsf/core\"\n xmlns:h=\"http://java.sun.com/jsf/html\">\n\n<h:body>\n<f:view>\n <h:form id=\"mainForm\">\n <h2><h:outputText value=\"Result of adding #{calculatorBean.x} and #{calculatorBean.y} is #{calculatorBean.result }\"/></h2>\n <h:commandLink action=\"back\">\n <h:outputText value=\"Home\"/>\n </h:commandLink>\n </h:form>\n</f:view>\n</h:body>\n</html>\n\n #faces-config.xml\n\n <?xml version=\"1.0\"?>\n <faces-config xmlns=\"http://java.sun.com/xml/ns/javaee\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee\n http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd\"\n version=\"2.0\">\n\n <navigation-rule>\n <from-view-id>/calculator.xhtml</from-view-id>\n <navigation-case>\n <from-outcome>success</from-outcome>\n <to-view-id>/result.xhtml</to-view-id>\n </navigation-case>\n </navigation-rule>\n\n <navigation-rule>\n <from-view-id>/result.xhtml</from-view-id>\n <navigation-case>\n <from-outcome>back</from-outcome>\n <to-view-id>/calculator.xhtml</to-view-id>\n </navigation-case>\n </navigation-rule>\n </faces-config>",
"url":"https://github.com/apache/tomee/tree/master/examples/jsf-cdi-and-ejb"
},
{
"name":"groovy-cdi",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/groovy-cdi"
},
{
"name":"cdi-ejbcontext-jaas",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/cdi-ejbcontext-jaas"
},
{
"name":"cdi-produces-disposes",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/cdi-produces-disposes"
},
{
"name":"cdi-interceptors",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/cdi-interceptors"
},
{
"name":"cdi-application-scope",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/cdi-application-scope"
},
{
"name":"cdi-request-scope",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/cdi-request-scope"
},
{
"name":"cdi-alternative-and-stereotypes",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/cdi-alternative-and-stereotypes"
},
{
"name":"cdi-produces-field",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/cdi-produces-field"
},
{
"name":"simple-cdi-interceptor",
"readme":"#Simple CDI Interceptor\n\nLet's write a simple application that would allow us to book tickets for a movie show. As with all applications, logging is one cross-cutting concern that we have. \n\n(Relevant snippets are inlined but you can check out the complete code, from the links provided)\n\nHow do we mark which methods are to be intercepted ? Wouldn't it be handy to annotate a method like \n\n @Log\n public void aMethod(){...} \n\nLet's create an annotation that would \"mark\" a method for interception. \n\n @InterceptorBinding\n @Target({ TYPE, METHOD })\n @Retention(RUNTIME)\n public @interface Log {\n }\n\nSure, you haven't missed the @InterceptorBinding annotation above ! Now that our custom annotation is created, lets attach it (or to use a better term for it, \"bind it\" )\nto an interceptor. \n\nSo here's our logging interceptor. An @AroundInvoke method and we are almost done.\n\n @Interceptor\n @Log //binding the interceptor here. now any method annotated with @Log would be intercepted by logMethodEntry\n public class LoggingInterceptor {\n @AroundInvoke\n public Object logMethodEntry(InvocationContext ctx) throws Exception {\n System.out.println(\"Entering method: \" + ctx.getMethod().getName());\n //or logger.info statement \n return ctx.proceed();\n }\n }\n\nNow the @Log annotation we created is bound to this interceptor.\n\nThat done, let's annotate at class-level or method-level and have fun intercepting ! \n\n @Log\n @Stateful\n public class BookShow implements Serializable {\n private static final long serialVersionUID = 6350400892234496909L;\n public List<String> getMoviesList() {\n List<String> moviesAvailable = new ArrayList<String>();\n moviesAvailable.add(\"12 Angry Men\");\n moviesAvailable.add(\"Kings speech\");\n return moviesAvailable;\n }\n public Integer getDiscountedPrice(int ticketPrice) {\n return ticketPrice - 50;\n }\n // assume more methods are present\n }\n\nThe `@Log` annotation applied at class level denotes that all the methods should be intercepted with `LoggingInterceptor`.\n\nBefore we say \"all done\" there's one last thing we are left with ! To enable the interceptors ! \n\nLets quickly put up a [beans.xml file]\n\n <beans>\n <interceptors>\n <class>org.superbiz.cdi.bookshow.interceptors.LoggingInterceptor\n </class>\n </interceptors>\n </beans>\n\n in META-INF\n\n\nThose lines in beans.xml not only \"enable\" the interceptors, but also define the \"order of execution\" of the interceptors.\nBut we'll see that in another example on multiple-cdi-interceptors.\n\nFire up the test, and we should see a 'Entering method: getMoviesList' printed in the console.\n\n#Tests\n Apache OpenEJB 4.0.0-beta-2 build: 20111103-01:00\n http://tomee.apache.org/\n INFO - openejb.home = /media/fthree/Workspace/open4/openejb/examples/cdi-simple-interceptors\n INFO - openejb.base = /media/fthree/Workspace/open4/openejb/examples/cdi-simple-interceptors\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true' \n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /media/fthree/Workspace/open4/openejb/examples/cdi-simple-interceptors/target/classes\n INFO - Beginning load: /media/fthree/Workspace/open4/openejb/examples/cdi-simple-interceptors/target/classes\n INFO - Configuring enterprise application: /media/fthree/Workspace/open4/openejb/examples/cdi-simple-interceptors\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean cdi-simple-interceptors.Comp: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring Service(id=Default Stateful Container, type=Container, provider-id=Default Stateful Container)\n INFO - Auto-creating a container for bean BookShow: Container(type=STATEFUL, id=Default Stateful Container)\n INFO - Enterprise application \"/media/fthree/Workspace/open4/openejb/examples/cdi-simple-interceptors\" loaded.\n INFO - Assembling app: /media/fthree/Workspace/open4/openejb/examples/cdi-simple-interceptors\n INFO - Jndi(name=\"java:global/cdi-simple-interceptors/BookShow!org.superbiz.cdi.bookshow.beans.BookShow\")\n INFO - Jndi(name=\"java:global/cdi-simple-interceptors/BookShow\")\n INFO - Created Ejb(deployment-id=BookShow, ejb-name=BookShow, container=Default Stateful Container)\n INFO - Started Ejb(deployment-id=BookShow, ejb-name=BookShow, container=Default Stateful Container)\n INFO - Deployed Application(path=/media/fthree/Workspace/open4/openejb/examples/cdi-simple-interceptors)\n Entering method: getMoviesList\n",
"url":"https://github.com/apache/tomee/tree/master/examples/simple-cdi-interceptor"
},
{
"name":"cdi-events",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/cdi-events"
},
{
"name":"cdi-realm",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/cdi-realm"
},
{
"name":"rest-cdi",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/rest-cdi"
},
{
"name":"cdi-session-scope",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/cdi-session-scope"
}
],
"ciphered":[
{
"name":"datasource-ciphered-password",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/datasource-ciphered-password"
}
],
"client":[
{
"name":"client-resource-lookup-preview",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/client-resource-lookup-preview"
}
],
"cmp2":[
{
"name":"simple-cmp2",
"readme":"Title: EJB 2.1 CMP EntityBeans (CMP2)\n\n\n\nOpenEJB, the EJB Container for TomEE and Geronimo, does support all of EJB 1.1 to 3.1, including CMP2.\n\nThe CMP2 implementation is actually done by adapting the CMP2 bean into a JPA Entity dynamically at deploy time.\n\nAppropriate subclasses, a JPA persistence.xml file and a mapping.xml file are generated at deployment\ntime for the CMP2 EntityBeans and all the Entities will be then run on OpenJPA. This innovative code\nhas been used as the sole CMP2 implementation in Geronimo for its J2EE 1.4, JavaEE 5 and JavaEE 6 certifications.\n\nThe persistence.xml and mapping.xml files generated at deploy time can be saved to disk and included\nin the application, allowing you to:\n\n - gain finer control over persistence options\n - slowly convert individual entities from CMP2 to JPA\n\nLet's see an example.\n\n# Movies application\n\nThe following is a basic EJB 2.1 application consisting of one CMP2 Entity. For those that are reading this example\nout of curiosity and are not familiar with CMP2 or EJB 2.x, each CMP2 Entity is composed of two parts\n\n - **A Home interface** which has data access methods like \"find\", \"create\", and \"remove\". This is essentially\n what people use `@Stateless` beans for today, but with difference that you do not need to supply\n the implementation of the interface -- the container will generate one for you. This is partly what inspired\n the creation of the OpenEJB-specific [Dynamic DAO](../dynamic-dao-implementation/README.html) feature.\n\n - **An abstract EntityBean class** which declares the persistent \"properties\" of the entity without actually\ndeclaring any fields. It is the container's job to implement the actual methods and create the appropriate\nfields. OpenEJB will implement this bean as a JPA `@Entity` bean.\n\nAs such a CMP2 EntityBean is really just the description of a persistent object and the description of a \ndata-access object. There is no actual code to write.\n\nThe majority of work in CMP2 is done in the xml:\n\n - **ejb-jar.xml** mapping information, which describes the persistent properties of the entity and the queries\n for all *Home* find, create and remove methods. This information will be converted by OpenEJB into\n a JPA mapping.xml file. All queries in the cmp2 part of the ejb-jar.xml are converted \n into named queries in JPA and generally everything is converted to its JPA equivalent. \n\n## CMP2 EntityBean, MovieBean\n\n package org.superbiz.cmp2;\n \n import javax.ejb.EntityBean;\n \n public abstract class MovieBean implements EntityBean {\n \n public MovieBean() {\n }\n \n public Integer ejbCreate(String director, String title, int year) {\n this.setDirector(director);\n this.setTitle(title);\n this.setYear(year);\n return null;\n }\n \n public abstract java.lang.Integer getId();\n \n public abstract void setId(java.lang.Integer id);\n \n public abstract String getDirector();\n \n public abstract void setDirector(String director);\n \n public abstract String getTitle();\n \n public abstract void setTitle(String title);\n \n public abstract int getYear();\n \n public abstract void setYear(int year);\n \n }\n\n## CMP2 Home interface, Movies\n\n package org.superbiz.cmp2;\n \n import javax.ejb.CreateException;\n import javax.ejb.FinderException;\n import java.util.Collection;\n \n /**\n * @version $Revision$ $Date$\n */\n interface Movies extends javax.ejb.EJBLocalHome {\n Movie create(String director, String title, int year) throws CreateException;\n \n Movie findByPrimaryKey(Integer primarykey) throws FinderException;\n \n Collection<Movie> findAll() throws FinderException;\n \n Collection<Movie> findByDirector(String director) throws FinderException;\n }\n\n## CMP2 mapping in ejb-jar.xml\n\n <ejb-jar>\n <enterprise-beans>\n <entity>\n <ejb-name>MovieBean</ejb-name>\n <local-home>org.superbiz.cmp2.Movies</local-home>\n <local>org.superbiz.cmp2.Movie</local>\n <ejb-class>org.superbiz.cmp2.MovieBean</ejb-class>\n <persistence-type>Container</persistence-type>\n <prim-key-class>java.lang.Integer</prim-key-class>\n <reentrant>false</reentrant>\n <cmp-version>2.x</cmp-version>\n <abstract-schema-name>MovieBean</abstract-schema-name>\n <cmp-field>\n <field-name>id</field-name>\n </cmp-field>\n <cmp-field>\n <field-name>director</field-name>\n </cmp-field>\n <cmp-field>\n <field-name>year</field-name>\n </cmp-field>\n <cmp-field>\n <field-name>title</field-name>\n </cmp-field>\n <primkey-field>id</primkey-field>\n <query>\n <query-method>\n <method-name>findByDirector</method-name>\n <method-params>\n <method-param>java.lang.String</method-param>\n </method-params>\n </query-method>\n <ejb-ql>SELECT m FROM MovieBean m WHERE m.director = ?1</ejb-ql>\n </query>\n <query>\n <query-method>\n <method-name>findAll</method-name>\n <method-params/>\n </query-method>\n <ejb-ql>SELECT m FROM MovieBean as m</ejb-ql>\n </query>\n </entity>\n </enterprise-beans>\n </ejb-jar>\n \n\n## openejb-jar.xml\n\n <openejb-jar xmlns=\"http://www.openejb.org/xml/ns/openejb-jar-2.1\">\n <enterprise-beans>\n <entity>\n <ejb-name>MovieBean</ejb-name>\n <key-generator xmlns=\"http://www.openejb.org/xml/ns/pkgen-2.1\">\n <uuid/>\n </key-generator>\n </entity>\n </enterprise-beans>\n </openejb-jar>\n \n\n## MoviesTest\n\n package org.superbiz.cmp2;\n \n import junit.framework.TestCase;\n \n import javax.naming.Context;\n import javax.naming.InitialContext;\n import java.util.Collection;\n import java.util.Properties;\n \n /**\n * @version $Revision: 607077 $ $Date: 2007-12-27 06:55:23 -0800 (Thu, 27 Dec 2007) $\n */\n public class MoviesTest extends TestCase {\n \n public void test() throws Exception {\n Properties p = new Properties();\n p.put(Context.INITIAL_CONTEXT_FACTORY, \"org.apache.openejb.core.LocalInitialContextFactory\");\n p.put(\"movieDatabase\", \"new://Resource?type=DataSource\");\n p.put(\"movieDatabase.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"movieDatabase.JdbcUrl\", \"jdbc:hsqldb:mem:moviedb\");\n \n p.put(\"movieDatabaseUnmanaged\", \"new://Resource?type=DataSource\");\n p.put(\"movieDatabaseUnmanaged.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"movieDatabaseUnmanaged.JdbcUrl\", \"jdbc:hsqldb:mem:moviedb\");\n p.put(\"movieDatabaseUnmanaged.JtaManaged\", \"false\");\n \n Context context = new InitialContext(p);\n \n Movies movies = (Movies) context.lookup(\"MovieBeanLocalHome\");\n \n movies.create(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992);\n movies.create(\"Joel Coen\", \"Fargo\", 1996);\n movies.create(\"Joel Coen\", \"The Big Lebowski\", 1998);\n \n Collection<Movie> list = movies.findAll();\n assertEquals(\"Collection.size()\", 3, list.size());\n \n for (Movie movie : list) {\n movies.remove(movie.getPrimaryKey());\n }\n \n assertEquals(\"Movies.findAll()\", 0, movies.findAll().size());\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.cmp2.MoviesTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/simple-cmp2/target\n INFO - openejb.base = /Users/dblevins/examples/simple-cmp2/target\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=movieDatabaseUnmanaged, type=Resource, provider-id=Default JDBC Database)\n INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/simple-cmp2/target/classes\n INFO - Beginning load: /Users/dblevins/examples/simple-cmp2/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/simple-cmp2/target/classpath.ear\n INFO - Configuring Service(id=Default CMP Container, type=Container, provider-id=Default CMP Container)\n INFO - Auto-creating a container for bean MovieBean: Container(type=CMP_ENTITY, id=Default CMP Container)\n INFO - Configuring PersistenceUnit(name=cmp)\n INFO - Adjusting PersistenceUnit cmp <jta-data-source> to Resource ID 'movieDatabase' from 'null'\n INFO - Adjusting PersistenceUnit cmp <non-jta-data-source> to Resource ID 'movieDatabaseUnmanaged' from 'null'\n INFO - Enterprise application \"/Users/dblevins/examples/simple-cmp2/target/classpath.ear\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/simple-cmp2/target/classpath.ear\n INFO - PersistenceUnit(name=cmp, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 160ms\n INFO - Jndi(name=MovieBeanLocalHome) --> Ejb(deployment-id=MovieBean)\n INFO - Jndi(name=global/classpath.ear/simple-cmp2/MovieBean!org.superbiz.cmp2.Movies) --> Ejb(deployment-id=MovieBean)\n INFO - Jndi(name=global/classpath.ear/simple-cmp2/MovieBean) --> Ejb(deployment-id=MovieBean)\n INFO - Created Ejb(deployment-id=MovieBean, ejb-name=MovieBean, container=Default CMP Container)\n INFO - Started Ejb(deployment-id=MovieBean, ejb-name=MovieBean, container=Default CMP Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/simple-cmp2/target/classpath.ear)\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.919 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n\n# CMP2 to JPA\n\nAs mentioned OpenEJB will implement the abstract CMP2 `EntityBean` as a JPA `@Entity`, create a `persistence.xml` file and convert all `ejb-jar.xml` mapping and queries to\na JPA `entity-mappings.xml` file.\n\nBoth of these files will be written to disk by setting the system property `openejb.descriptors.output` to `true`. In the testcase\nabove, this can be done via the `InitialContext` parameters via code like this:\n\n Properties p = new Properties();\n p.put(Context.INITIAL_CONTEXT_FACTORY, \"org.apache.openejb.core.LocalInitialContextFactory\");\n\n // setup the data sources as usual...\n\n // write the generated descriptors\n p.put(\"openejb.descriptors.output\", \"true\");\n\n Context context = new InitialContext(p);\n\nBelow are the generated `persistence.xml` and `mapping.xml` files for our CMP2 `EntityBean`\n\n## CMP2 to JPA generated persistence.xml file\n\n <?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n <persistence xmlns=\"http://java.sun.com/xml/ns/persistence\" version=\"1.0\">\n <persistence-unit name=\"cmp\" transaction-type=\"JTA\">\n <jta-data-source>movieDatabase</jta-data-source>\n <non-jta-data-source>movieDatabaseUnmanaged</non-jta-data-source>\n <mapping-file>META-INF/openejb-cmp-generated-orm.xml</mapping-file>\n <class>openejb.org.superbiz.cmp2.MovieBean</class>\n <properties>\n <property name=\"openjpa.jdbc.SynchronizeMappings\"\n value=\"buildSchema(ForeignKeys=true, Indexes=false, IgnoreErrors=true)\"/>\n <property name=\"openjpa.Log\" value=\"DefaultLevel=INFO\"/>\n </properties>\n </persistence-unit>\n </persistence>\n\nAll of this `persitence.xml` can be changed, however the `persistence-unit` must have the `name` fixed to `cmp`.\n\n## CMP2 to JPA generated mapping file\n\nNote that the `persistence.xml` above refers to this mappings file as `META-INF/openejb-cmp-generated-orm.xml`. It is possible\nto rename this file to whatever name you prefer, just make sure to update the `<mapping-file>` element of the `cmp` persistence unit\naccordingly.\n\n <?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n <entity-mappings xmlns=\"http://java.sun.com/xml/ns/persistence/orm\" version=\"1.0\">\n <entity class=\"openejb.org.superbiz.cmp2.MovieBean\" name=\"MovieBean\">\n <description>simple-cmp2#MovieBean</description>\n <table/>\n <named-query name=\"MovieBean.findByDirector(java.lang.String)\">\n <query>SELECT m FROM MovieBean m WHERE m.director = ?1</query>\n </named-query>\n <named-query name=\"MovieBean.findAll\">\n <query>SELECT m FROM MovieBean as m</query>\n </named-query>\n <attributes>\n <id name=\"id\">\n <generated-value strategy=\"IDENTITY\"/>\n </id>\n <basic name=\"director\"/>\n <basic name=\"year\"/>\n <basic name=\"title\"/>\n </attributes>\n </entity>\n </entity-mappings>\n",
"url":"https://github.com/apache/tomee/tree/master/examples/simple-cmp2"
}
],
"codi":[
{
"name":"myfaces-codi-demo",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/myfaces-codi-demo"
}
],
"component":[
{
"name":"component-interfaces",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/component-interfaces"
}
],
"config":[
{
"name":"deltaspike-configproperty",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/deltaspike-configproperty"
},
{
"name":"webservice-ws-with-resources-config",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/webservice-ws-with-resources-config"
}
],
"connectionfactory":[
{
"name":"injection-of-connectionfactory",
"readme":"Title: Injection Of Connectionfactory\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## Messages\n\n package org.superbiz.injection.jms;\n \n import javax.annotation.Resource;\n import javax.ejb.Stateless;\n import javax.jms.Connection;\n import javax.jms.ConnectionFactory;\n import javax.jms.DeliveryMode;\n import javax.jms.JMSException;\n import javax.jms.MessageConsumer;\n import javax.jms.MessageProducer;\n import javax.jms.Queue;\n import javax.jms.Session;\n import javax.jms.TextMessage;\n \n @Stateless\n public class Messages {\n \n @Resource\n private ConnectionFactory connectionFactory;\n \n @Resource\n private Queue chatQueue;\n \n \n public void sendMessage(String text) throws JMSException {\n \n Connection connection = null;\n Session session = null;\n \n try {\n connection = connectionFactory.createConnection();\n connection.start();\n \n // Create a Session\n session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);\n \n // Create a MessageProducer from the Session to the Topic or Queue\n MessageProducer producer = session.createProducer(chatQueue);\n producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);\n \n // Create a message\n TextMessage message = session.createTextMessage(text);\n \n // Tell the producer to send the message\n producer.send(message);\n } finally {\n // Clean up\n if (session != null) session.close();\n if (connection != null) connection.close();\n }\n }\n \n public String receiveMessage() throws JMSException {\n \n Connection connection = null;\n Session session = null;\n MessageConsumer consumer = null;\n try {\n connection = connectionFactory.createConnection();\n connection.start();\n \n // Create a Session\n session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);\n \n // Create a MessageConsumer from the Session to the Topic or Queue\n consumer = session.createConsumer(chatQueue);\n \n // Wait for a message\n TextMessage message = (TextMessage) consumer.receive(1000);\n \n return message.getText();\n } finally {\n if (consumer != null) consumer.close();\n if (session != null) session.close();\n if (connection != null) connection.close();\n }\n }\n }\n\n## MessagingBeanTest\n\n package org.superbiz.injection.jms;\n \n import junit.framework.TestCase;\n \n import javax.ejb.embeddable.EJBContainer;\n import javax.naming.Context;\n \n public class MessagingBeanTest extends TestCase {\n \n public void test() throws Exception {\n \n final Context context = EJBContainer.createEJBContainer().getContext();\n \n Messages messages = (Messages) context.lookup(\"java:global/injection-of-connectionfactory/Messages\");\n \n messages.sendMessage(\"Hello World!\");\n messages.sendMessage(\"How are you?\");\n messages.sendMessage(\"Still spinning?\");\n \n assertEquals(messages.receiveMessage(), \"Hello World!\");\n assertEquals(messages.receiveMessage(), \"How are you?\");\n assertEquals(messages.receiveMessage(), \"Still spinning?\");\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.injection.jms.MessagingBeanTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/injection-of-connectionfactory\n INFO - openejb.base = /Users/dblevins/examples/injection-of-connectionfactory\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/injection-of-connectionfactory/target/classes\n INFO - Beginning load: /Users/dblevins/examples/injection-of-connectionfactory/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/injection-of-connectionfactory\n WARN - Method 'lookup' is not available for 'javax.annotation.Resource'. Probably using an older Runtime.\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean Messages: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Configuring Service(id=Default JMS Connection Factory, type=Resource, provider-id=Default JMS Connection Factory)\n INFO - Auto-creating a Resource with id 'Default JMS Connection Factory' of type 'javax.jms.ConnectionFactory for 'Messages'.\n INFO - Configuring Service(id=Default JMS Resource Adapter, type=Resource, provider-id=Default JMS Resource Adapter)\n INFO - Auto-linking resource-ref 'java:comp/env/org.superbiz.injection.jms.Messages/connectionFactory' in bean Messages to Resource(id=Default JMS Connection Factory)\n INFO - Configuring Service(id=org.superbiz.injection.jms.Messages/chatQueue, type=Resource, provider-id=Default Queue)\n INFO - Auto-creating a Resource with id 'org.superbiz.injection.jms.Messages/chatQueue' of type 'javax.jms.Queue for 'Messages'.\n INFO - Auto-linking resource-env-ref 'java:comp/env/org.superbiz.injection.jms.Messages/chatQueue' in bean Messages to Resource(id=org.superbiz.injection.jms.Messages/chatQueue)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.injection.jms.MessagingBeanTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Enterprise application \"/Users/dblevins/examples/injection-of-connectionfactory\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/injection-of-connectionfactory\n INFO - Jndi(name=\"java:global/injection-of-connectionfactory/Messages!org.superbiz.injection.jms.Messages\")\n INFO - Jndi(name=\"java:global/injection-of-connectionfactory/Messages\")\n INFO - Jndi(name=\"java:global/EjbModule1634151355/org.superbiz.injection.jms.MessagingBeanTest!org.superbiz.injection.jms.MessagingBeanTest\")\n INFO - Jndi(name=\"java:global/EjbModule1634151355/org.superbiz.injection.jms.MessagingBeanTest\")\n INFO - Created Ejb(deployment-id=Messages, ejb-name=Messages, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=org.superbiz.injection.jms.MessagingBeanTest, ejb-name=org.superbiz.injection.jms.MessagingBeanTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=Messages, ejb-name=Messages, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=org.superbiz.injection.jms.MessagingBeanTest, ejb-name=org.superbiz.injection.jms.MessagingBeanTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/injection-of-connectionfactory)\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.562 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/injection-of-connectionfactory"
}
],
"contract":[
{
"name":"bean-validation-design-by-contract",
"readme":"# Bean Validation - Design By Contract\n\nBean Validation (aka JSR 303) contains an optional appendix dealing with method validation.\n\nSome implementions of this JSR implement this appendix (Apache bval, Hibernate validator for example).\n\nOpenEJB provides an interceptor which allows you to use this feature to do design by contract.\n\n# Design by contract\n\nThe goal is to be able to configure with a finer grain your contract. In the example you specify\nthe minimum centimeters a sport man should jump at pole vaulting:\n\n @Local\n public interface PoleVaultingManager {\n int points(@Min(120) int centimeters);\n }\n\n# Usage\n\nTomEE and OpenEJB do not provide anymore `BeanValidationAppendixInterceptor` since\nBean Validation 1.1 does it (with a slighly different usage but the exact same feature).\n\nSo basically you don't need to configure anything to use it.\n# Errors\n\nIf a parameter is not validated an exception is thrown, it is an EJBException wrapping a ConstraintViolationException:\n\n try {\n gamesManager.addSportMan(\"I lose\", \"EN\");\n fail(\"no space should be in names\");\n } catch (EJBException wrappingException) {\n assertTrue(wrappingException.getCause() instanceof ConstraintViolationException);\n ConstraintViolationException exception = ConstraintViolationException.class.cast(wrappingException.getCausedByException());\n assertEquals(1, exception.getConstraintViolations().size());\n }\n\n# Example\n\n## OlympicGamesManager\n\n package org.superbiz.designbycontract;\n\n import javax.ejb.Stateless;\n import javax.validation.constraints.NotNull;\n import javax.validation.constraints.Pattern;\n import javax.validation.constraints.Size;\n\n @Stateless\n public class OlympicGamesManager {\n public String addSportMan(@Pattern(regexp = \"^[A-Za-z]+$\") String name, @Size(min = 2, max = 4) String country) {\n if (country.equals(\"USA\")) {\n return null;\n }\n return new StringBuilder(name).append(\" [\").append(country).append(\"]\").toString();\n }\n }\n\n## PoleVaultingManager\n\n package org.superbiz.designbycontract;\n\n import javax.ejb.Local;\n import javax.validation.constraints.Min;\n\n @Local\n public interface PoleVaultingManager {\n int points(@Min(120) int centimeters);\n }\n\n## PoleVaultingManagerBean\n\n package org.superbiz.designbycontract;\n\n import javax.ejb.Stateless;\n\n @Stateless\n public class PoleVaultingManagerBean implements PoleVaultingManager {\n @Override\n public int points(int centimeters) {\n return centimeters - 120;\n }\n }\n\n## OlympicGamesTest\n\n public class OlympicGamesTest {\n private static Context context;\n\n @EJB\n private OlympicGamesManager gamesManager;\n\n @EJB\n private PoleVaultingManager poleVaultingManager;\n\n @BeforeClass\n public static void start() {\n Properties properties = new Properties();\n properties.setProperty(BeanContext.USER_INTERCEPTOR_KEY, BeanValidationAppendixInterceptor.class.getName());\n context = EJBContainer.createEJBContainer(properties).getContext();\n }\n\n @Before\n public void inject() throws Exception {\n context.bind(\"inject\", this);\n }\n\n @AfterClass\n public static void stop() throws Exception {\n if (context != null) {\n context.close();\n }\n }\n\n @Test\n public void sportMenOk() throws Exception {\n assertEquals(\"IWin [FR]\", gamesManager.addSportMan(\"IWin\", \"FR\"));\n }\n\n @Test\n public void sportMenKoBecauseOfName() throws Exception {\n try {\n gamesManager.addSportMan(\"I lose\", \"EN\");\n fail(\"no space should be in names\");\n } catch (EJBException wrappingException) {\n assertTrue(wrappingException.getCause() instanceof ConstraintViolationException);\n ConstraintViolationException exception = ConstraintViolationException.class.cast(wrappingException.getCausedByException());\n assertEquals(1, exception.getConstraintViolations().size());\n }\n }\n\n @Test\n public void sportMenKoBecauseOfCountry() throws Exception {\n try {\n gamesManager.addSportMan(\"ILoseTwo\", \"TOO-LONG\");\n fail(\"country should be between 2 and 4 characters\");\n } catch (EJBException wrappingException) {\n assertTrue(wrappingException.getCause() instanceof ConstraintViolationException);\n ConstraintViolationException exception = ConstraintViolationException.class.cast(wrappingException.getCausedByException());\n assertEquals(1, exception.getConstraintViolations().size());\n }\n }\n\n @Test\n public void polVaulting() throws Exception {\n assertEquals(100, poleVaultingManager.points(220));\n }\n\n @Test\n public void tooShortPolVaulting() throws Exception {\n try {\n poleVaultingManager.points(119);\n fail(\"the jump is too short\");\n } catch (EJBException wrappingException) {\n assertTrue(wrappingException.getCause() instanceof ConstraintViolationException);\n ConstraintViolationException exception = ConstraintViolationException.class.cast(wrappingException.getCausedByException());\n assertEquals(1, exception.getConstraintViolations().size());\n }\n }\n }\n\n# Running\n\n\n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running OlympicGamesTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/bean-validation-design-by-contract\n INFO - openejb.base = /Users/dblevins/examples/bean-validation-design-by-contract\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/bean-validation-design-by-contract/target/classes\n INFO - Beginning load: /Users/dblevins/examples/bean-validation-design-by-contract/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/bean-validation-design-by-contract\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean PoleVaultingManagerBean: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean OlympicGamesTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Enterprise application \"/Users/dblevins/examples/bean-validation-design-by-contract\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/bean-validation-design-by-contract\n INFO - Jndi(name=\"java:global/bean-validation-design-by-contract/PoleVaultingManagerBean!org.superbiz.designbycontract.PoleVaultingManager\")\n INFO - Jndi(name=\"java:global/bean-validation-design-by-contract/PoleVaultingManagerBean\")\n INFO - Jndi(name=\"java:global/bean-validation-design-by-contract/OlympicGamesManager!org.superbiz.designbycontract.OlympicGamesManager\")\n INFO - Jndi(name=\"java:global/bean-validation-design-by-contract/OlympicGamesManager\")\n INFO - Jndi(name=\"java:global/EjbModule236054577/OlympicGamesTest!OlympicGamesTest\")\n INFO - Jndi(name=\"java:global/EjbModule236054577/OlympicGamesTest\")\n INFO - Created Ejb(deployment-id=OlympicGamesManager, ejb-name=OlympicGamesManager, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=PoleVaultingManagerBean, ejb-name=PoleVaultingManagerBean, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=OlympicGamesTest, ejb-name=OlympicGamesTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=OlympicGamesManager, ejb-name=OlympicGamesManager, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=PoleVaultingManagerBean, ejb-name=PoleVaultingManagerBean, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=OlympicGamesTest, ejb-name=OlympicGamesTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/bean-validation-design-by-contract)\n Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.245 sec\n\n Results :\n\n Tests run: 5, Failures: 0, Errors: 0, Skipped: 0\n",
"url":"https://github.com/apache/tomee/tree/master/examples/bean-validation-design-by-contract"
}
],
"cucumber":[
{
"name":"cucumber-jvm",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/cucumber-jvm"
}
],
"dao":[
{
"name":"dynamic-dao-implementation",
"readme":"Title: Dynamic DAO Implementation\n\nMany aspects of Data Access Objects (DAOs) are very repetitive and boiler plate. As a fun and experimental feature, TomEE supports dynamically implementing an interface\nthat is seen to have standard DAO-style methods.\n\nThe interface has to be annotated with @PersistenceContext to define which EntityManager to use.\n\nMethods should respect these conventions:\n\n * void save(Foo foo): persist foo\n * Foo update(Foo foo): merge foo\n * void delete(Foo foo): remove foo, if foo is detached it tries to attach it\n * Collection<Foo>|Foo namedQuery(String name[, Map<String, ?> params, int first, int max]): run the named query called name, params contains bindings, first and max are used for magination. Last three parameters are optionnals\n * Collection<Foo>|Foo nativeQuery(String name[, Map<String, ?> params, int first, int max]): run the native query called name, params contains bindings, first and max are used for magination. Last three parameters are optionnals\n * Collection<Foo>|Foo query(String value [, Map<String, ?> params, int first, int max]): run the query put as first parameter, params contains bindings, first and max are used for magination. Last three parameters are optionnals\n * Collection<Foo> findAll([int first, int max]): find all Foo, parameters are used for pagination\n * Collection<Foo> findByBar1AndBar2AndBar3(<bar 1 type> bar1, <bar 2 type> bar2, <bar3 type> bar3 [, int first, int max]): find all Foo with specified field values for bar1, bar2, bar3.\n\nDynamic finder can have as much as you want field constraints. For String like is used and for other type equals is used.\n\n# Example\n\n## User\n\n package org.superbiz.dynamic;\n \n import javax.persistence.Entity;\n import javax.persistence.GeneratedValue;\n import javax.persistence.Id;\n import javax.persistence.NamedQueries;\n import javax.persistence.NamedQuery;\n \n @Entity\n @NamedQueries({\n @NamedQuery(name = \"dynamic-ejb-impl-test.query\", query = \"SELECT u FROM User AS u WHERE u.name LIKE :name\"),\n @NamedQuery(name = \"dynamic-ejb-impl-test.all\", query = \"SELECT u FROM User AS u\")\n })\n public class User {\n @Id\n @GeneratedValue\n private long id;\n private String name;\n private int age;\n\n public long getId() {\n return id;\n }\n\n public void setId(long id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public int getAge() {\n return age;\n }\n\n public void setAge(int age) {\n this.age = age;\n }\n }\n\n## UserDao\n\n package org.superbiz.dynamic;\n \n \n import javax.ejb.Stateless;\n import javax.persistence.PersistenceContext;\n import java.util.Collection;\n import java.util.Map;\n \n @Stateless\n @PersistenceContext(name = \"dynamic\")\n public interface UserDao {\n User findById(long id);\n \n Collection<User> findByName(String name);\n \n Collection<User> findByNameAndAge(String name, int age);\n \n Collection<User> findAll();\n \n Collection<User> findAll(int first, int max);\n \n Collection<User> namedQuery(String name, Map<String, ?> params, int first, int max);\n \n Collection<User> namedQuery(String name, int first, int max, Map<String, ?> params);\n \n Collection<User> namedQuery(String name, Map<String, ?> params);\n \n Collection<User> namedQuery(String name);\n \n Collection<User> query(String value, Map<String, ?> params);\n \n void save(User u);\n \n void delete(User u);\n \n User update(User u);\n }\n\n## persistence.xml\n\n <persistence version=\"2.0\"\n xmlns=\"http://java.sun.com/xml/ns/persistence\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"\n http://java.sun.com/xml/ns/persistence\n http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd\">\n <persistence-unit name=\"dynamic\" transaction-type=\"JTA\">\n <jta-data-source>jdbc/dynamicDB</jta-data-source>\n <class>org.superbiz.dynamic.User</class>\n <properties>\n <property name=\"openjpa.jdbc.SynchronizeMappings\" value=\"buildSchema(ForeignKeys=true)\"/>\n </properties>\n </persistence-unit>\n </persistence>\n \n\n## DynamicUserDaoTest\n\n package org.superbiz.dynamic;\n \n import junit.framework.Assert;\n import org.junit.BeforeClass;\n import org.junit.Test;\n \n import javax.ejb.EJBException;\n import javax.ejb.Stateless;\n import javax.ejb.embeddable.EJBContainer;\n import javax.naming.Context;\n import javax.persistence.EntityManager;\n import javax.persistence.NoResultException;\n import javax.persistence.PersistenceContext;\n import java.util.Collection;\n import java.util.HashMap;\n import java.util.Map;\n import java.util.Properties;\n \n import static junit.framework.Assert.assertEquals;\n import static junit.framework.Assert.assertNotNull;\n import static junit.framework.Assert.assertTrue;\n \n public class DynamicUserDaoTest {\n private static UserDao dao;\n private static Util util;\n \n @BeforeClass\n public static void init() throws Exception {\n final Properties p = new Properties();\n p.put(\"jdbc/dynamicDB\", \"new://Resource?type=DataSource\");\n p.put(\"jdbc/dynamicDB.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"jdbc/dynamicDB.JdbcUrl\", \"jdbc:hsqldb:mem:moviedb\");\n p.put(\"jdbc/dynamicDB.UserName\", \"sa\");\n p.put(\"jdbc/dynamicDB.Password\", \"\");\n \n final Context context = EJBContainer.createEJBContainer(p).getContext();\n dao = (UserDao) context.lookup(\"java:global/dynamic-dao-implementation/UserDao\");\n util = (Util) context.lookup(\"java:global/dynamic-dao-implementation/Util\");\n \n util.init(); // init database\n }\n \n @Test\n public void simple() {\n User user = dao.findById(1);\n assertNotNull(user);\n assertEquals(1, user.getId());\n }\n \n @Test\n public void findAll() {\n Collection<User> users = dao.findAll();\n assertEquals(10, users.size());\n }\n \n @Test\n public void pagination() {\n Collection<User> users = dao.findAll(0, 5);\n assertEquals(5, users.size());\n \n users = dao.findAll(6, 1);\n assertEquals(1, users.size());\n assertEquals(7, users.iterator().next().getId());\n }\n \n @Test\n public void persist() {\n User u = new User();\n dao.save(u);\n assertNotNull(u.getId());\n util.remove(u);\n }\n \n @Test\n public void remove() {\n User u = new User();\n dao.save(u);\n assertNotNull(u.getId());\n dao.delete(u);\n try {\n dao.findById(u.getId());\n Assert.fail();\n } catch (EJBException ee) {\n assertTrue(ee.getCause() instanceof NoResultException);\n }\n }\n \n @Test\n public void merge() {\n User u = new User();\n u.setAge(1);\n dao.save(u);\n assertEquals(1, u.getAge());\n assertNotNull(u.getId());\n \n u.setAge(2);\n dao.update(u);\n assertEquals(2, u.getAge());\n \n dao.delete(u);\n }\n \n @Test\n public void oneCriteria() {\n Collection<User> users = dao.findByName(\"foo\");\n assertEquals(4, users.size());\n for (User user : users) {\n assertEquals(\"foo\", user.getName());\n }\n }\n \n @Test\n public void twoCriteria() {\n Collection<User> users = dao.findByNameAndAge(\"bar-1\", 1);\n assertEquals(1, users.size());\n \n User user = users.iterator().next();\n assertEquals(\"bar-1\", user.getName());\n assertEquals(1, user.getAge());\n }\n \n @Test\n public void query() {\n Map<String, Object> params = new HashMap<String, Object>();\n params.put(\"name\", \"foo\");\n \n Collection<User> users = dao.namedQuery(\"dynamic-ejb-impl-test.query\", params, 0, 100);\n assertEquals(4, users.size());\n \n users = dao.namedQuery(\"dynamic-ejb-impl-test.query\", params);\n assertEquals(4, users.size());\n \n users = dao.namedQuery(\"dynamic-ejb-impl-test.query\", params, 0, 2);\n assertEquals(2, users.size());\n \n users = dao.namedQuery(\"dynamic-ejb-impl-test.query\", 0, 2, params);\n assertEquals(2, users.size());\n \n users = dao.namedQuery(\"dynamic-ejb-impl-test.all\");\n assertEquals(10, users.size());\n \n params.remove(\"name\");\n params.put(\"age\", 1);\n users = dao.query(\"SELECT u FROM User AS u WHERE u.age = :age\", params);\n assertEquals(3, users.size());\n }\n \n @Stateless\n public static class Util {\n @PersistenceContext\n private EntityManager em;\n \n public void remove(User o) {\n em.remove(em.find(User.class, o.getId()));\n }\n \n public void init() {\n for (int i = 0; i < 10; i++) {\n User u = new User();\n u.setAge(i % 4);\n if (i % 3 == 0) {\n u.setName(\"foo\");\n } else {\n u.setName(\"bar-\" + i);\n }\n em.persist(u);\n }\n }\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.dynamic.DynamicUserDaoTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/dynamic-dao-implementation\n INFO - openejb.base = /Users/dblevins/examples/dynamic-dao-implementation\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=jdbc/dynamicDB, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/dynamic-dao-implementation/target/classes\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/dynamic-dao-implementation/target/test-classes\n INFO - Beginning load: /Users/dblevins/examples/dynamic-dao-implementation/target/classes\n INFO - Beginning load: /Users/dblevins/examples/dynamic-dao-implementation/target/test-classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/dynamic-dao-implementation\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean UserDao: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.dynamic.DynamicUserDaoTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring PersistenceUnit(name=dynamic)\n INFO - Auto-creating a Resource with id 'jdbc/dynamicDBNonJta' of type 'DataSource for 'dynamic'.\n INFO - Configuring Service(id=jdbc/dynamicDBNonJta, type=Resource, provider-id=jdbc/dynamicDB)\n INFO - Adjusting PersistenceUnit dynamic <non-jta-data-source> to Resource ID 'jdbc/dynamicDBNonJta' from 'null'\n INFO - Enterprise application \"/Users/dblevins/examples/dynamic-dao-implementation\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/dynamic-dao-implementation\n INFO - PersistenceUnit(name=dynamic, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 417ms\n INFO - Jndi(name=\"java:global/dynamic-dao-implementation/UserDao!org.superbiz.dynamic.UserDao\")\n INFO - Jndi(name=\"java:global/dynamic-dao-implementation/UserDao\")\n INFO - Jndi(name=\"java:global/dynamic-dao-implementation/Util!org.superbiz.dynamic.DynamicUserDaoTest$Util\")\n INFO - Jndi(name=\"java:global/dynamic-dao-implementation/Util\")\n INFO - Jndi(name=\"java:global/EjbModule346613126/org.superbiz.dynamic.DynamicUserDaoTest!org.superbiz.dynamic.DynamicUserDaoTest\")\n INFO - Jndi(name=\"java:global/EjbModule346613126/org.superbiz.dynamic.DynamicUserDaoTest\")\n INFO - Created Ejb(deployment-id=UserDao, ejb-name=UserDao, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=Util, ejb-name=Util, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=org.superbiz.dynamic.DynamicUserDaoTest, ejb-name=org.superbiz.dynamic.DynamicUserDaoTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=UserDao, ejb-name=UserDao, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=Util, ejb-name=Util, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=org.superbiz.dynamic.DynamicUserDaoTest, ejb-name=org.superbiz.dynamic.DynamicUserDaoTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/dynamic-dao-implementation)\n WARN - Meta class \"org.superbiz.dynamic.User_\" for entity class org.superbiz.dynamic.User can not be registered with following exception \"java.security.PrivilegedActionException: java.lang.ClassNotFoundException: org.superbiz.dynamic.User_\"\n WARN - Query \"SELECT u FROM User AS u WHERE u.name LIKE :name\" is removed from cache excluded permanently. Query \"SELECT u FROM User AS u WHERE u.name LIKE :name\" is not cached because it uses pagination..\n Tests run: 9, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.471 sec\n \n Results :\n \n Tests run: 9, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/dynamic-dao-implementation"
}
],
"data":[
{
"name":"spring-data-proxy",
"readme":"# Spring Data sample #\n\nThis example uses OpenEJB hooks to replace an EJB implementation by a proxy\nto uses Spring Data in your preferred container.\n\nIt is pretty simple: simply provide to OpenEJB an InvocationHandler using delegating to spring data\nand that's it!\n\nIt is what is done in org.superbiz.dynamic.SpringDataProxy.\n\nIt contains a little trick: even if it is not annotated \"implementingInterfaceClass\" attribute\nis injected by OpenEJB to get the interface.\n\nThen we simply create the Spring Data repository and delegate to it.\n",
"url":"https://github.com/apache/tomee/tree/master/examples/spring-data-proxy"
},
{
"name":"spring-data-proxy-meta",
"readme":"# Spring Data With Meta sample #\n\nThis example simply simplifies the usage of spring-data sample\nproviding a meta annotation @SpringRepository to do all the dynamic procy EJB job.\n\nIt replaces @Proxy and @Stateless annotations.\n\nIsn't it more comfortable?\n\nTo do it we defined a meta annotation \"Metatype\" and used it.\n\nThe proxy implementation is the same than for spring-data sample.\n",
"url":"https://github.com/apache/tomee/tree/master/examples/spring-data-proxy-meta"
}
],
"datasource":[
{
"name":"dynamic-datasource-routing",
"readme":"Title: Dynamic Datasource Routing\n\nThe TomEE dynamic datasource api aims to allow to use multiple data sources as one from an application point of view.\n\nIt can be useful for technical reasons (load balancing for example) or more generally\nfunctionnal reasons (filtering, aggregation, enriching...). However please note you can choose\nonly one datasource by transaction. It means the goal of this feature is not to switch more than\nonce of datasource in a transaction. The following code will not work:\n\n @Stateless\n public class MyEJB {\n @Resource private MyRouter router;\n @PersistenceContext private EntityManager em;\n\n public void workWithDataSources() {\n router.setDataSource(\"ds1\");\n em.persist(new MyEntity());\n\n router.setDataSource(\"ds2\"); // same transaction -> this invocation doesn't work\n em.persist(new MyEntity());\n }\n }\n\nIn this example the implementation simply use a datasource from its name and needs to be set before using any JPA\noperation in the transaction (to keep the logic simple in the example).\n\n# The implementation of the Router\n\nOur router has two configuration parameters:\n* a list of jndi names representing datasources to use\n* a default datasource to use\n\n## Router implementation\n\nThe interface Router (`org.apache.openejb.resource.jdbc.Router`) has only one method to implement, `public DataSource getDataSource()`\n\nOur `DeterminedRouter` implementation uses a ThreadLocal to manage the currently used datasource. Keep in mind JPA used more than once the getDatasource() method\nfor one operation. To change the datasource in one transaction is dangerous and should be avoid.\n\n package org.superbiz.dynamicdatasourcerouting;\n\n import org.apache.openejb.resource.jdbc.AbstractRouter;\n\n import javax.naming.NamingException;\n import javax.sql.DataSource;\n import java.util.Map;\n import java.util.concurrent.ConcurrentHashMap;\n\n public class DeterminedRouter extends AbstractRouter {\n private String dataSourceNames;\n private String defaultDataSourceName;\n private Map<String, DataSource> dataSources = null;\n private ThreadLocal<DataSource> currentDataSource = new ThreadLocal<DataSource>();\n\n /**\n * @param datasourceList datasource resource name, separator is a space\n */\n public void setDataSourceNames(String datasourceList) {\n dataSourceNames = datasourceList;\n }\n\n /**\n * lookup datasource in openejb resources\n */\n private void init() {\n dataSources = new ConcurrentHashMap<String, DataSource>();\n for (String ds : dataSourceNames.split(\" \")) {\n try {\n Object o = getOpenEJBResource(ds);\n if (o instanceof DataSource) {\n dataSources.put(ds, DataSource.class.cast(o));\n }\n } catch (NamingException e) {\n // ignored\n }\n }\n }\n\n /**\n * @return the user selected data source if it is set\n * or the default one\n * @throws IllegalArgumentException if the data source is not found\n */\n @Override\n public DataSource getDataSource() {\n // lazy init of routed datasources\n if (dataSources == null) {\n init();\n }\n\n // if no datasource is selected use the default one\n if (currentDataSource.get() == null) {\n if (dataSources.containsKey(defaultDataSourceName)) {\n return dataSources.get(defaultDataSourceName);\n\n } else {\n throw new IllegalArgumentException(\"you have to specify at least one datasource\");\n }\n }\n\n // the developper set the datasource to use\n return currentDataSource.get();\n }\n\n /**\n *\n * @param datasourceName data source name\n */\n public void setDataSource(String datasourceName) {\n if (dataSources == null) {\n init();\n }\n if (!dataSources.containsKey(datasourceName)) {\n throw new IllegalArgumentException(\"data source called \" + datasourceName + \" can't be found.\");\n }\n DataSource ds = dataSources.get(datasourceName);\n currentDataSource.set(ds);\n }\n\n /**\n * reset the data source\n */\n public void clear() {\n currentDataSource.remove();\n }\n\n public void setDefaultDataSourceName(String name) {\n this.defaultDataSourceName = name;\n }\n }\n\n## Declaring the implementation\n\nTo be able to use your router as a resource you need to provide a service configuration. It is done in a file\nyou can find in META-INF/org.router/ and called service-jar.xml\n(for your implementation you can of course change the package name).\n\nIt contains the following code:\n\n <ServiceJar>\n <ServiceProvider id=\"DeterminedRouter\" <!-- the name you want to use -->\n service=\"Resource\"\n type=\"org.apache.openejb.resource.jdbc.Router\"\n class-name=\"org.superbiz.dynamicdatasourcerouting.DeterminedRouter\"> <!-- implementation class -->\n\n # the parameters\n\n DataSourceNames\n DefaultDataSourceName\n </ServiceProvider>\n </ServiceJar>\n\n\n# Using the Router\n\nHere we have a `RoutedPersister` stateless bean which uses our `DeterminedRouter`\n\n package org.superbiz.dynamicdatasourcerouting;\n\n import javax.annotation.Resource;\n import javax.ejb.Stateless;\n import javax.persistence.EntityManager;\n import javax.persistence.PersistenceContext;\n\n @Stateless\n public class RoutedPersister {\n @PersistenceContext(unitName = \"router\")\n private EntityManager em;\n\n @Resource(name = \"My Router\", type = DeterminedRouter.class)\n private DeterminedRouter router;\n\n public void persist(int id, String name, String ds) {\n router.setDataSource(ds);\n em.persist(new Person(id, name));\n }\n }\n\n# The test\n\nIn test mode and using property style configuration the foolowing configuration is used:\n\n public class DynamicDataSourceTest {\n @Test\n public void route() throws Exception {\n String[] databases = new String[]{\"database1\", \"database2\", \"database3\"};\n\n Properties properties = new Properties();\n properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, LocalInitialContextFactory.class.getName());\n\n // resources\n // datasources\n for (int i = 1; i <= databases.length; i++) {\n String dbName = databases[i - 1];\n properties.setProperty(dbName, \"new://Resource?type=DataSource\");\n dbName += \".\";\n properties.setProperty(dbName + \"JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n properties.setProperty(dbName + \"JdbcUrl\", \"jdbc:hsqldb:mem:db\" + i);\n properties.setProperty(dbName + \"UserName\", \"sa\");\n properties.setProperty(dbName + \"Password\", \"\");\n properties.setProperty(dbName + \"JtaManaged\", \"true\");\n }\n\n // router\n properties.setProperty(\"My Router\", \"new://Resource?provider=org.router:DeterminedRouter&type=\" + DeterminedRouter.class.getName());\n properties.setProperty(\"My Router.DatasourceNames\", \"database1 database2 database3\");\n properties.setProperty(\"My Router.DefaultDataSourceName\", \"database1\");\n\n // routed datasource\n properties.setProperty(\"Routed Datasource\", \"new://Resource?provider=RoutedDataSource&type=\" + Router.class.getName());\n properties.setProperty(\"Routed Datasource.Router\", \"My Router\");\n\n Context ctx = EJBContainer.createEJBContainer(properties).getContext();\n RoutedPersister ejb = (RoutedPersister) ctx.lookup(\"java:global/dynamic-datasource-routing/RoutedPersister\");\n for (int i = 0; i < 18; i++) {\n // persisting a person on database db -> kind of manual round robin\n String name = \"record \" + i;\n String db = databases[i % 3];\n ejb.persist(i, name, db);\n }\n\n // assert database records number using jdbc\n for (int i = 1; i <= databases.length; i++) {\n Connection connection = DriverManager.getConnection(\"jdbc:hsqldb:mem:db\" + i, \"sa\", \"\");\n Statement st = connection.createStatement();\n ResultSet rs = st.executeQuery(\"select count(*) from PERSON\");\n rs.next();\n assertEquals(6, rs.getInt(1));\n st.close();\n connection.close();\n }\n\n ctx.close();\n }\n }\n\n# Configuration via openejb.xml\n\nThe testcase above uses properties for configuration. The identical way to do it via the `conf/openejb.xml` is as follows:\n\n <!-- Router and datasource -->\n <Resource id=\"My Router\" type=\"org.apache.openejb.router.test.DynamicDataSourceTest$DeterminedRouter\" provider=\"org.routertest:DeterminedRouter\">\n DatasourceNames = database1 database2 database3\n DefaultDataSourceName = database1\n </Resource>\n <Resource id=\"Routed Datasource\" type=\"org.apache.openejb.resource.jdbc.Router\" provider=\"RoutedDataSource\">\n Router = My Router\n </Resource>\n\n <!-- real datasources -->\n <Resource id=\"database1\" type=\"DataSource\">\n JdbcDriver = org.hsqldb.jdbcDriver\n JdbcUrl = jdbc:hsqldb:mem:db1\n UserName = sa\n Password\n JtaManaged = true\n </Resource>\n <Resource id=\"database2\" type=\"DataSource\">\n JdbcDriver = org.hsqldb.jdbcDriver\n JdbcUrl = jdbc:hsqldb:mem:db2\n UserName = sa\n Password\n JtaManaged = true\n </Resource>\n <Resource id=\"database3\" type=\"DataSource\">\n JdbcDriver = org.hsqldb.jdbcDriver\n JdbcUrl = jdbc:hsqldb:mem:db3\n UserName = sa\n Password\n JtaManaged = true\n </Resource>\n\n\n\n\n## Some hack for OpenJPA\n\nUsing more than one datasource behind one EntityManager means the databases are already created. If it is not the case,\nthe JPA provider has to create the datasource at boot time.\n\nHibernate do it so if you declare your databases it will work. However with OpenJPA\n(the default JPA provider for OpenEJB), the creation is lazy and it happens only once so when you'll switch of database\nit will no more work.\n\nOf course OpenEJB provides @Singleton and @Startup features of Java EE 6 and we can do a bean just making a simple find,\neven on none existing entities, just to force the database creation:\n\n @Startup\n @Singleton\n public class BoostrapUtility {\n // inject all real databases\n\n @PersistenceContext(unitName = \"db1\")\n private EntityManager em1;\n\n @PersistenceContext(unitName = \"db2\")\n private EntityManager em2;\n\n @PersistenceContext(unitName = \"db3\")\n private EntityManager em3;\n\n // force database creation\n\n @PostConstruct\n @TransactionAttribute(TransactionAttributeType.SUPPORTS)\n public void initDatabase() {\n em1.find(Person.class, 0);\n em2.find(Person.class, 0);\n em3.find(Person.class, 0);\n }\n }\n\n## Using the routed datasource\n\nNow you configured the way you want to route your JPA operation, you registered the resources and you initialized\nyour databases you can use it and see how it is simple:\n\n @Stateless\n public class RoutedPersister {\n // injection of the \"proxied\" datasource\n @PersistenceContext(unitName = \"router\")\n private EntityManager em;\n\n // injection of the router you need it to configured the database\n @Resource(name = \"My Router\", type = DeterminedRouter.class)\n private DeterminedRouter router;\n\n public void persist(int id, String name, String ds) {\n router.setDataSource(ds); // configuring the database for the current transaction\n em.persist(new Person(id, name)); // will use ds database automatically\n }\n }\n\n# Running\n\n\n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.dynamicdatasourcerouting.DynamicDataSourceTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/dynamic-datasource-routing\n INFO - openejb.base = /Users/dblevins/examples/dynamic-datasource-routing\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=My Router, type=Resource, provider-id=DeterminedRouter)\n INFO - Configuring Service(id=database3, type=Resource, provider-id=Default JDBC Database)\n INFO - Configuring Service(id=database2, type=Resource, provider-id=Default JDBC Database)\n INFO - Configuring Service(id=Routed Datasource, type=Resource, provider-id=RoutedDataSource)\n INFO - Configuring Service(id=database1, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/dynamic-datasource-routing/target/classes\n INFO - Beginning load: /Users/dblevins/examples/dynamic-datasource-routing/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/dynamic-datasource-routing\n WARN - Method 'lookup' is not available for 'javax.annotation.Resource'. Probably using an older Runtime.\n INFO - Configuring Service(id=Default Singleton Container, type=Container, provider-id=Default Singleton Container)\n INFO - Auto-creating a container for bean BoostrapUtility: Container(type=SINGLETON, id=Default Singleton Container)\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean RoutedPersister: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Auto-linking resource-ref 'java:comp/env/My Router' in bean RoutedPersister to Resource(id=My Router)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.dynamicdatasourcerouting.DynamicDataSourceTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring PersistenceUnit(name=router)\n INFO - Configuring PersistenceUnit(name=db1)\n INFO - Auto-creating a Resource with id 'database1NonJta' of type 'DataSource for 'db1'.\n INFO - Configuring Service(id=database1NonJta, type=Resource, provider-id=database1)\n INFO - Adjusting PersistenceUnit db1 <non-jta-data-source> to Resource ID 'database1NonJta' from 'null'\n INFO - Configuring PersistenceUnit(name=db2)\n INFO - Auto-creating a Resource with id 'database2NonJta' of type 'DataSource for 'db2'.\n INFO - Configuring Service(id=database2NonJta, type=Resource, provider-id=database2)\n INFO - Adjusting PersistenceUnit db2 <non-jta-data-source> to Resource ID 'database2NonJta' from 'null'\n INFO - Configuring PersistenceUnit(name=db3)\n INFO - Auto-creating a Resource with id 'database3NonJta' of type 'DataSource for 'db3'.\n INFO - Configuring Service(id=database3NonJta, type=Resource, provider-id=database3)\n INFO - Adjusting PersistenceUnit db3 <non-jta-data-source> to Resource ID 'database3NonJta' from 'null'\n INFO - Enterprise application \"/Users/dblevins/examples/dynamic-datasource-routing\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/dynamic-datasource-routing\n INFO - PersistenceUnit(name=router, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 504ms\n INFO - PersistenceUnit(name=db1, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 11ms\n INFO - PersistenceUnit(name=db2, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 7ms\n INFO - PersistenceUnit(name=db3, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 6ms\n INFO - Jndi(name=\"java:global/dynamic-datasource-routing/BoostrapUtility!org.superbiz.dynamicdatasourcerouting.BoostrapUtility\")\n INFO - Jndi(name=\"java:global/dynamic-datasource-routing/BoostrapUtility\")\n INFO - Jndi(name=\"java:global/dynamic-datasource-routing/RoutedPersister!org.superbiz.dynamicdatasourcerouting.RoutedPersister\")\n INFO - Jndi(name=\"java:global/dynamic-datasource-routing/RoutedPersister\")\n INFO - Jndi(name=\"java:global/EjbModule1519652738/org.superbiz.dynamicdatasourcerouting.DynamicDataSourceTest!org.superbiz.dynamicdatasourcerouting.DynamicDataSourceTest\")\n INFO - Jndi(name=\"java:global/EjbModule1519652738/org.superbiz.dynamicdatasourcerouting.DynamicDataSourceTest\")\n INFO - Created Ejb(deployment-id=RoutedPersister, ejb-name=RoutedPersister, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=org.superbiz.dynamicdatasourcerouting.DynamicDataSourceTest, ejb-name=org.superbiz.dynamicdatasourcerouting.DynamicDataSourceTest, container=Default Managed Container)\n INFO - Created Ejb(deployment-id=BoostrapUtility, ejb-name=BoostrapUtility, container=Default Singleton Container)\n INFO - Started Ejb(deployment-id=RoutedPersister, ejb-name=RoutedPersister, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=org.superbiz.dynamicdatasourcerouting.DynamicDataSourceTest, ejb-name=org.superbiz.dynamicdatasourcerouting.DynamicDataSourceTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=BoostrapUtility, ejb-name=BoostrapUtility, container=Default Singleton Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/dynamic-datasource-routing)\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.504 sec\n\n Results :\n\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n\n",
"url":"https://github.com/apache/tomee/tree/master/examples/dynamic-datasource-routing"
},
{
"name":"injection-of-datasource",
"readme":"Title: Injection Of Datasource\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## Movie\n\n package org.superbiz.injection;\n \n /**\n * @version $Revision: 607077 $ $Date: 2007-12-27 06:55:23 -0800 (Thu, 27 Dec 2007) $\n */\n public class Movie {\n private String director;\n private String title;\n private int year;\n \n public Movie() {\n }\n \n public Movie(String director, String title, int year) {\n this.director = director;\n this.title = title;\n this.year = year;\n }\n \n public String getDirector() {\n return director;\n }\n \n public void setDirector(String director) {\n this.director = director;\n }\n \n public String getTitle() {\n return title;\n }\n \n public void setTitle(String title) {\n this.title = title;\n }\n \n public int getYear() {\n return year;\n }\n \n public void setYear(int year) {\n this.year = year;\n }\n \n }\n\n## Movies\n\n package org.superbiz.injection;\n \n import javax.annotation.PostConstruct;\n import javax.annotation.Resource;\n import javax.ejb.Stateful;\n import javax.sql.DataSource;\n import java.sql.Connection;\n import java.sql.PreparedStatement;\n import java.sql.ResultSet;\n import java.util.ArrayList;\n import java.util.List;\n \n @Stateful\n public class Movies {\n \n /**\n * The field name \"movieDatabase\" matches the DataSource we\n * configure in the TestCase via :\n * p.put(\"movieDatabase\", \"new://Resource?type=DataSource\");\n * <p/>\n * This would also match an equivalent delcaration in an openejb.xml:\n * <Resource id=\"movieDatabase\" type=\"DataSource\"/>\n * <p/>\n * If you'd like the freedom to change the field name without\n * impact on your configuration you can set the \"name\" attribute\n * of the @Resource annotation to \"movieDatabase\" instead.\n */\n @Resource\n private DataSource movieDatabase;\n \n @PostConstruct\n private void construct() throws Exception {\n Connection connection = movieDatabase.getConnection();\n try {\n PreparedStatement stmt = connection.prepareStatement(\"CREATE TABLE movie ( director VARCHAR(255), title VARCHAR(255), year integer)\");\n stmt.execute();\n } finally {\n connection.close();\n }\n }\n \n public void addMovie(Movie movie) throws Exception {\n Connection conn = movieDatabase.getConnection();\n try {\n PreparedStatement sql = conn.prepareStatement(\"INSERT into movie (director, title, year) values (?, ?, ?)\");\n sql.setString(1, movie.getDirector());\n sql.setString(2, movie.getTitle());\n sql.setInt(3, movie.getYear());\n sql.execute();\n } finally {\n conn.close();\n }\n }\n \n public void deleteMovie(Movie movie) throws Exception {\n Connection conn = movieDatabase.getConnection();\n try {\n PreparedStatement sql = conn.prepareStatement(\"DELETE from movie where director = ? AND title = ? AND year = ?\");\n sql.setString(1, movie.getDirector());\n sql.setString(2, movie.getTitle());\n sql.setInt(3, movie.getYear());\n sql.execute();\n } finally {\n conn.close();\n }\n }\n \n public List<Movie> getMovies() throws Exception {\n ArrayList<Movie> movies = new ArrayList<Movie>();\n Connection conn = movieDatabase.getConnection();\n try {\n PreparedStatement sql = conn.prepareStatement(\"SELECT director, title, year from movie\");\n ResultSet set = sql.executeQuery();\n while (set.next()) {\n Movie movie = new Movie();\n movie.setDirector(set.getString(\"director\"));\n movie.setTitle(set.getString(\"title\"));\n movie.setYear(set.getInt(\"year\"));\n movies.add(movie);\n }\n } finally {\n conn.close();\n }\n return movies;\n }\n }\n\n## MoviesTest\n\n package org.superbiz.injection;\n \n import junit.framework.TestCase;\n \n import javax.ejb.embeddable.EJBContainer;\n import javax.naming.Context;\n import java.util.List;\n import java.util.Properties;\n \n //START SNIPPET: code\n public class MoviesTest extends TestCase {\n \n public void test() throws Exception {\n \n Properties p = new Properties();\n p.put(\"movieDatabase\", \"new://Resource?type=DataSource\");\n p.put(\"movieDatabase.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"movieDatabase.JdbcUrl\", \"jdbc:hsqldb:mem:moviedb\");\n \n Context context = EJBContainer.createEJBContainer(p).getContext();\n \n Movies movies = (Movies) context.lookup(\"java:global/injection-of-datasource/Movies\");\n \n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n movies.addMovie(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n movies.addMovie(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n \n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n \n for (Movie movie : list) {\n movies.deleteMovie(movie);\n }\n \n assertEquals(\"Movies.getMovies()\", 0, movies.getMovies().size());\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.injection.MoviesTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/injection-of-datasource\n INFO - openejb.base = /Users/dblevins/examples/injection-of-datasource\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/injection-of-datasource/target/classes\n INFO - Beginning load: /Users/dblevins/examples/injection-of-datasource/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/injection-of-datasource\n WARN - Method 'lookup' is not available for 'javax.annotation.Resource'. Probably using an older Runtime.\n INFO - Configuring Service(id=Default Stateful Container, type=Container, provider-id=Default Stateful Container)\n INFO - Auto-creating a container for bean Movies: Container(type=STATEFUL, id=Default Stateful Container)\n INFO - Auto-linking resource-ref 'java:comp/env/org.superbiz.injection.Movies/movieDatabase' in bean Movies to Resource(id=movieDatabase)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.injection.MoviesTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Enterprise application \"/Users/dblevins/examples/injection-of-datasource\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/injection-of-datasource\n INFO - Jndi(name=\"java:global/injection-of-datasource/Movies!org.superbiz.injection.Movies\")\n INFO - Jndi(name=\"java:global/injection-of-datasource/Movies\")\n INFO - Jndi(name=\"java:global/EjbModule1508028338/org.superbiz.injection.MoviesTest!org.superbiz.injection.MoviesTest\")\n INFO - Jndi(name=\"java:global/EjbModule1508028338/org.superbiz.injection.MoviesTest\")\n INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Created Ejb(deployment-id=org.superbiz.injection.MoviesTest, ejb-name=org.superbiz.injection.MoviesTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Started Ejb(deployment-id=org.superbiz.injection.MoviesTest, ejb-name=org.superbiz.injection.MoviesTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/injection-of-datasource)\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.276 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/injection-of-datasource"
},
{
"name":"datasource-definition",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/datasource-definition"
},
{
"name":"datasource-versioning",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/datasource-versioning"
},
{
"name":"datasource-ciphered-password",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/datasource-ciphered-password"
}
],
"decorators":[
{
"name":"decorators",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/decorators"
}
],
"definition":[
{
"name":"datasource-definition",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/datasource-definition"
}
],
"deltaspike":[
{
"name":"deltaspike-fullstack",
"readme":"Title: Apache DeltaSpike Demo\nNotice: Licensed to the Apache Software Foundation (ASF) under one\n or more contributor license agreements. See the NOTICE file\n distributed with this work for additional information\n regarding copyright ownership. The ASF licenses this file\n to you under the Apache License, Version 2.0 (the\n \"License\"); you may not use this file except in compliance\n with the License. You may obtain a copy of the License at\n .\n http://www.apache.org/licenses/LICENSE-2.0\n .\n Unless required by applicable law or agreed to in writing,\n software distributed under the License is distributed on an\n \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n KIND, either express or implied. See the License for the\n specific language governing permissions and limitations\n under the License.\n\n<h2>Steps to run the example</h2>\n\nBuild and start the demo:\n\n mvn clean package tomee:run\n\nOpen:\n\n http://localhost:8080/\n\nThis example shows how to improve JSF2/CDI/BV/JPA applications with features provided by Apache DeltaSpike and MyFaces ExtVal.\n\n<h2>Intro of Apache DeltaSpike and MyFaces ExtVal</h2>\n\nThe Apache DeltaSpike project hosts portable extensions for Contexts and Dependency Injection (CDI - JSR 299). DeltaSpike is a toolbox for your CDI application. Like CDI itself DeltaSpike is focused on type-safety. It is a modularized and extensible framework. So it's easy to choose the needed parts to facilitate the daily work in your project.\n\nMyFaces Extensions Validator (aka ExtVal) is a JSF centric validation framework which is compatible with JSF 1.x and JSF 2.x.\nThis example shows how it improves the default integration of Bean-Validation (JSR-303) with JSF2 as well as meta-data based cross-field validation.\n\n\n<h2>Illustrated Features</h2>\n\n<h3>Apache DeltaSpike</h3>\n\n<ul>\n <li><a href=\"./src/main/java/org/superbiz/deltaspike/view/config/Pages.java\" target=\"_blank\">Type-safe view-config</a></li>\n <li><a href=\"./src/main/java/org/superbiz/deltaspike/view/InfoPage.java\" target=\"_blank\">Type-safe (custom) view-meta-data</a></li>\n <li><a href=\"./src/main/java/org/superbiz/deltaspike/view/MenuBean.java\" target=\"_blank\">Type-safe navigation</a></li>\n <li><a href=\"./src/main/java/org/superbiz/deltaspike/CustomProjectStage.java\" target=\"_blank\">Type-safe custom project-stage</a></li>\n <li><a href=\"./src/main/java/org/superbiz/deltaspike/view/UserHolder.java\" target=\"_blank\">@WindowScoped</a></li>\n <li><a href=\"./src/main/java/org/superbiz/deltaspike/view/MenuBean.java\" target=\"_blank\">Controlling DeltaSpike grouped-conversations with GroupedConversationManager</a></li>\n <li><a href=\"./src/main/java/org/superbiz/deltaspike/view/FeedbackPage.java\" target=\"_blank\">@GroupedConversationScoped</a></li>\n <li><a href=\"./src/main/java/org/superbiz/deltaspike/view/FeedbackPage.java\" target=\"_blank\">Manual conversation handling</a></li>\n <li><a href=\"./src/main/java/org/superbiz/deltaspike/view/security/LoginAccessDecisionVoter.java\" target=\"_blank\">Secured pages (AccessDecisionVoter)</a></li>\n <li><a href=\"./src/main/java/org/superbiz/deltaspike/repository/Repository.java\" target=\"_blank\">@Transactional</a></li>\n <li><a href=\"./src/main/java/org/superbiz/deltaspike/view/RegistrationPage.java\" target=\"_blank\">I18n (type-safe messages)</a></li>\n <li><a href=\"./src/main/java/org/superbiz/deltaspike/domain/validation/UniqueUserNameValidator.java\" target=\"_blank\">Dependency-Injection for JSR303 (BV) constraint-validators</a></li>\n <li><a href=\"./src/main/java/org/superbiz/deltaspike/DebugPhaseListener.java\" target=\"_blank\">Dependency-Injection for JSF phase-listeners</a></li>\n</ul>\n\n<h3>Apache MyFaces ExtVal</h3>\n\n<ul>\n <li><a href=\"./src/main/java/org/superbiz/myfaces/view/RegistrationPage.java\" target=\"_blank\">Cross-Field validation (@Equals)</a></li>\n <li><a href=\"./src/main/java/org/superbiz/myfaces/view/RegistrationPage.java\" target=\"_blank\">Type-safe group-validation (@BeanValidation) for JSF action-methods</a></li>\n</ul>\n",
"url":"https://github.com/apache/tomee/tree/master/examples/deltaspike-fullstack"
},
{
"name":"deltaspike-exception-handling",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/deltaspike-exception-handling"
},
{
"name":"deltaspike-i18n",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/deltaspike-i18n"
},
{
"name":"deltaspike-configproperty",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/deltaspike-configproperty"
}
],
"descriptor":[
{
"name":"simple-stateless-with-descriptor",
"readme":"Title: Simple Stateless with Descriptor\n\nThis test is similar to simple-stateless, with two major differences. In this case all the classes are regular POJOs without annotations.\nThe EJB-specific metadata is provided via an XML descriptor. The second difference is the explicite use of Local and Remote interfaces. \n\n## CalculatorImpl\n\n package org.superbiz.calculator;\n \n /**\n * This is an EJB 3 stateless session bean, configured using an EJB 3\n * deployment descriptor as opposed to using annotations.\n * This EJB has 2 business interfaces: CalculatorRemote, a remote business\n * interface, and CalculatorLocal, a local business interface\n */\n public class CalculatorImpl implements CalculatorRemote, CalculatorLocal {\n \n public int sum(int add1, int add2) {\n return add1 + add2;\n }\n \n public int multiply(int mul1, int mul2) {\n return mul1 * mul2;\n }\n }\n\n## CalculatorLocal\n\n package org.superbiz.calculator;\n \n /**\n * This is an EJB 3 local business interface\n * This interface is specified using the business-local tag in the deployment descriptor\n */\n public interface CalculatorLocal {\n \n public int sum(int add1, int add2);\n \n public int multiply(int mul1, int mul2);\n }\n\n## CalculatorRemote\n\n package org.superbiz.calculator;\n \n \n /**\n * This is an EJB 3 remote business interface\n * This interface is specified using the business-local tag in the deployment descriptor\n */\n public interface CalculatorRemote {\n \n public int sum(int add1, int add2);\n \n public int multiply(int mul1, int mul2);\n }\n\n## ejb-jar.xml\n\nThe XML descriptor defines the EJB class and both local and remote interfaces.\n\n <ejb-jar xmlns=\"http://java.sun.com/xml/ns/javaee\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd\"\n version=\"3.0\">\n <enterprise-beans>\n <session>\n <ejb-name>CalculatorImpl</ejb-name>\n <business-local>org.superbiz.calculator.CalculatorLocal</business-local>\n <business-remote>org.superbiz.calculator.CalculatorRemote</business-remote>\n <ejb-class>org.superbiz.calculator.CalculatorImpl</ejb-class>\n <session-type>Stateless</session-type>\n <transaction-type>Container</transaction-type>\n </session>\n </enterprise-beans>\n </ejb-jar>\n\n \n\n## CalculatorTest\n\nTwo tests obtain a Local and Remote interface to the bean instance. This time an `InitialContext` object is directly created, \nas opposed to getting the context from `EJBContainer`, as we did in the previous example. \n\n package org.superbiz.calculator;\n \n import junit.framework.TestCase;\n \n import javax.naming.Context;\n import javax.naming.InitialContext;\n import java.util.Properties;\n \n public class CalculatorTest extends TestCase {\n \n private InitialContext initialContext;\n \n protected void setUp() throws Exception {\n Properties properties = new Properties();\n properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, \"org.apache.openejb.core.LocalInitialContextFactory\");\n \n initialContext = new InitialContext(properties);\n }\n\n /**\n * Lookup the Calculator bean via its remote home interface\n *\n * @throws Exception\n */\n public void testCalculatorViaRemoteInterface() throws Exception {\n Object object = initialContext.lookup(\"CalculatorImplRemote\");\n \n assertNotNull(object);\n assertTrue(object instanceof CalculatorRemote);\n CalculatorRemote calc = (CalculatorRemote) object;\n assertEquals(10, calc.sum(4, 6));\n assertEquals(12, calc.multiply(3, 4));\n }\n\n /**\n * Lookup the Calculator bean via its local home interface\n *\n * @throws Exception\n */\n public void testCalculatorViaLocalInterface() throws Exception {\n Object object = initialContext.lookup(\"CalculatorImplLocal\");\n \n assertNotNull(object);\n assertTrue(object instanceof CalculatorLocal);\n CalculatorLocal calc = (CalculatorLocal) object;\n assertEquals(10, calc.sum(4, 6));\n assertEquals(12, calc.multiply(3, 4));\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.calculator.CalculatorTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/simple-stateless-with-descriptor\n INFO - openejb.base = /Users/dblevins/examples/simple-stateless-with-descriptor\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/simple-stateless-with-descriptor/target/classes\n INFO - Beginning load: /Users/dblevins/examples/simple-stateless-with-descriptor/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/simple-stateless-with-descriptor/classpath.ear\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean CalculatorImpl: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Enterprise application \"/Users/dblevins/examples/simple-stateless-with-descriptor/classpath.ear\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/simple-stateless-with-descriptor/classpath.ear\n INFO - Jndi(name=CalculatorImplLocal) --> Ejb(deployment-id=CalculatorImpl)\n INFO - Jndi(name=global/classpath.ear/simple-stateless-with-descriptor/CalculatorImpl!org.superbiz.calculator.CalculatorLocal) --> Ejb(deployment-id=CalculatorImpl)\n INFO - Jndi(name=CalculatorImplRemote) --> Ejb(deployment-id=CalculatorImpl)\n INFO - Jndi(name=global/classpath.ear/simple-stateless-with-descriptor/CalculatorImpl!org.superbiz.calculator.CalculatorRemote) --> Ejb(deployment-id=CalculatorImpl)\n INFO - Jndi(name=global/classpath.ear/simple-stateless-with-descriptor/CalculatorImpl) --> Ejb(deployment-id=CalculatorImpl)\n INFO - Created Ejb(deployment-id=CalculatorImpl, ejb-name=CalculatorImpl, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=CalculatorImpl, ejb-name=CalculatorImpl, container=Default Stateless Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/simple-stateless-with-descriptor/classpath.ear)\n Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.475 sec\n \n Results :\n \n Tests run: 2, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/simple-stateless-with-descriptor"
},
{
"name":"simple-mdb-with-descriptor",
"readme":"Title: Simple MDB with Descriptor\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## ChatBean\n\n package org.superbiz.mdbdesc;\n \n import javax.jms.Connection;\n import javax.jms.ConnectionFactory;\n import javax.jms.DeliveryMode;\n import javax.jms.JMSException;\n import javax.jms.Message;\n import javax.jms.MessageListener;\n import javax.jms.MessageProducer;\n import javax.jms.Queue;\n import javax.jms.Session;\n import javax.jms.TextMessage;\n \n public class ChatBean implements MessageListener {\n \n private ConnectionFactory connectionFactory;\n \n private Queue answerQueue;\n \n public void onMessage(Message message) {\n try {\n \n final TextMessage textMessage = (TextMessage) message;\n final String question = textMessage.getText();\n \n if (\"Hello World!\".equals(question)) {\n \n respond(\"Hello, Test Case!\");\n } else if (\"How are you?\".equals(question)) {\n \n respond(\"I'm doing well.\");\n } else if (\"Still spinning?\".equals(question)) {\n \n respond(\"Once every day, as usual.\");\n }\n } catch (JMSException e) {\n throw new IllegalStateException(e);\n }\n }\n \n private void respond(String text) throws JMSException {\n \n Connection connection = null;\n Session session = null;\n \n try {\n connection = connectionFactory.createConnection();\n connection.start();\n \n // Create a Session\n session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);\n \n // Create a MessageProducer from the Session to the Topic or Queue\n MessageProducer producer = session.createProducer(answerQueue);\n producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);\n \n // Create a message\n TextMessage message = session.createTextMessage(text);\n \n // Tell the producer to send the message\n producer.send(message);\n } finally {\n // Clean up\n if (session != null) session.close();\n if (connection != null) connection.close();\n }\n }\n }\n\n## ejb-jar.xml\n\n <ejb-jar xmlns=\"http://java.sun.com/xml/ns/javaee\" metadata-complete=\"true\">\n <enterprise-beans>\n \n <message-driven>\n \n <ejb-name>ChatBean</ejb-name>\n <ejb-class>org.superbiz.mdbdesc.ChatBean</ejb-class>\n \n <messaging-type>javax.jms.MessageListener</messaging-type>\n \n <activation-config>\n <activation-config-property>\n <activation-config-property-name>destination</activation-config-property-name>\n <activation-config-property-value>ChatBean</activation-config-property-value>\n </activation-config-property>\n <activation-config-property>\n <activation-config-property-name>destinationType</activation-config-property-name>\n <activation-config-property-value>javax.jms.Queue</activation-config-property-value>\n </activation-config-property>\n </activation-config>\n \n <resource-ref>\n <res-ref-name>java:comp/env/org.superbiz.mdbdesc.ChatBean/connectionFactory</res-ref-name>\n <res-type>javax.jms.ConnectionFactory</res-type>\n <injection-target>\n <injection-target-class>org.superbiz.mdbdesc.ChatBean</injection-target-class>\n <injection-target-name>connectionFactory</injection-target-name>\n </injection-target>\n </resource-ref>\n \n <resource-env-ref>\n <resource-env-ref-name>java:comp/env/AnswerQueue</resource-env-ref-name>\n <resource-env-ref-type>javax.jms.Queue</resource-env-ref-type>\n <mapped-name>AnswerQueue</mapped-name>\n <injection-target>\n <injection-target-class>org.superbiz.mdbdesc.ChatBean</injection-target-class>\n <injection-target-name>answerQueue</injection-target-name>\n </injection-target>\n </resource-env-ref>\n \n </message-driven>\n \n </enterprise-beans>\n </ejb-jar>\n \n\n## ChatBeanTest\n\n package org.superbiz.mdb;\n \n import junit.framework.TestCase;\n \n import javax.annotation.Resource;\n import javax.ejb.embeddable.EJBContainer;\n import javax.jms.Connection;\n import javax.jms.ConnectionFactory;\n import javax.jms.JMSException;\n import javax.jms.MessageConsumer;\n import javax.jms.MessageProducer;\n import javax.jms.Queue;\n import javax.jms.Session;\n import javax.jms.TextMessage;\n \n public class ChatBeanTest extends TestCase {\n \n @Resource\n private ConnectionFactory connectionFactory;\n \n @Resource(name = \"ChatBean\")\n private Queue questionQueue;\n \n @Resource(name = \"AnswerQueue\")\n private Queue answerQueue;\n \n public void test() throws Exception {\n \n EJBContainer.createEJBContainer().getContext().bind(\"inject\", this);\n \n final Connection connection = connectionFactory.createConnection();\n \n connection.start();\n \n final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);\n \n final MessageProducer questions = session.createProducer(questionQueue);\n \n final MessageConsumer answers = session.createConsumer(answerQueue);\n \n \n sendText(\"Hello World!\", questions, session);\n \n assertEquals(\"Hello, Test Case!\", receiveText(answers));\n \n \n sendText(\"How are you?\", questions, session);\n \n assertEquals(\"I'm doing well.\", receiveText(answers));\n \n \n sendText(\"Still spinning?\", questions, session);\n \n assertEquals(\"Once every day, as usual.\", receiveText(answers));\n }\n \n private void sendText(String text, MessageProducer questions, Session session) throws JMSException {\n \n questions.send(session.createTextMessage(text));\n }\n \n private String receiveText(MessageConsumer answers) throws JMSException {\n \n return ((TextMessage) answers.receive(1000)).getText();\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.mdb.ChatBeanTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/simple-mdb-with-descriptor\n INFO - openejb.base = /Users/dblevins/examples/simple-mdb-with-descriptor\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/simple-mdb-with-descriptor/target/classes\n INFO - Beginning load: /Users/dblevins/examples/simple-mdb-with-descriptor/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/simple-mdb-with-descriptor\n WARN - Method 'lookup' is not available for 'javax.annotation.Resource'. Probably using an older Runtime.\n INFO - Configuring Service(id=Default MDB Container, type=Container, provider-id=Default MDB Container)\n INFO - Auto-creating a container for bean ChatBean: Container(type=MESSAGE, id=Default MDB Container)\n INFO - Configuring Service(id=Default JMS Resource Adapter, type=Resource, provider-id=Default JMS Resource Adapter)\n INFO - Configuring Service(id=Default JMS Connection Factory, type=Resource, provider-id=Default JMS Connection Factory)\n INFO - Auto-creating a Resource with id 'Default JMS Connection Factory' of type 'javax.jms.ConnectionFactory for 'ChatBean'.\n INFO - Auto-linking resource-ref 'java:comp/env/org.superbiz.mdbdesc.ChatBean/connectionFactory' in bean ChatBean to Resource(id=Default JMS Connection Factory)\n INFO - Configuring Service(id=AnswerQueue, type=Resource, provider-id=Default Queue)\n INFO - Auto-creating a Resource with id 'AnswerQueue' of type 'javax.jms.Queue for 'ChatBean'.\n INFO - Auto-linking resource-env-ref 'java:comp/env/AnswerQueue' in bean ChatBean to Resource(id=AnswerQueue)\n INFO - Configuring Service(id=ChatBean, type=Resource, provider-id=Default Queue)\n INFO - Auto-creating a Resource with id 'ChatBean' of type 'javax.jms.Queue for 'ChatBean'.\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.mdb.ChatBeanTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Auto-linking resource-ref 'java:comp/env/org.superbiz.mdb.ChatBeanTest/connectionFactory' in bean org.superbiz.mdb.ChatBeanTest to Resource(id=Default JMS Connection Factory)\n INFO - Auto-linking resource-env-ref 'java:comp/env/AnswerQueue' in bean org.superbiz.mdb.ChatBeanTest to Resource(id=AnswerQueue)\n INFO - Auto-linking resource-env-ref 'java:comp/env/ChatBean' in bean org.superbiz.mdb.ChatBeanTest to Resource(id=ChatBean)\n INFO - Enterprise application \"/Users/dblevins/examples/simple-mdb-with-descriptor\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/simple-mdb-with-descriptor\n INFO - Jndi(name=\"java:global/EjbModule1842275169/org.superbiz.mdb.ChatBeanTest!org.superbiz.mdb.ChatBeanTest\")\n INFO - Jndi(name=\"java:global/EjbModule1842275169/org.superbiz.mdb.ChatBeanTest\")\n INFO - Created Ejb(deployment-id=org.superbiz.mdb.ChatBeanTest, ejb-name=org.superbiz.mdb.ChatBeanTest, container=Default Managed Container)\n INFO - Created Ejb(deployment-id=ChatBean, ejb-name=ChatBean, container=Default MDB Container)\n INFO - Started Ejb(deployment-id=org.superbiz.mdb.ChatBeanTest, ejb-name=org.superbiz.mdb.ChatBeanTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=ChatBean, ejb-name=ChatBean, container=Default MDB Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/simple-mdb-with-descriptor)\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.914 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/simple-mdb-with-descriptor"
},
{
"name":"alternate-descriptors",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/alternate-descriptors"
},
{
"name":"lookup-of-ejbs-with-descriptor",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/lookup-of-ejbs-with-descriptor"
}
],
"design":[
{
"name":"bean-validation-design-by-contract",
"readme":"# Bean Validation - Design By Contract\n\nBean Validation (aka JSR 303) contains an optional appendix dealing with method validation.\n\nSome implementions of this JSR implement this appendix (Apache bval, Hibernate validator for example).\n\nOpenEJB provides an interceptor which allows you to use this feature to do design by contract.\n\n# Design by contract\n\nThe goal is to be able to configure with a finer grain your contract. In the example you specify\nthe minimum centimeters a sport man should jump at pole vaulting:\n\n @Local\n public interface PoleVaultingManager {\n int points(@Min(120) int centimeters);\n }\n\n# Usage\n\nTomEE and OpenEJB do not provide anymore `BeanValidationAppendixInterceptor` since\nBean Validation 1.1 does it (with a slighly different usage but the exact same feature).\n\nSo basically you don't need to configure anything to use it.\n# Errors\n\nIf a parameter is not validated an exception is thrown, it is an EJBException wrapping a ConstraintViolationException:\n\n try {\n gamesManager.addSportMan(\"I lose\", \"EN\");\n fail(\"no space should be in names\");\n } catch (EJBException wrappingException) {\n assertTrue(wrappingException.getCause() instanceof ConstraintViolationException);\n ConstraintViolationException exception = ConstraintViolationException.class.cast(wrappingException.getCausedByException());\n assertEquals(1, exception.getConstraintViolations().size());\n }\n\n# Example\n\n## OlympicGamesManager\n\n package org.superbiz.designbycontract;\n\n import javax.ejb.Stateless;\n import javax.validation.constraints.NotNull;\n import javax.validation.constraints.Pattern;\n import javax.validation.constraints.Size;\n\n @Stateless\n public class OlympicGamesManager {\n public String addSportMan(@Pattern(regexp = \"^[A-Za-z]+$\") String name, @Size(min = 2, max = 4) String country) {\n if (country.equals(\"USA\")) {\n return null;\n }\n return new StringBuilder(name).append(\" [\").append(country).append(\"]\").toString();\n }\n }\n\n## PoleVaultingManager\n\n package org.superbiz.designbycontract;\n\n import javax.ejb.Local;\n import javax.validation.constraints.Min;\n\n @Local\n public interface PoleVaultingManager {\n int points(@Min(120) int centimeters);\n }\n\n## PoleVaultingManagerBean\n\n package org.superbiz.designbycontract;\n\n import javax.ejb.Stateless;\n\n @Stateless\n public class PoleVaultingManagerBean implements PoleVaultingManager {\n @Override\n public int points(int centimeters) {\n return centimeters - 120;\n }\n }\n\n## OlympicGamesTest\n\n public class OlympicGamesTest {\n private static Context context;\n\n @EJB\n private OlympicGamesManager gamesManager;\n\n @EJB\n private PoleVaultingManager poleVaultingManager;\n\n @BeforeClass\n public static void start() {\n Properties properties = new Properties();\n properties.setProperty(BeanContext.USER_INTERCEPTOR_KEY, BeanValidationAppendixInterceptor.class.getName());\n context = EJBContainer.createEJBContainer(properties).getContext();\n }\n\n @Before\n public void inject() throws Exception {\n context.bind(\"inject\", this);\n }\n\n @AfterClass\n public static void stop() throws Exception {\n if (context != null) {\n context.close();\n }\n }\n\n @Test\n public void sportMenOk() throws Exception {\n assertEquals(\"IWin [FR]\", gamesManager.addSportMan(\"IWin\", \"FR\"));\n }\n\n @Test\n public void sportMenKoBecauseOfName() throws Exception {\n try {\n gamesManager.addSportMan(\"I lose\", \"EN\");\n fail(\"no space should be in names\");\n } catch (EJBException wrappingException) {\n assertTrue(wrappingException.getCause() instanceof ConstraintViolationException);\n ConstraintViolationException exception = ConstraintViolationException.class.cast(wrappingException.getCausedByException());\n assertEquals(1, exception.getConstraintViolations().size());\n }\n }\n\n @Test\n public void sportMenKoBecauseOfCountry() throws Exception {\n try {\n gamesManager.addSportMan(\"ILoseTwo\", \"TOO-LONG\");\n fail(\"country should be between 2 and 4 characters\");\n } catch (EJBException wrappingException) {\n assertTrue(wrappingException.getCause() instanceof ConstraintViolationException);\n ConstraintViolationException exception = ConstraintViolationException.class.cast(wrappingException.getCausedByException());\n assertEquals(1, exception.getConstraintViolations().size());\n }\n }\n\n @Test\n public void polVaulting() throws Exception {\n assertEquals(100, poleVaultingManager.points(220));\n }\n\n @Test\n public void tooShortPolVaulting() throws Exception {\n try {\n poleVaultingManager.points(119);\n fail(\"the jump is too short\");\n } catch (EJBException wrappingException) {\n assertTrue(wrappingException.getCause() instanceof ConstraintViolationException);\n ConstraintViolationException exception = ConstraintViolationException.class.cast(wrappingException.getCausedByException());\n assertEquals(1, exception.getConstraintViolations().size());\n }\n }\n }\n\n# Running\n\n\n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running OlympicGamesTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/bean-validation-design-by-contract\n INFO - openejb.base = /Users/dblevins/examples/bean-validation-design-by-contract\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/bean-validation-design-by-contract/target/classes\n INFO - Beginning load: /Users/dblevins/examples/bean-validation-design-by-contract/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/bean-validation-design-by-contract\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean PoleVaultingManagerBean: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean OlympicGamesTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Enterprise application \"/Users/dblevins/examples/bean-validation-design-by-contract\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/bean-validation-design-by-contract\n INFO - Jndi(name=\"java:global/bean-validation-design-by-contract/PoleVaultingManagerBean!org.superbiz.designbycontract.PoleVaultingManager\")\n INFO - Jndi(name=\"java:global/bean-validation-design-by-contract/PoleVaultingManagerBean\")\n INFO - Jndi(name=\"java:global/bean-validation-design-by-contract/OlympicGamesManager!org.superbiz.designbycontract.OlympicGamesManager\")\n INFO - Jndi(name=\"java:global/bean-validation-design-by-contract/OlympicGamesManager\")\n INFO - Jndi(name=\"java:global/EjbModule236054577/OlympicGamesTest!OlympicGamesTest\")\n INFO - Jndi(name=\"java:global/EjbModule236054577/OlympicGamesTest\")\n INFO - Created Ejb(deployment-id=OlympicGamesManager, ejb-name=OlympicGamesManager, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=PoleVaultingManagerBean, ejb-name=PoleVaultingManagerBean, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=OlympicGamesTest, ejb-name=OlympicGamesTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=OlympicGamesManager, ejb-name=OlympicGamesManager, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=PoleVaultingManagerBean, ejb-name=PoleVaultingManagerBean, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=OlympicGamesTest, ejb-name=OlympicGamesTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/bean-validation-design-by-contract)\n Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.245 sec\n\n Results :\n\n Tests run: 5, Failures: 0, Errors: 0, Skipped: 0\n",
"url":"https://github.com/apache/tomee/tree/master/examples/bean-validation-design-by-contract"
}
],
"disposes":[
{
"name":"cdi-produces-disposes",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/cdi-produces-disposes"
}
],
"dynamic":[
{
"name":"dynamic-implementation",
"readme":"Title: Dynamic Implementation\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## SocialBean\n\n package org.superbiz.dynamic;\n \n import org.apache.openejb.api.Proxy;\n \n import javax.ejb.Singleton;\n import javax.interceptor.Interceptors;\n \n @Singleton\n @Proxy(SocialHandler.class)\n @Interceptors(SocialInterceptor.class)\n public interface SocialBean {\n public String facebookStatus();\n \n public String twitterStatus();\n \n public String status();\n }\n\n## SocialHandler\n\n package org.superbiz.dynamic;\n \n import java.lang.reflect.InvocationHandler;\n import java.lang.reflect.Method;\n \n public class SocialHandler implements InvocationHandler {\n @Override\n public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {\n String mtd = method.getName();\n if (mtd.toLowerCase().contains(\"facebook\")) {\n return \"You think you have a life!\";\n } else if (mtd.toLowerCase().contains(\"twitter\")) {\n return \"Wow, you eat pop corn!\";\n }\n return \"Hey, you have no virtual friend!\";\n }\n }\n\n## SocialInterceptor\n\n packagenull\n }\n\n## SocialTest\n\n package org.superbiz.dynamic;\n \n import org.junit.AfterClass;\n import org.junit.BeforeClass;\n import org.junit.Test;\n \n import javax.ejb.embeddable.EJBContainer;\n \n import static junit.framework.Assert.assertTrue;\n \n public class SocialTest {\n private static SocialBean social;\n private static EJBContainer container;\n \n @BeforeClass\n public static void init() throws Exception {\n container = EJBContainer.createEJBContainer();\n social = (SocialBean) container.getContext().lookup(\"java:global/dynamic-implementation/SocialBean\");\n }\n \n @AfterClass\n public static void close() {\n container.close();\n }\n \n @Test\n public void simple() {\n assertTrue(social.facebookStatus().contains(\"think\"));\n assertTrue(social.twitterStatus().contains(\"eat\"));\n assertTrue(social.status().contains(\"virtual\"));\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.dynamic.SocialTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/dynamic-implementation\n INFO - openejb.base = /Users/dblevins/examples/dynamic-implementation\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/dynamic-implementation/target/classes\n INFO - Beginning load: /Users/dblevins/examples/dynamic-implementation/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/dynamic-implementation\n INFO - Configuring Service(id=Default Singleton Container, type=Container, provider-id=Default Singleton Container)\n INFO - Auto-creating a container for bean SocialBean: Container(type=SINGLETON, id=Default Singleton Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.dynamic.SocialTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Enterprise application \"/Users/dblevins/examples/dynamic-implementation\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/dynamic-implementation\n INFO - Jndi(name=\"java:global/dynamic-implementation/SocialBean!org.superbiz.dynamic.SocialBean\")\n INFO - Jndi(name=\"java:global/dynamic-implementation/SocialBean\")\n INFO - Jndi(name=\"java:global/EjbModule236706648/org.superbiz.dynamic.SocialTest!org.superbiz.dynamic.SocialTest\")\n INFO - Jndi(name=\"java:global/EjbModule236706648/org.superbiz.dynamic.SocialTest\")\n INFO - Created Ejb(deployment-id=org.superbiz.dynamic.SocialTest, ejb-name=org.superbiz.dynamic.SocialTest, container=Default Managed Container)\n INFO - Created Ejb(deployment-id=SocialBean, ejb-name=SocialBean, container=Default Singleton Container)\n INFO - Started Ejb(deployment-id=org.superbiz.dynamic.SocialTest, ejb-name=org.superbiz.dynamic.SocialTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=SocialBean, ejb-name=SocialBean, container=Default Singleton Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/dynamic-implementation)\n INFO - Undeploying app: /Users/dblevins/examples/dynamic-implementation\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.107 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/dynamic-implementation"
},
{
"name":"dynamic-datasource-routing",
"readme":"Title: Dynamic Datasource Routing\n\nThe TomEE dynamic datasource api aims to allow to use multiple data sources as one from an application point of view.\n\nIt can be useful for technical reasons (load balancing for example) or more generally\nfunctionnal reasons (filtering, aggregation, enriching...). However please note you can choose\nonly one datasource by transaction. It means the goal of this feature is not to switch more than\nonce of datasource in a transaction. The following code will not work:\n\n @Stateless\n public class MyEJB {\n @Resource private MyRouter router;\n @PersistenceContext private EntityManager em;\n\n public void workWithDataSources() {\n router.setDataSource(\"ds1\");\n em.persist(new MyEntity());\n\n router.setDataSource(\"ds2\"); // same transaction -> this invocation doesn't work\n em.persist(new MyEntity());\n }\n }\n\nIn this example the implementation simply use a datasource from its name and needs to be set before using any JPA\noperation in the transaction (to keep the logic simple in the example).\n\n# The implementation of the Router\n\nOur router has two configuration parameters:\n* a list of jndi names representing datasources to use\n* a default datasource to use\n\n## Router implementation\n\nThe interface Router (`org.apache.openejb.resource.jdbc.Router`) has only one method to implement, `public DataSource getDataSource()`\n\nOur `DeterminedRouter` implementation uses a ThreadLocal to manage the currently used datasource. Keep in mind JPA used more than once the getDatasource() method\nfor one operation. To change the datasource in one transaction is dangerous and should be avoid.\n\n package org.superbiz.dynamicdatasourcerouting;\n\n import org.apache.openejb.resource.jdbc.AbstractRouter;\n\n import javax.naming.NamingException;\n import javax.sql.DataSource;\n import java.util.Map;\n import java.util.concurrent.ConcurrentHashMap;\n\n public class DeterminedRouter extends AbstractRouter {\n private String dataSourceNames;\n private String defaultDataSourceName;\n private Map<String, DataSource> dataSources = null;\n private ThreadLocal<DataSource> currentDataSource = new ThreadLocal<DataSource>();\n\n /**\n * @param datasourceList datasource resource name, separator is a space\n */\n public void setDataSourceNames(String datasourceList) {\n dataSourceNames = datasourceList;\n }\n\n /**\n * lookup datasource in openejb resources\n */\n private void init() {\n dataSources = new ConcurrentHashMap<String, DataSource>();\n for (String ds : dataSourceNames.split(\" \")) {\n try {\n Object o = getOpenEJBResource(ds);\n if (o instanceof DataSource) {\n dataSources.put(ds, DataSource.class.cast(o));\n }\n } catch (NamingException e) {\n // ignored\n }\n }\n }\n\n /**\n * @return the user selected data source if it is set\n * or the default one\n * @throws IllegalArgumentException if the data source is not found\n */\n @Override\n public DataSource getDataSource() {\n // lazy init of routed datasources\n if (dataSources == null) {\n init();\n }\n\n // if no datasource is selected use the default one\n if (currentDataSource.get() == null) {\n if (dataSources.containsKey(defaultDataSourceName)) {\n return dataSources.get(defaultDataSourceName);\n\n } else {\n throw new IllegalArgumentException(\"you have to specify at least one datasource\");\n }\n }\n\n // the developper set the datasource to use\n return currentDataSource.get();\n }\n\n /**\n *\n * @param datasourceName data source name\n */\n public void setDataSource(String datasourceName) {\n if (dataSources == null) {\n init();\n }\n if (!dataSources.containsKey(datasourceName)) {\n throw new IllegalArgumentException(\"data source called \" + datasourceName + \" can't be found.\");\n }\n DataSource ds = dataSources.get(datasourceName);\n currentDataSource.set(ds);\n }\n\n /**\n * reset the data source\n */\n public void clear() {\n currentDataSource.remove();\n }\n\n public void setDefaultDataSourceName(String name) {\n this.defaultDataSourceName = name;\n }\n }\n\n## Declaring the implementation\n\nTo be able to use your router as a resource you need to provide a service configuration. It is done in a file\nyou can find in META-INF/org.router/ and called service-jar.xml\n(for your implementation you can of course change the package name).\n\nIt contains the following code:\n\n <ServiceJar>\n <ServiceProvider id=\"DeterminedRouter\" <!-- the name you want to use -->\n service=\"Resource\"\n type=\"org.apache.openejb.resource.jdbc.Router\"\n class-name=\"org.superbiz.dynamicdatasourcerouting.DeterminedRouter\"> <!-- implementation class -->\n\n # the parameters\n\n DataSourceNames\n DefaultDataSourceName\n </ServiceProvider>\n </ServiceJar>\n\n\n# Using the Router\n\nHere we have a `RoutedPersister` stateless bean which uses our `DeterminedRouter`\n\n package org.superbiz.dynamicdatasourcerouting;\n\n import javax.annotation.Resource;\n import javax.ejb.Stateless;\n import javax.persistence.EntityManager;\n import javax.persistence.PersistenceContext;\n\n @Stateless\n public class RoutedPersister {\n @PersistenceContext(unitName = \"router\")\n private EntityManager em;\n\n @Resource(name = \"My Router\", type = DeterminedRouter.class)\n private DeterminedRouter router;\n\n public void persist(int id, String name, String ds) {\n router.setDataSource(ds);\n em.persist(new Person(id, name));\n }\n }\n\n# The test\n\nIn test mode and using property style configuration the foolowing configuration is used:\n\n public class DynamicDataSourceTest {\n @Test\n public void route() throws Exception {\n String[] databases = new String[]{\"database1\", \"database2\", \"database3\"};\n\n Properties properties = new Properties();\n properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, LocalInitialContextFactory.class.getName());\n\n // resources\n // datasources\n for (int i = 1; i <= databases.length; i++) {\n String dbName = databases[i - 1];\n properties.setProperty(dbName, \"new://Resource?type=DataSource\");\n dbName += \".\";\n properties.setProperty(dbName + \"JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n properties.setProperty(dbName + \"JdbcUrl\", \"jdbc:hsqldb:mem:db\" + i);\n properties.setProperty(dbName + \"UserName\", \"sa\");\n properties.setProperty(dbName + \"Password\", \"\");\n properties.setProperty(dbName + \"JtaManaged\", \"true\");\n }\n\n // router\n properties.setProperty(\"My Router\", \"new://Resource?provider=org.router:DeterminedRouter&type=\" + DeterminedRouter.class.getName());\n properties.setProperty(\"My Router.DatasourceNames\", \"database1 database2 database3\");\n properties.setProperty(\"My Router.DefaultDataSourceName\", \"database1\");\n\n // routed datasource\n properties.setProperty(\"Routed Datasource\", \"new://Resource?provider=RoutedDataSource&type=\" + Router.class.getName());\n properties.setProperty(\"Routed Datasource.Router\", \"My Router\");\n\n Context ctx = EJBContainer.createEJBContainer(properties).getContext();\n RoutedPersister ejb = (RoutedPersister) ctx.lookup(\"java:global/dynamic-datasource-routing/RoutedPersister\");\n for (int i = 0; i < 18; i++) {\n // persisting a person on database db -> kind of manual round robin\n String name = \"record \" + i;\n String db = databases[i % 3];\n ejb.persist(i, name, db);\n }\n\n // assert database records number using jdbc\n for (int i = 1; i <= databases.length; i++) {\n Connection connection = DriverManager.getConnection(\"jdbc:hsqldb:mem:db\" + i, \"sa\", \"\");\n Statement st = connection.createStatement();\n ResultSet rs = st.executeQuery(\"select count(*) from PERSON\");\n rs.next();\n assertEquals(6, rs.getInt(1));\n st.close();\n connection.close();\n }\n\n ctx.close();\n }\n }\n\n# Configuration via openejb.xml\n\nThe testcase above uses properties for configuration. The identical way to do it via the `conf/openejb.xml` is as follows:\n\n <!-- Router and datasource -->\n <Resource id=\"My Router\" type=\"org.apache.openejb.router.test.DynamicDataSourceTest$DeterminedRouter\" provider=\"org.routertest:DeterminedRouter\">\n DatasourceNames = database1 database2 database3\n DefaultDataSourceName = database1\n </Resource>\n <Resource id=\"Routed Datasource\" type=\"org.apache.openejb.resource.jdbc.Router\" provider=\"RoutedDataSource\">\n Router = My Router\n </Resource>\n\n <!-- real datasources -->\n <Resource id=\"database1\" type=\"DataSource\">\n JdbcDriver = org.hsqldb.jdbcDriver\n JdbcUrl = jdbc:hsqldb:mem:db1\n UserName = sa\n Password\n JtaManaged = true\n </Resource>\n <Resource id=\"database2\" type=\"DataSource\">\n JdbcDriver = org.hsqldb.jdbcDriver\n JdbcUrl = jdbc:hsqldb:mem:db2\n UserName = sa\n Password\n JtaManaged = true\n </Resource>\n <Resource id=\"database3\" type=\"DataSource\">\n JdbcDriver = org.hsqldb.jdbcDriver\n JdbcUrl = jdbc:hsqldb:mem:db3\n UserName = sa\n Password\n JtaManaged = true\n </Resource>\n\n\n\n\n## Some hack for OpenJPA\n\nUsing more than one datasource behind one EntityManager means the databases are already created. If it is not the case,\nthe JPA provider has to create the datasource at boot time.\n\nHibernate do it so if you declare your databases it will work. However with OpenJPA\n(the default JPA provider for OpenEJB), the creation is lazy and it happens only once so when you'll switch of database\nit will no more work.\n\nOf course OpenEJB provides @Singleton and @Startup features of Java EE 6 and we can do a bean just making a simple find,\neven on none existing entities, just to force the database creation:\n\n @Startup\n @Singleton\n public class BoostrapUtility {\n // inject all real databases\n\n @PersistenceContext(unitName = \"db1\")\n private EntityManager em1;\n\n @PersistenceContext(unitName = \"db2\")\n private EntityManager em2;\n\n @PersistenceContext(unitName = \"db3\")\n private EntityManager em3;\n\n // force database creation\n\n @PostConstruct\n @TransactionAttribute(TransactionAttributeType.SUPPORTS)\n public void initDatabase() {\n em1.find(Person.class, 0);\n em2.find(Person.class, 0);\n em3.find(Person.class, 0);\n }\n }\n\n## Using the routed datasource\n\nNow you configured the way you want to route your JPA operation, you registered the resources and you initialized\nyour databases you can use it and see how it is simple:\n\n @Stateless\n public class RoutedPersister {\n // injection of the \"proxied\" datasource\n @PersistenceContext(unitName = \"router\")\n private EntityManager em;\n\n // injection of the router you need it to configured the database\n @Resource(name = \"My Router\", type = DeterminedRouter.class)\n private DeterminedRouter router;\n\n public void persist(int id, String name, String ds) {\n router.setDataSource(ds); // configuring the database for the current transaction\n em.persist(new Person(id, name)); // will use ds database automatically\n }\n }\n\n# Running\n\n\n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.dynamicdatasourcerouting.DynamicDataSourceTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/dynamic-datasource-routing\n INFO - openejb.base = /Users/dblevins/examples/dynamic-datasource-routing\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=My Router, type=Resource, provider-id=DeterminedRouter)\n INFO - Configuring Service(id=database3, type=Resource, provider-id=Default JDBC Database)\n INFO - Configuring Service(id=database2, type=Resource, provider-id=Default JDBC Database)\n INFO - Configuring Service(id=Routed Datasource, type=Resource, provider-id=RoutedDataSource)\n INFO - Configuring Service(id=database1, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/dynamic-datasource-routing/target/classes\n INFO - Beginning load: /Users/dblevins/examples/dynamic-datasource-routing/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/dynamic-datasource-routing\n WARN - Method 'lookup' is not available for 'javax.annotation.Resource'. Probably using an older Runtime.\n INFO - Configuring Service(id=Default Singleton Container, type=Container, provider-id=Default Singleton Container)\n INFO - Auto-creating a container for bean BoostrapUtility: Container(type=SINGLETON, id=Default Singleton Container)\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean RoutedPersister: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Auto-linking resource-ref 'java:comp/env/My Router' in bean RoutedPersister to Resource(id=My Router)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.dynamicdatasourcerouting.DynamicDataSourceTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring PersistenceUnit(name=router)\n INFO - Configuring PersistenceUnit(name=db1)\n INFO - Auto-creating a Resource with id 'database1NonJta' of type 'DataSource for 'db1'.\n INFO - Configuring Service(id=database1NonJta, type=Resource, provider-id=database1)\n INFO - Adjusting PersistenceUnit db1 <non-jta-data-source> to Resource ID 'database1NonJta' from 'null'\n INFO - Configuring PersistenceUnit(name=db2)\n INFO - Auto-creating a Resource with id 'database2NonJta' of type 'DataSource for 'db2'.\n INFO - Configuring Service(id=database2NonJta, type=Resource, provider-id=database2)\n INFO - Adjusting PersistenceUnit db2 <non-jta-data-source> to Resource ID 'database2NonJta' from 'null'\n INFO - Configuring PersistenceUnit(name=db3)\n INFO - Auto-creating a Resource with id 'database3NonJta' of type 'DataSource for 'db3'.\n INFO - Configuring Service(id=database3NonJta, type=Resource, provider-id=database3)\n INFO - Adjusting PersistenceUnit db3 <non-jta-data-source> to Resource ID 'database3NonJta' from 'null'\n INFO - Enterprise application \"/Users/dblevins/examples/dynamic-datasource-routing\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/dynamic-datasource-routing\n INFO - PersistenceUnit(name=router, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 504ms\n INFO - PersistenceUnit(name=db1, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 11ms\n INFO - PersistenceUnit(name=db2, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 7ms\n INFO - PersistenceUnit(name=db3, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 6ms\n INFO - Jndi(name=\"java:global/dynamic-datasource-routing/BoostrapUtility!org.superbiz.dynamicdatasourcerouting.BoostrapUtility\")\n INFO - Jndi(name=\"java:global/dynamic-datasource-routing/BoostrapUtility\")\n INFO - Jndi(name=\"java:global/dynamic-datasource-routing/RoutedPersister!org.superbiz.dynamicdatasourcerouting.RoutedPersister\")\n INFO - Jndi(name=\"java:global/dynamic-datasource-routing/RoutedPersister\")\n INFO - Jndi(name=\"java:global/EjbModule1519652738/org.superbiz.dynamicdatasourcerouting.DynamicDataSourceTest!org.superbiz.dynamicdatasourcerouting.DynamicDataSourceTest\")\n INFO - Jndi(name=\"java:global/EjbModule1519652738/org.superbiz.dynamicdatasourcerouting.DynamicDataSourceTest\")\n INFO - Created Ejb(deployment-id=RoutedPersister, ejb-name=RoutedPersister, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=org.superbiz.dynamicdatasourcerouting.DynamicDataSourceTest, ejb-name=org.superbiz.dynamicdatasourcerouting.DynamicDataSourceTest, container=Default Managed Container)\n INFO - Created Ejb(deployment-id=BoostrapUtility, ejb-name=BoostrapUtility, container=Default Singleton Container)\n INFO - Started Ejb(deployment-id=RoutedPersister, ejb-name=RoutedPersister, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=org.superbiz.dynamicdatasourcerouting.DynamicDataSourceTest, ejb-name=org.superbiz.dynamicdatasourcerouting.DynamicDataSourceTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=BoostrapUtility, ejb-name=BoostrapUtility, container=Default Singleton Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/dynamic-datasource-routing)\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.504 sec\n\n Results :\n\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n\n",
"url":"https://github.com/apache/tomee/tree/master/examples/dynamic-datasource-routing"
},
{
"name":"dynamic-dao-implementation",
"readme":"Title: Dynamic DAO Implementation\n\nMany aspects of Data Access Objects (DAOs) are very repetitive and boiler plate. As a fun and experimental feature, TomEE supports dynamically implementing an interface\nthat is seen to have standard DAO-style methods.\n\nThe interface has to be annotated with @PersistenceContext to define which EntityManager to use.\n\nMethods should respect these conventions:\n\n * void save(Foo foo): persist foo\n * Foo update(Foo foo): merge foo\n * void delete(Foo foo): remove foo, if foo is detached it tries to attach it\n * Collection<Foo>|Foo namedQuery(String name[, Map<String, ?> params, int first, int max]): run the named query called name, params contains bindings, first and max are used for magination. Last three parameters are optionnals\n * Collection<Foo>|Foo nativeQuery(String name[, Map<String, ?> params, int first, int max]): run the native query called name, params contains bindings, first and max are used for magination. Last three parameters are optionnals\n * Collection<Foo>|Foo query(String value [, Map<String, ?> params, int first, int max]): run the query put as first parameter, params contains bindings, first and max are used for magination. Last three parameters are optionnals\n * Collection<Foo> findAll([int first, int max]): find all Foo, parameters are used for pagination\n * Collection<Foo> findByBar1AndBar2AndBar3(<bar 1 type> bar1, <bar 2 type> bar2, <bar3 type> bar3 [, int first, int max]): find all Foo with specified field values for bar1, bar2, bar3.\n\nDynamic finder can have as much as you want field constraints. For String like is used and for other type equals is used.\n\n# Example\n\n## User\n\n package org.superbiz.dynamic;\n \n import javax.persistence.Entity;\n import javax.persistence.GeneratedValue;\n import javax.persistence.Id;\n import javax.persistence.NamedQueries;\n import javax.persistence.NamedQuery;\n \n @Entity\n @NamedQueries({\n @NamedQuery(name = \"dynamic-ejb-impl-test.query\", query = \"SELECT u FROM User AS u WHERE u.name LIKE :name\"),\n @NamedQuery(name = \"dynamic-ejb-impl-test.all\", query = \"SELECT u FROM User AS u\")\n })\n public class User {\n @Id\n @GeneratedValue\n private long id;\n private String name;\n private int age;\n\n public long getId() {\n return id;\n }\n\n public void setId(long id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public int getAge() {\n return age;\n }\n\n public void setAge(int age) {\n this.age = age;\n }\n }\n\n## UserDao\n\n package org.superbiz.dynamic;\n \n \n import javax.ejb.Stateless;\n import javax.persistence.PersistenceContext;\n import java.util.Collection;\n import java.util.Map;\n \n @Stateless\n @PersistenceContext(name = \"dynamic\")\n public interface UserDao {\n User findById(long id);\n \n Collection<User> findByName(String name);\n \n Collection<User> findByNameAndAge(String name, int age);\n \n Collection<User> findAll();\n \n Collection<User> findAll(int first, int max);\n \n Collection<User> namedQuery(String name, Map<String, ?> params, int first, int max);\n \n Collection<User> namedQuery(String name, int first, int max, Map<String, ?> params);\n \n Collection<User> namedQuery(String name, Map<String, ?> params);\n \n Collection<User> namedQuery(String name);\n \n Collection<User> query(String value, Map<String, ?> params);\n \n void save(User u);\n \n void delete(User u);\n \n User update(User u);\n }\n\n## persistence.xml\n\n <persistence version=\"2.0\"\n xmlns=\"http://java.sun.com/xml/ns/persistence\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"\n http://java.sun.com/xml/ns/persistence\n http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd\">\n <persistence-unit name=\"dynamic\" transaction-type=\"JTA\">\n <jta-data-source>jdbc/dynamicDB</jta-data-source>\n <class>org.superbiz.dynamic.User</class>\n <properties>\n <property name=\"openjpa.jdbc.SynchronizeMappings\" value=\"buildSchema(ForeignKeys=true)\"/>\n </properties>\n </persistence-unit>\n </persistence>\n \n\n## DynamicUserDaoTest\n\n package org.superbiz.dynamic;\n \n import junit.framework.Assert;\n import org.junit.BeforeClass;\n import org.junit.Test;\n \n import javax.ejb.EJBException;\n import javax.ejb.Stateless;\n import javax.ejb.embeddable.EJBContainer;\n import javax.naming.Context;\n import javax.persistence.EntityManager;\n import javax.persistence.NoResultException;\n import javax.persistence.PersistenceContext;\n import java.util.Collection;\n import java.util.HashMap;\n import java.util.Map;\n import java.util.Properties;\n \n import static junit.framework.Assert.assertEquals;\n import static junit.framework.Assert.assertNotNull;\n import static junit.framework.Assert.assertTrue;\n \n public class DynamicUserDaoTest {\n private static UserDao dao;\n private static Util util;\n \n @BeforeClass\n public static void init() throws Exception {\n final Properties p = new Properties();\n p.put(\"jdbc/dynamicDB\", \"new://Resource?type=DataSource\");\n p.put(\"jdbc/dynamicDB.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"jdbc/dynamicDB.JdbcUrl\", \"jdbc:hsqldb:mem:moviedb\");\n p.put(\"jdbc/dynamicDB.UserName\", \"sa\");\n p.put(\"jdbc/dynamicDB.Password\", \"\");\n \n final Context context = EJBContainer.createEJBContainer(p).getContext();\n dao = (UserDao) context.lookup(\"java:global/dynamic-dao-implementation/UserDao\");\n util = (Util) context.lookup(\"java:global/dynamic-dao-implementation/Util\");\n \n util.init(); // init database\n }\n \n @Test\n public void simple() {\n User user = dao.findById(1);\n assertNotNull(user);\n assertEquals(1, user.getId());\n }\n \n @Test\n public void findAll() {\n Collection<User> users = dao.findAll();\n assertEquals(10, users.size());\n }\n \n @Test\n public void pagination() {\n Collection<User> users = dao.findAll(0, 5);\n assertEquals(5, users.size());\n \n users = dao.findAll(6, 1);\n assertEquals(1, users.size());\n assertEquals(7, users.iterator().next().getId());\n }\n \n @Test\n public void persist() {\n User u = new User();\n dao.save(u);\n assertNotNull(u.getId());\n util.remove(u);\n }\n \n @Test\n public void remove() {\n User u = new User();\n dao.save(u);\n assertNotNull(u.getId());\n dao.delete(u);\n try {\n dao.findById(u.getId());\n Assert.fail();\n } catch (EJBException ee) {\n assertTrue(ee.getCause() instanceof NoResultException);\n }\n }\n \n @Test\n public void merge() {\n User u = new User();\n u.setAge(1);\n dao.save(u);\n assertEquals(1, u.getAge());\n assertNotNull(u.getId());\n \n u.setAge(2);\n dao.update(u);\n assertEquals(2, u.getAge());\n \n dao.delete(u);\n }\n \n @Test\n public void oneCriteria() {\n Collection<User> users = dao.findByName(\"foo\");\n assertEquals(4, users.size());\n for (User user : users) {\n assertEquals(\"foo\", user.getName());\n }\n }\n \n @Test\n public void twoCriteria() {\n Collection<User> users = dao.findByNameAndAge(\"bar-1\", 1);\n assertEquals(1, users.size());\n \n User user = users.iterator().next();\n assertEquals(\"bar-1\", user.getName());\n assertEquals(1, user.getAge());\n }\n \n @Test\n public void query() {\n Map<String, Object> params = new HashMap<String, Object>();\n params.put(\"name\", \"foo\");\n \n Collection<User> users = dao.namedQuery(\"dynamic-ejb-impl-test.query\", params, 0, 100);\n assertEquals(4, users.size());\n \n users = dao.namedQuery(\"dynamic-ejb-impl-test.query\", params);\n assertEquals(4, users.size());\n \n users = dao.namedQuery(\"dynamic-ejb-impl-test.query\", params, 0, 2);\n assertEquals(2, users.size());\n \n users = dao.namedQuery(\"dynamic-ejb-impl-test.query\", 0, 2, params);\n assertEquals(2, users.size());\n \n users = dao.namedQuery(\"dynamic-ejb-impl-test.all\");\n assertEquals(10, users.size());\n \n params.remove(\"name\");\n params.put(\"age\", 1);\n users = dao.query(\"SELECT u FROM User AS u WHERE u.age = :age\", params);\n assertEquals(3, users.size());\n }\n \n @Stateless\n public static class Util {\n @PersistenceContext\n private EntityManager em;\n \n public void remove(User o) {\n em.remove(em.find(User.class, o.getId()));\n }\n \n public void init() {\n for (int i = 0; i < 10; i++) {\n User u = new User();\n u.setAge(i % 4);\n if (i % 3 == 0) {\n u.setName(\"foo\");\n } else {\n u.setName(\"bar-\" + i);\n }\n em.persist(u);\n }\n }\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.dynamic.DynamicUserDaoTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/dynamic-dao-implementation\n INFO - openejb.base = /Users/dblevins/examples/dynamic-dao-implementation\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=jdbc/dynamicDB, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/dynamic-dao-implementation/target/classes\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/dynamic-dao-implementation/target/test-classes\n INFO - Beginning load: /Users/dblevins/examples/dynamic-dao-implementation/target/classes\n INFO - Beginning load: /Users/dblevins/examples/dynamic-dao-implementation/target/test-classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/dynamic-dao-implementation\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean UserDao: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.dynamic.DynamicUserDaoTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring PersistenceUnit(name=dynamic)\n INFO - Auto-creating a Resource with id 'jdbc/dynamicDBNonJta' of type 'DataSource for 'dynamic'.\n INFO - Configuring Service(id=jdbc/dynamicDBNonJta, type=Resource, provider-id=jdbc/dynamicDB)\n INFO - Adjusting PersistenceUnit dynamic <non-jta-data-source> to Resource ID 'jdbc/dynamicDBNonJta' from 'null'\n INFO - Enterprise application \"/Users/dblevins/examples/dynamic-dao-implementation\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/dynamic-dao-implementation\n INFO - PersistenceUnit(name=dynamic, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 417ms\n INFO - Jndi(name=\"java:global/dynamic-dao-implementation/UserDao!org.superbiz.dynamic.UserDao\")\n INFO - Jndi(name=\"java:global/dynamic-dao-implementation/UserDao\")\n INFO - Jndi(name=\"java:global/dynamic-dao-implementation/Util!org.superbiz.dynamic.DynamicUserDaoTest$Util\")\n INFO - Jndi(name=\"java:global/dynamic-dao-implementation/Util\")\n INFO - Jndi(name=\"java:global/EjbModule346613126/org.superbiz.dynamic.DynamicUserDaoTest!org.superbiz.dynamic.DynamicUserDaoTest\")\n INFO - Jndi(name=\"java:global/EjbModule346613126/org.superbiz.dynamic.DynamicUserDaoTest\")\n INFO - Created Ejb(deployment-id=UserDao, ejb-name=UserDao, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=Util, ejb-name=Util, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=org.superbiz.dynamic.DynamicUserDaoTest, ejb-name=org.superbiz.dynamic.DynamicUserDaoTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=UserDao, ejb-name=UserDao, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=Util, ejb-name=Util, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=org.superbiz.dynamic.DynamicUserDaoTest, ejb-name=org.superbiz.dynamic.DynamicUserDaoTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/dynamic-dao-implementation)\n WARN - Meta class \"org.superbiz.dynamic.User_\" for entity class org.superbiz.dynamic.User can not be registered with following exception \"java.security.PrivilegedActionException: java.lang.ClassNotFoundException: org.superbiz.dynamic.User_\"\n WARN - Query \"SELECT u FROM User AS u WHERE u.name LIKE :name\" is removed from cache excluded permanently. Query \"SELECT u FROM User AS u WHERE u.name LIKE :name\" is not cached because it uses pagination..\n Tests run: 9, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.471 sec\n \n Results :\n \n Tests run: 9, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/dynamic-dao-implementation"
},
{
"name":"dynamic-proxy-to-access-mbean",
"readme":"Title: dynamic-proxy-to-access-mbean\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## Example\n\nAcessing MBean is something simple through the JMX API but it is often technical and not very interesting.\n\nThis example simplify this work simply doing it generically in a proxy.\n\nSo from an user side you simple declare an interface to access your MBeans.\n\nNote: the example implementation uses a local MBeanServer but enhancing the example API\nit is easy to imagine a remote connection with user/password if needed.\n\n## ObjectName API (annotation)\n\nSimply an annotation to get the object\n\n package org.superbiz.dynamic.mbean;\n\n import java.lang.annotation.Retention;\n import java.lang.annotation.Target;\n\n import static java.lang.annotation.ElementType.TYPE;\n import static java.lang.annotation.ElementType.METHOD;\n import static java.lang.annotation.RetentionPolicy.RUNTIME;\n\n @Target({TYPE, METHOD})\n @Retention(RUNTIME)\n public @interface ObjectName {\n String value();\n\n // for remote usage only\n String url() default \"\";\n String user() default \"\";\n String password() default \"\";\n }\n\n## DynamicMBeanHandler (thr proxy implementation)\n\n package org.superbiz.dynamic.mbean;\n\n import javax.annotation.PreDestroy;\n import javax.management.Attribute;\n import javax.management.MBeanAttributeInfo;\n import javax.management.MBeanInfo;\n import javax.management.MBeanServer;\n import javax.management.MBeanServerConnection;\n import javax.management.ObjectName;\n import javax.management.remote.JMXConnector;\n import javax.management.remote.JMXConnectorFactory;\n import javax.management.remote.JMXServiceURL;\n import java.io.IOException;\n import java.lang.management.ManagementFactory;\n import java.lang.reflect.InvocationHandler;\n import java.lang.reflect.Method;\n import java.util.HashMap;\n import java.util.Map;\n import java.util.concurrent.ConcurrentHashMap;\n\n /**\n * Need a @PreDestroy method to disconnect the remote host when used in remote mode.\n */\n public class DynamicMBeanHandler implements InvocationHandler {\n private final Map<Method, ConnectionInfo> infos = new ConcurrentHashMap<Method, ConnectionInfo>();\n\n @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {\n final String methodName = method.getName();\n if (method.getDeclaringClass().equals(Object.class) && \"toString\".equals(methodName)) {\n return getClass().getSimpleName() + \" Proxy\";\n }\n if (method.getAnnotation(PreDestroy.class) != null) {\n return destroy();\n }\n\n final ConnectionInfo info = getConnectionInfo(method);\n final MBeanInfo infos = info.getMBeanInfo();\n if (methodName.startsWith(\"set\") && methodName.length() > 3 && args != null && args.length == 1\n && (Void.TYPE.equals(method.getReturnType()) || Void.class.equals(method.getReturnType()))) {\n final String attributeName = attributeName(infos, methodName, method.getParameterTypes()[0]);\n info.setAttribute(new Attribute(attributeName, args[0]));\n return null;\n } else if (methodName.startsWith(\"get\") && (args == null || args.length == 0) && methodName.length() > 3) {\n final String attributeName = attributeName(infos, methodName, method.getReturnType());\n return info.getAttribute(attributeName);\n }\n // operation\n return info.invoke(methodName, args, getSignature(method));\n }\n\n public Object destroy() {\n for (ConnectionInfo info : infos.values()) {\n info.clean();\n }\n infos.clear();\n return null;\n }\n\n private String[] getSignature(Method method) {\n String[] args = new String[method.getParameterTypes().length];\n for (int i = 0; i < method.getParameterTypes().length; i++) {\n args[i] = method.getParameterTypes()[i].getName();\n }\n return args; // note: null should often work...\n }\n\n private String attributeName(MBeanInfo infos, String methodName, Class<?> type) {\n String found = null;\n String foundBackUp = null; // without checking the type\n final String attributeName = methodName.substring(3, methodName.length());\n final String lowerName = Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4, methodName.length());\n\n for (MBeanAttributeInfo attribute : infos.getAttributes()) {\n final String name = attribute.getName();\n if (attributeName.equals(name)) {\n foundBackUp = attributeName;\n if (attribute.getType().equals(type.getName())) {\n found = name;\n }\n } else if (found == null && ((lowerName.equals(name) && !attributeName.equals(name))\n || lowerName.equalsIgnoreCase(name))) {\n foundBackUp = name;\n if (attribute.getType().equals(type.getName())) {\n found = name;\n }\n }\n }\n\n if (found == null && foundBackUp == null) {\n throw new UnsupportedOperationException(\"cannot find attribute \" + attributeName);\n }\n\n if (found != null) {\n return found;\n }\n return foundBackUp;\n }\n\n private synchronized ConnectionInfo getConnectionInfo(Method method) throws Exception {\n if (!infos.containsKey(method)) {\n synchronized (infos) {\n if (!infos.containsKey(method)) { // double check for synchro\n org.superbiz.dynamic.mbean.ObjectName on = method.getAnnotation(org.superbiz.dynamic.mbean.ObjectName.class);\n if (on == null) {\n Class<?> current = method.getDeclaringClass();\n do {\n on = method.getDeclaringClass().getAnnotation(org.superbiz.dynamic.mbean.ObjectName.class);\n current = current.getSuperclass();\n } while (on == null && current != null);\n if (on == null) {\n throw new UnsupportedOperationException(\"class or method should define the objectName to use for invocation: \" + method.toGenericString());\n }\n }\n final ConnectionInfo info;\n if (on.url().isEmpty()) {\n info = new LocalConnectionInfo();\n ((LocalConnectionInfo) info).server = ManagementFactory.getPlatformMBeanServer(); // could use an id...\n } else {\n info = new RemoteConnectionInfo();\n final Map<String, String[]> environment = new HashMap<String, String[]>();\n if (!on.user().isEmpty()) {\n environment.put(JMXConnector.CREDENTIALS, new String[]{ on.user(), on.password() });\n }\n // ((RemoteConnectionInfo) info).connector = JMXConnectorFactory.newJMXConnector(new JMXServiceURL(on.url()), environment);\n ((RemoteConnectionInfo) info).connector = JMXConnectorFactory.connect(new JMXServiceURL(on.url()), environment);\n\n }\n info.objectName = new ObjectName(on.value());\n\n infos.put(method, info);\n }\n }\n }\n return infos.get(method);\n }\n\n private abstract static class ConnectionInfo {\n protected ObjectName objectName;\n\n public abstract void setAttribute(Attribute attribute) throws Exception;\n public abstract Object getAttribute(String attribute) throws Exception;\n public abstract Object invoke(String operationName, Object params[], String signature[]) throws Exception;\n public abstract MBeanInfo getMBeanInfo() throws Exception;\n public abstract void clean();\n }\n\n private static class LocalConnectionInfo extends ConnectionInfo {\n private MBeanServer server;\n\n @Override public void setAttribute(Attribute attribute) throws Exception {\n server.setAttribute(objectName, attribute);\n }\n\n @Override public Object getAttribute(String attribute) throws Exception {\n return server.getAttribute(objectName, attribute);\n }\n\n @Override\n public Object invoke(String operationName, Object[] params, String[] signature) throws Exception {\n return server.invoke(objectName, operationName, params, signature);\n }\n\n @Override public MBeanInfo getMBeanInfo() throws Exception {\n return server.getMBeanInfo(objectName);\n }\n\n @Override public void clean() {\n // no-op\n }\n }\n\n private static class RemoteConnectionInfo extends ConnectionInfo {\n private JMXConnector connector;\n private MBeanServerConnection connection;\n\n private void before() throws IOException {\n connection = connector.getMBeanServerConnection();\n }\n\n private void after() throws IOException {\n // no-op\n }\n\n @Override public void setAttribute(Attribute attribute) throws Exception {\n before();\n connection.setAttribute(objectName, attribute);\n after();\n }\n\n @Override public Object getAttribute(String attribute) throws Exception {\n before();\n try {\n return connection.getAttribute(objectName, attribute);\n } finally {\n after();\n }\n }\n\n @Override\n public Object invoke(String operationName, Object[] params, String[] signature) throws Exception {\n before();\n try {\n return connection.invoke(objectName, operationName, params, signature);\n } finally {\n after();\n }\n }\n\n @Override public MBeanInfo getMBeanInfo() throws Exception {\n before();\n try {\n return connection.getMBeanInfo(objectName);\n } finally {\n after();\n }\n }\n\n @Override public void clean() {\n try {\n connector.close();\n } catch (IOException e) {\n // no-op\n }\n }\n }\n }\n\n## Dynamic Proxies \n\n### DynamicMBeanClient (the dynamic JMX client)\n\n\tpackage org.superbiz.dynamic.mbean;\n\n\timport org.apache.openejb.api.Proxy;\n\timport org.superbiz.dynamic.mbean.DynamicMBeanHandler;\n\timport org.superbiz.dynamic.mbean.ObjectName;\n\n\timport javax.ejb.Singleton;\n\n\t/**\n\t * @author rmannibucau\n\t */\n\t@Singleton\n\t@Proxy(DynamicMBeanHandler.class)\n\t@ObjectName(DynamicMBeanClient.OBJECT_NAME)\n\tpublic interface DynamicMBeanClient {\n\t\tstatic final String OBJECT_NAME = \"test:group=DynamicMBeanClientTest\";\n\n\t\tint getCounter();\n\t\tvoid setCounter(int i);\n\t\tint length(String aString);\n\t}\n\n### DynamicMBeanClient (the dynamic JMX client)\n package org.superbiz.dynamic.mbean;\n\n import org.apache.openejb.api.Proxy;\n\n import javax.annotation.PreDestroy;\n import javax.ejb.Singleton;\n\n\n @Singleton\n @Proxy(DynamicMBeanHandler.class)\n @ObjectName(value = DynamicRemoteMBeanClient.OBJECT_NAME, url = \"service:jmx:rmi:///jndi/rmi://localhost:8243/jmxrmi\")\n public interface DynamicRemoteMBeanClient {\n static final String OBJECT_NAME = \"test:group=DynamicMBeanClientTest\";\n\n int getCounter();\n void setCounter(int i);\n int length(String aString);\n\n @PreDestroy void clean();\n }\n\n## The MBean used for the test\n\n### SimpleMBean\n\n\tpackage org.superbiz.dynamic.mbean.simple;\n\n\tpublic interface SimpleMBean {\n\t\tint length(String s);\n\n\t\tint getCounter();\n\t\tvoid setCounter(int c);\n\t}\n\n## Simple\n\n\tpackage org.superbiz.dynamic.mbean.simple;\n\n\tpublic class Simple implements SimpleMBean {\n\t\tprivate int counter = 0;\n\n\t\t@Override public int length(String s) {\n\t\t if (s == null) {\n\t\t return 0;\n\t\t }\n\t\t return s.length();\n\t\t}\n\n\t\t@Override public int getCounter() {\n\t\t return counter;\n\t\t}\n\n\t\t@Override public void setCounter(int c) {\n\t\t counter = c;\n\t\t}\n\t}\n\n## DynamicMBeanClientTest (The test)\n\n package org.superbiz.dynamic.mbean;\n\n import org.junit.After;\n import org.junit.AfterClass;\n import org.junit.Before;\n import org.junit.BeforeClass;\n import org.junit.Test;\n import org.superbiz.dynamic.mbean.simple.Simple;\n\n import javax.ejb.EJB;\n import javax.ejb.embeddable.EJBContainer;\n import javax.management.Attribute;\n import javax.management.ObjectName;\n import java.lang.management.ManagementFactory;\n\n import static junit.framework.Assert.assertEquals;\n\n public class DynamicMBeanClientTest {\n private static ObjectName objectName;\n private static EJBContainer container;\n\n @EJB private DynamicMBeanClient localClient;\n @EJB private DynamicRemoteMBeanClient remoteClient;\n\n @BeforeClass public static void start() {\n container = EJBContainer.createEJBContainer();\n }\n\n @Before public void injectAndRegisterMBean() throws Exception {\n container.getContext().bind(\"inject\", this);\n objectName = new ObjectName(DynamicMBeanClient.OBJECT_NAME);\n ManagementFactory.getPlatformMBeanServer().registerMBean(new Simple(), objectName);\n }\n\n @After public void unregisterMBean() throws Exception {\n if (objectName != null) {\n ManagementFactory.getPlatformMBeanServer().unregisterMBean(objectName);\n }\n }\n\n @Test public void localGet() throws Exception {\n assertEquals(0, localClient.getCounter());\n ManagementFactory.getPlatformMBeanServer().setAttribute(objectName, new Attribute(\"Counter\", 5));\n assertEquals(5, localClient.getCounter());\n }\n\n @Test public void localSet() throws Exception {\n assertEquals(0, ((Integer) ManagementFactory.getPlatformMBeanServer().getAttribute(objectName, \"Counter\")).intValue());\n localClient.setCounter(8);\n assertEquals(8, ((Integer) ManagementFactory.getPlatformMBeanServer().getAttribute(objectName, \"Counter\")).intValue());\n }\n\n @Test public void localOperation() {\n assertEquals(7, localClient.length(\"openejb\"));\n }\n\n @Test public void remoteGet() throws Exception {\n assertEquals(0, remoteClient.getCounter());\n ManagementFactory.getPlatformMBeanServer().setAttribute(objectName, new Attribute(\"Counter\", 5));\n assertEquals(5, remoteClient.getCounter());\n }\n\n @Test public void remoteSet() throws Exception {\n assertEquals(0, ((Integer) ManagementFactory.getPlatformMBeanServer().getAttribute(objectName, \"Counter\")).intValue());\n remoteClient.setCounter(8);\n assertEquals(8, ((Integer) ManagementFactory.getPlatformMBeanServer().getAttribute(objectName, \"Counter\")).intValue());\n }\n\n @Test public void remoteOperation() {\n assertEquals(7, remoteClient.length(\"openejb\"));\n }\n\n @AfterClass public static void close() {\n if (container != null) {\n container.close();\n }\n }\n }\n\n",
"url":"https://github.com/apache/tomee/tree/master/examples/dynamic-proxy-to-access-mbean"
}
],
"ear":[
{
"name":"ear-testing",
"readme":"Title: EAR Testing\n\nThe goal of this example is to demonstrate how maven projects might be organized in a more real world style and how testing with OpenEJB can fit into that structure.\n\nThis example takes the basic moviefun code we us in many of examples and splits it into two modules:\n\n - `business-logic`\n - `business-model`\n\nAs the names imply, we keep our `@Entity` beans in the `business-model` module and our session beans in the `business-logic` model. The tests located and run from the business logic module.\n\n ear-testing\n ear-testing/business-logic\n ear-testing/business-logic/pom.xml\n ear-testing/business-logic/src/main/java/org/superbiz/logic/Movies.java\n ear-testing/business-logic/src/main/java/org/superbiz/logic/MoviesImpl.java\n ear-testing/business-logic/src/main/resources\n ear-testing/business-logic/src/main/resources/META-INF\n ear-testing/business-logic/src/main/resources/META-INF/ejb-jar.xml\n ear-testing/business-logic/src/test/java/org/superbiz/logic/MoviesTest.java\n ear-testing/business-model\n ear-testing/business-model/pom.xml\n ear-testing/business-model/src/main/java/org/superbiz/model/Movie.java\n ear-testing/business-model/src/main/resources/META-INF/persistence.xml\n ear-testing/pom.xml\n\n# Project configuration\n\nThe parent pom, trimmed to the minimum, looks like so:\n\n <project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n\n <modelVersion>4.0.0</modelVersion>\n <groupId>org.superbiz</groupId>\n <artifactId>myear</artifactId>\n <version>1.1.0-SNAPSHOT</version>\n\n <packaging>pom</packaging>\n\n <modules>\n <module>business-model</module>\n <module>business-logic</module>\n </modules>\n\n <dependencyManagement>\n <dependencies>\n <dependency>\n <groupId>org.apache.openejb</groupId>\n <artifactId>javaee-api</artifactId>\n <version>6.0-2</version>\n </dependency>\n <dependency>\n <groupId>junit</groupId>\n <artifactId>junit</artifactId>\n <version>4.8.1</version>\n </dependency>\n </dependencies>\n </dependencyManagement>\n </project>\n\nThe `business-model/pom.xml` as follows:\n\n <project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n <parent>\n <groupId>org.superbiz</groupId>\n <artifactId>myear</artifactId>\n <version>1.1.0-SNAPSHOT</version>\n </parent>\n\n <modelVersion>4.0.0</modelVersion>\n\n <artifactId>business-model</artifactId>\n <packaging>jar</packaging>\n\n <dependencies>\n <dependency>\n <groupId>org.apache.openejb</groupId>\n <artifactId>javaee-api</artifactId>\n <scope>provided</scope>\n </dependency>\n <dependency>\n <groupId>junit</groupId>\n <artifactId>junit</artifactId>\n <scope>test</scope>\n </dependency>\n\n </dependencies>\n\n </project>\n\nAnd finally, the `business-logic/pom.xml` which is setup to support embedded testing with OpenEJB:\n\n <project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n <parent>\n <groupId>org.superbiz</groupId>\n <artifactId>myear</artifactId>\n <version>1.1.0-SNAPSHOT</version>\n </parent>\n\n <modelVersion>4.0.0</modelVersion>\n\n <artifactId>business-logic</artifactId>\n <packaging>jar</packaging>\n\n <dependencies>\n <dependency>\n <groupId>org.superbiz</groupId>\n <artifactId>business-model</artifactId>\n <version>${project.version}</version>\n </dependency>\n <dependency>\n <groupId>org.apache.openejb</groupId>\n <artifactId>javaee-api</artifactId>\n <scope>provided</scope>\n </dependency>\n <dependency>\n <groupId>junit</groupId>\n <artifactId>junit</artifactId>\n <scope>test</scope>\n </dependency>\n <!--\n The <scope>test</scope> guarantees that non of your runtime\n code is dependent on any OpenEJB classes.\n -->\n <dependency>\n <groupId>org.apache.openejb</groupId>\n <artifactId>openejb-core</artifactId>\n <version>7.0.0-SNAPSHOT</version>\n <scope>test</scope>\n </dependency>\n </dependencies>\n </project>\n\n# TestCode\n\nThe test code is the same as always:\n\n public class MoviesTest extends TestCase {\n\n public void test() throws Exception {\n Properties p = new Properties();\n p.put(Context.INITIAL_CONTEXT_FACTORY, \"org.apache.openejb.core.LocalInitialContextFactory\");\n\n p.put(\"openejb.deployments.classpath.ear\", \"true\");\n\n p.put(\"movieDatabase\", \"new://Resource?type=DataSource\");\n p.put(\"movieDatabase.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"movieDatabase.JdbcUrl\", \"jdbc:hsqldb:mem:moviedb\");\n\n p.put(\"movieDatabaseUnmanaged\", \"new://Resource?type=DataSource\");\n p.put(\"movieDatabaseUnmanaged.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"movieDatabaseUnmanaged.JdbcUrl\", \"jdbc:hsqldb:mem:moviedb\");\n p.put(\"movieDatabaseUnmanaged.JtaManaged\", \"false\");\n\n Context context = new InitialContext(p);\n\n Movies movies = (Movies) context.lookup(\"MoviesLocal\");\n\n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n movies.addMovie(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n movies.addMovie(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n\n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n\n for (Movie movie : list) {\n movies.deleteMovie(movie);\n }\n\n assertEquals(\"Movies.getMovies()\", 0, movies.getMovies().size());\n }\n }\n\n\n# Running\n\n\n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.logic.MoviesTest\n Apache OpenEJB 7.0.0-SNAPSHOT build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/ear-testing/business-logic\n INFO - openejb.base = /Users/dblevins/examples/ear-testing/business-logic\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=movieDatabaseUnmanaged, type=Resource, provider-id=Default JDBC Database)\n INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Found PersistenceModule in classpath: /Users/dblevins/examples/ear-testing/business-model/target/business-model-1.0.jar\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/ear-testing/business-logic/target/classes\n INFO - Using 'openejb.deployments.classpath.ear=true'\n INFO - Beginning load: /Users/dblevins/examples/ear-testing/business-model/target/business-model-1.0.jar\n INFO - Beginning load: /Users/dblevins/examples/ear-testing/business-logic/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/ear-testing/business-logic/classpath.ear\n INFO - Configuring Service(id=Default Stateful Container, type=Container, provider-id=Default Stateful Container)\n INFO - Auto-creating a container for bean Movies: Container(type=STATEFUL, id=Default Stateful Container)\n INFO - Configuring PersistenceUnit(name=movie-unit)\n INFO - Enterprise application \"/Users/dblevins/examples/ear-testing/business-logic/classpath.ear\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/ear-testing/business-logic/classpath.ear\n INFO - PersistenceUnit(name=movie-unit, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 415ms\n INFO - Jndi(name=MoviesLocal) --> Ejb(deployment-id=Movies)\n INFO - Jndi(name=global/classpath.ear/business-logic/Movies!org.superbiz.logic.Movies) --> Ejb(deployment-id=Movies)\n INFO - Jndi(name=global/classpath.ear/business-logic/Movies) --> Ejb(deployment-id=Movies)\n INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/ear-testing/business-logic/classpath.ear)\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.393 sec\n\n Results :\n\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n",
"url":"https://github.com/apache/tomee/tree/master/examples/ear-testing"
}
],
"eclipselink":[
{
"name":"jpa-eclipselink",
"readme":"Title: JPA Eclipselink\n\nThis 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.\n\n## Creating the JPA Entity\n\nThe entity itself is simply a pojo annotated with `@Entity`. We create one pojo called `Movie` which we can use to hold movie records.\n\n package org.superbiz.eclipselink;\n \n import javax.persistence.Entity;\n import javax.persistence.GeneratedValue;\n import javax.persistence.GenerationType;\n import javax.persistence.Id;\n \n @Entity\n public class Movie {\n \n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private long id;\n \n private String director;\n private String title;\n private int year;\n \n public Movie() {\n }\n \n public Movie(String director, String title, int year) {\n this.director = director;\n this.title = title;\n this.year = year;\n }\n \n public String getDirector() {\n return director;\n }\n \n public void setDirector(String director) {\n this.director = director;\n }\n \n public String getTitle() {\n return title;\n }\n \n public void setTitle(String title) {\n this.title = title;\n }\n \n public int getYear() {\n return year;\n }\n \n public void setYear(int year) {\n this.year = year;\n }\n \n }\n\n## Database Operations\n\nThis is the bean responsible for database operations; it allows us to persist or delete entities.\nFor more information we recommend you to see [injection-of-entitymanager](http://tomee.apache.org/examples-trunk/injection-of-entitymanager/README.html)\n\n\n package org.superbiz.eclipselink;\n \n import javax.ejb.Stateful;\n import javax.persistence.EntityManager;\n import javax.persistence.PersistenceContext;\n import javax.persistence.PersistenceContextType;\n import javax.persistence.Query;\n import java.util.List;\n \n @Stateful\n public class Movies {\n \n @PersistenceContext(unitName = \"movie-unit\", type = PersistenceContextType.EXTENDED)\n private EntityManager entityManager;\n \n public void addMovie(Movie movie) throws Exception {\n entityManager.persist(movie);\n }\n \n public void deleteMovie(Movie movie) throws Exception {\n entityManager.remove(movie);\n }\n \n public List<Movie> getMovies() throws Exception {\n Query query = entityManager.createQuery(\"SELECT m from Movie as m\");\n return query.getResultList();\n }\n }\n\n## Persistence.xml with EclipseLink configuration\n\nThis operation is too easy, just set the `provider` to `org.eclipse.persistence.jpa.PersistenceProvider` and add additional properties to the persistence unit. \nThe example has followed a strategy that allows the creation of tables in a HSQL database.\nFor a complete list of persistence unit properties see [here](http://www.eclipse.org/eclipselink/api/2.4/org/eclipse/persistence/config/PersistenceUnitProperties.html)\n\n <persistence version=\"1.0\"\n xmlns=\"http://java.sun.com/xml/ns/persistence\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd\">\n <persistence-unit name=\"movie-unit\">\n <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>\n <jta-data-source>movieDatabase</jta-data-source>\n <non-jta-data-source>movieDatabaseUnmanaged</non-jta-data-source>\n <properties>\n <property name=\"eclipselink.target-database\" value=\"org.eclipse.persistence.platform.database.HSQLPlatform\"/>\n <property name=\"eclipselink.ddl-generation\" value=\"create-tables\"/>\n <property name=\"eclipselink.ddl-generation.output-mode\" value=\"database\"/>\n </properties>\n </persistence-unit>\n </persistence>\n \n\n## MoviesTest\n\nTesting JPA is quite easy, we can simply use the `EJBContainer` API to create a container in our test case.\n\n package org.superbiz.eclipselink;\n \n import junit.framework.TestCase;\n \n import javax.ejb.embeddable.EJBContainer;\n import javax.naming.Context;\n import java.util.List;\n import java.util.Properties;\n \n /**\n * @version $Revision: 607077 $ $Date: 2007-12-27 06:55:23 -0800 (Thu, 27 Dec 2007) $\n */\n public class MoviesTest extends TestCase {\n \n public void test() throws Exception {\n Properties p = new Properties();\n p.put(\"movieDatabase\", \"new://Resource?type=DataSource\");\n p.put(\"movieDatabase.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"movieDatabase.JdbcUrl\", \"jdbc:hsqldb:mem:moviedb\");\n \n final Context context = EJBContainer.createEJBContainer(p).getContext();\n \n Movies movies = (Movies) context.lookup(\"java:global/jpa-eclipselink/Movies\");\n \n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n movies.addMovie(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n movies.addMovie(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n \n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n \n for (Movie movie : list) {\n movies.deleteMovie(movie);\n }\n \n assertEquals(\"Movies.getMovies()\", 0, movies.getMovies().size());\n }\n }\n\n# Running\n\nWhen we run our test case we should see output similar to the following. \n\n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.eclipselink.MoviesTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/jpa-eclipselink\n INFO - openejb.base = /Users/dblevins/examples/jpa-eclipselink\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/jpa-eclipselink/target/classes\n INFO - Beginning load: /Users/dblevins/examples/jpa-eclipselink/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/jpa-eclipselink\n INFO - Configuring Service(id=Default Stateful Container, type=Container, provider-id=Default Stateful Container)\n INFO - Auto-creating a container for bean Movies: Container(type=STATEFUL, id=Default Stateful Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.eclipselink.MoviesTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring PersistenceUnit(name=movie-unit, provider=org.eclipse.persistence.jpa.PersistenceProvider)\n INFO - Auto-creating a Resource with id 'movieDatabaseNonJta' of type 'DataSource for 'movie-unit'.\n INFO - Configuring Service(id=movieDatabaseNonJta, type=Resource, provider-id=movieDatabase)\n INFO - Adjusting PersistenceUnit movie-unit <non-jta-data-source> to Resource ID 'movieDatabaseNonJta' from 'movieDatabaseUnmanaged'\n INFO - Enterprise application \"/Users/dblevins/examples/jpa-eclipselink\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/jpa-eclipselink\n INFO - PersistenceUnit(name=movie-unit, provider=org.eclipse.persistence.jpa.PersistenceProvider) - provider time 511ms\n INFO - Jndi(name=\"java:global/jpa-eclipselink/Movies!org.superbiz.eclipselink.Movies\")\n INFO - Jndi(name=\"java:global/jpa-eclipselink/Movies\")\n INFO - Jndi(name=\"java:global/EjbModule225280863/org.superbiz.eclipselink.MoviesTest!org.superbiz.eclipselink.MoviesTest\")\n INFO - Jndi(name=\"java:global/EjbModule225280863/org.superbiz.eclipselink.MoviesTest\")\n INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Created Ejb(deployment-id=org.superbiz.eclipselink.MoviesTest, ejb-name=org.superbiz.eclipselink.MoviesTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Started Ejb(deployment-id=org.superbiz.eclipselink.MoviesTest, ejb-name=org.superbiz.eclipselink.MoviesTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/jpa-eclipselink)\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.188 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n ",
"url":"https://github.com/apache/tomee/tree/master/examples/jpa-eclipselink"
},
{
"name":"tomee-jersey-eclipselink",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/tomee-jersey-eclipselink"
}
],
"ejb":[
{
"name":"rest-on-ejb",
"readme":"Title: REST on EJB\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## User\n\n package org.superbiz.rest;\n \n import javax.persistence.Entity;\n import javax.persistence.GeneratedValue;\n import javax.persistence.Id;\n import javax.persistence.NamedQueries;\n import javax.persistence.NamedQuery;\n import javax.xml.bind.annotation.XmlRootElement;\n \n @Entity\n @NamedQueries({\n @NamedQuery(name = \"user.list\", query = \"select u from User u\")\n }\n\n## UserService\n\n package org.superbiz.rest;\n \n import javax.ejb.Lock;\n import javax.ejb.LockType;\n import javax.ejb.Singleton;\n import javax.persistence.EntityManager;\n import javax.persistence.PersistenceContext;\n import javax.ws.rs.DELETE;\n import javax.ws.rs.DefaultValue;\n import javax.ws.rs.GET;\n import javax.ws.rs.POST;\n import javax.ws.rs.PUT;\n import javax.ws.rs.Path;\n import javax.ws.rs.PathParam;\n import javax.ws.rs.Produces;\n import javax.ws.rs.QueryParam;\n import javax.ws.rs.core.MediaType;\n import javax.ws.rs.core.Response;\n import java.util.ArrayList;\n import java.util.List;\n \n /**\n * Outputs are copied because of the enhancement of OpenJPA.\n *\n */\n @Singleton\n @Lock(LockType.WRITE)\n @Path(\"/user\")\n @Produces(MediaType.APPLICATION_XML)\n public class UserService {\n @PersistenceContext\n private EntityManager em;\n \n @Path(\"/create\")\n @PUT\n public User create(@QueryParam(\"name\") String name,\n @QueryParam(\"pwd\") String pwd,\n @QueryParam(\"mail\") String mail) {\n User user = new User();\n user.setFullname(name);\n user.setPassword(pwd);\n user.setEmail(mail);\n em.persist(user);\n return user;\n }\n \n @Path(\"/list\")\n @GET\n public List<User> list(@QueryParam(\"first\") @DefaultValue(\"0\") int first,\n @QueryParam(\"max\") @DefaultValue(\"20\") int max) {\n List<User> users = new ArrayList<User>();\n List<User> found = em.createNamedQuery(\"user.list\", User.class).setFirstResult(first).setMaxResults(max).getResultList();\n for (User u : found) {\n users.add(u.copy());\n }\n return users;\n }\n \n @Path(\"/show/{id}\")\n @GET\n public User find(@PathParam(\"id\") long id) {\n User user = em.find(User.class, id);\n if (user == null) {\n return null;\n }\n return user.copy();\n }\n \n @Path(\"/delete/{id}\")\n @DELETE\n public void delete(@PathParam(\"id\") long id) {\n User user = em.find(User.class, id);\n if (user != null) {\n em.remove(user);\n }\n }\n \n @Path(\"/update/{id}\")\n @POST\n public Response update(@PathParam(\"id\") long id,\n @QueryParam(\"name\") String name,\n @QueryParam(\"pwd\") String pwd,\n @QueryParam(\"mail\") String mail) {\n User user = em.find(User.class, id);\n if (user == null) {\n throw new IllegalArgumentException(\"user id \" + id + \" not found\");\n }\n \n user.setFullname(name);\n user.setPassword(pwd);\n user.setEmail(mail);\n em.merge(user);\n \n return Response.ok(user.copy()).build();\n }\n }\n\n## persistence.xml\n\n <persistence version=\"2.0\"\n xmlns=\"http://java.sun.com/xml/ns/persistence\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\n http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd\">\n <persistence-unit name=\"user\">\n <jta-data-source>My DataSource</jta-data-source>\n <non-jta-data-source>My Unmanaged DataSource</non-jta-data-source>\n <class>org.superbiz.rest.User</class>\n <properties>\n <property name=\"openjpa.jdbc.SynchronizeMappings\" value=\"buildSchema(ForeignKeys=true)\"/>\n </properties>\n </persistence-unit>\n </persistence>\n\n## UserServiceTest\n\n package org.superbiz.rest;\n \n import org.apache.cxf.jaxrs.client.WebClient;\n import org.apache.openejb.OpenEjbContainer;\n import org.junit.AfterClass;\n import org.junit.BeforeClass;\n import org.junit.Test;\n \n import javax.ejb.embeddable.EJBContainer;\n import javax.naming.Context;\n import javax.naming.NamingException;\n import javax.ws.rs.core.Response;\n import javax.xml.bind.JAXBContext;\n import javax.xml.bind.Unmarshaller;\n import java.io.InputStream;\n import java.util.ArrayList;\n import java.util.List;\n import java.util.Properties;\n \n import static junit.framework.Assert.assertEquals;\n import static junit.framework.Assert.assertNull;\n import static junit.framework.Assert.fail;\n \n public class UserServiceTest {\n private static Context context;\n private static UserService service;\n private static List<User> users = new ArrayList<User>();\n \n @BeforeClass\n public static void start() throws NamingException {\n Properties properties = new Properties();\n properties.setProperty(OpenEjbContainer.OPENEJB_EMBEDDED_REMOTABLE, \"true\");\n context = EJBContainer.createEJBContainer(properties).getContext();\n \n // create some records\n service = (UserService) context.lookup(\"java:global/rest-on-ejb/UserService\");\n users.add(service.create(\"foo\", \"foopwd\", \"foo@foo.com\"));\n users.add(service.create(\"bar\", \"barpwd\", \"bar@bar.com\"));\n }\n \n @AfterClass\n public static void close() throws NamingException {\n if (context != null) {\n context.close();\n }\n }\n \n @Test\n public void create() {\n int expected = service.list(0, 100).size() + 1;\n Response response = WebClient.create(\"http://localhost:4204\")\n .path(\"/user/create\")\n .query(\"name\", \"dummy\")\n .query(\"pwd\", \"unbreakable\")\n .query(\"mail\", \"foo@bar.fr\")\n .put(null);\n List<User> list = service.list(0, 100);\n for (User u : list) {\n if (!users.contains(u)) {\n service.delete(u.getId());\n return;\n }\n }\n fail(\"user was not added\");\n }\n \n @Test\n public void delete() throws Exception {\n User user = service.create(\"todelete\", \"dontforget\", \"delete@me.com\");\n \n WebClient.create(\"http://localhost:4204\").path(\"/user/delete/\" + user.getId()).delete();\n \n user = service.find(user.getId());\n assertNull(user);\n }\n \n @Test\n public void show() {\n User user = WebClient.create(\"http://localhost:4204\")\n .path(\"/user/show/\" + users.iterator().next().getId())\n .get(User.class);\n assertEquals(\"foo\", user.getFullname());\n assertEquals(\"foopwd\", user.getPassword());\n assertEquals(\"foo@foo.com\", user.getEmail());\n }\n \n @Test\n public void list() throws Exception {\n String users = WebClient.create(\"http://localhost:4204\")\n .path(\"/user/list\")\n .get(String.class);\n assertEquals(\n \"<users>\" +\n \"<user>\" +\n \"<email>foo@foo.com</email>\" +\n \"<fullname>foo</fullname>\" +\n \"<id>1</id>\" +\n \"<password>foopwd</password>\" +\n \"</user>\" +\n \"<user>\" +\n \"<email>bar@bar.com</email>\" +\n \"<fullname>bar</fullname>\" +\n \"<id>2</id>\" +\n \"<password>barpwd</password>\" +\n \"</user>\" +\n \"</users>\", users);\n }\n \n @Test\n public void update() throws Exception {\n User created = service.create(\"name\", \"pwd\", \"mail\");\n Response response = WebClient.create(\"http://localhost:4204\")\n .path(\"/user/update/\" + created.getId())\n .query(\"name\", \"corrected\")\n .query(\"pwd\", \"userpwd\")\n .query(\"mail\", \"it@is.ok\")\n .post(null);\n \n JAXBContext ctx = JAXBContext.newInstance(User.class);\n Unmarshaller unmarshaller = ctx.createUnmarshaller();\n User modified = (User) unmarshaller.unmarshal(InputStream.class.cast(response.getEntity()));\n \n assertEquals(\"corrected\", modified.getFullname());\n assertEquals(\"userpwd\", modified.getPassword());\n assertEquals(\"it@is.ok\", modified.getEmail());\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.rest.UserServiceTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/rest-on-ejb\n INFO - openejb.base = /Users/dblevins/examples/rest-on-ejb\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/rest-on-ejb/target/classes\n INFO - Beginning load: /Users/dblevins/examples/rest-on-ejb/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/rest-on-ejb\n INFO - Configuring Service(id=Default Singleton Container, type=Container, provider-id=Default Singleton Container)\n INFO - Auto-creating a container for bean UserService: Container(type=SINGLETON, id=Default Singleton Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.rest.UserServiceTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring PersistenceUnit(name=user)\n INFO - Configuring Service(id=Default JDBC Database, type=Resource, provider-id=Default JDBC Database)\n INFO - Auto-creating a Resource with id 'Default JDBC Database' of type 'DataSource for 'user'.\n INFO - Configuring Service(id=Default Unmanaged JDBC Database, type=Resource, provider-id=Default Unmanaged JDBC Database)\n INFO - Auto-creating a Resource with id 'Default Unmanaged JDBC Database' of type 'DataSource for 'user'.\n INFO - Adjusting PersistenceUnit user <jta-data-source> to Resource ID 'Default JDBC Database' from 'My DataSource'\n INFO - Adjusting PersistenceUnit user <non-jta-data-source> to Resource ID 'Default Unmanaged JDBC Database' from 'My Unmanaged DataSource'\n INFO - Enterprise application \"/Users/dblevins/examples/rest-on-ejb\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/rest-on-ejb\n INFO - PersistenceUnit(name=user, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 407ms\n INFO - Jndi(name=\"java:global/rest-on-ejb/UserService!org.superbiz.rest.UserService\")\n INFO - Jndi(name=\"java:global/rest-on-ejb/UserService\")\n INFO - Jndi(name=\"java:global/EjbModule1789767313/org.superbiz.rest.UserServiceTest!org.superbiz.rest.UserServiceTest\")\n INFO - Jndi(name=\"java:global/EjbModule1789767313/org.superbiz.rest.UserServiceTest\")\n INFO - Created Ejb(deployment-id=org.superbiz.rest.UserServiceTest, ejb-name=org.superbiz.rest.UserServiceTest, container=Default Managed Container)\n INFO - Created Ejb(deployment-id=UserService, ejb-name=UserService, container=Default Singleton Container)\n INFO - Started Ejb(deployment-id=org.superbiz.rest.UserServiceTest, ejb-name=org.superbiz.rest.UserServiceTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=UserService, ejb-name=UserService, container=Default Singleton Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/rest-on-ejb)\n INFO - Initializing network services\n INFO - Creating ServerService(id=httpejbd)\n INFO - Creating ServerService(id=admin)\n INFO - Creating ServerService(id=ejbd)\n INFO - Creating ServerService(id=ejbds)\n INFO - Creating ServerService(id=cxf-rs)\n INFO - Initializing network services\n ** Starting Services **\n NAME IP PORT \n httpejbd 127.0.0.1 4204 \n admin thread 127.0.0.1 4200 \n ejbd 127.0.0.1 4201 \n ejbd 127.0.0.1 4203 \n -------\n Ready!\n WARN - Query \"select u from User u\" is removed from cache excluded permanently. Query \"select u from User u\" is not cached because it uses pagination..\n Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.102 sec\n \n Results :\n \n Tests run: 5, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/rest-on-ejb"
},
{
"name":"jsf-managedBean-and-ejb",
"readme":"Title: JSF Application that uses managed-bean and ejb\n\nThis is a simple web-app showing how to use dependency injection in JSF managed beans using TomEE.\n\nIt contains a Local Stateless session bean `CalculatorImpl` which adds two numbers and returns the result.\nThe application also contains a JSF managed bean `CalculatorBean`, which uses the EJB to add two numbers\nand display the results to the user. The EJB is injected in the managed bean using `@EJB` annotation.\n\n\n## A little note on the setup:\n\nYou could run this in the latest Apache TomEE [snapshot](https://repository.apache.org/content/repositories/snapshots/org/apache/openejb/apache-tomee/)\n\nAs for the libraries, myfaces-api and myfaces-impl are provided in tomee/lib and hence they should not be a part of the\nwar. In maven terms, they would be with scope 'provided'\n\nAlso note that we use servlet 2.5 declaration in web.xml\n \n <web-app xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns=\"http://java.sun.com/xml/ns/javaee\"\n xmlns:web=\"http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee\n http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n version=\"2.5\">\n\nAnd we use 2.0 version of faces-config\n\n <faces-config xmlns=\"http://java.sun.com/xml/ns/javaee\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee\n http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd\"\n version=\"2.0\">\n\n\nThe complete source code is provided below but let's break down to look at some smaller snippets and see how it works.\n\nWe'll first declare the `FacesServlet` in the `web.xml`\n\n <servlet>\n <servlet-name>Faces Servlet</servlet-name>\n <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>\n <load-on-startup>1</load-on-startup>\n </servlet>\n\n`FacesServlet` acts as the master controller.\n\nWe'll then create the `calculator.xhtml` file.\n\n <h:outputText value='Enter first number'/>\n <h:inputText value='#{calculatorBean.x}'/>\n <h:outputText value='Enter second number'/>\n <h:inputText value='#{calculatorBean.y}'/>\n <h:commandButton action=\"#{calculatorBean.add}\" value=\"Add\"/>\n\n\nNotice how we've use the bean here.\nBy default it is the simple class name of the managed bean.\n\nWhen a request comes in, the bean is instantiated and placed in the appropriate scope.\nBy default, the bean is placed in the request scope.\n\n <h:inputText value='#{calculatorBean.x}'/>\n\nHere, getX() method of calculatorBean is invoked and the resulting value is displayed.\nx being a Double, we rightly should see 0.0 displayed.\n\nWhen you change the value and submit the form, these entered values are bound using the setters\nin the bean and then the commandButton-action method is invoked.\n\nIn this case, `CalculatorBean#add()` is invoked.\n\n`Calculator#add()` delegates the work to the ejb, gets the result, stores it\nand then instructs what view is to be rendered.\n\nYou're right. The return value \"success\" is checked up in faces-config navigation-rules\nand the respective page is rendered.\n\nIn our case, `result.xhtml` page is rendered.\n\nThe request scoped `calculatorBean` is available here, and we use EL to display the values.\n\n## Source\n\n## Calculator\n\n package org.superbiz.jsf;\n \n import javax.ejb.Local;\n \n @Local\n public interface Calculator {\n public double add(double x, double y);\n }\n\n\n## CalculatorBean\n\n package org.superbiz.jsf;\n \n import javax.ejb.EJB;\n import javax.faces.bean.ManagedBean;\n\n @ManagedBean\n public class CalculatorBean {\n @EJB\n Calculator calculator;\n private double x;\n private double y;\n private double result;\n \n public double getX() {\n return x;\n }\n \n public void setX(double x) {\n this.x = x;\n }\n \n public double getY() {\n return y;\n }\n \n public void setY(double y) {\n this.y = y;\n }\n \n public double getResult() {\n return result;\n }\n \n public void setResult(double result) {\n this.result = result;\n }\n \n public String add() {\n result = calculator.add(x, y);\n return \"success\";\n }\n }\n\n## CalculatorImpl\n\n package org.superbiz.jsf;\n \n import javax.ejb.Stateless;\n \n @Stateless\n public class CalculatorImpl implements Calculator {\n \n public double add(double x, double y) {\n return x + y;\n }\n }\n\n\n# web.xml\n\n <?xml version=\"1.0\"?>\n\n <web-app xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns=\"http://java.sun.com/xml/ns/javaee\"\n xmlns:web=\"http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee\n http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n version=\"2.5\">\n\n <description>MyProject web.xml</description>\n\n <!-- Faces Servlet -->\n <servlet>\n <servlet-name>Faces Servlet</servlet-name>\n <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>\n <load-on-startup>1</load-on-startup>\n </servlet>\n\n <!-- Faces Servlet Mapping -->\n <servlet-mapping>\n <servlet-name>Faces Servlet</servlet-name>\n <url-pattern>*.jsf</url-pattern>\n </servlet-mapping>\n\n <!-- Welcome files -->\n <welcome-file-list>\n <welcome-file>index.jsp</welcome-file>\n <welcome-file>index.html</welcome-file>\n </welcome-file-list>\n </web-app>\n\n \n##Calculator.xhtml\n\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n <html xmlns=\"http://www.w3.org/1999/xhtml\"\n xmlns:f=\"http://java.sun.com/jsf/core\"\n xmlns:h=\"http://java.sun.com/jsf/html\">\n\n\n <h:body bgcolor=\"white\">\n <f:view>\n <h:form>\n <h:panelGrid columns=\"2\">\n <h:outputText value='Enter first number'/>\n <h:inputText value='#{calculatorBean.x}'/>\n <h:outputText value='Enter second number'/>\n <h:inputText value='#{calculatorBean.y}'/>\n <h:commandButton action=\"#{calculatorBean.add}\" value=\"Add\"/>\n </h:panelGrid>\n </h:form>\n </f:view>\n </h:body>\n </html>\n\n \n##Result.xhtml\n\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n <html xmlns=\"http://www.w3.org/1999/xhtml\"\n xmlns:f=\"http://java.sun.com/jsf/core\"\n xmlns:h=\"http://java.sun.com/jsf/html\">\n\n <h:body>\n <f:view>\n <h:form id=\"mainForm\">\n <h2><h:outputText value=\"Result of adding #{calculatorBean.x} and #{calculatorBean.y} is #{calculatorBean.result }\"/></h2>\n <h:commandLink action=\"back\">\n <h:outputText value=\"Home\"/>\n </h:commandLink>\n </h:form>\n </f:view>\n </h:body>\n </html>\n \n#faces-config.xml\n\n <?xml version=\"1.0\"?>\n <faces-config xmlns=\"http://java.sun.com/xml/ns/javaee\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee\n http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd\"\n version=\"2.0\">\n\n <navigation-rule>\n <from-view-id>/calculator.xhtml</from-view-id>\n <navigation-case>\n <from-outcome>success</from-outcome>\n <to-view-id>/result.xhtml</to-view-id>\n </navigation-case>\n </navigation-rule>\n\n <navigation-rule>\n <from-view-id>/result.xhtml</from-view-id>\n <navigation-case>\n <from-outcome>back</from-outcome>\n <to-view-id>/calculator.xhtml</to-view-id>\n </navigation-case>\n </navigation-rule>\n </faces-config>\n",
"url":"https://github.com/apache/tomee/tree/master/examples/jsf-managedBean-and-ejb"
},
{
"name":"ejb-examples",
"readme":"Title: EJB Examples\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## AnnotatedEJB\n\n package org.superbiz.servlet;\n \n import javax.annotation.Resource;\n import javax.ejb.LocalBean;\n import javax.ejb.Stateless;\n import javax.sql.DataSource;\n \n @Stateless\n @LocalBean\n public class AnnotatedEJB implements AnnotatedEJBLocal, AnnotatedEJBRemote {\n @Resource\n private DataSource ds;\n \n private String name = \"foo\";\n \n public String getName() {\n return name;\n }\n \n public void setName(String name) {\n this.name = name;\n }\n \n public DataSource getDs() {\n return ds;\n }\n \n public void setDs(DataSource ds) {\n this.ds = ds;\n }\n \n public String toString() {\n return \"AnnotatedEJB[name=\" + name + \"]\";\n }\n }\n\n## AnnotatedEJBLocal\n\n package org.superbiz.servlet;\n \n import javax.ejb.Local;\n import javax.sql.DataSource;\n \n @Local\n public interface AnnotatedEJBLocal {\n String getName();\n \n void setName(String name);\n \n DataSource getDs();\n \n void setDs(DataSource ds);\n }\n\n## AnnotatedEJBRemote\n\n package org.superbiz.servlet;\n \n import javax.ejb.Remote;\n \n @Remote\n public interface AnnotatedEJBRemote {\n String getName();\n \n void setName(String name);\n }\n\n## AnnotatedServlet\n\n package org.superbiz.servlet;\n \n import javax.annotation.Resource;\n import javax.ejb.EJB;\n import javax.naming.InitialContext;\n import javax.naming.NamingException;\n import javax.servlet.ServletException;\n import javax.servlet.ServletOutputStream;\n import javax.servlet.http.HttpServlet;\n import javax.servlet.http.HttpServletRequest;\n import javax.servlet.http.HttpServletResponse;\n import javax.sql.DataSource;\n import java.io.IOException;\n \n public class AnnotatedServlet extends HttpServlet {\n @EJB\n private AnnotatedEJBLocal localEJB;\n \n @EJB\n private AnnotatedEJBRemote remoteEJB;\n \n @EJB\n private AnnotatedEJB localbeanEJB;\n \n @Resource\n private DataSource ds;\n \n \n protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n response.setContentType(\"text/plain\");\n ServletOutputStream out = response.getOutputStream();\n \n out.println(\"LocalBean EJB\");\n out.println(\"@EJB=\" + localbeanEJB);\n if (localbeanEJB != null) {\n out.println(\"@EJB.getName()=\" + localbeanEJB.getName());\n out.println(\"@EJB.getDs()=\" + localbeanEJB.getDs());\n }\n out.println(\"JNDI=\" + lookupField(\"localbeanEJB\"));\n out.println();\n \n out.println(\"Local EJB\");\n out.println(\"@EJB=\" + localEJB);\n if (localEJB != null) {\n out.println(\"@EJB.getName()=\" + localEJB.getName());\n out.println(\"@EJB.getDs()=\" + localEJB.getDs());\n }\n out.println(\"JNDI=\" + lookupField(\"localEJB\"));\n out.println();\n \n out.println(\"Remote EJB\");\n out.println(\"@EJB=\" + remoteEJB);\n if (localEJB != null) {\n out.println(\"@EJB.getName()=\" + remoteEJB.getName());\n }\n out.println(\"JNDI=\" + lookupField(\"remoteEJB\"));\n out.println();\n \n \n out.println(\"DataSource\");\n out.println(\"@Resource=\" + ds);\n out.println(\"JNDI=\" + lookupField(\"ds\"));\n }\n \n private Object lookupField(String name) {\n try {\n return new InitialContext().lookup(\"java:comp/env/\" + getClass().getName() + \"/\" + name);\n } catch (NamingException e) {\n return null;\n }\n }\n }\n\n## ClientHandler\n\n package org.superbiz.servlet;\n \n import javax.xml.ws.handler.Handler;\n import javax.xml.ws.handler.MessageContext;\n \n public class ClientHandler implements Handler {\n public boolean handleMessage(MessageContext messageContext) {\n WebserviceServlet.write(\" ClientHandler handleMessage\");\n return true;\n }\n \n public void close(MessageContext messageContext) {\n WebserviceServlet.write(\" ClientHandler close\");\n }\n \n public boolean handleFault(MessageContext messageContext) {\n WebserviceServlet.write(\" ClientHandler handleFault\");\n return true;\n }\n }\n\n## HelloEjb\n\n package org.superbiz.servlet;\n \n import javax.jws.WebService;\n \n @WebService(targetNamespace = \"http://examples.org/wsdl\")\n public interface HelloEjb {\n String hello(String name);\n }\n\n## HelloEjbService\n\n package org.superbiz.servlet;\n \n import javax.ejb.Stateless;\n import javax.jws.HandlerChain;\n import javax.jws.WebService;\n \n @WebService(\n portName = \"HelloEjbPort\",\n serviceName = \"HelloEjbService\",\n targetNamespace = \"http://examples.org/wsdl\",\n endpointInterface = \"org.superbiz.servlet.HelloEjb\"\n )\n @HandlerChain(file = \"server-handlers.xml\")\n @Stateless\n public class HelloEjbService implements HelloEjb {\n public String hello(String name) {\n WebserviceServlet.write(\" HelloEjbService hello(\" + name + \")\");\n if (name == null) name = \"World\";\n return \"Hello \" + name + \" from EJB Webservice!\";\n }\n }\n\n## HelloPojo\n\n package org.superbiz.servlet;\n \n import javax.jws.WebService;\n \n @WebService(targetNamespace = \"http://examples.org/wsdl\")\n public interface HelloPojo {\n String hello(String name);\n }\n\n## HelloPojoService\n\n package org.superbiz.servlet;\n \n import javax.jws.HandlerChain;\n import javax.jws.WebService;\n \n @WebService(\n portName = \"HelloPojoPort\",\n serviceName = \"HelloPojoService\",\n targetNamespace = \"http://examples.org/wsdl\",\n endpointInterface = \"org.superbiz.servlet.HelloPojo\"\n )\n @HandlerChain(file = \"server-handlers.xml\")\n public class HelloPojoService implements HelloPojo {\n public String hello(String name) {\n WebserviceServlet.write(\" HelloPojoService hello(\" + name + \")\");\n if (name == null) name = \"World\";\n return \"Hello \" + name + \" from Pojo Webservice!\";\n }\n }\n\n## JndiServlet\n\n package org.superbiz.servlet;\n \n import javax.naming.Context;\n import javax.naming.InitialContext;\n import javax.naming.NameClassPair;\n import javax.naming.NamingException;\n import javax.servlet.ServletException;\n import javax.servlet.ServletOutputStream;\n import javax.servlet.http.HttpServlet;\n import javax.servlet.http.HttpServletRequest;\n import javax.servlet.http.HttpServletResponse;\n import java.io.IOException;\n import java.util.Collections;\n import java.util.Map;\n import java.util.TreeMap;\n \n public class JndiServlet extends HttpServlet {\n protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n response.setContentType(\"text/plain\");\n ServletOutputStream out = response.getOutputStream();\n \n Map<String, Object> bindings = new TreeMap<String, Object>(String.CASE_INSENSITIVE_ORDER);\n try {\n Context context = (Context) new InitialContext().lookup(\"java:comp/\");\n addBindings(\"\", bindings, context);\n } catch (NamingException e) {\n throw new ServletException(e);\n }\n \n out.println(\"JNDI Context:\");\n for (Map.Entry<String, Object> entry : bindings.entrySet()) {\n if (entry.getValue() != null) {\n out.println(\" \" + entry.getKey() + \"=\" + entry.getValue());\n } else {\n out.println(\" \" + entry.getKey());\n }\n }\n }\n \n private void addBindings(String path, Map<String, Object> bindings, Context context) {\n try {\n for (NameClassPair pair : Collections.list(context.list(\"\"))) {\n String name = pair.getName();\n String className = pair.getClassName();\n if (\"org.apache.naming.resources.FileDirContext$FileResource\".equals(className)) {\n bindings.put(path + name, \"<file>\");\n } else {\n try {\n Object value = context.lookup(name);\n if (value instanceof Context) {\n Context nextedContext = (Context) value;\n bindings.put(path + name, \"\");\n addBindings(path + name + \"/\", bindings, nextedContext);\n } else {\n bindings.put(path + name, value);\n }\n } catch (NamingException e) {\n // lookup failed\n bindings.put(path + name, \"ERROR: \" + e.getMessage());\n }\n }\n }\n } catch (NamingException e) {\n bindings.put(path, \"ERROR: list bindings threw an exception: \" + e.getMessage());\n }\n }\n }\n\n## JpaBean\n\n package org.superbiz.servlet;\n \n import javax.persistence.Column;\n import javax.persistence.Entity;\n import javax.persistence.GeneratedValue;\n import javax.persistence.GenerationType;\n import javax.persistence.Id;\n \n @Entity\n public class JpaBean {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column(name = \"id\")\n private int id;\n \n @Column(name = \"name\")\n private String name;\n \n public int getId() {\n return id;\n }\n \n public String getName() {\n return name;\n }\n \n public void setName(String name) {\n this.name = name;\n }\n \n \n public String toString() {\n return \"[JpaBean id=\" + id + \", name=\" + name + \"]\";\n }\n }\n\n## JpaServlet\n\n package org.superbiz.servlet;\n \n import javax.persistence.EntityManager;\n import javax.persistence.EntityManagerFactory;\n import javax.persistence.EntityTransaction;\n import javax.persistence.PersistenceUnit;\n import javax.persistence.Query;\n import javax.servlet.ServletException;\n import javax.servlet.ServletOutputStream;\n import javax.servlet.http.HttpServlet;\n import javax.servlet.http.HttpServletRequest;\n import javax.servlet.http.HttpServletResponse;\n import java.io.IOException;\n \n public class JpaServlet extends HttpServlet {\n @PersistenceUnit(name = \"jpa-example\")\n private EntityManagerFactory emf;\n \n \n protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n response.setContentType(\"text/plain\");\n ServletOutputStream out = response.getOutputStream();\n \n out.println(\"@PersistenceUnit=\" + emf);\n \n EntityManager em = emf.createEntityManager();\n EntityTransaction transaction = em.getTransaction();\n transaction.begin();\n \n JpaBean jpaBean = new JpaBean();\n jpaBean.setName(\"JpaBean\");\n em.persist(jpaBean);\n \n transaction.commit();\n transaction.begin();\n \n Query query = em.createQuery(\"SELECT j FROM JpaBean j WHERE j.name='JpaBean'\");\n jpaBean = (JpaBean) query.getSingleResult();\n out.println(\"Loaded \" + jpaBean);\n \n em.remove(jpaBean);\n \n transaction.commit();\n transaction.begin();\n \n query = em.createQuery(\"SELECT count(j) FROM JpaBean j WHERE j.name='JpaBean'\");\n int count = ((Number) query.getSingleResult()).intValue();\n if (count == 0) {\n out.println(\"Removed \" + jpaBean);\n } else {\n out.println(\"ERROR: unable to remove\" + jpaBean);\n }\n \n transaction.commit();\n }\n }\n\n## ResourceBean\n\n package org.superbiz.servlet;\n \n public class ResourceBean {\n private String value;\n \n public String getValue() {\n return value;\n }\n \n public void setValue(String value) {\n this.value = value;\n }\n \n public String toString() {\n return \"[ResourceBean \" + value + \"]\";\n }\n }\n\n## RunAsServlet\n\n package org.superbiz.servlet;\n \n import javax.ejb.EJB;\n import javax.ejb.EJBAccessException;\n import javax.servlet.ServletException;\n import javax.servlet.ServletOutputStream;\n import javax.servlet.http.HttpServlet;\n import javax.servlet.http.HttpServletRequest;\n import javax.servlet.http.HttpServletResponse;\n import java.io.IOException;\n import java.security.Principal;\n \n public class RunAsServlet extends HttpServlet {\n @EJB\n private SecureEJBLocal secureEJBLocal;\n \n protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n response.setContentType(\"text/plain\");\n ServletOutputStream out = response.getOutputStream();\n \n out.println(\"Servlet\");\n Principal principal = request.getUserPrincipal();\n if (principal != null) {\n out.println(\"Servlet.getUserPrincipal()=\" + principal + \" [\" + principal.getName() + \"]\");\n } else {\n out.println(\"Servlet.getUserPrincipal()=<null>\");\n }\n out.println(\"Servlet.isCallerInRole(\\\"user\\\")=\" + request.isUserInRole(\"user\"));\n out.println(\"Servlet.isCallerInRole(\\\"manager\\\")=\" + request.isUserInRole(\"manager\"));\n out.println(\"Servlet.isCallerInRole(\\\"fake\\\")=\" + request.isUserInRole(\"fake\"));\n out.println();\n \n out.println(\"@EJB=\" + secureEJBLocal);\n if (secureEJBLocal != null) {\n principal = secureEJBLocal.getCallerPrincipal();\n if (principal != null) {\n out.println(\"@EJB.getCallerPrincipal()=\" + principal + \" [\" + principal.getName() + \"]\");\n } else {\n out.println(\"@EJB.getCallerPrincipal()=<null>\");\n }\n out.println(\"@EJB.isCallerInRole(\\\"user\\\")=\" + secureEJBLocal.isCallerInRole(\"user\"));\n out.println(\"@EJB.isCallerInRole(\\\"manager\\\")=\" + secureEJBLocal.isCallerInRole(\"manager\"));\n out.println(\"@EJB.isCallerInRole(\\\"fake\\\")=\" + secureEJBLocal.isCallerInRole(\"fake\"));\n \n try {\n secureEJBLocal.allowUserMethod();\n out.println(\"@EJB.allowUserMethod() ALLOWED\");\n } catch (EJBAccessException e) {\n out.println(\"@EJB.allowUserMethod() DENIED\");\n }\n \n try {\n secureEJBLocal.allowManagerMethod();\n out.println(\"@EJB.allowManagerMethod() ALLOWED\");\n } catch (EJBAccessException e) {\n out.println(\"@EJB.allowManagerMethod() DENIED\");\n }\n \n try {\n secureEJBLocal.allowFakeMethod();\n out.println(\"@EJB.allowFakeMethod() ALLOWED\");\n } catch (EJBAccessException e) {\n out.println(\"@EJB.allowFakeMethod() DENIED\");\n }\n \n try {\n secureEJBLocal.denyAllMethod();\n out.println(\"@EJB.denyAllMethod() ALLOWED\");\n } catch (EJBAccessException e) {\n out.println(\"@EJB.denyAllMethod() DENIED\");\n }\n }\n out.println();\n }\n }\n\n## SecureEJB\n\n package org.superbiz.servlet;\n \n import javax.annotation.Resource;\n import javax.annotation.security.DeclareRoles;\n import javax.annotation.security.DenyAll;\n import javax.annotation.security.RolesAllowed;\n import javax.ejb.SessionContext;\n import javax.ejb.Stateless;\n import java.security.Principal;\n \n @Stateless\n @DeclareRoles({\"user\", \"manager\", \"fake\"})\n public class SecureEJB implements SecureEJBLocal {\n @Resource\n private SessionContext context;\n \n public Principal getCallerPrincipal() {\n return context.getCallerPrincipal();\n }\n \n public boolean isCallerInRole(String role) {\n return context.isCallerInRole(role);\n }\n \n @RolesAllowed(\"user\")\n public void allowUserMethod() {\n }\n \n @RolesAllowed(\"manager\")\n public void allowManagerMethod() {\n }\n \n @RolesAllowed(\"fake\")\n public void allowFakeMethod() {\n }\n \n @DenyAll\n public void denyAllMethod() {\n }\n \n public String toString() {\n return \"SecureEJB[userName=\" + getCallerPrincipal() + \"]\";\n }\n }\n\n## SecureEJBLocal\n\n package org.superbiz.servlet;\n \n import javax.ejb.Local;\n import java.security.Principal;\n \n @Local\n public interface SecureEJBLocal {\n Principal getCallerPrincipal();\n \n boolean isCallerInRole(String role);\n \n void allowUserMethod();\n \n void allowManagerMethod();\n \n void allowFakeMethod();\n \n void denyAllMethod();\n }\n\n## SecureServlet\n\n package org.superbiz.servlet;\n \n import javax.ejb.EJB;\n import javax.ejb.EJBAccessException;\n import javax.servlet.ServletException;\n import javax.servlet.ServletOutputStream;\n import javax.servlet.http.HttpServlet;\n import javax.servlet.http.HttpServletRequest;\n import javax.servlet.http.HttpServletResponse;\n import java.io.IOException;\n import java.security.Principal;\n \n public class SecureServlet extends HttpServlet {\n @EJB\n private SecureEJBLocal secureEJBLocal;\n \n protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n response.setContentType(\"text/plain\");\n ServletOutputStream out = response.getOutputStream();\n \n out.println(\"Servlet\");\n Principal principal = request.getUserPrincipal();\n if (principal != null) {\n out.println(\"Servlet.getUserPrincipal()=\" + principal + \" [\" + principal.getName() + \"]\");\n } else {\n out.println(\"Servlet.getUserPrincipal()=<null>\");\n }\n out.println(\"Servlet.isCallerInRole(\\\"user\\\")=\" + request.isUserInRole(\"user\"));\n out.println(\"Servlet.isCallerInRole(\\\"manager\\\")=\" + request.isUserInRole(\"manager\"));\n out.println(\"Servlet.isCallerInRole(\\\"fake\\\")=\" + request.isUserInRole(\"fake\"));\n out.println();\n \n out.println(\"@EJB=\" + secureEJBLocal);\n if (secureEJBLocal != null) {\n principal = secureEJBLocal.getCallerPrincipal();\n if (principal != null) {\n out.println(\"@EJB.getCallerPrincipal()=\" + principal + \" [\" + principal.getName() + \"]\");\n } else {\n out.println(\"@EJB.getCallerPrincipal()=<null>\");\n }\n out.println(\"@EJB.isCallerInRole(\\\"user\\\")=\" + secureEJBLocal.isCallerInRole(\"user\"));\n out.println(\"@EJB.isCallerInRole(\\\"manager\\\")=\" + secureEJBLocal.isCallerInRole(\"manager\"));\n out.println(\"@EJB.isCallerInRole(\\\"fake\\\")=\" + secureEJBLocal.isCallerInRole(\"fake\"));\n \n try {\n secureEJBLocal.allowUserMethod();\n out.println(\"@EJB.allowUserMethod() ALLOWED\");\n } catch (EJBAccessException e) {\n out.println(\"@EJB.allowUserMethod() DENIED\");\n }\n \n try {\n secureEJBLocal.allowManagerMethod();\n out.println(\"@EJB.allowManagerMethod() ALLOWED\");\n } catch (EJBAccessException e) {\n out.println(\"@EJB.allowManagerMethod() DENIED\");\n }\n \n try {\n secureEJBLocal.allowFakeMethod();\n out.println(\"@EJB.allowFakeMethod() ALLOWED\");\n } catch (EJBAccessException e) {\n out.println(\"@EJB.allowFakeMethod() DENIED\");\n }\n \n try {\n secureEJBLocal.denyAllMethod();\n out.println(\"@EJB.denyAllMethod() ALLOWED\");\n } catch (EJBAccessException e) {\n out.println(\"@EJB.denyAllMethod() DENIED\");\n }\n }\n out.println();\n }\n }\n\n## ServerHandler\n\n package org.superbiz.servlet;\n \n import javax.xml.ws.handler.Handler;\n import javax.xml.ws.handler.MessageContext;\n \n public class ServerHandler implements Handler {\n public boolean handleMessage(MessageContext messageContext) {\n WebserviceServlet.write(\" ServerHandler handleMessage\");\n return true;\n }\n \n public void close(MessageContext messageContext) {\n WebserviceServlet.write(\" ServerHandler close\");\n }\n \n public boolean handleFault(MessageContext messageContext) {\n WebserviceServlet.write(\" ServerHandler handleFault\");\n return true;\n }\n }\n\n## WebserviceClient\n\n package org.superbiz.servlet;\n \n import javax.xml.ws.Service;\n import java.io.PrintStream;\n import java.net.URL;\n \n public class WebserviceClient {\n /**\n * Unfortunately, to run this example with CXF you need to have a HUGE class path. This\n * is just what is required to run CXF:\n * <p/>\n * jaxb-api-2.0.jar\n * jaxb-impl-2.0.3.jar\n * <p/>\n * saaj-api-1.3.jar\n * saaj-impl-1.3.jar\n * <p/>\n * <p/>\n * cxf-api-2.0.2-incubator.jar\n * cxf-common-utilities-2.0.2-incubator.jar\n * cxf-rt-bindings-soap-2.0.2-incubator.jar\n * cxf-rt-core-2.0.2-incubator.jar\n * cxf-rt-databinding-jaxb-2.0.2-incubator.jar\n * cxf-rt-frontend-jaxws-2.0.2-incubator.jar\n * cxf-rt-frontend-simple-2.0.2-incubator.jar\n * cxf-rt-transports-http-jetty-2.0.2-incubator.jar\n * cxf-rt-transports-http-2.0.2-incubator.jar\n * cxf-tools-common-2.0.2-incubator.jar\n * <p/>\n * geronimo-activation_1.1_spec-1.0.jar\n * geronimo-annotation_1.0_spec-1.1.jar\n * geronimo-ejb_3.0_spec-1.0.jar\n * geronimo-jpa_3.0_spec-1.1.jar\n * geronimo-servlet_2.5_spec-1.1.jar\n * geronimo-stax-api_1.0_spec-1.0.jar\n * jaxws-api-2.0.jar\n * axis2-jws-api-1.3.jar\n * <p/>\n * wsdl4j-1.6.1.jar\n * xml-resolver-1.2.jar\n * XmlSchema-1.3.1.jar\n */\n public static void main(String[] args) throws Exception {\n PrintStream out = System.out;\n \n Service helloPojoService = Service.create(new URL(\"http://localhost:8080/ejb-examples/hello?wsdl\"), null);\n HelloPojo helloPojo = helloPojoService.getPort(HelloPojo.class);\n out.println();\n out.println(\"Pojo Webservice\");\n out.println(\" helloPojo.hello(\\\"Bob\\\")=\" + helloPojo.hello(\"Bob\"));\n out.println(\" helloPojo.hello(null)=\" + helloPojo.hello(null));\n out.println();\n \n Service helloEjbService = Service.create(new URL(\"http://localhost:8080/HelloEjbService?wsdl\"), null);\n HelloEjb helloEjb = helloEjbService.getPort(HelloEjb.class);\n out.println();\n out.println(\"EJB Webservice\");\n out.println(\" helloEjb.hello(\\\"Bob\\\")=\" + helloEjb.hello(\"Bob\"));\n out.println(\" helloEjb.hello(null)=\" + helloEjb.hello(null));\n out.println();\n }\n }\n\n## WebserviceServlet\n\n package org.superbiz.servlet;\n \n import javax.jws.HandlerChain;\n import javax.servlet.ServletException;\n import javax.servlet.ServletOutputStream;\n import javax.servlet.http.HttpServlet;\n import javax.servlet.http.HttpServletRequest;\n import javax.servlet.http.HttpServletResponse;\n import javax.xml.ws.WebServiceRef;\n import java.io.IOException;\n \n public class WebserviceServlet extends HttpServlet {\n \n @WebServiceRef\n @HandlerChain(file = \"client-handlers.xml\")\n private HelloPojo helloPojo;\n \n @WebServiceRef\n @HandlerChain(file = \"client-handlers.xml\")\n private HelloEjb helloEjb;\n \n protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n response.setContentType(\"text/plain\");\n ServletOutputStream out = response.getOutputStream();\n \n OUT = out;\n try {\n out.println(\"Pojo Webservice\");\n out.println(\" helloPojo.hello(\\\"Bob\\\")=\" + helloPojo.hello(\"Bob\"));\n out.println();\n out.println(\" helloPojo.hello(null)=\" + helloPojo.hello(null));\n out.println();\n out.println(\"EJB Webservice\");\n out.println(\" helloEjb.hello(\\\"Bob\\\")=\" + helloEjb.hello(\"Bob\"));\n out.println();\n out.println(\" helloEjb.hello(null)=\" + helloEjb.hello(null));\n out.println();\n } finally {\n OUT = out;\n }\n }\n \n private static ServletOutputStream OUT;\n \n public static void write(String message) {\n try {\n ServletOutputStream out = OUT;\n out.println(message);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n }\n\n\n## persistence.xml\n\n <persistence xmlns=\"http://java.sun.com/xml/ns/persistence\" version=\"1.0\">\n <persistence-unit transaction-type=\"RESOURCE_LOCAL\" name=\"jpa-example\">\n <jta-data-source>java:openejb/Connector/Default JDBC Database</jta-data-source>\n <non-jta-data-source>java:openejb/Connector/Default Unmanaged JDBC Database</non-jta-data-source>\n <class>org.superbiz.servlet.JpaBean</class>\n \n <properties>\n <property name=\"openjpa.jdbc.SynchronizeMappings\" value=\"buildSchema(ForeignKeys=true)\"/>\n </properties>\n </persistence-unit>\n </persistence>\n\n## client-handlers.xml\n\n <jws:handler-chains xmlns:jws=\"http://java.sun.com/xml/ns/javaee\">\n <jws:handler-chain>\n <jws:handler>\n <jws:handler-name>ClientHandler</jws:handler-name>\n <jws:handler-class>org.superbiz.servlet.ClientHandler</jws:handler-class>\n </jws:handler>\n </jws:handler-chain>\n </jws:handler-chains>\n \n\n## server-handlers.xml\n\n <jws:handler-chains xmlns:jws=\"http://java.sun.com/xml/ns/javaee\">\n <jws:handler-chain>\n <jws:handler>\n <jws:handler-name>ServerHandler</jws:handler-name>\n <jws:handler-class>org.superbiz.servlet.ServerHandler</jws:handler-class>\n </jws:handler>\n </jws:handler-chain>\n </jws:handler-chains>\n \n\n## context.xml\n\n <Context>\n <!-- This only works if the context is installed under the correct name -->\n <Realm className=\"org.apache.catalina.realm.MemoryRealm\"\n pathname=\"webapps/ejb-examples-1.0-SNAPSHOT/WEB-INF/tomcat-users.xml\"/>\n \n <Environment\n name=\"context.xml/environment\"\n value=\"ContextString\"\n type=\"java.lang.String\"/>\n <Resource\n name=\"context.xml/resource\"\n auth=\"Container\"\n type=\"org.superbiz.servlet.ResourceBean\"\n factory=\"org.apache.naming.factory.BeanFactory\"\n value=\"ContextResource\"/>\n <ResourceLink\n name=\"context.xml/resource-link\"\n global=\"server.xml/environment\"\n type=\"java.lang.String\"/>\n \n <!-- web.xml resources -->\n <Resource\n name=\"web.xml/resource-env-ref\"\n auth=\"Container\"\n type=\"org.superbiz.servlet.ResourceBean\"\n factory=\"org.apache.naming.factory.BeanFactory\"\n value=\"ContextResourceEnvRef\"/>\n <Resource\n name=\"web.xml/resource-ref\"\n auth=\"Container\"\n type=\"org.superbiz.servlet.ResourceBean\"\n factory=\"org.apache.naming.factory.BeanFactory\"\n value=\"ContextResourceRef\"/>\n <ResourceLink\n name=\"web.xml/resource-link\"\n global=\"server.xml/environment\"\n type=\"java.lang.String\"/>\n </Context>\n \n\n## jetty-web.xml\n\n <Configure class=\"org.eclipse.jetty.webapp.WebAppContext\">\n <Get name=\"securityHandler\">\n <Set name=\"loginService\">\n <New class=\"org.eclipse.jetty.security.HashLoginService\">\n <Set name=\"name\">Test Realm</Set>\n <Set name=\"config\"><SystemProperty name=\"jetty.home\" default=\".\"/>/etc/realm.properties\n </Set>\n </New>\n </Set>\n </Get>\n </Configure>\n\n## tomcat-users.xml\n\n <tomcat-users>\n <user name=\"manager\" password=\"manager\" roles=\"manager,user\"/>\n <user name=\"user\" password=\"user\" roles=\"user\"/>\n </tomcat-users>\n \n\n## web.xml\n\n <web-app xmlns=\"http://java.sun.com/xml/ns/javaee\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n metadata-complete=\"false\"\n version=\"2.5\">\n \n <display-name>OpenEJB Servlet Examples</display-name>\n \n <servlet>\n <servlet-name>AnnotatedServlet</servlet-name>\n <servlet-class>org.superbiz.servlet.AnnotatedServlet</servlet-class>\n </servlet>\n \n <servlet-mapping>\n <servlet-name>AnnotatedServlet</servlet-name>\n <url-pattern>/annotated/*</url-pattern>\n </servlet-mapping>\n \n <servlet>\n <servlet-name>JpaServlet</servlet-name>\n <servlet-class>org.superbiz.servlet.JpaServlet</servlet-class>\n </servlet>\n \n <servlet-mapping>\n <servlet-name>JpaServlet</servlet-name>\n <url-pattern>/jpa/*</url-pattern>\n </servlet-mapping>\n \n <servlet>\n <servlet-name>JndiServlet</servlet-name>\n <servlet-class>org.superbiz.servlet.JndiServlet</servlet-class>\n </servlet>\n \n <servlet-mapping>\n <servlet-name>JndiServlet</servlet-name>\n <url-pattern>/jndi/*</url-pattern>\n </servlet-mapping>\n \n <servlet>\n <servlet-name>RunAsServlet</servlet-name>\n <servlet-class>org.superbiz.servlet.RunAsServlet</servlet-class>\n <run-as>\n <role-name>fake</role-name>\n </run-as>\n </servlet>\n \n <servlet-mapping>\n <servlet-name>RunAsServlet</servlet-name>\n <url-pattern>/runas/*</url-pattern>\n </servlet-mapping>\n \n <servlet>\n <servlet-name>SecureServlet</servlet-name>\n <servlet-class>org.superbiz.servlet.SecureServlet</servlet-class>\n </servlet>\n \n <servlet-mapping>\n <servlet-name>SecureServlet</servlet-name>\n <url-pattern>/secure/*</url-pattern>\n </servlet-mapping>\n \n <security-constraint>\n <web-resource-collection>\n <web-resource-name>Secure Area</web-resource-name>\n <url-pattern>/secure/*</url-pattern>\n <url-pattern>/runas/*</url-pattern>\n </web-resource-collection>\n <auth-constraint>\n <role-name>user</role-name>\n </auth-constraint>\n </security-constraint>\n \n <servlet>\n <servlet-name>WebserviceServlet</servlet-name>\n <servlet-class>org.superbiz.servlet.WebserviceServlet</servlet-class>\n </servlet>\n \n <servlet-mapping>\n <servlet-name>WebserviceServlet</servlet-name>\n <url-pattern>/webservice/*</url-pattern>\n </servlet-mapping>\n \n \n <servlet>\n <servlet-name>HelloPojoService</servlet-name>\n <servlet-class>org.superbiz.servlet.HelloPojoService</servlet-class>\n </servlet>\n \n <servlet-mapping>\n <servlet-name>HelloPojoService</servlet-name>\n <url-pattern>/hello</url-pattern>\n </servlet-mapping>\n \n <login-config>\n <auth-method>BASIC</auth-method>\n </login-config>\n \n <security-role>\n <role-name>manager</role-name>\n </security-role>\n \n <security-role>\n <role-name>user</role-name>\n </security-role>\n \n <env-entry>\n <env-entry-name>web.xml/env-entry</env-entry-name>\n <env-entry-type>java.lang.String</env-entry-type>\n <env-entry-value>WebValue</env-entry-value>\n </env-entry>\n \n <resource-ref>\n <res-ref-name>web.xml/Data Source</res-ref-name>\n <res-type>javax.sql.DataSource</res-type>\n <res-auth>Container</res-auth>\n </resource-ref>\n \n <resource-env-ref>\n <resource-env-ref-name>web.xml/Queue</resource-env-ref-name>\n <resource-env-ref-type>javax.jms.Queue</resource-env-ref-type>\n </resource-env-ref>\n \n <ejb-ref>\n <ejb-ref-name>web.xml/EjbRemote</ejb-ref-name>\n <ejb-ref-type>Session</ejb-ref-type>\n <remote>org.superbiz.servlet.AnnotatedEJBRemote</remote>\n </ejb-ref>\n \n <ejb-local-ref>\n <ejb-ref-name>web.xml/EjLocal</ejb-ref-name>\n <ejb-ref-type>Session</ejb-ref-type>\n <local>org.superbiz.servlet.AnnotatedEJBLocal</local>\n </ejb-local-ref>\n \n <persistence-unit-ref>\n <persistence-unit-ref-name>web.xml/PersistenceUnit</persistence-unit-ref-name>\n <persistence-unit-name>jpa-example</persistence-unit-name>\n </persistence-unit-ref>\n \n <persistence-context-ref>\n <persistence-context-ref-name>web.xml/PersistenceContext</persistence-context-ref-name>\n <persistence-unit-name>jpa-example</persistence-unit-name>\n <persistence-context-type>Transactional</persistence-context-type>\n </persistence-context-ref>\n </web-app>\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/ejb-examples"
},
{
"name":"injection-of-ejbs",
"readme":"Title: Injection Of Ejbs\n\nThis example shows how to use the @EJB annotation on a bean class to refer to other beans.\n\nThis functionality is often referred as dependency injection (see\nhttp://www.martinfowler.com/articles/injection.html), and has been recently introduced in\nJava EE 5.\n\nIn this particular example, we will create two session stateless beans\n\n * a DataStore session bean\n * a DataReader session bean\n\nThe DataReader bean uses the DataStore to retrieve some informations, and\nwe will see how we can, inside the DataReader bean, get a reference to the\nDataStore bean using the @EJB annotation, thus avoiding the use of the\nJNDI API.\n\n## DataReader\n\n package org.superbiz.injection;\n \n import javax.ejb.EJB;\n import javax.ejb.Stateless;\n \n /**\n * This is an EJB 3.1 style pojo stateless session bean\n * Every stateless session bean implementation must be annotated\n * using the annotation @Stateless\n * This EJB has 2 business interfaces: DataReaderRemote, a remote business\n * interface, and DataReaderLocal, a local business interface\n * <p/>\n * The instance variables 'dataStoreRemote' is annotated with the @EJB annotation:\n * this means that the application server, at runtime, will inject in this instance\n * variable a reference to the EJB DataStoreRemote\n * <p/>\n * The instance variables 'dataStoreLocal' is annotated with the @EJB annotation:\n * this means that the application server, at runtime, will inject in this instance\n * variable a reference to the EJB DataStoreLocal\n */\n //START SNIPPET: code\n @Stateless\n public class DataReader {\n \n @EJB\n private DataStoreRemote dataStoreRemote;\n @EJB\n private DataStoreLocal dataStoreLocal;\n @EJB\n private DataStore dataStore;\n \n public String readDataFromLocalStore() {\n return \"LOCAL:\" + dataStoreLocal.getData();\n }\n \n public String readDataFromLocalBeanStore() {\n return \"LOCALBEAN:\" + dataStore.getData();\n }\n \n public String readDataFromRemoteStore() {\n return \"REMOTE:\" + dataStoreRemote.getData();\n }\n }\n\n## DataStore\n\n package org.superbiz.injection;\n \n import javax.ejb.LocalBean;\n import javax.ejb.Stateless;\n \n /**\n * This is an EJB 3 style pojo stateless session bean\n * Every stateless session bean implementation must be annotated\n * using the annotation @Stateless\n * This EJB has 2 business interfaces: DataStoreRemote, a remote business\n * interface, and DataStoreLocal, a local business interface\n */\n //START SNIPPET: code\n @Stateless\n @LocalBean\n public class DataStore implements DataStoreLocal, DataStoreRemote {\n \n public String getData() {\n return \"42\";\n }\n }\n\n## DataStoreLocal\n\n package org.superbiz.injection;\n \n import javax.ejb.Local;\n \n /**\n * This is an EJB 3 local business interface\n * A local business interface may be annotated with the @Local\n * annotation, but it's optional. A business interface which is\n * not annotated with @Local or @Remote is assumed to be Local\n */\n //START SNIPPET: code\n @Local\n public interface DataStoreLocal {\n \n public String getData();\n }\n\n## DataStoreRemote\n\n package org.superbiz.injection;\n \n import javax.ejb.Remote;\n \n /**\n * This is an EJB 3 remote business interface\n * A remote business interface must be annotated with the @Remote\n * annotation\n */\n //START SNIPPET: code\n @Remote\n public interface DataStoreRemote {\n \n public String getData();\n }\n\n## EjbDependencyTest\n\n package org.superbiz.injection;\n \n import junit.framework.TestCase;\n \n import javax.ejb.embeddable.EJBContainer;\n import javax.naming.Context;\n \n /**\n * A test case for DataReaderImpl ejb, testing both the remote and local interface\n */\n //START SNIPPET: code\n public class EjbDependencyTest extends TestCase {\n \n public void test() throws Exception {\n final Context context = EJBContainer.createEJBContainer().getContext();\n \n DataReader dataReader = (DataReader) context.lookup(\"java:global/injection-of-ejbs/DataReader\");\n \n assertNotNull(dataReader);\n \n assertEquals(\"LOCAL:42\", dataReader.readDataFromLocalStore());\n assertEquals(\"REMOTE:42\", dataReader.readDataFromRemoteStore());\n assertEquals(\"LOCALBEAN:42\", dataReader.readDataFromLocalBeanStore());\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.injection.EjbDependencyTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/injection-of-ejbs\n INFO - openejb.base = /Users/dblevins/examples/injection-of-ejbs\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/injection-of-ejbs/target/classes\n INFO - Beginning load: /Users/dblevins/examples/injection-of-ejbs/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/injection-of-ejbs\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean DataReader: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.injection.EjbDependencyTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Enterprise application \"/Users/dblevins/examples/injection-of-ejbs\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/injection-of-ejbs\n INFO - Jndi(name=\"java:global/injection-of-ejbs/DataReader!org.superbiz.injection.DataReader\")\n INFO - Jndi(name=\"java:global/injection-of-ejbs/DataReader\")\n INFO - Jndi(name=\"java:global/injection-of-ejbs/DataStore!org.superbiz.injection.DataStore\")\n INFO - Jndi(name=\"java:global/injection-of-ejbs/DataStore!org.superbiz.injection.DataStoreLocal\")\n INFO - Jndi(name=\"java:global/injection-of-ejbs/DataStore!org.superbiz.injection.DataStoreRemote\")\n INFO - Jndi(name=\"java:global/injection-of-ejbs/DataStore\")\n INFO - Jndi(name=\"java:global/EjbModule355598874/org.superbiz.injection.EjbDependencyTest!org.superbiz.injection.EjbDependencyTest\")\n INFO - Jndi(name=\"java:global/EjbModule355598874/org.superbiz.injection.EjbDependencyTest\")\n INFO - Created Ejb(deployment-id=DataReader, ejb-name=DataReader, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=DataStore, ejb-name=DataStore, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=org.superbiz.injection.EjbDependencyTest, ejb-name=org.superbiz.injection.EjbDependencyTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=DataReader, ejb-name=DataReader, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=DataStore, ejb-name=DataStore, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=org.superbiz.injection.EjbDependencyTest, ejb-name=org.superbiz.injection.EjbDependencyTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/injection-of-ejbs)\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.225 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/injection-of-ejbs"
},
{
"name":"jsf-cdi-and-ejb",
"readme":"Title: JSF-CDI-EJB\n\nThe simple application contains a CDI managed bean `CalculatorBean`, which uses the `Calculator` EJB to add two numbers\nand display the results to the user. The EJB is injected in the managed bean using @Inject annotation.\n\nYou could run this in the latest Apache TomEE [snapshot](https://repository.apache.org/content/repositories/snapshots/org/apache/openejb/apache-tomee/)\n\nThe complete source code is below but lets break down to look at some smaller snippets and see how it works.\n\n\nA little note on the setup:\n\nAs for the libraries, myfaces-api and myfaces-impl are provided in tomee/lib and hence they should not be a part of the\nwar. In maven terms, they would be with scope 'provided'\n\nAlso note that we use servlet 2.5 declaration in web.xml\n<web-app xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns=\"http://java.sun.com/xml/ns/javaee\"\n xmlns:web=\"http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee\n http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n version=\"2.5\">\n\nAnd we use 2.0 version of faces-config\n\n <faces-config xmlns=\"http://java.sun.com/xml/ns/javaee\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee\n http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd\"\n version=\"2.0\">\n\nTo make this a cdi-aware-archive (i.e bean archive) an empty beans.xml is added in WEB-INF\n\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n <beans xmlns=\"http://java.sun.com/xml/ns/javaee\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee\n http://java.sun.com/xml/ns/javaee/beans_1_0.xsd\">\n </beans>\n\nWe'll first declare the FacesServlet in the web.xml\n\n <servlet>\n <servlet-name>Faces Servlet</servlet-name>\n <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>\n <load-on-startup>1</load-on-startup>\n </servlet>\n\nFacesServlet acts as the master controller.\n\nWe'll then create the calculator.xhtml file.\n\n <h:outputText value='Enter first number'/>\n <h:inputText value='#{calculatorBean.x}'/>\n <h:outputText value='Enter second number'/>\n <h:inputText value='#{calculatorBean.y}'/>\n <h:commandButton action=\"#{calculatorBean.add}\" value=\"Add\"/>\n\nNotice how we've used the bean here. By default, the bean name would be the simple name of the bean\nclass with the first letter in lower case.\n\nWe've annotated the `CalculatorBean` with `@RequestScoped`.\nSo when a request comes in, the bean is instantiated and placed in the request scope.\n\n<h:inputText value='#{calculatorBean.x}'/>\n\nHere, getX() method of calculatorBean is invoked and the resulting value is displayed.\nx being a Double, we rightly should see 0.0 displayed.\n\nWhen you change the value and submit the form, these entered values are bound using the setters\nin the bean and then the commandButton-action method is invoked.\n\nIn this case, CalculatorBean#add() is invoked.\n\nCalculator#add() delegates the work to the ejb, gets the result, stores it\nand then returns what view is to be rendered.\n\nThe return value \"success\" is checked up in faces-config navigation-rules\nand the respective page is rendered.\n\nIn our case, 'result.xhtml' page is rendered where\nuse EL and display the result from the request-scoped `calculatorBean`.\n\n#Source Code\n\n## CalculatorBean\n\n import javax.enterprise.context.RequestScoped;\n import javax.inject.Named;\n import javax.inject.Inject;\n\n @RequestScoped\n @Named\n public class CalculatorBean {\n @Inject\n Calculator calculator;\n private double x;\n private double y;\n private double result;\n \n public double getX() {\n return x;\n }\n \n public void setX(double x) {\n this.x = x;\n }\n \n public double getY() {\n return y;\n }\n \n public void setY(double y) {\n this.y = y;\n }\n \n public double getResult() {\n return result;\n }\n \n public void setResult(double result) {\n this.result = result;\n }\n \n public String add() {\n result = calculator.add(x, y);\n return \"success\";\n }\n }\n\n## Calculator\n\n package org.superbiz.jsf;\n \n import javax.ejb.Stateless;\n \n @Stateless\n public class Calculator{\n \n public double add(double x, double y) {\n return x + y;\n }\n }\n\n\n#web.xml\n\n<?xml version=\"1.0\"?>\n\n<web-app xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns=\"http://java.sun.com/xml/ns/javaee\"\n xmlns:web=\"http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee\n http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n version=\"2.5\">\n\n <description>MyProject web.xml</description>\n\n <!-- Faces Servlet -->\n <servlet>\n <servlet-name>Faces Servlet</servlet-name>\n <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>\n <load-on-startup>1</load-on-startup>\n </servlet>\n\n <!-- Faces Servlet Mapping -->\n <servlet-mapping>\n <servlet-name>Faces Servlet</servlet-name>\n <url-pattern>*.jsf</url-pattern>\n </servlet-mapping>\n\n <!-- Welcome files -->\n <welcome-file-list>\n <welcome-file>index.jsp</welcome-file>\n <welcome-file>index.html</welcome-file>\n </welcome-file-list>\n\n</web-app>\n\n\n#Calculator.xhtml\n\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\"\n xmlns:f=\"http://java.sun.com/jsf/core\"\n xmlns:h=\"http://java.sun.com/jsf/html\">\n\n\n<h:body bgcolor=\"white\">\n <f:view>\n <h:form>\n <h:panelGrid columns=\"2\">\n <h:outputText value='Enter first number'/>\n <h:inputText value='#{calculatorBean.x}'/>\n <h:outputText value='Enter second number'/>\n <h:inputText value='#{calculatorBean.y}'/>\n <h:commandButton action=\"#{calculatorBean.add}\" value=\"Add\"/>\n </h:panelGrid>\n </h:form>\n </f:view>\n</h:body>\n</html>\n\n\n #Result.xhtml\n\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\"\n xmlns:f=\"http://java.sun.com/jsf/core\"\n xmlns:h=\"http://java.sun.com/jsf/html\">\n\n<h:body>\n<f:view>\n <h:form id=\"mainForm\">\n <h2><h:outputText value=\"Result of adding #{calculatorBean.x} and #{calculatorBean.y} is #{calculatorBean.result }\"/></h2>\n <h:commandLink action=\"back\">\n <h:outputText value=\"Home\"/>\n </h:commandLink>\n </h:form>\n</f:view>\n</h:body>\n</html>\n\n #faces-config.xml\n\n <?xml version=\"1.0\"?>\n <faces-config xmlns=\"http://java.sun.com/xml/ns/javaee\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee\n http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd\"\n version=\"2.0\">\n\n <navigation-rule>\n <from-view-id>/calculator.xhtml</from-view-id>\n <navigation-case>\n <from-outcome>success</from-outcome>\n <to-view-id>/result.xhtml</to-view-id>\n </navigation-case>\n </navigation-rule>\n\n <navigation-rule>\n <from-view-id>/result.xhtml</from-view-id>\n <navigation-case>\n <from-outcome>back</from-outcome>\n <to-view-id>/calculator.xhtml</to-view-id>\n </navigation-case>\n </navigation-rule>\n </faces-config>",
"url":"https://github.com/apache/tomee/tree/master/examples/jsf-cdi-and-ejb"
},
{
"name":"ejb-webservice",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/ejb-webservice"
},
{
"name":"lookup-of-ejbs",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/lookup-of-ejbs"
},
{
"name":"lookup-of-ejbs-with-descriptor",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/lookup-of-ejbs-with-descriptor"
}
],
"ejbcontext":[
{
"name":"cdi-ejbcontext-jaas",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/cdi-ejbcontext-jaas"
}
],
"entitymanager":[
{
"name":"injection-of-entitymanager",
"readme":"Title: Injection Of Entitymanager\n\nThis example shows use of `@PersistenceContext` to have an `EntityManager` with an\n`EXTENDED` persistence context injected into a `@Stateful bean`. A JPA\n`@Entity` bean is used with the `EntityManager` to create, persist and merge\ndata to a database.\n\n## Creating the JPA Entity\n\nThe entity itself is simply a pojo annotated with `@Entity`. We create one called `Movie` which we can use to hold movie records.\n\n package org.superbiz.injection.jpa;\n\n import javax.persistence.Entity;\n \n @Entity\n public class Movie {\n\n @Id @GeneratedValue\n private long id;\n\n private String director;\n private String title;\n private int year;\n\n public Movie() {\n }\n\n public long getId() {\n return id;\n }\n\n public void setId(long id) {\n this.id = id;\n }\n\n public Movie(String director, String title, int year) {\n this.director = director;\n this.title = title;\n this.year = year;\n }\n\n public String getDirector() {\n return director;\n }\n\n public void setDirector(String director) {\n this.director = director;\n }\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public int getYear() {\n return year;\n }\n\n public void setYear(int year) {\n this.year = year;\n }\n }\n\n## Configure the EntityManager via a persistence.xml file\n\nThe above `Movie` entity can be created, removed, updated or deleted via an `EntityManager` object. The `EntityManager` itself is\nconfigured via a `META-INF/persistence.xml` file that is placed in the same jar as the `Movie` entity.\n\n <persistence xmlns=\"http://java.sun.com/xml/ns/persistence\" version=\"1.0\">\n\n <persistence-unit name=\"movie-unit\">\n <jta-data-source>movieDatabase</jta-data-source>\n <non-jta-data-source>movieDatabaseUnmanaged</non-jta-data-source>\n <class>org.superbiz.injection.jpa.Movie</class>\n\n <properties>\n <property name=\"openjpa.jdbc.SynchronizeMappings\" value=\"buildSchema(ForeignKeys=true)\"/>\n </properties>\n </persistence-unit>\n </persistence>\n\nNotice that the `Movie` entity is listed via a `<class>` element. This is not required, but can help when testing or when the\n`Movie` class is located in a different jar than the jar containing the `persistence.xml` file.\n\n## Injection via @PersistenceContext\n\nThe `EntityManager` itself is created by the container using the information in the `persistence.xml`, so to use it at\nruntime, we simply need to request it be injected into one of our components. We do this via `@PersistenceContext`\n\nThe `@PersistenceContext` annotation can be used on any CDI bean, EJB, Servlet, Servlet Listener, Servlet Filter, or JSF ManagedBean. If you don't use an EJB you will need to use a `UserTransaction` begin and commit transactions manually. A transaction is required for any of the create, update or delete methods of the EntityManager to work.\n\n package org.superbiz.injection.jpa;\n\n import javax.ejb.Stateful;\n import javax.persistence.EntityManager;\n import javax.persistence.PersistenceContext;\n import javax.persistence.PersistenceContextType;\n import javax.persistence.Query;\n import java.util.List;\n \n @Stateful\n public class Movies {\n \n @PersistenceContext(unitName = \"movie-unit\", type = PersistenceContextType.EXTENDED)\n private EntityManager entityManager;\n \n public void addMovie(Movie movie) throws Exception {\n entityManager.persist(movie);\n }\n \n public void deleteMovie(Movie movie) throws Exception {\n entityManager.remove(movie);\n }\n \n public List<Movie> getMovies() throws Exception {\n Query query = entityManager.createQuery(\"SELECT m from Movie as m\");\n return query.getResultList();\n }\n }\n\nThis particular `EntityManager` is injected as an `EXTENDED` persistence context, which simply means that the `EntityManager`\nis created when the `@Stateful` bean is created and destroyed when the `@Stateful` bean is destroyed. Simply put, the\ndata in the `EntityManager` is cached for the lifetime of the `@Stateful` bean.\n\nThe use of `EXTENDED` persistence contexts is **only** available to `@Stateful` beans. See the [JPA Concepts](../../jpa-concepts.html) page for an high level explanation of what a \"persistence context\" really is and how it is significant to JPA.\n\n## MoviesTest\n\nTesting JPA is quite easy, we can simply use the `EJBContainer` API to create a container in our test case.\n\n package org.superbiz.injection.jpa;\n \n import junit.framework.TestCase;\n \n import javax.ejb.embeddable.EJBContainer;\n import javax.naming.Context;\n import java.util.List;\n import java.util.Properties;\n \n //START SNIPPET: code\n public class MoviesTest extends TestCase {\n \n public void test() throws Exception {\n \n final Properties p = new Properties();\n p.put(\"movieDatabase\", \"new://Resource?type=DataSource\");\n p.put(\"movieDatabase.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"movieDatabase.JdbcUrl\", \"jdbc:hsqldb:mem:moviedb\");\n \n final Context context = EJBContainer.createEJBContainer(p).getContext();\n \n Movies movies = (Movies) context.lookup(\"java:global/injection-of-entitymanager/Movies\");\n \n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n movies.addMovie(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n movies.addMovie(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n \n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n \n for (Movie movie : list) {\n movies.deleteMovie(movie);\n }\n \n assertEquals(\"Movies.getMovies()\", 0, movies.getMovies().size());\n }\n }\n\n# Running\n\nWhen we run our test case we should see output similar to the following.\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.injection.jpa.MoviesTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/injection-of-entitymanager\n INFO - openejb.base = /Users/dblevins/examples/injection-of-entitymanager\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/injection-of-entitymanager/target/classes\n INFO - Beginning load: /Users/dblevins/examples/injection-of-entitymanager/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/injection-of-entitymanager\n INFO - Configuring Service(id=Default Stateful Container, type=Container, provider-id=Default Stateful Container)\n INFO - Auto-creating a container for bean Movies: Container(type=STATEFUL, id=Default Stateful Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.injection.jpa.MoviesTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring PersistenceUnit(name=movie-unit)\n INFO - Auto-creating a Resource with id 'movieDatabaseNonJta' of type 'DataSource for 'movie-unit'.\n INFO - Configuring Service(id=movieDatabaseNonJta, type=Resource, provider-id=movieDatabase)\n INFO - Adjusting PersistenceUnit movie-unit <non-jta-data-source> to Resource ID 'movieDatabaseNonJta' from 'movieDatabaseUnmanaged'\n INFO - Enterprise application \"/Users/dblevins/examples/injection-of-entitymanager\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/injection-of-entitymanager\n INFO - PersistenceUnit(name=movie-unit, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 462ms\n INFO - Jndi(name=\"java:global/injection-of-entitymanager/Movies!org.superbiz.injection.jpa.Movies\")\n INFO - Jndi(name=\"java:global/injection-of-entitymanager/Movies\")\n INFO - Jndi(name=\"java:global/EjbModule1461341140/org.superbiz.injection.jpa.MoviesTest!org.superbiz.injection.jpa.MoviesTest\")\n INFO - Jndi(name=\"java:global/EjbModule1461341140/org.superbiz.injection.jpa.MoviesTest\")\n INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Created Ejb(deployment-id=org.superbiz.injection.jpa.MoviesTest, ejb-name=org.superbiz.injection.jpa.MoviesTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Started Ejb(deployment-id=org.superbiz.injection.jpa.MoviesTest, ejb-name=org.superbiz.injection.jpa.MoviesTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/injection-of-entitymanager)\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.301 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/injection-of-entitymanager"
}
],
"enumerated":[
{
"name":"jpa-enumerated",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/jpa-enumerated"
}
],
"enventry":[
{
"name":"injection-of-env-entry",
"readme":"Title: Using EnvEntries\n\nThe `@Resource` annotation can be used to inject several things including\nDataSources, Topics, Queues, etc. Most of these are container supplied objects.\n\nIt is possible, however, to supply your own values to be injected via an `<env-entry>`\nin your `ejb-jar.xml` or `web.xml` deployment descriptor. Java EE 6 supported `<env-entry>` types\nare limited to the following:\n\n - java.lang.String\n - java.lang.Integer\n - java.lang.Short\n - java.lang.Float\n - java.lang.Double\n - java.lang.Byte\n - java.lang.Character\n - java.lang.Boolean\n - java.lang.Class\n - java.lang.Enum (any enum)\n\nSee also the [Custom Injection](../custom-injection) exmaple for a TomEE and OpenEJB feature that will let you\nuse more than just the above types as well as declare `<env-entry>` items with a plain properties file.\n\n# Using @Resource for basic properties\n\nThe use of the `@Resource` annotation isn't limited to setters. For\nexample, this annotation could have been used on the corresponding *field*\nlike so:\n\n @Resource\n private int maxLineItems;\n\nA fuller example might look like this:\n\n package org.superbiz.injection.enventry;\n \n import javax.annotation.Resource;\n import javax.ejb.Singleton;\n import java.util.Date;\n \n @Singleton\n public class Configuration {\n \n @Resource\n private String color;\n \n @Resource\n private Shape shape;\n \n @Resource\n private Class strategy;\n \n @Resource(name = \"date\")\n private long date;\n \n public String getColor() {\n return color;\n }\n \n public Shape getShape() {\n return shape;\n }\n \n public Class getStrategy() {\n return strategy;\n }\n \n public Date getDate() {\n return new Date(date);\n }\n }\n\nHere we have an `@Singleton` bean called `Confuration` that has the following properties (`<env-entry>` items)\n\n- String color\n- Shape shape\n- Class strategy\n- long date\n\n## Supplying @Resource values for <env-entry> items in ejb-jar.xml\n\nThe values for our `color`, `shape`, `strategy` and `date` properties are supplied via `<env-entry>` elements in the `ejb-jar.xml` file or the\n`web.xml` file like so:\n\n\n <ejb-jar xmlns=\"http://java.sun.com/xml/ns/javaee\" version=\"3.0\" metadata-complete=\"false\">\n <enterprise-beans>\n <session>\n <ejb-name>Configuration</ejb-name>\n <env-entry>\n <env-entry-name>org.superbiz.injection.enventry.Configuration/color</env-entry-name>\n <env-entry-type>java.lang.String</env-entry-type>\n <env-entry-value>orange</env-entry-value>\n </env-entry>\n <env-entry>\n <env-entry-name>org.superbiz.injection.enventry.Configuration/shape</env-entry-name>\n <env-entry-type>org.superbiz.injection.enventry.Shape</env-entry-type>\n <env-entry-value>TRIANGLE</env-entry-value>\n </env-entry>\n <env-entry>\n <env-entry-name>org.superbiz.injection.enventry.Configuration/strategy</env-entry-name>\n <env-entry-type>java.lang.Class</env-entry-type>\n <env-entry-value>org.superbiz.injection.enventry.Widget</env-entry-value>\n </env-entry>\n <env-entry>\n <description>The name was explicitly set in the annotation so the classname prefix isn't required</description>\n <env-entry-name>date</env-entry-name>\n <env-entry-type>java.lang.Long</env-entry-type>\n <env-entry-value>123456789</env-entry-value>\n </env-entry>\n </session>\n </enterprise-beans>\n </ejb-jar>\n\n\n### Using the @Resource 'name' attribute\n\nNote that `date` was referenced by `name` as:\n\n @Resource(name = \"date\")\n private long date;\n\nWhen the `@Resource(name)` is used, you do not need to specify the full class name of the bean and can do it briefly like so:\n\n <env-entry>\n <description>The name was explicitly set in the annotation so the classname prefix isn't required</description>\n <env-entry-name>date</env-entry-name>\n <env-entry-type>java.lang.Long</env-entry-type>\n <env-entry-value>123456789</env-entry-value>\n </env-entry>\n\nConversly, `color` was not referenced by `name`\n\n @Resource\n private String color;\n\nWhen something is not referenced by `name` in the `@Resource` annotation a default name is created. The format is essentially this:\n\n bean.getClass() + \"/\" + field.getName()\n\nSo the default `name` of the above `color` property ends up being `org.superbiz.injection.enventry.Configuration/color`. This is the name\nwe must use when we attempt to decalre a value for it in xml.\n\n <env-entry>\n <env-entry-name>org.superbiz.injection.enventry.Configuration/color</env-entry-name>\n <env-entry-type>java.lang.String</env-entry-type>\n <env-entry-value>orange</env-entry-value>\n </env-entry>\n\n### @Resource and Enum (Enumerations)\n\nThe `shape` field is actually a custom Java Enum type\n\n package org.superbiz.injection.enventry;\n\n public enum Shape {\n \n CIRCLE,\n TRIANGLE,\n SQUARE\n }\n\nAs of Java EE 6, java.lang.Enum types are allowed as `<env-entry>` items. Declaring one in xml is done using the actual enum's class name like so:\n\n <env-entry>\n <env-entry-name>org.superbiz.injection.enventry.Configuration/shape</env-entry-name>\n <env-entry-type>org.superbiz.injection.enventry.Shape</env-entry-type>\n <env-entry-value>TRIANGLE</env-entry-value>\n </env-entry>\n\nDo not use `<env-entry-type>java.lang.Enum</env-entry-type>` or it will not work!\n\n## ConfigurationTest\n\n package org.superbiz.injection.enventry;\n \n import junit.framework.TestCase;\n \n import javax.ejb.embeddable.EJBContainer;\n import javax.naming.Context;\n import java.util.Date;\n \n public class ConfigurationTest extends TestCase {\n \n \n public void test() throws Exception {\n final Context context = EJBContainer.createEJBContainer().getContext();\n \n final Configuration configuration = (Configuration) context.lookup(\"java:global/injection-of-env-entry/Configuration\");\n \n assertEquals(\"orange\", configuration.getColor());\n \n assertEquals(Shape.TRIANGLE, configuration.getShape());\n \n assertEquals(Widget.class, configuration.getStrategy());\n \n assertEquals(new Date(123456789), configuration.getDate());\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.injection.enventry.ConfigurationTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/injection-of-env-entry\n INFO - openejb.base = /Users/dblevins/examples/injection-of-env-entry\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/injection-of-env-entry/target/classes\n INFO - Beginning load: /Users/dblevins/examples/injection-of-env-entry/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/injection-of-env-entry\n WARN - Method 'lookup' is not available for 'javax.annotation.Resource'. Probably using an older Runtime.\n INFO - Configuring Service(id=Default Singleton Container, type=Container, provider-id=Default Singleton Container)\n INFO - Auto-creating a container for bean Configuration: Container(type=SINGLETON, id=Default Singleton Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.injection.enventry.ConfigurationTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Enterprise application \"/Users/dblevins/examples/injection-of-env-entry\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/injection-of-env-entry\n INFO - Jndi(name=\"java:global/injection-of-env-entry/Configuration!org.superbiz.injection.enventry.Configuration\")\n INFO - Jndi(name=\"java:global/injection-of-env-entry/Configuration\")\n INFO - Jndi(name=\"java:global/EjbModule1355224018/org.superbiz.injection.enventry.ConfigurationTest!org.superbiz.injection.enventry.ConfigurationTest\")\n INFO - Jndi(name=\"java:global/EjbModule1355224018/org.superbiz.injection.enventry.ConfigurationTest\")\n INFO - Created Ejb(deployment-id=org.superbiz.injection.enventry.ConfigurationTest, ejb-name=org.superbiz.injection.enventry.ConfigurationTest, container=Default Managed Container)\n INFO - Created Ejb(deployment-id=Configuration, ejb-name=Configuration, container=Default Singleton Container)\n INFO - Started Ejb(deployment-id=org.superbiz.injection.enventry.ConfigurationTest, ejb-name=org.superbiz.injection.enventry.ConfigurationTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=Configuration, ejb-name=Configuration, container=Default Singleton Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/injection-of-env-entry)\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.664 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/injection-of-env-entry"
}
],
"evaluation":[
{
"name":"bval-evaluation-redeployment",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/bval-evaluation-redeployment"
}
],
"event":[
{
"name":"server-events",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/server-events"
},
{
"name":"cdi-events",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/cdi-events"
},
{
"name":"schedule-events",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/schedule-events"
}
],
"examples":[
{
"name":"ejb-examples",
"readme":"Title: EJB Examples\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## AnnotatedEJB\n\n package org.superbiz.servlet;\n \n import javax.annotation.Resource;\n import javax.ejb.LocalBean;\n import javax.ejb.Stateless;\n import javax.sql.DataSource;\n \n @Stateless\n @LocalBean\n public class AnnotatedEJB implements AnnotatedEJBLocal, AnnotatedEJBRemote {\n @Resource\n private DataSource ds;\n \n private String name = \"foo\";\n \n public String getName() {\n return name;\n }\n \n public void setName(String name) {\n this.name = name;\n }\n \n public DataSource getDs() {\n return ds;\n }\n \n public void setDs(DataSource ds) {\n this.ds = ds;\n }\n \n public String toString() {\n return \"AnnotatedEJB[name=\" + name + \"]\";\n }\n }\n\n## AnnotatedEJBLocal\n\n package org.superbiz.servlet;\n \n import javax.ejb.Local;\n import javax.sql.DataSource;\n \n @Local\n public interface AnnotatedEJBLocal {\n String getName();\n \n void setName(String name);\n \n DataSource getDs();\n \n void setDs(DataSource ds);\n }\n\n## AnnotatedEJBRemote\n\n package org.superbiz.servlet;\n \n import javax.ejb.Remote;\n \n @Remote\n public interface AnnotatedEJBRemote {\n String getName();\n \n void setName(String name);\n }\n\n## AnnotatedServlet\n\n package org.superbiz.servlet;\n \n import javax.annotation.Resource;\n import javax.ejb.EJB;\n import javax.naming.InitialContext;\n import javax.naming.NamingException;\n import javax.servlet.ServletException;\n import javax.servlet.ServletOutputStream;\n import javax.servlet.http.HttpServlet;\n import javax.servlet.http.HttpServletRequest;\n import javax.servlet.http.HttpServletResponse;\n import javax.sql.DataSource;\n import java.io.IOException;\n \n public class AnnotatedServlet extends HttpServlet {\n @EJB\n private AnnotatedEJBLocal localEJB;\n \n @EJB\n private AnnotatedEJBRemote remoteEJB;\n \n @EJB\n private AnnotatedEJB localbeanEJB;\n \n @Resource\n private DataSource ds;\n \n \n protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n response.setContentType(\"text/plain\");\n ServletOutputStream out = response.getOutputStream();\n \n out.println(\"LocalBean EJB\");\n out.println(\"@EJB=\" + localbeanEJB);\n if (localbeanEJB != null) {\n out.println(\"@EJB.getName()=\" + localbeanEJB.getName());\n out.println(\"@EJB.getDs()=\" + localbeanEJB.getDs());\n }\n out.println(\"JNDI=\" + lookupField(\"localbeanEJB\"));\n out.println();\n \n out.println(\"Local EJB\");\n out.println(\"@EJB=\" + localEJB);\n if (localEJB != null) {\n out.println(\"@EJB.getName()=\" + localEJB.getName());\n out.println(\"@EJB.getDs()=\" + localEJB.getDs());\n }\n out.println(\"JNDI=\" + lookupField(\"localEJB\"));\n out.println();\n \n out.println(\"Remote EJB\");\n out.println(\"@EJB=\" + remoteEJB);\n if (localEJB != null) {\n out.println(\"@EJB.getName()=\" + remoteEJB.getName());\n }\n out.println(\"JNDI=\" + lookupField(\"remoteEJB\"));\n out.println();\n \n \n out.println(\"DataSource\");\n out.println(\"@Resource=\" + ds);\n out.println(\"JNDI=\" + lookupField(\"ds\"));\n }\n \n private Object lookupField(String name) {\n try {\n return new InitialContext().lookup(\"java:comp/env/\" + getClass().getName() + \"/\" + name);\n } catch (NamingException e) {\n return null;\n }\n }\n }\n\n## ClientHandler\n\n package org.superbiz.servlet;\n \n import javax.xml.ws.handler.Handler;\n import javax.xml.ws.handler.MessageContext;\n \n public class ClientHandler implements Handler {\n public boolean handleMessage(MessageContext messageContext) {\n WebserviceServlet.write(\" ClientHandler handleMessage\");\n return true;\n }\n \n public void close(MessageContext messageContext) {\n WebserviceServlet.write(\" ClientHandler close\");\n }\n \n public boolean handleFault(MessageContext messageContext) {\n WebserviceServlet.write(\" ClientHandler handleFault\");\n return true;\n }\n }\n\n## HelloEjb\n\n package org.superbiz.servlet;\n \n import javax.jws.WebService;\n \n @WebService(targetNamespace = \"http://examples.org/wsdl\")\n public interface HelloEjb {\n String hello(String name);\n }\n\n## HelloEjbService\n\n package org.superbiz.servlet;\n \n import javax.ejb.Stateless;\n import javax.jws.HandlerChain;\n import javax.jws.WebService;\n \n @WebService(\n portName = \"HelloEjbPort\",\n serviceName = \"HelloEjbService\",\n targetNamespace = \"http://examples.org/wsdl\",\n endpointInterface = \"org.superbiz.servlet.HelloEjb\"\n )\n @HandlerChain(file = \"server-handlers.xml\")\n @Stateless\n public class HelloEjbService implements HelloEjb {\n public String hello(String name) {\n WebserviceServlet.write(\" HelloEjbService hello(\" + name + \")\");\n if (name == null) name = \"World\";\n return \"Hello \" + name + \" from EJB Webservice!\";\n }\n }\n\n## HelloPojo\n\n package org.superbiz.servlet;\n \n import javax.jws.WebService;\n \n @WebService(targetNamespace = \"http://examples.org/wsdl\")\n public interface HelloPojo {\n String hello(String name);\n }\n\n## HelloPojoService\n\n package org.superbiz.servlet;\n \n import javax.jws.HandlerChain;\n import javax.jws.WebService;\n \n @WebService(\n portName = \"HelloPojoPort\",\n serviceName = \"HelloPojoService\",\n targetNamespace = \"http://examples.org/wsdl\",\n endpointInterface = \"org.superbiz.servlet.HelloPojo\"\n )\n @HandlerChain(file = \"server-handlers.xml\")\n public class HelloPojoService implements HelloPojo {\n public String hello(String name) {\n WebserviceServlet.write(\" HelloPojoService hello(\" + name + \")\");\n if (name == null) name = \"World\";\n return \"Hello \" + name + \" from Pojo Webservice!\";\n }\n }\n\n## JndiServlet\n\n package org.superbiz.servlet;\n \n import javax.naming.Context;\n import javax.naming.InitialContext;\n import javax.naming.NameClassPair;\n import javax.naming.NamingException;\n import javax.servlet.ServletException;\n import javax.servlet.ServletOutputStream;\n import javax.servlet.http.HttpServlet;\n import javax.servlet.http.HttpServletRequest;\n import javax.servlet.http.HttpServletResponse;\n import java.io.IOException;\n import java.util.Collections;\n import java.util.Map;\n import java.util.TreeMap;\n \n public class JndiServlet extends HttpServlet {\n protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n response.setContentType(\"text/plain\");\n ServletOutputStream out = response.getOutputStream();\n \n Map<String, Object> bindings = new TreeMap<String, Object>(String.CASE_INSENSITIVE_ORDER);\n try {\n Context context = (Context) new InitialContext().lookup(\"java:comp/\");\n addBindings(\"\", bindings, context);\n } catch (NamingException e) {\n throw new ServletException(e);\n }\n \n out.println(\"JNDI Context:\");\n for (Map.Entry<String, Object> entry : bindings.entrySet()) {\n if (entry.getValue() != null) {\n out.println(\" \" + entry.getKey() + \"=\" + entry.getValue());\n } else {\n out.println(\" \" + entry.getKey());\n }\n }\n }\n \n private void addBindings(String path, Map<String, Object> bindings, Context context) {\n try {\n for (NameClassPair pair : Collections.list(context.list(\"\"))) {\n String name = pair.getName();\n String className = pair.getClassName();\n if (\"org.apache.naming.resources.FileDirContext$FileResource\".equals(className)) {\n bindings.put(path + name, \"<file>\");\n } else {\n try {\n Object value = context.lookup(name);\n if (value instanceof Context) {\n Context nextedContext = (Context) value;\n bindings.put(path + name, \"\");\n addBindings(path + name + \"/\", bindings, nextedContext);\n } else {\n bindings.put(path + name, value);\n }\n } catch (NamingException e) {\n // lookup failed\n bindings.put(path + name, \"ERROR: \" + e.getMessage());\n }\n }\n }\n } catch (NamingException e) {\n bindings.put(path, \"ERROR: list bindings threw an exception: \" + e.getMessage());\n }\n }\n }\n\n## JpaBean\n\n package org.superbiz.servlet;\n \n import javax.persistence.Column;\n import javax.persistence.Entity;\n import javax.persistence.GeneratedValue;\n import javax.persistence.GenerationType;\n import javax.persistence.Id;\n \n @Entity\n public class JpaBean {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column(name = \"id\")\n private int id;\n \n @Column(name = \"name\")\n private String name;\n \n public int getId() {\n return id;\n }\n \n public String getName() {\n return name;\n }\n \n public void setName(String name) {\n this.name = name;\n }\n \n \n public String toString() {\n return \"[JpaBean id=\" + id + \", name=\" + name + \"]\";\n }\n }\n\n## JpaServlet\n\n package org.superbiz.servlet;\n \n import javax.persistence.EntityManager;\n import javax.persistence.EntityManagerFactory;\n import javax.persistence.EntityTransaction;\n import javax.persistence.PersistenceUnit;\n import javax.persistence.Query;\n import javax.servlet.ServletException;\n import javax.servlet.ServletOutputStream;\n import javax.servlet.http.HttpServlet;\n import javax.servlet.http.HttpServletRequest;\n import javax.servlet.http.HttpServletResponse;\n import java.io.IOException;\n \n public class JpaServlet extends HttpServlet {\n @PersistenceUnit(name = \"jpa-example\")\n private EntityManagerFactory emf;\n \n \n protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n response.setContentType(\"text/plain\");\n ServletOutputStream out = response.getOutputStream();\n \n out.println(\"@PersistenceUnit=\" + emf);\n \n EntityManager em = emf.createEntityManager();\n EntityTransaction transaction = em.getTransaction();\n transaction.begin();\n \n JpaBean jpaBean = new JpaBean();\n jpaBean.setName(\"JpaBean\");\n em.persist(jpaBean);\n \n transaction.commit();\n transaction.begin();\n \n Query query = em.createQuery(\"SELECT j FROM JpaBean j WHERE j.name='JpaBean'\");\n jpaBean = (JpaBean) query.getSingleResult();\n out.println(\"Loaded \" + jpaBean);\n \n em.remove(jpaBean);\n \n transaction.commit();\n transaction.begin();\n \n query = em.createQuery(\"SELECT count(j) FROM JpaBean j WHERE j.name='JpaBean'\");\n int count = ((Number) query.getSingleResult()).intValue();\n if (count == 0) {\n out.println(\"Removed \" + jpaBean);\n } else {\n out.println(\"ERROR: unable to remove\" + jpaBean);\n }\n \n transaction.commit();\n }\n }\n\n## ResourceBean\n\n package org.superbiz.servlet;\n \n public class ResourceBean {\n private String value;\n \n public String getValue() {\n return value;\n }\n \n public void setValue(String value) {\n this.value = value;\n }\n \n public String toString() {\n return \"[ResourceBean \" + value + \"]\";\n }\n }\n\n## RunAsServlet\n\n package org.superbiz.servlet;\n \n import javax.ejb.EJB;\n import javax.ejb.EJBAccessException;\n import javax.servlet.ServletException;\n import javax.servlet.ServletOutputStream;\n import javax.servlet.http.HttpServlet;\n import javax.servlet.http.HttpServletRequest;\n import javax.servlet.http.HttpServletResponse;\n import java.io.IOException;\n import java.security.Principal;\n \n public class RunAsServlet extends HttpServlet {\n @EJB\n private SecureEJBLocal secureEJBLocal;\n \n protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n response.setContentType(\"text/plain\");\n ServletOutputStream out = response.getOutputStream();\n \n out.println(\"Servlet\");\n Principal principal = request.getUserPrincipal();\n if (principal != null) {\n out.println(\"Servlet.getUserPrincipal()=\" + principal + \" [\" + principal.getName() + \"]\");\n } else {\n out.println(\"Servlet.getUserPrincipal()=<null>\");\n }\n out.println(\"Servlet.isCallerInRole(\\\"user\\\")=\" + request.isUserInRole(\"user\"));\n out.println(\"Servlet.isCallerInRole(\\\"manager\\\")=\" + request.isUserInRole(\"manager\"));\n out.println(\"Servlet.isCallerInRole(\\\"fake\\\")=\" + request.isUserInRole(\"fake\"));\n out.println();\n \n out.println(\"@EJB=\" + secureEJBLocal);\n if (secureEJBLocal != null) {\n principal = secureEJBLocal.getCallerPrincipal();\n if (principal != null) {\n out.println(\"@EJB.getCallerPrincipal()=\" + principal + \" [\" + principal.getName() + \"]\");\n } else {\n out.println(\"@EJB.getCallerPrincipal()=<null>\");\n }\n out.println(\"@EJB.isCallerInRole(\\\"user\\\")=\" + secureEJBLocal.isCallerInRole(\"user\"));\n out.println(\"@EJB.isCallerInRole(\\\"manager\\\")=\" + secureEJBLocal.isCallerInRole(\"manager\"));\n out.println(\"@EJB.isCallerInRole(\\\"fake\\\")=\" + secureEJBLocal.isCallerInRole(\"fake\"));\n \n try {\n secureEJBLocal.allowUserMethod();\n out.println(\"@EJB.allowUserMethod() ALLOWED\");\n } catch (EJBAccessException e) {\n out.println(\"@EJB.allowUserMethod() DENIED\");\n }\n \n try {\n secureEJBLocal.allowManagerMethod();\n out.println(\"@EJB.allowManagerMethod() ALLOWED\");\n } catch (EJBAccessException e) {\n out.println(\"@EJB.allowManagerMethod() DENIED\");\n }\n \n try {\n secureEJBLocal.allowFakeMethod();\n out.println(\"@EJB.allowFakeMethod() ALLOWED\");\n } catch (EJBAccessException e) {\n out.println(\"@EJB.allowFakeMethod() DENIED\");\n }\n \n try {\n secureEJBLocal.denyAllMethod();\n out.println(\"@EJB.denyAllMethod() ALLOWED\");\n } catch (EJBAccessException e) {\n out.println(\"@EJB.denyAllMethod() DENIED\");\n }\n }\n out.println();\n }\n }\n\n## SecureEJB\n\n package org.superbiz.servlet;\n \n import javax.annotation.Resource;\n import javax.annotation.security.DeclareRoles;\n import javax.annotation.security.DenyAll;\n import javax.annotation.security.RolesAllowed;\n import javax.ejb.SessionContext;\n import javax.ejb.Stateless;\n import java.security.Principal;\n \n @Stateless\n @DeclareRoles({\"user\", \"manager\", \"fake\"})\n public class SecureEJB implements SecureEJBLocal {\n @Resource\n private SessionContext context;\n \n public Principal getCallerPrincipal() {\n return context.getCallerPrincipal();\n }\n \n public boolean isCallerInRole(String role) {\n return context.isCallerInRole(role);\n }\n \n @RolesAllowed(\"user\")\n public void allowUserMethod() {\n }\n \n @RolesAllowed(\"manager\")\n public void allowManagerMethod() {\n }\n \n @RolesAllowed(\"fake\")\n public void allowFakeMethod() {\n }\n \n @DenyAll\n public void denyAllMethod() {\n }\n \n public String toString() {\n return \"SecureEJB[userName=\" + getCallerPrincipal() + \"]\";\n }\n }\n\n## SecureEJBLocal\n\n package org.superbiz.servlet;\n \n import javax.ejb.Local;\n import java.security.Principal;\n \n @Local\n public interface SecureEJBLocal {\n Principal getCallerPrincipal();\n \n boolean isCallerInRole(String role);\n \n void allowUserMethod();\n \n void allowManagerMethod();\n \n void allowFakeMethod();\n \n void denyAllMethod();\n }\n\n## SecureServlet\n\n package org.superbiz.servlet;\n \n import javax.ejb.EJB;\n import javax.ejb.EJBAccessException;\n import javax.servlet.ServletException;\n import javax.servlet.ServletOutputStream;\n import javax.servlet.http.HttpServlet;\n import javax.servlet.http.HttpServletRequest;\n import javax.servlet.http.HttpServletResponse;\n import java.io.IOException;\n import java.security.Principal;\n \n public class SecureServlet extends HttpServlet {\n @EJB\n private SecureEJBLocal secureEJBLocal;\n \n protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n response.setContentType(\"text/plain\");\n ServletOutputStream out = response.getOutputStream();\n \n out.println(\"Servlet\");\n Principal principal = request.getUserPrincipal();\n if (principal != null) {\n out.println(\"Servlet.getUserPrincipal()=\" + principal + \" [\" + principal.getName() + \"]\");\n } else {\n out.println(\"Servlet.getUserPrincipal()=<null>\");\n }\n out.println(\"Servlet.isCallerInRole(\\\"user\\\")=\" + request.isUserInRole(\"user\"));\n out.println(\"Servlet.isCallerInRole(\\\"manager\\\")=\" + request.isUserInRole(\"manager\"));\n out.println(\"Servlet.isCallerInRole(\\\"fake\\\")=\" + request.isUserInRole(\"fake\"));\n out.println();\n \n out.println(\"@EJB=\" + secureEJBLocal);\n if (secureEJBLocal != null) {\n principal = secureEJBLocal.getCallerPrincipal();\n if (principal != null) {\n out.println(\"@EJB.getCallerPrincipal()=\" + principal + \" [\" + principal.getName() + \"]\");\n } else {\n out.println(\"@EJB.getCallerPrincipal()=<null>\");\n }\n out.println(\"@EJB.isCallerInRole(\\\"user\\\")=\" + secureEJBLocal.isCallerInRole(\"user\"));\n out.println(\"@EJB.isCallerInRole(\\\"manager\\\")=\" + secureEJBLocal.isCallerInRole(\"manager\"));\n out.println(\"@EJB.isCallerInRole(\\\"fake\\\")=\" + secureEJBLocal.isCallerInRole(\"fake\"));\n \n try {\n secureEJBLocal.allowUserMethod();\n out.println(\"@EJB.allowUserMethod() ALLOWED\");\n } catch (EJBAccessException e) {\n out.println(\"@EJB.allowUserMethod() DENIED\");\n }\n \n try {\n secureEJBLocal.allowManagerMethod();\n out.println(\"@EJB.allowManagerMethod() ALLOWED\");\n } catch (EJBAccessException e) {\n out.println(\"@EJB.allowManagerMethod() DENIED\");\n }\n \n try {\n secureEJBLocal.allowFakeMethod();\n out.println(\"@EJB.allowFakeMethod() ALLOWED\");\n } catch (EJBAccessException e) {\n out.println(\"@EJB.allowFakeMethod() DENIED\");\n }\n \n try {\n secureEJBLocal.denyAllMethod();\n out.println(\"@EJB.denyAllMethod() ALLOWED\");\n } catch (EJBAccessException e) {\n out.println(\"@EJB.denyAllMethod() DENIED\");\n }\n }\n out.println();\n }\n }\n\n## ServerHandler\n\n package org.superbiz.servlet;\n \n import javax.xml.ws.handler.Handler;\n import javax.xml.ws.handler.MessageContext;\n \n public class ServerHandler implements Handler {\n public boolean handleMessage(MessageContext messageContext) {\n WebserviceServlet.write(\" ServerHandler handleMessage\");\n return true;\n }\n \n public void close(MessageContext messageContext) {\n WebserviceServlet.write(\" ServerHandler close\");\n }\n \n public boolean handleFault(MessageContext messageContext) {\n WebserviceServlet.write(\" ServerHandler handleFault\");\n return true;\n }\n }\n\n## WebserviceClient\n\n package org.superbiz.servlet;\n \n import javax.xml.ws.Service;\n import java.io.PrintStream;\n import java.net.URL;\n \n public class WebserviceClient {\n /**\n * Unfortunately, to run this example with CXF you need to have a HUGE class path. This\n * is just what is required to run CXF:\n * <p/>\n * jaxb-api-2.0.jar\n * jaxb-impl-2.0.3.jar\n * <p/>\n * saaj-api-1.3.jar\n * saaj-impl-1.3.jar\n * <p/>\n * <p/>\n * cxf-api-2.0.2-incubator.jar\n * cxf-common-utilities-2.0.2-incubator.jar\n * cxf-rt-bindings-soap-2.0.2-incubator.jar\n * cxf-rt-core-2.0.2-incubator.jar\n * cxf-rt-databinding-jaxb-2.0.2-incubator.jar\n * cxf-rt-frontend-jaxws-2.0.2-incubator.jar\n * cxf-rt-frontend-simple-2.0.2-incubator.jar\n * cxf-rt-transports-http-jetty-2.0.2-incubator.jar\n * cxf-rt-transports-http-2.0.2-incubator.jar\n * cxf-tools-common-2.0.2-incubator.jar\n * <p/>\n * geronimo-activation_1.1_spec-1.0.jar\n * geronimo-annotation_1.0_spec-1.1.jar\n * geronimo-ejb_3.0_spec-1.0.jar\n * geronimo-jpa_3.0_spec-1.1.jar\n * geronimo-servlet_2.5_spec-1.1.jar\n * geronimo-stax-api_1.0_spec-1.0.jar\n * jaxws-api-2.0.jar\n * axis2-jws-api-1.3.jar\n * <p/>\n * wsdl4j-1.6.1.jar\n * xml-resolver-1.2.jar\n * XmlSchema-1.3.1.jar\n */\n public static void main(String[] args) throws Exception {\n PrintStream out = System.out;\n \n Service helloPojoService = Service.create(new URL(\"http://localhost:8080/ejb-examples/hello?wsdl\"), null);\n HelloPojo helloPojo = helloPojoService.getPort(HelloPojo.class);\n out.println();\n out.println(\"Pojo Webservice\");\n out.println(\" helloPojo.hello(\\\"Bob\\\")=\" + helloPojo.hello(\"Bob\"));\n out.println(\" helloPojo.hello(null)=\" + helloPojo.hello(null));\n out.println();\n \n Service helloEjbService = Service.create(new URL(\"http://localhost:8080/HelloEjbService?wsdl\"), null);\n HelloEjb helloEjb = helloEjbService.getPort(HelloEjb.class);\n out.println();\n out.println(\"EJB Webservice\");\n out.println(\" helloEjb.hello(\\\"Bob\\\")=\" + helloEjb.hello(\"Bob\"));\n out.println(\" helloEjb.hello(null)=\" + helloEjb.hello(null));\n out.println();\n }\n }\n\n## WebserviceServlet\n\n package org.superbiz.servlet;\n \n import javax.jws.HandlerChain;\n import javax.servlet.ServletException;\n import javax.servlet.ServletOutputStream;\n import javax.servlet.http.HttpServlet;\n import javax.servlet.http.HttpServletRequest;\n import javax.servlet.http.HttpServletResponse;\n import javax.xml.ws.WebServiceRef;\n import java.io.IOException;\n \n public class WebserviceServlet extends HttpServlet {\n \n @WebServiceRef\n @HandlerChain(file = \"client-handlers.xml\")\n private HelloPojo helloPojo;\n \n @WebServiceRef\n @HandlerChain(file = \"client-handlers.xml\")\n private HelloEjb helloEjb;\n \n protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n response.setContentType(\"text/plain\");\n ServletOutputStream out = response.getOutputStream();\n \n OUT = out;\n try {\n out.println(\"Pojo Webservice\");\n out.println(\" helloPojo.hello(\\\"Bob\\\")=\" + helloPojo.hello(\"Bob\"));\n out.println();\n out.println(\" helloPojo.hello(null)=\" + helloPojo.hello(null));\n out.println();\n out.println(\"EJB Webservice\");\n out.println(\" helloEjb.hello(\\\"Bob\\\")=\" + helloEjb.hello(\"Bob\"));\n out.println();\n out.println(\" helloEjb.hello(null)=\" + helloEjb.hello(null));\n out.println();\n } finally {\n OUT = out;\n }\n }\n \n private static ServletOutputStream OUT;\n \n public static void write(String message) {\n try {\n ServletOutputStream out = OUT;\n out.println(message);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n }\n\n\n## persistence.xml\n\n <persistence xmlns=\"http://java.sun.com/xml/ns/persistence\" version=\"1.0\">\n <persistence-unit transaction-type=\"RESOURCE_LOCAL\" name=\"jpa-example\">\n <jta-data-source>java:openejb/Connector/Default JDBC Database</jta-data-source>\n <non-jta-data-source>java:openejb/Connector/Default Unmanaged JDBC Database</non-jta-data-source>\n <class>org.superbiz.servlet.JpaBean</class>\n \n <properties>\n <property name=\"openjpa.jdbc.SynchronizeMappings\" value=\"buildSchema(ForeignKeys=true)\"/>\n </properties>\n </persistence-unit>\n </persistence>\n\n## client-handlers.xml\n\n <jws:handler-chains xmlns:jws=\"http://java.sun.com/xml/ns/javaee\">\n <jws:handler-chain>\n <jws:handler>\n <jws:handler-name>ClientHandler</jws:handler-name>\n <jws:handler-class>org.superbiz.servlet.ClientHandler</jws:handler-class>\n </jws:handler>\n </jws:handler-chain>\n </jws:handler-chains>\n \n\n## server-handlers.xml\n\n <jws:handler-chains xmlns:jws=\"http://java.sun.com/xml/ns/javaee\">\n <jws:handler-chain>\n <jws:handler>\n <jws:handler-name>ServerHandler</jws:handler-name>\n <jws:handler-class>org.superbiz.servlet.ServerHandler</jws:handler-class>\n </jws:handler>\n </jws:handler-chain>\n </jws:handler-chains>\n \n\n## context.xml\n\n <Context>\n <!-- This only works if the context is installed under the correct name -->\n <Realm className=\"org.apache.catalina.realm.MemoryRealm\"\n pathname=\"webapps/ejb-examples-1.0-SNAPSHOT/WEB-INF/tomcat-users.xml\"/>\n \n <Environment\n name=\"context.xml/environment\"\n value=\"ContextString\"\n type=\"java.lang.String\"/>\n <Resource\n name=\"context.xml/resource\"\n auth=\"Container\"\n type=\"org.superbiz.servlet.ResourceBean\"\n factory=\"org.apache.naming.factory.BeanFactory\"\n value=\"ContextResource\"/>\n <ResourceLink\n name=\"context.xml/resource-link\"\n global=\"server.xml/environment\"\n type=\"java.lang.String\"/>\n \n <!-- web.xml resources -->\n <Resource\n name=\"web.xml/resource-env-ref\"\n auth=\"Container\"\n type=\"org.superbiz.servlet.ResourceBean\"\n factory=\"org.apache.naming.factory.BeanFactory\"\n value=\"ContextResourceEnvRef\"/>\n <Resource\n name=\"web.xml/resource-ref\"\n auth=\"Container\"\n type=\"org.superbiz.servlet.ResourceBean\"\n factory=\"org.apache.naming.factory.BeanFactory\"\n value=\"ContextResourceRef\"/>\n <ResourceLink\n name=\"web.xml/resource-link\"\n global=\"server.xml/environment\"\n type=\"java.lang.String\"/>\n </Context>\n \n\n## jetty-web.xml\n\n <Configure class=\"org.eclipse.jetty.webapp.WebAppContext\">\n <Get name=\"securityHandler\">\n <Set name=\"loginService\">\n <New class=\"org.eclipse.jetty.security.HashLoginService\">\n <Set name=\"name\">Test Realm</Set>\n <Set name=\"config\"><SystemProperty name=\"jetty.home\" default=\".\"/>/etc/realm.properties\n </Set>\n </New>\n </Set>\n </Get>\n </Configure>\n\n## tomcat-users.xml\n\n <tomcat-users>\n <user name=\"manager\" password=\"manager\" roles=\"manager,user\"/>\n <user name=\"user\" password=\"user\" roles=\"user\"/>\n </tomcat-users>\n \n\n## web.xml\n\n <web-app xmlns=\"http://java.sun.com/xml/ns/javaee\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n metadata-complete=\"false\"\n version=\"2.5\">\n \n <display-name>OpenEJB Servlet Examples</display-name>\n \n <servlet>\n <servlet-name>AnnotatedServlet</servlet-name>\n <servlet-class>org.superbiz.servlet.AnnotatedServlet</servlet-class>\n </servlet>\n \n <servlet-mapping>\n <servlet-name>AnnotatedServlet</servlet-name>\n <url-pattern>/annotated/*</url-pattern>\n </servlet-mapping>\n \n <servlet>\n <servlet-name>JpaServlet</servlet-name>\n <servlet-class>org.superbiz.servlet.JpaServlet</servlet-class>\n </servlet>\n \n <servlet-mapping>\n <servlet-name>JpaServlet</servlet-name>\n <url-pattern>/jpa/*</url-pattern>\n </servlet-mapping>\n \n <servlet>\n <servlet-name>JndiServlet</servlet-name>\n <servlet-class>org.superbiz.servlet.JndiServlet</servlet-class>\n </servlet>\n \n <servlet-mapping>\n <servlet-name>JndiServlet</servlet-name>\n <url-pattern>/jndi/*</url-pattern>\n </servlet-mapping>\n \n <servlet>\n <servlet-name>RunAsServlet</servlet-name>\n <servlet-class>org.superbiz.servlet.RunAsServlet</servlet-class>\n <run-as>\n <role-name>fake</role-name>\n </run-as>\n </servlet>\n \n <servlet-mapping>\n <servlet-name>RunAsServlet</servlet-name>\n <url-pattern>/runas/*</url-pattern>\n </servlet-mapping>\n \n <servlet>\n <servlet-name>SecureServlet</servlet-name>\n <servlet-class>org.superbiz.servlet.SecureServlet</servlet-class>\n </servlet>\n \n <servlet-mapping>\n <servlet-name>SecureServlet</servlet-name>\n <url-pattern>/secure/*</url-pattern>\n </servlet-mapping>\n \n <security-constraint>\n <web-resource-collection>\n <web-resource-name>Secure Area</web-resource-name>\n <url-pattern>/secure/*</url-pattern>\n <url-pattern>/runas/*</url-pattern>\n </web-resource-collection>\n <auth-constraint>\n <role-name>user</role-name>\n </auth-constraint>\n </security-constraint>\n \n <servlet>\n <servlet-name>WebserviceServlet</servlet-name>\n <servlet-class>org.superbiz.servlet.WebserviceServlet</servlet-class>\n </servlet>\n \n <servlet-mapping>\n <servlet-name>WebserviceServlet</servlet-name>\n <url-pattern>/webservice/*</url-pattern>\n </servlet-mapping>\n \n \n <servlet>\n <servlet-name>HelloPojoService</servlet-name>\n <servlet-class>org.superbiz.servlet.HelloPojoService</servlet-class>\n </servlet>\n \n <servlet-mapping>\n <servlet-name>HelloPojoService</servlet-name>\n <url-pattern>/hello</url-pattern>\n </servlet-mapping>\n \n <login-config>\n <auth-method>BASIC</auth-method>\n </login-config>\n \n <security-role>\n <role-name>manager</role-name>\n </security-role>\n \n <security-role>\n <role-name>user</role-name>\n </security-role>\n \n <env-entry>\n <env-entry-name>web.xml/env-entry</env-entry-name>\n <env-entry-type>java.lang.String</env-entry-type>\n <env-entry-value>WebValue</env-entry-value>\n </env-entry>\n \n <resource-ref>\n <res-ref-name>web.xml/Data Source</res-ref-name>\n <res-type>javax.sql.DataSource</res-type>\n <res-auth>Container</res-auth>\n </resource-ref>\n \n <resource-env-ref>\n <resource-env-ref-name>web.xml/Queue</resource-env-ref-name>\n <resource-env-ref-type>javax.jms.Queue</resource-env-ref-type>\n </resource-env-ref>\n \n <ejb-ref>\n <ejb-ref-name>web.xml/EjbRemote</ejb-ref-name>\n <ejb-ref-type>Session</ejb-ref-type>\n <remote>org.superbiz.servlet.AnnotatedEJBRemote</remote>\n </ejb-ref>\n \n <ejb-local-ref>\n <ejb-ref-name>web.xml/EjLocal</ejb-ref-name>\n <ejb-ref-type>Session</ejb-ref-type>\n <local>org.superbiz.servlet.AnnotatedEJBLocal</local>\n </ejb-local-ref>\n \n <persistence-unit-ref>\n <persistence-unit-ref-name>web.xml/PersistenceUnit</persistence-unit-ref-name>\n <persistence-unit-name>jpa-example</persistence-unit-name>\n </persistence-unit-ref>\n \n <persistence-context-ref>\n <persistence-context-ref-name>web.xml/PersistenceContext</persistence-context-ref-name>\n <persistence-unit-name>jpa-example</persistence-unit-name>\n <persistence-context-type>Transactional</persistence-context-type>\n </persistence-context-ref>\n </web-app>\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/ejb-examples"
}
],
"exception":[
{
"name":"deltaspike-exception-handling",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/deltaspike-exception-handling"
}
],
"expression":[
{
"name":"schedule-expression",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/schedule-expression"
}
],
"field":[
{
"name":"cdi-produces-field",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/cdi-produces-field"
}
],
"fragment":[
{
"name":"persistence-fragment",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/persistence-fragment"
}
],
"fullstack":[
{
"name":"deltaspike-fullstack",
"readme":"Title: Apache DeltaSpike Demo\nNotice: Licensed to the Apache Software Foundation (ASF) under one\n or more contributor license agreements. See the NOTICE file\n distributed with this work for additional information\n regarding copyright ownership. The ASF licenses this file\n to you under the Apache License, Version 2.0 (the\n \"License\"); you may not use this file except in compliance\n with the License. You may obtain a copy of the License at\n .\n http://www.apache.org/licenses/LICENSE-2.0\n .\n Unless required by applicable law or agreed to in writing,\n software distributed under the License is distributed on an\n \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n KIND, either express or implied. See the License for the\n specific language governing permissions and limitations\n under the License.\n\n<h2>Steps to run the example</h2>\n\nBuild and start the demo:\n\n mvn clean package tomee:run\n\nOpen:\n\n http://localhost:8080/\n\nThis example shows how to improve JSF2/CDI/BV/JPA applications with features provided by Apache DeltaSpike and MyFaces ExtVal.\n\n<h2>Intro of Apache DeltaSpike and MyFaces ExtVal</h2>\n\nThe Apache DeltaSpike project hosts portable extensions for Contexts and Dependency Injection (CDI - JSR 299). DeltaSpike is a toolbox for your CDI application. Like CDI itself DeltaSpike is focused on type-safety. It is a modularized and extensible framework. So it's easy to choose the needed parts to facilitate the daily work in your project.\n\nMyFaces Extensions Validator (aka ExtVal) is a JSF centric validation framework which is compatible with JSF 1.x and JSF 2.x.\nThis example shows how it improves the default integration of Bean-Validation (JSR-303) with JSF2 as well as meta-data based cross-field validation.\n\n\n<h2>Illustrated Features</h2>\n\n<h3>Apache DeltaSpike</h3>\n\n<ul>\n <li><a href=\"./src/main/java/org/superbiz/deltaspike/view/config/Pages.java\" target=\"_blank\">Type-safe view-config</a></li>\n <li><a href=\"./src/main/java/org/superbiz/deltaspike/view/InfoPage.java\" target=\"_blank\">Type-safe (custom) view-meta-data</a></li>\n <li><a href=\"./src/main/java/org/superbiz/deltaspike/view/MenuBean.java\" target=\"_blank\">Type-safe navigation</a></li>\n <li><a href=\"./src/main/java/org/superbiz/deltaspike/CustomProjectStage.java\" target=\"_blank\">Type-safe custom project-stage</a></li>\n <li><a href=\"./src/main/java/org/superbiz/deltaspike/view/UserHolder.java\" target=\"_blank\">@WindowScoped</a></li>\n <li><a href=\"./src/main/java/org/superbiz/deltaspike/view/MenuBean.java\" target=\"_blank\">Controlling DeltaSpike grouped-conversations with GroupedConversationManager</a></li>\n <li><a href=\"./src/main/java/org/superbiz/deltaspike/view/FeedbackPage.java\" target=\"_blank\">@GroupedConversationScoped</a></li>\n <li><a href=\"./src/main/java/org/superbiz/deltaspike/view/FeedbackPage.java\" target=\"_blank\">Manual conversation handling</a></li>\n <li><a href=\"./src/main/java/org/superbiz/deltaspike/view/security/LoginAccessDecisionVoter.java\" target=\"_blank\">Secured pages (AccessDecisionVoter)</a></li>\n <li><a href=\"./src/main/java/org/superbiz/deltaspike/repository/Repository.java\" target=\"_blank\">@Transactional</a></li>\n <li><a href=\"./src/main/java/org/superbiz/deltaspike/view/RegistrationPage.java\" target=\"_blank\">I18n (type-safe messages)</a></li>\n <li><a href=\"./src/main/java/org/superbiz/deltaspike/domain/validation/UniqueUserNameValidator.java\" target=\"_blank\">Dependency-Injection for JSR303 (BV) constraint-validators</a></li>\n <li><a href=\"./src/main/java/org/superbiz/deltaspike/DebugPhaseListener.java\" target=\"_blank\">Dependency-Injection for JSF phase-listeners</a></li>\n</ul>\n\n<h3>Apache MyFaces ExtVal</h3>\n\n<ul>\n <li><a href=\"./src/main/java/org/superbiz/myfaces/view/RegistrationPage.java\" target=\"_blank\">Cross-Field validation (@Equals)</a></li>\n <li><a href=\"./src/main/java/org/superbiz/myfaces/view/RegistrationPage.java\" target=\"_blank\">Type-safe group-validation (@BeanValidation) for JSF action-methods</a></li>\n</ul>\n",
"url":"https://github.com/apache/tomee/tree/master/examples/deltaspike-fullstack"
}
],
"groovy":[
{
"name":"groovy-jpa",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/groovy-jpa"
},
{
"name":"groovy-spock",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/groovy-spock"
},
{
"name":"groovy-cdi",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/groovy-cdi"
}
],
"handlerchain":[
{
"name":"webservice-handlerchain",
"readme":"Title: @WebService handlers with @HandlerChain\n\nIn this example we see a basic JAX-WS `@WebService` component use a handler chain to alter incoming and outgoing SOAP messages. SOAP Handlers are similar to Servlet Filters or EJB/CDI Interceptors.\n\nAt high level, the steps involved are:\n\n 1. Create handler(s) implementing `javax.xml.ws.handler.soap.SOAPHandler`\n 1. Declare and order them in an xml file via `<handler-chain>`\n 1. Associate the xml file with an `@WebService` component via `@HandlerChain`\n\n## The @HandlerChain\n\nFirst we'll start with our plain `@WebService` bean, called `Calculator`, which is annotated with `@HandlerChain`\n\n @Singleton\n @WebService(\n portName = \"CalculatorPort\",\n serviceName = \"CalculatorService\",\n targetNamespace = \"http://superbiz.org/wsdl\",\n endpointInterface = \"org.superbiz.calculator.wsh.CalculatorWs\")\n @HandlerChain(file = \"handlers.xml\")\n public class Calculator implements CalculatorWs {\n\n public int sum(int add1, int add2) {\n return add1 + add2;\n }\n\n public int multiply(int mul1, int mul2) {\n return mul1 * mul2;\n }\n }\n\nHere we see `@HandlerChain` pointing to a file called `handlers.xml`. This file could be called anything, but it must be in the same jar and java package as our `Calculator` component.\n\n## The &lt;handler-chains> file\n\nOur `Calculator` service is in the package `org.superbiz.calculator.wsh`, which means our handler chain xml file must be at `org/superbiz/calculator/wsh/handlers.xml` in our application's classpath or the file will not be found and no handlers will be used.\n\nIn maven we achieve this by putting our handlers.xml in `src/main/resources` like so:\n\n - `src/main/resources/org/superbiz/calculator/wsh/handlers.xml`\n\nWith this file we declare and **order** our handler chain.\n\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <handler-chains xmlns=\"http://java.sun.com/xml/ns/javaee\">\n <handler-chain>\n <handler>\n <handler-name>org.superbiz.calculator.wsh.Inflate</handler-name>\n <handler-class>org.superbiz.calculator.wsh.Inflate</handler-class>\n </handler>\n <handler>\n <handler-name>org.superbiz.calculator.wsh.Increment</handler-name>\n <handler-class>org.superbiz.calculator.wsh.Increment</handler-class>\n </handler>\n </handler-chain>\n </handler-chains>\n\nThe order as you might suspect is:\n\n - `Inflate`\n - `Increment`\n\n## The SOAPHandler implementation\n\nOur `Inflate` handler has the job of monitoring *responses* to the `sum` and `multiply` operations and making them 1000 times better. Manipulation of the message is done by walking the `SOAPBody` and editing the nodes. The `handleMessage` method is invoked for both requests and responses, so it is important to check the `SOAPBody` before attempting to naviage the nodes.\n\n import org.w3c.dom.Node;\n import javax.xml.namespace.QName;\n import javax.xml.soap.SOAPBody;\n import javax.xml.soap.SOAPException;\n import javax.xml.soap.SOAPMessage;\n import javax.xml.ws.handler.MessageContext;\n import javax.xml.ws.handler.soap.SOAPHandler;\n import javax.xml.ws.handler.soap.SOAPMessageContext;\n import java.util.Collections;\n import java.util.Set;\n\n public class Inflate implements SOAPHandler<SOAPMessageContext> {\n\n public boolean handleMessage(SOAPMessageContext mc) {\n try {\n final SOAPMessage message = mc.getMessage();\n final SOAPBody body = message.getSOAPBody();\n final String localName = body.getFirstChild().getLocalName();\n\n if (\"sumResponse\".equals(localName) || \"multiplyResponse\".equals(localName)) {\n final Node responseNode = body.getFirstChild();\n final Node returnNode = responseNode.getFirstChild();\n final Node intNode = returnNode.getFirstChild();\n\n final int value = new Integer(intNode.getNodeValue());\n intNode.setNodeValue(Integer.toString(value * 1000));\n }\n\n return true;\n } catch (SOAPException e) {\n return false;\n }\n }\n\n public Set<QName> getHeaders() {\n return Collections.emptySet();\n }\n\n public void close(MessageContext mc) {\n }\n\n public boolean handleFault(SOAPMessageContext mc) {\n return true;\n }\n }\n\nThe `Increment` handler is identical in code and therefore not shown. Instead of multiplying by 1000, it simply adds 1.\n\n## The TestCase\n\nWe use the JAX-WS API to create a Java client for our `Calculator` web service and use it to invoke both the `sum` and `multiply` operations. Note the clever use of math to assert both the existence and order of our handlers. If `Inflate` and `Increment` were reversed, the responses would be 11000 and 13000 respectively.\n\n public class CalculatorTest {\n\n @BeforeClass\n public static void setUp() throws Exception {\n Properties properties = new Properties();\n properties.setProperty(\"openejb.embedded.remotable\", \"true\");\n EJBContainer.createEJBContainer(properties);\n }\n\n @Test\n public void testCalculatorViaWsInterface() throws Exception {\n final Service calculatorService = Service.create(\n new URL(\"http://127.0.0.1:4204/Calculator?wsdl\"),\n new QName(\"http://superbiz.org/wsdl\", \"CalculatorService\"));\n\n assertNotNull(calculatorService);\n\n final CalculatorWs calculator = calculatorService.getPort(CalculatorWs.class);\n\n // we expect our answers to come back 1000 times better, plus one!\n assertEquals(10001, calculator.sum(4, 6));\n assertEquals(12001, calculator.multiply(3, 4));\n }\n }\n\n## Running the example\n\nSimply run `mvn clean install` and you should see output similar to the following:\n\n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.calculator.wsh.CalculatorTest\n INFO - openejb.home = /Users/dblevins/work/all/trunk/openejb/examples/webservice-handlers\n INFO - openejb.base = /Users/dblevins/work/all/trunk/openejb/examples/webservice-handlers\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Cannot find the configuration file [conf/openejb.xml]. Will attempt to create one for the beans deployed.\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Creating TransactionManager(id=Default Transaction Manager)\n INFO - Creating SecurityService(id=Default Security Service)\n INFO - Beginning load: /Users/dblevins/work/all/trunk/openejb/examples/webservice-handlers/target/test-classes\n INFO - Beginning load: /Users/dblevins/work/all/trunk/openejb/examples/webservice-handlers/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/work/all/trunk/openejb/examples/webservice-handlers\n INFO - Auto-deploying ejb Calculator: EjbDeployment(deployment-id=Calculator)\n INFO - Configuring Service(id=Default Singleton Container, type=Container, provider-id=Default Singleton Container)\n INFO - Auto-creating a container for bean Calculator: Container(type=SINGLETON, id=Default Singleton Container)\n INFO - Creating Container(id=Default Singleton Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.calculator.wsh.CalculatorTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Creating Container(id=Default Managed Container)\n INFO - Enterprise application \"/Users/dblevins/work/all/trunk/openejb/examples/webservice-handlers\" loaded.\n INFO - Assembling app: /Users/dblevins/work/all/trunk/openejb/examples/webservice-handlers\n INFO - Created Ejb(deployment-id=Calculator, ejb-name=Calculator, container=Default Singleton Container)\n INFO - Started Ejb(deployment-id=Calculator, ejb-name=Calculator, container=Default Singleton Container)\n INFO - Deployed Application(path=/Users/dblevins/work/all/trunk/openejb/examples/webservice-handlers)\n INFO - Initializing network services\n INFO - Creating ServerService(id=httpejbd)\n INFO - Creating ServerService(id=cxf)\n INFO - Creating ServerService(id=admin)\n INFO - Creating ServerService(id=ejbd)\n INFO - Creating ServerService(id=ejbds)\n INFO - Initializing network services\n INFO - ** Starting Services **\n INFO - NAME IP PORT\n INFO - httpejbd 127.0.0.1 4204\n INFO - Creating Service {http://superbiz.org/wsdl}CalculatorService from class org.superbiz.calculator.wsh.CalculatorWs\n INFO - Setting the server's publish address to be http://nopath:80\n INFO - Webservice(wsdl=http://127.0.0.1:4204/Calculator, qname={http://superbiz.org/wsdl}CalculatorService) --> Ejb(id=Calculator)\n INFO - admin thread 127.0.0.1 4200\n INFO - ejbd 127.0.0.1 4201\n INFO - ejbd 127.0.0.1 4203\n INFO - -------\n INFO - Ready!\n INFO - Creating Service {http://superbiz.org/wsdl}CalculatorService from WSDL: http://127.0.0.1:4204/Calculator?wsdl\n INFO - Creating Service {http://superbiz.org/wsdl}CalculatorService from WSDL: http://127.0.0.1:4204/Calculator?wsdl\n INFO - Default SAAJ universe not set\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.783 sec\n\n Results :\n\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n\n## Inspecting the messages\n\nThe above would generate the following messages.\n\n### Calculator wsdl\n\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <wsdl:definitions xmlns:wsdl=\"http://schemas.xmlsoap.org/wsdl/\"\n name=\"CalculatorService\" targetNamespace=\"http://superbiz.org/wsdl\"\n xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\"\n xmlns:tns=\"http://superbiz.org/wsdl\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n <wsdl:types>\n <xsd:schema attributeFormDefault=\"unqualified\" elementFormDefault=\"unqualified\"\n targetNamespace=\"http://superbiz.org/wsdl\" xmlns:tns=\"http://superbiz.org/wsdl\"\n xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n <xsd:element name=\"multiply\" type=\"tns:multiply\"/>\n <xsd:complexType name=\"multiply\">\n <xsd:sequence>\n <xsd:element name=\"arg0\" type=\"xsd:int\"/>\n <xsd:element name=\"arg1\" type=\"xsd:int\"/>\n </xsd:sequence>\n </xsd:complexType>\n <xsd:element name=\"multiplyResponse\" type=\"tns:multiplyResponse\"/>\n <xsd:complexType name=\"multiplyResponse\">\n <xsd:sequence>\n <xsd:element name=\"return\" type=\"xsd:int\"/>\n </xsd:sequence>\n </xsd:complexType>\n <xsd:element name=\"sum\" type=\"tns:sum\"/>\n <xsd:complexType name=\"sum\">\n <xsd:sequence>\n <xsd:element name=\"arg0\" type=\"xsd:int\"/>\n <xsd:element name=\"arg1\" type=\"xsd:int\"/>\n </xsd:sequence>\n </xsd:complexType>\n <xsd:element name=\"sumResponse\" type=\"tns:sumResponse\"/>\n <xsd:complexType name=\"sumResponse\">\n <xsd:sequence>\n <xsd:element name=\"return\" type=\"xsd:int\"/>\n </xsd:sequence>\n </xsd:complexType>\n </xsd:schema>\n </wsdl:types>\n <wsdl:message name=\"multiplyResponse\">\n <wsdl:part element=\"tns:multiplyResponse\" name=\"parameters\">\n </wsdl:part>\n </wsdl:message>\n <wsdl:message name=\"sumResponse\">\n <wsdl:part element=\"tns:sumResponse\" name=\"parameters\">\n </wsdl:part>\n </wsdl:message>\n <wsdl:message name=\"sum\">\n <wsdl:part element=\"tns:sum\" name=\"parameters\">\n </wsdl:part>\n </wsdl:message>\n <wsdl:message name=\"multiply\">\n <wsdl:part element=\"tns:multiply\" name=\"parameters\">\n </wsdl:part>\n </wsdl:message>\n <wsdl:portType name=\"CalculatorWs\">\n <wsdl:operation name=\"multiply\">\n <wsdl:input message=\"tns:multiply\" name=\"multiply\">\n </wsdl:input>\n <wsdl:output message=\"tns:multiplyResponse\" name=\"multiplyResponse\">\n </wsdl:output>\n </wsdl:operation>\n <wsdl:operation name=\"sum\">\n <wsdl:input message=\"tns:sum\" name=\"sum\">\n </wsdl:input>\n <wsdl:output message=\"tns:sumResponse\" name=\"sumResponse\">\n </wsdl:output>\n </wsdl:operation>\n </wsdl:portType>\n <wsdl:binding name=\"CalculatorServiceSoapBinding\" type=\"tns:CalculatorWs\">\n <soap:binding style=\"document\" transport=\"http://schemas.xmlsoap.org/soap/http\"/>\n <wsdl:operation name=\"multiply\">\n <soap:operation soapAction=\"\" style=\"document\"/>\n <wsdl:input name=\"multiply\">\n <soap:body use=\"literal\"/>\n </wsdl:input>\n <wsdl:output name=\"multiplyResponse\">\n <soap:body use=\"literal\"/>\n </wsdl:output>\n </wsdl:operation>\n <wsdl:operation name=\"sum\">\n <soap:operation soapAction=\"\" style=\"document\"/>\n <wsdl:input name=\"sum\">\n <soap:body use=\"literal\"/>\n </wsdl:input>\n <wsdl:output name=\"sumResponse\">\n <soap:body use=\"literal\"/>\n </wsdl:output>\n </wsdl:operation>\n </wsdl:binding>\n <wsdl:service name=\"CalculatorService\">\n <wsdl:port binding=\"tns:CalculatorServiceSoapBinding\" name=\"CalculatorPort\">\n <soap:address location=\"http://127.0.0.1:4204/Calculator?wsdl\"/>\n </wsdl:port>\n </wsdl:service>\n </wsdl:definitions>\n\n### SOAP sum and sumResponse\n\nRequest:\n\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <soap:Body>\n <ns1:sum xmlns:ns1=\"http://superbiz.org/wsdl\">\n <arg0>4</arg0>\n <arg1>6</arg1>\n </ns1:sum>\n </soap:Body>\n </soap:Envelope>\n\nResponse:\n\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <soap:Body>\n <ns1:sumResponse xmlns:ns1=\"http://superbiz.org/wsdl\">\n <return>10001</return>\n </ns1:sumResponse>\n </soap:Body>\n </soap:Envelope>\n\n### SOAP multiply and multiplyResponse\n\nRequest:\n\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <soap:Body>\n <ns1:multiply xmlns:ns1=\"http://superbiz.org/wsdl\">\n <arg0>3</arg0>\n <arg1>4</arg1>\n </ns1:multiply>\n </soap:Body>\n </soap:Envelope>\n\nResponse:\n\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <soap:Body>\n <ns1:multiplyResponse xmlns:ns1=\"http://superbiz.org/wsdl\">\n <return>12001</return>\n </ns1:multiplyResponse>\n </soap:Body>\n </soap:Envelope>\n",
"url":"https://github.com/apache/tomee/tree/master/examples/webservice-handlerchain"
}
],
"helloworld":[
{
"name":"helloworld-weblogic",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/helloworld-weblogic"
}
],
"hibernate":[
{
"name":"jpa-hibernate",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/jpa-hibernate"
}
],
"holder":[
{
"name":"webservice-holder",
"readme":"Title: @WebService OUT params via javax.xml.ws.Holder\n\nWith SOAP it is possible to return multiple values in a single request. This is impossible in Java as a method can only return one object.\n\nJAX-WS solves this problem with the concept of Holders. A `javax.xml.ws.Holder` is a simple wrapper object that can be passed into the `@WebService` method as a parameter. The application sets the value of the holder during the request and the server will send the value back as an OUT parameter.\n\n## Using @WebParam and javax.xml.ws.Holder\n\nThe `@WebParam` annotation allows us to declare the `sum` and `multiply` Holders as `WebParam.Mode.OUT` parameters. As mentioned, these holders are simply empty buckets the application can fill in with data to have sent to the client. The server will pass them in uninitialized.\n\n @Stateless\n @WebService(\n portName = \"CalculatorPort\",\n serviceName = \"CalculatorService\",\n targetNamespace = \"http://superbiz.org/wsdl\",\n endpointInterface = \"org.superbiz.ws.out.CalculatorWs\")\n public class Calculator implements CalculatorWs {\n\n public void sumAndMultiply(int a, int b,\n @WebParam(name = \"sum\", mode = WebParam.Mode.OUT) Holder<Integer> sum,\n @WebParam(name = \"multiply\", mode = WebParam.Mode.OUT) Holder<Integer> multiply) {\n sum.value = a + b;\n multiply.value = a * b;\n }\n }\n\nIf the Holders were specified as `WebParam.Mode.INOUT` params, then the client could use them to send data and the application as well. The `Holder` instances would then be initialized with the data from the client request. The application could check the data before eventually overriting it with the response values.\n\n## The WSDL\n\nThe above JAX-WS `@WebService` component results in the folliwing WSDL that will be created automatically. Note the `sumAndMultiplyResponse` complext type returns two elements. These match the `@WebParam` declarations and our two `Holder<Integer>` params.\n\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <wsdl:definitions xmlns:wsdl=\"http://schemas.xmlsoap.org/wsdl/\"\n name=\"CalculatorService\"\n targetNamespace=\"http://superbiz.org/wsdl\"\n xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\"\n xmlns:tns=\"http://superbiz.org/wsdl\"\n xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n <wsdl:types>\n <xsd:schema attributeFormDefault=\"unqualified\" elementFormDefault=\"unqualified\"\n targetNamespace=\"http://superbiz.org/wsdl\"\n xmlns:tns=\"http://superbiz.org/wsdl\"\n xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n <xsd:element name=\"sumAndMultiply\" type=\"tns:sumAndMultiply\"/>\n <xsd:complexType name=\"sumAndMultiply\">\n <xsd:sequence>\n <xsd:element name=\"arg0\" type=\"xsd:int\"/>\n <xsd:element name=\"arg1\" type=\"xsd:int\"/>\n </xsd:sequence>\n </xsd:complexType>\n <xsd:element name=\"sumAndMultiplyResponse\" type=\"tns:sumAndMultiplyResponse\"/>\n <xsd:complexType name=\"sumAndMultiplyResponse\">\n <xsd:sequence>\n <xsd:element minOccurs=\"0\" name=\"sum\" type=\"xsd:int\"/>\n <xsd:element minOccurs=\"0\" name=\"multiply\" type=\"xsd:int\"/>\n </xsd:sequence>\n </xsd:complexType>\n </xsd:schema>\n </wsdl:types>\n <wsdl:message name=\"sumAndMultiplyResponse\">\n <wsdl:part element=\"tns:sumAndMultiplyResponse\" name=\"parameters\"/>\n </wsdl:message>\n <wsdl:message name=\"sumAndMultiply\">\n <wsdl:part element=\"tns:sumAndMultiply\" name=\"parameters\"/>\n </wsdl:message>\n <wsdl:portType name=\"CalculatorWs\">\n <wsdl:operation name=\"sumAndMultiply\">\n <wsdl:input message=\"tns:sumAndMultiply\" name=\"sumAndMultiply\"/>\n <wsdl:output message=\"tns:sumAndMultiplyResponse\" name=\"sumAndMultiplyResponse\"/>\n </wsdl:operation>\n </wsdl:portType>\n <wsdl:binding name=\"CalculatorServiceSoapBinding\" type=\"tns:CalculatorWs\">\n <soap:binding style=\"document\" transport=\"http://schemas.xmlsoap.org/soap/http\"/>\n <wsdl:operation name=\"sumAndMultiply\">\n <soap:operation soapAction=\"\" style=\"document\"/>\n <wsdl:input name=\"sumAndMultiply\">\n <soap:body use=\"literal\"/>\n </wsdl:input>\n <wsdl:output name=\"sumAndMultiplyResponse\">\n <soap:body use=\"literal\"/>\n </wsdl:output>\n </wsdl:operation>\n </wsdl:binding>\n <wsdl:service name=\"CalculatorService\">\n <wsdl:port binding=\"tns:CalculatorServiceSoapBinding\" name=\"CalculatorPort\">\n <soap:address location=\"http://127.0.0.1:4204/Calculator?wsdl\"/>\n </wsdl:port>\n </wsdl:service>\n </wsdl:definitions>\n\n## Testing the OUT params\n\nHere we see a JAX-WS client executing the `sumAndMultiply` operation. Two empty `Holder` instances are created and passed in as parameters. The data from the `sumAndMultiplyResponse` is placed in the `Holder` instances and is then available to the client after the operation completes.\n\nThe holders themselves are not actually sent in the request unless they are configured as INOUT params via WebParam.Mode.INOUT on `@WebParam`\n\n import org.junit.BeforeClass;\n import org.junit.Test;\n\n import javax.ejb.embeddable.EJBContainer;\n import javax.xml.namespace.QName;\n import javax.xml.ws.Holder;\n import javax.xml.ws.Service;\n import java.net.URL;\n import java.util.Properties;\n\n import static org.junit.Assert.assertEquals;\n import static org.junit.Assert.assertNotNull;\n\n public class CalculatorTest {\n\n @BeforeClass\n public static void setUp() throws Exception {\n Properties properties = new Properties();\n properties.setProperty(\"openejb.embedded.remotable\", \"true\");\n //properties.setProperty(\"httpejbd.print\", \"true\");\n //properties.setProperty(\"httpejbd.indent.xml\", \"true\");\n EJBContainer.createEJBContainer(properties);\n }\n\n @Test\n public void outParams() throws Exception {\n final Service calculatorService = Service.create(\n new URL(\"http://127.0.0.1:4204/Calculator?wsdl\"),\n new QName(\"http://superbiz.org/wsdl\", \"CalculatorService\"));\n\n assertNotNull(calculatorService);\n\n final CalculatorWs calculator = calculatorService.getPort(CalculatorWs.class);\n\n final Holder<Integer> sum = new Holder<Integer>();\n final Holder<Integer> multiply = new Holder<Integer>();\n\n calculator.sumAndMultiply(4, 6, sum, multiply);\n\n assertEquals(10, (int) sum.value);\n assertEquals(24, (int) multiply.value);\n }\n }\n\n\n## Inspecting the messages\n\nThe above execution results in the following SOAP message.\n\n### SOAP sumAndMultiply <small>client request</small>\n\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <soap:Body>\n <ns1:sumAndMultiply xmlns:ns1=\"http://superbiz.org/wsdl\">\n <arg0>4</arg0>\n <arg1>6</arg1>\n </ns1:sumAndMultiply>\n </soap:Body>\n </soap:Envelope>\n\n### SOAP sumAndMultiplyResponse <small>server response</small>\n\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <soap:Body>\n <ns1:sumAndMultiplyResponse xmlns:ns1=\"http://superbiz.org/wsdl\">\n <sum>10</sum>\n <multiply>24</multiply>\n </ns1:sumAndMultiplyResponse>\n </soap:Body>\n </soap:Envelope>\n",
"url":"https://github.com/apache/tomee/tree/master/examples/webservice-holder"
}
],
"i18n":[
{
"name":"deltaspike-i18n",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/deltaspike-i18n"
}
],
"implementation":[
{
"name":"dynamic-implementation",
"readme":"Title: Dynamic Implementation\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## SocialBean\n\n package org.superbiz.dynamic;\n \n import org.apache.openejb.api.Proxy;\n \n import javax.ejb.Singleton;\n import javax.interceptor.Interceptors;\n \n @Singleton\n @Proxy(SocialHandler.class)\n @Interceptors(SocialInterceptor.class)\n public interface SocialBean {\n public String facebookStatus();\n \n public String twitterStatus();\n \n public String status();\n }\n\n## SocialHandler\n\n package org.superbiz.dynamic;\n \n import java.lang.reflect.InvocationHandler;\n import java.lang.reflect.Method;\n \n public class SocialHandler implements InvocationHandler {\n @Override\n public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {\n String mtd = method.getName();\n if (mtd.toLowerCase().contains(\"facebook\")) {\n return \"You think you have a life!\";\n } else if (mtd.toLowerCase().contains(\"twitter\")) {\n return \"Wow, you eat pop corn!\";\n }\n return \"Hey, you have no virtual friend!\";\n }\n }\n\n## SocialInterceptor\n\n packagenull\n }\n\n## SocialTest\n\n package org.superbiz.dynamic;\n \n import org.junit.AfterClass;\n import org.junit.BeforeClass;\n import org.junit.Test;\n \n import javax.ejb.embeddable.EJBContainer;\n \n import static junit.framework.Assert.assertTrue;\n \n public class SocialTest {\n private static SocialBean social;\n private static EJBContainer container;\n \n @BeforeClass\n public static void init() throws Exception {\n container = EJBContainer.createEJBContainer();\n social = (SocialBean) container.getContext().lookup(\"java:global/dynamic-implementation/SocialBean\");\n }\n \n @AfterClass\n public static void close() {\n container.close();\n }\n \n @Test\n public void simple() {\n assertTrue(social.facebookStatus().contains(\"think\"));\n assertTrue(social.twitterStatus().contains(\"eat\"));\n assertTrue(social.status().contains(\"virtual\"));\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.dynamic.SocialTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/dynamic-implementation\n INFO - openejb.base = /Users/dblevins/examples/dynamic-implementation\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/dynamic-implementation/target/classes\n INFO - Beginning load: /Users/dblevins/examples/dynamic-implementation/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/dynamic-implementation\n INFO - Configuring Service(id=Default Singleton Container, type=Container, provider-id=Default Singleton Container)\n INFO - Auto-creating a container for bean SocialBean: Container(type=SINGLETON, id=Default Singleton Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.dynamic.SocialTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Enterprise application \"/Users/dblevins/examples/dynamic-implementation\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/dynamic-implementation\n INFO - Jndi(name=\"java:global/dynamic-implementation/SocialBean!org.superbiz.dynamic.SocialBean\")\n INFO - Jndi(name=\"java:global/dynamic-implementation/SocialBean\")\n INFO - Jndi(name=\"java:global/EjbModule236706648/org.superbiz.dynamic.SocialTest!org.superbiz.dynamic.SocialTest\")\n INFO - Jndi(name=\"java:global/EjbModule236706648/org.superbiz.dynamic.SocialTest\")\n INFO - Created Ejb(deployment-id=org.superbiz.dynamic.SocialTest, ejb-name=org.superbiz.dynamic.SocialTest, container=Default Managed Container)\n INFO - Created Ejb(deployment-id=SocialBean, ejb-name=SocialBean, container=Default Singleton Container)\n INFO - Started Ejb(deployment-id=org.superbiz.dynamic.SocialTest, ejb-name=org.superbiz.dynamic.SocialTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=SocialBean, ejb-name=SocialBean, container=Default Singleton Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/dynamic-implementation)\n INFO - Undeploying app: /Users/dblevins/examples/dynamic-implementation\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.107 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/dynamic-implementation"
},
{
"name":"dynamic-dao-implementation",
"readme":"Title: Dynamic DAO Implementation\n\nMany aspects of Data Access Objects (DAOs) are very repetitive and boiler plate. As a fun and experimental feature, TomEE supports dynamically implementing an interface\nthat is seen to have standard DAO-style methods.\n\nThe interface has to be annotated with @PersistenceContext to define which EntityManager to use.\n\nMethods should respect these conventions:\n\n * void save(Foo foo): persist foo\n * Foo update(Foo foo): merge foo\n * void delete(Foo foo): remove foo, if foo is detached it tries to attach it\n * Collection<Foo>|Foo namedQuery(String name[, Map<String, ?> params, int first, int max]): run the named query called name, params contains bindings, first and max are used for magination. Last three parameters are optionnals\n * Collection<Foo>|Foo nativeQuery(String name[, Map<String, ?> params, int first, int max]): run the native query called name, params contains bindings, first and max are used for magination. Last three parameters are optionnals\n * Collection<Foo>|Foo query(String value [, Map<String, ?> params, int first, int max]): run the query put as first parameter, params contains bindings, first and max are used for magination. Last three parameters are optionnals\n * Collection<Foo> findAll([int first, int max]): find all Foo, parameters are used for pagination\n * Collection<Foo> findByBar1AndBar2AndBar3(<bar 1 type> bar1, <bar 2 type> bar2, <bar3 type> bar3 [, int first, int max]): find all Foo with specified field values for bar1, bar2, bar3.\n\nDynamic finder can have as much as you want field constraints. For String like is used and for other type equals is used.\n\n# Example\n\n## User\n\n package org.superbiz.dynamic;\n \n import javax.persistence.Entity;\n import javax.persistence.GeneratedValue;\n import javax.persistence.Id;\n import javax.persistence.NamedQueries;\n import javax.persistence.NamedQuery;\n \n @Entity\n @NamedQueries({\n @NamedQuery(name = \"dynamic-ejb-impl-test.query\", query = \"SELECT u FROM User AS u WHERE u.name LIKE :name\"),\n @NamedQuery(name = \"dynamic-ejb-impl-test.all\", query = \"SELECT u FROM User AS u\")\n })\n public class User {\n @Id\n @GeneratedValue\n private long id;\n private String name;\n private int age;\n\n public long getId() {\n return id;\n }\n\n public void setId(long id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public int getAge() {\n return age;\n }\n\n public void setAge(int age) {\n this.age = age;\n }\n }\n\n## UserDao\n\n package org.superbiz.dynamic;\n \n \n import javax.ejb.Stateless;\n import javax.persistence.PersistenceContext;\n import java.util.Collection;\n import java.util.Map;\n \n @Stateless\n @PersistenceContext(name = \"dynamic\")\n public interface UserDao {\n User findById(long id);\n \n Collection<User> findByName(String name);\n \n Collection<User> findByNameAndAge(String name, int age);\n \n Collection<User> findAll();\n \n Collection<User> findAll(int first, int max);\n \n Collection<User> namedQuery(String name, Map<String, ?> params, int first, int max);\n \n Collection<User> namedQuery(String name, int first, int max, Map<String, ?> params);\n \n Collection<User> namedQuery(String name, Map<String, ?> params);\n \n Collection<User> namedQuery(String name);\n \n Collection<User> query(String value, Map<String, ?> params);\n \n void save(User u);\n \n void delete(User u);\n \n User update(User u);\n }\n\n## persistence.xml\n\n <persistence version=\"2.0\"\n xmlns=\"http://java.sun.com/xml/ns/persistence\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"\n http://java.sun.com/xml/ns/persistence\n http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd\">\n <persistence-unit name=\"dynamic\" transaction-type=\"JTA\">\n <jta-data-source>jdbc/dynamicDB</jta-data-source>\n <class>org.superbiz.dynamic.User</class>\n <properties>\n <property name=\"openjpa.jdbc.SynchronizeMappings\" value=\"buildSchema(ForeignKeys=true)\"/>\n </properties>\n </persistence-unit>\n </persistence>\n \n\n## DynamicUserDaoTest\n\n package org.superbiz.dynamic;\n \n import junit.framework.Assert;\n import org.junit.BeforeClass;\n import org.junit.Test;\n \n import javax.ejb.EJBException;\n import javax.ejb.Stateless;\n import javax.ejb.embeddable.EJBContainer;\n import javax.naming.Context;\n import javax.persistence.EntityManager;\n import javax.persistence.NoResultException;\n import javax.persistence.PersistenceContext;\n import java.util.Collection;\n import java.util.HashMap;\n import java.util.Map;\n import java.util.Properties;\n \n import static junit.framework.Assert.assertEquals;\n import static junit.framework.Assert.assertNotNull;\n import static junit.framework.Assert.assertTrue;\n \n public class DynamicUserDaoTest {\n private static UserDao dao;\n private static Util util;\n \n @BeforeClass\n public static void init() throws Exception {\n final Properties p = new Properties();\n p.put(\"jdbc/dynamicDB\", \"new://Resource?type=DataSource\");\n p.put(\"jdbc/dynamicDB.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"jdbc/dynamicDB.JdbcUrl\", \"jdbc:hsqldb:mem:moviedb\");\n p.put(\"jdbc/dynamicDB.UserName\", \"sa\");\n p.put(\"jdbc/dynamicDB.Password\", \"\");\n \n final Context context = EJBContainer.createEJBContainer(p).getContext();\n dao = (UserDao) context.lookup(\"java:global/dynamic-dao-implementation/UserDao\");\n util = (Util) context.lookup(\"java:global/dynamic-dao-implementation/Util\");\n \n util.init(); // init database\n }\n \n @Test\n public void simple() {\n User user = dao.findById(1);\n assertNotNull(user);\n assertEquals(1, user.getId());\n }\n \n @Test\n public void findAll() {\n Collection<User> users = dao.findAll();\n assertEquals(10, users.size());\n }\n \n @Test\n public void pagination() {\n Collection<User> users = dao.findAll(0, 5);\n assertEquals(5, users.size());\n \n users = dao.findAll(6, 1);\n assertEquals(1, users.size());\n assertEquals(7, users.iterator().next().getId());\n }\n \n @Test\n public void persist() {\n User u = new User();\n dao.save(u);\n assertNotNull(u.getId());\n util.remove(u);\n }\n \n @Test\n public void remove() {\n User u = new User();\n dao.save(u);\n assertNotNull(u.getId());\n dao.delete(u);\n try {\n dao.findById(u.getId());\n Assert.fail();\n } catch (EJBException ee) {\n assertTrue(ee.getCause() instanceof NoResultException);\n }\n }\n \n @Test\n public void merge() {\n User u = new User();\n u.setAge(1);\n dao.save(u);\n assertEquals(1, u.getAge());\n assertNotNull(u.getId());\n \n u.setAge(2);\n dao.update(u);\n assertEquals(2, u.getAge());\n \n dao.delete(u);\n }\n \n @Test\n public void oneCriteria() {\n Collection<User> users = dao.findByName(\"foo\");\n assertEquals(4, users.size());\n for (User user : users) {\n assertEquals(\"foo\", user.getName());\n }\n }\n \n @Test\n public void twoCriteria() {\n Collection<User> users = dao.findByNameAndAge(\"bar-1\", 1);\n assertEquals(1, users.size());\n \n User user = users.iterator().next();\n assertEquals(\"bar-1\", user.getName());\n assertEquals(1, user.getAge());\n }\n \n @Test\n public void query() {\n Map<String, Object> params = new HashMap<String, Object>();\n params.put(\"name\", \"foo\");\n \n Collection<User> users = dao.namedQuery(\"dynamic-ejb-impl-test.query\", params, 0, 100);\n assertEquals(4, users.size());\n \n users = dao.namedQuery(\"dynamic-ejb-impl-test.query\", params);\n assertEquals(4, users.size());\n \n users = dao.namedQuery(\"dynamic-ejb-impl-test.query\", params, 0, 2);\n assertEquals(2, users.size());\n \n users = dao.namedQuery(\"dynamic-ejb-impl-test.query\", 0, 2, params);\n assertEquals(2, users.size());\n \n users = dao.namedQuery(\"dynamic-ejb-impl-test.all\");\n assertEquals(10, users.size());\n \n params.remove(\"name\");\n params.put(\"age\", 1);\n users = dao.query(\"SELECT u FROM User AS u WHERE u.age = :age\", params);\n assertEquals(3, users.size());\n }\n \n @Stateless\n public static class Util {\n @PersistenceContext\n private EntityManager em;\n \n public void remove(User o) {\n em.remove(em.find(User.class, o.getId()));\n }\n \n public void init() {\n for (int i = 0; i < 10; i++) {\n User u = new User();\n u.setAge(i % 4);\n if (i % 3 == 0) {\n u.setName(\"foo\");\n } else {\n u.setName(\"bar-\" + i);\n }\n em.persist(u);\n }\n }\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.dynamic.DynamicUserDaoTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/dynamic-dao-implementation\n INFO - openejb.base = /Users/dblevins/examples/dynamic-dao-implementation\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=jdbc/dynamicDB, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/dynamic-dao-implementation/target/classes\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/dynamic-dao-implementation/target/test-classes\n INFO - Beginning load: /Users/dblevins/examples/dynamic-dao-implementation/target/classes\n INFO - Beginning load: /Users/dblevins/examples/dynamic-dao-implementation/target/test-classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/dynamic-dao-implementation\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean UserDao: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.dynamic.DynamicUserDaoTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring PersistenceUnit(name=dynamic)\n INFO - Auto-creating a Resource with id 'jdbc/dynamicDBNonJta' of type 'DataSource for 'dynamic'.\n INFO - Configuring Service(id=jdbc/dynamicDBNonJta, type=Resource, provider-id=jdbc/dynamicDB)\n INFO - Adjusting PersistenceUnit dynamic <non-jta-data-source> to Resource ID 'jdbc/dynamicDBNonJta' from 'null'\n INFO - Enterprise application \"/Users/dblevins/examples/dynamic-dao-implementation\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/dynamic-dao-implementation\n INFO - PersistenceUnit(name=dynamic, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 417ms\n INFO - Jndi(name=\"java:global/dynamic-dao-implementation/UserDao!org.superbiz.dynamic.UserDao\")\n INFO - Jndi(name=\"java:global/dynamic-dao-implementation/UserDao\")\n INFO - Jndi(name=\"java:global/dynamic-dao-implementation/Util!org.superbiz.dynamic.DynamicUserDaoTest$Util\")\n INFO - Jndi(name=\"java:global/dynamic-dao-implementation/Util\")\n INFO - Jndi(name=\"java:global/EjbModule346613126/org.superbiz.dynamic.DynamicUserDaoTest!org.superbiz.dynamic.DynamicUserDaoTest\")\n INFO - Jndi(name=\"java:global/EjbModule346613126/org.superbiz.dynamic.DynamicUserDaoTest\")\n INFO - Created Ejb(deployment-id=UserDao, ejb-name=UserDao, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=Util, ejb-name=Util, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=org.superbiz.dynamic.DynamicUserDaoTest, ejb-name=org.superbiz.dynamic.DynamicUserDaoTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=UserDao, ejb-name=UserDao, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=Util, ejb-name=Util, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=org.superbiz.dynamic.DynamicUserDaoTest, ejb-name=org.superbiz.dynamic.DynamicUserDaoTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/dynamic-dao-implementation)\n WARN - Meta class \"org.superbiz.dynamic.User_\" for entity class org.superbiz.dynamic.User can not be registered with following exception \"java.security.PrivilegedActionException: java.lang.ClassNotFoundException: org.superbiz.dynamic.User_\"\n WARN - Query \"SELECT u FROM User AS u WHERE u.name LIKE :name\" is removed from cache excluded permanently. Query \"SELECT u FROM User AS u WHERE u.name LIKE :name\" is not cached because it uses pagination..\n Tests run: 9, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.471 sec\n \n Results :\n \n Tests run: 9, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/dynamic-dao-implementation"
}
],
"inheritance":[
{
"name":"webservice-inheritance",
"readme":"Title: Webservice Inheritance\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## Item\n\n package org.superbiz.inheritance;\n \n import javax.persistence.Entity;\n import javax.persistence.GeneratedValue;\n import javax.persistence.GenerationType;\n import javax.persistence.Id;\n import javax.persistence.Inheritance;\n import javax.persistence.InheritanceType;\n import java.io.Serializable;\n \n @Entity\n @Inheritance(strategy = InheritanceType.JOINED)\n public class Item implements Serializable {\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private Long id;\n private String brand;\n private String itemName;\n private double price;\n \n public Long getId() {\n return id;\n }\n \n public void setId(Long id) {\n this.id = id;\n }\n \n public String getBrand() {\n return brand;\n }\n \n public void setBrand(String brand) {\n this.brand = brand;\n }\n \n public String getItemName() {\n return itemName;\n }\n \n public void setItemName(String itemName) {\n this.itemName = itemName;\n }\n \n public double getPrice() {\n return price;\n }\n \n public void setPrice(double price) {\n this.price = price;\n }\n }\n\n## Tower\n\n package org.superbiz.inheritance;\n \n import javax.persistence.Entity;\n \n @Entity\n public class Tower extends Item {\n private Fit fit;\n private String tubing;\n \n public static enum Fit {\n Custom, Exact, Universal\n }\n \n public Fit getFit() {\n return fit;\n }\n \n public void setFit(Fit fit) {\n this.fit = fit;\n }\n \n public String getTubing() {\n return tubing;\n }\n \n public void setTubing(String tubing) {\n this.tubing = tubing;\n }\n \n ;\n }\n\n## Wakeboard\n\n package org.superbiz.inheritance;\n \n import javax.persistence.Entity;\n \n @Entity\n public class Wakeboard extends Wearable {\n }\n\n## WakeboardBinding\n\n package org.superbiz.inheritance;\n \n import javax.persistence.Entity;\n \n @Entity\n public class WakeboardBinding extends Wearable {\n }\n\n## WakeRiderImpl\n\n package org.superbiz.inheritance;\n \n import javax.ejb.Stateless;\n import javax.jws.WebService;\n import javax.persistence.EntityManager;\n import javax.persistence.PersistenceContext;\n import javax.persistence.PersistenceContextType;\n import javax.persistence.Query;\n import java.util.List;\n \n /**\n * This is an EJB 3 style pojo stateless session bean Every stateless session\n * bean implementation must be annotated using the annotation @Stateless This\n * EJB has a single interface: {@link WakeRiderWs} a webservice interface.\n */\n @Stateless\n @WebService(\n portName = \"InheritancePort\",\n serviceName = \"InheritanceWsService\",\n targetNamespace = \"http://superbiz.org/wsdl\",\n endpointInterface = \"org.superbiz.inheritance.WakeRiderWs\")\n public class WakeRiderImpl implements WakeRiderWs {\n \n @PersistenceContext(unitName = \"wakeboard-unit\", type = PersistenceContextType.TRANSACTION)\n private EntityManager entityManager;\n \n public void addItem(Item item) throws Exception {\n entityManager.persist(item);\n }\n \n public void deleteMovie(Item item) throws Exception {\n entityManager.remove(item);\n }\n \n public List<Item> getItems() throws Exception {\n Query query = entityManager.createQuery(\"SELECT i FROM Item i\");\n List<Item> items = query.getResultList();\n return items;\n }\n }\n\n## WakeRiderWs\n\n package org.superbiz.inheritance;\n \n import javax.jws.WebService;\n import javax.xml.bind.annotation.XmlSeeAlso;\n import java.util.List;\n \n /**\n * This is an EJB 3 webservice interface that uses inheritance.\n */\n @WebService(targetNamespace = \"http://superbiz.org/wsdl\")\n @XmlSeeAlso({Wakeboard.class, WakeboardBinding.class, Tower.class})\n public interface WakeRiderWs {\n public void addItem(Item item) throws Exception;\n \n public void deleteMovie(Item item) throws Exception;\n \n public List<Item> getItems() throws Exception;\n }\n\n## Wearable\n\n package org.superbiz.inheritance;\n \n import javax.persistence.MappedSuperclass;\n \n @MappedSuperclass\n public abstract class Wearable extends Item {\n protected String size;\n \n public String getSize() {\n return size;\n }\n \n public void setSize(String size) {\n this.size = size;\n }\n }\n\n## ejb-jar.xml\n\n <ejb-jar/>\n \n\n## persistence.xml\n\n <persistence xmlns=\"http://java.sun.com/xml/ns/persistence\" version=\"1.0\">\n \n <persistence-unit name=\"wakeboard-unit\">\n \n <jta-data-source>wakeBoardDatabase</jta-data-source>\n <non-jta-data-source>wakeBoardDatabaseUnmanaged</non-jta-data-source>\n \n <class>org.superbiz.inheritance.Item</class>\n <class>org.superbiz.inheritance.Tower</class>\n <class>org.superbiz.inheritance.Wakeboard</class>\n <class>org.superbiz.inheritance.WakeboardBinding</class>\n <class>org.superbiz.inheritance.Wearable</class>\n \n <properties>\n <property name=\"openjpa.jdbc.SynchronizeMappings\" value=\"buildSchema(ForeignKeys=true)\"/>\n </properties>\n \n </persistence-unit>\n </persistence>\n\n## InheritanceTest\n\n package org.superbiz.inheritance;\n \n import junit.framework.TestCase;\n import org.superbiz.inheritance.Tower.Fit;\n \n import javax.naming.Context;\n import javax.naming.InitialContext;\n import javax.xml.namespace.QName;\n import javax.xml.ws.Service;\n import java.net.URL;\n import java.util.List;\n import java.util.Properties;\n \n public class InheritanceTest extends TestCase {\n \n //START SNIPPET: setup\t\n private InitialContext initialContext;\n \n protected void setUp() throws Exception {\n \n Properties p = new Properties();\n p.put(Context.INITIAL_CONTEXT_FACTORY, \"org.apache.openejb.core.LocalInitialContextFactory\");\n p.put(\"wakeBoardDatabase\", \"new://Resource?type=DataSource\");\n p.put(\"wakeBoardDatabase.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"wakeBoardDatabase.JdbcUrl\", \"jdbc:hsqldb:mem:wakeBoarddb\");\n \n p.put(\"wakeBoardDatabaseUnmanaged\", \"new://Resource?type=DataSource\");\n p.put(\"wakeBoardDatabaseUnmanaged.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"wakeBoardDatabaseUnmanaged.JdbcUrl\", \"jdbc:hsqldb:mem:wakeBoarddb\");\n p.put(\"wakeBoardDatabaseUnmanaged.JtaManaged\", \"false\");\n \n p.put(\"openejb.embedded.remotable\", \"true\");\n \n initialContext = new InitialContext(p);\n }\n //END SNIPPET: setup \n \n /**\n * Create a webservice client using wsdl url\n *\n * @throws Exception\n */\n //START SNIPPET: webservice\n public void testInheritanceViaWsInterface() throws Exception {\n Service service = Service.create(\n new URL(\"http://127.0.0.1:4204/WakeRiderImpl?wsdl\"),\n new QName(\"http://superbiz.org/wsdl\", \"InheritanceWsService\"));\n assertNotNull(service);\n \n WakeRiderWs ws = service.getPort(WakeRiderWs.class);\n \n Tower tower = createTower();\n Item item = createItem();\n Wakeboard wakeBoard = createWakeBoard();\n WakeboardBinding wakeBoardbinding = createWakeboardBinding();\n \n ws.addItem(tower);\n ws.addItem(item);\n ws.addItem(wakeBoard);\n ws.addItem(wakeBoardbinding);\n \n \n List<Item> returnedItems = ws.getItems();\n \n assertEquals(\"testInheritanceViaWsInterface, nb Items\", 4, returnedItems.size());\n \n //check tower\n assertEquals(\"testInheritanceViaWsInterface, first Item\", returnedItems.get(0).getClass(), Tower.class);\n tower = (Tower) returnedItems.get(0);\n assertEquals(\"testInheritanceViaWsInterface, first Item\", tower.getBrand(), \"Tower brand\");\n assertEquals(\"testInheritanceViaWsInterface, first Item\", tower.getFit().ordinal(), Fit.Custom.ordinal());\n assertEquals(\"testInheritanceViaWsInterface, first Item\", tower.getItemName(), \"Tower item name\");\n assertEquals(\"testInheritanceViaWsInterface, first Item\", tower.getPrice(), 1.0d);\n assertEquals(\"testInheritanceViaWsInterface, first Item\", tower.getTubing(), \"Tower tubing\");\n \n //check item\n assertEquals(\"testInheritanceViaWsInterface, second Item\", returnedItems.get(1).getClass(), Item.class);\n item = (Item) returnedItems.get(1);\n assertEquals(\"testInheritanceViaWsInterface, second Item\", item.getBrand(), \"Item brand\");\n assertEquals(\"testInheritanceViaWsInterface, second Item\", item.getItemName(), \"Item name\");\n assertEquals(\"testInheritanceViaWsInterface, second Item\", item.getPrice(), 2.0d);\n \n //check wakeboard\n assertEquals(\"testInheritanceViaWsInterface, third Item\", returnedItems.get(2).getClass(), Wakeboard.class);\n wakeBoard = (Wakeboard) returnedItems.get(2);\n assertEquals(\"testInheritanceViaWsInterface, third Item\", wakeBoard.getBrand(), \"Wakeboard brand\");\n assertEquals(\"testInheritanceViaWsInterface, third Item\", wakeBoard.getItemName(), \"Wakeboard item name\");\n assertEquals(\"testInheritanceViaWsInterface, third Item\", wakeBoard.getPrice(), 3.0d);\n assertEquals(\"testInheritanceViaWsInterface, third Item\", wakeBoard.getSize(), \"WakeBoard size\");\n \n //check wakeboardbinding\n assertEquals(\"testInheritanceViaWsInterface, fourth Item\", returnedItems.get(3).getClass(), WakeboardBinding.class);\n wakeBoardbinding = (WakeboardBinding) returnedItems.get(3);\n assertEquals(\"testInheritanceViaWsInterface, fourth Item\", wakeBoardbinding.getBrand(), \"Wakeboardbinding brand\");\n assertEquals(\"testInheritanceViaWsInterface, fourth Item\", wakeBoardbinding.getItemName(), \"Wakeboardbinding item name\");\n assertEquals(\"testInheritanceViaWsInterface, fourth Item\", wakeBoardbinding.getPrice(), 4.0d);\n assertEquals(\"testInheritanceViaWsInterface, fourth Item\", wakeBoardbinding.getSize(), \"WakeBoardbinding size\");\n }\n //END SNIPPET: webservice\n \n private Tower createTower() {\n Tower tower = new Tower();\n tower.setBrand(\"Tower brand\");\n tower.setFit(Fit.Custom);\n tower.setItemName(\"Tower item name\");\n tower.setPrice(1.0f);\n tower.setTubing(\"Tower tubing\");\n return tower;\n }\n \n private Item createItem() {\n Item item = new Item();\n item.setBrand(\"Item brand\");\n item.setItemName(\"Item name\");\n item.setPrice(2.0f);\n return item;\n }\n \n private Wakeboard createWakeBoard() {\n Wakeboard wakeBoard = new Wakeboard();\n wakeBoard.setBrand(\"Wakeboard brand\");\n wakeBoard.setItemName(\"Wakeboard item name\");\n wakeBoard.setPrice(3.0f);\n wakeBoard.setSize(\"WakeBoard size\");\n return wakeBoard;\n }\n \n private WakeboardBinding createWakeboardBinding() {\n WakeboardBinding wakeBoardBinding = new WakeboardBinding();\n wakeBoardBinding.setBrand(\"Wakeboardbinding brand\");\n wakeBoardBinding.setItemName(\"Wakeboardbinding item name\");\n wakeBoardBinding.setPrice(4.0f);\n wakeBoardBinding.setSize(\"WakeBoardbinding size\");\n return wakeBoardBinding;\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.inheritance.InheritanceTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/webservice-inheritance\n INFO - openejb.base = /Users/dblevins/examples/webservice-inheritance\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=wakeBoardDatabaseUnmanaged, type=Resource, provider-id=Default JDBC Database)\n INFO - Configuring Service(id=wakeBoardDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/webservice-inheritance/target/classes\n INFO - Beginning load: /Users/dblevins/examples/webservice-inheritance/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/webservice-inheritance/classpath.ear\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean WakeRiderImpl: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Configuring PersistenceUnit(name=wakeboard-unit)\n INFO - Enterprise application \"/Users/dblevins/examples/webservice-inheritance/classpath.ear\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/webservice-inheritance/classpath.ear\n INFO - PersistenceUnit(name=wakeboard-unit, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 396ms\n INFO - Created Ejb(deployment-id=WakeRiderImpl, ejb-name=WakeRiderImpl, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=WakeRiderImpl, ejb-name=WakeRiderImpl, container=Default Stateless Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/webservice-inheritance/classpath.ear)\n INFO - Initializing network services\n INFO - Creating ServerService(id=httpejbd)\n INFO - Creating ServerService(id=cxf)\n INFO - Creating ServerService(id=admin)\n INFO - Creating ServerService(id=ejbd)\n INFO - Creating ServerService(id=ejbds)\n INFO - Initializing network services\n ** Starting Services **\n NAME IP PORT \n httpejbd 127.0.0.1 4204 \n admin thread 127.0.0.1 4200 \n ejbd 127.0.0.1 4201 \n ejbd 127.0.0.1 4203 \n -------\n Ready!\n WARN - Found no persistent property in \"org.superbiz.inheritance.WakeboardBinding\"\n WARN - Found no persistent property in \"org.superbiz.inheritance.Wakeboard\"\n WARN - Found no persistent property in \"org.superbiz.inheritance.WakeboardBinding\"\n WARN - Found no persistent property in \"org.superbiz.inheritance.Wakeboard\"\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 4.442 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/webservice-inheritance"
}
],
"injection":[
{
"name":"injection-of-connectionfactory",
"readme":"Title: Injection Of Connectionfactory\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## Messages\n\n package org.superbiz.injection.jms;\n \n import javax.annotation.Resource;\n import javax.ejb.Stateless;\n import javax.jms.Connection;\n import javax.jms.ConnectionFactory;\n import javax.jms.DeliveryMode;\n import javax.jms.JMSException;\n import javax.jms.MessageConsumer;\n import javax.jms.MessageProducer;\n import javax.jms.Queue;\n import javax.jms.Session;\n import javax.jms.TextMessage;\n \n @Stateless\n public class Messages {\n \n @Resource\n private ConnectionFactory connectionFactory;\n \n @Resource\n private Queue chatQueue;\n \n \n public void sendMessage(String text) throws JMSException {\n \n Connection connection = null;\n Session session = null;\n \n try {\n connection = connectionFactory.createConnection();\n connection.start();\n \n // Create a Session\n session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);\n \n // Create a MessageProducer from the Session to the Topic or Queue\n MessageProducer producer = session.createProducer(chatQueue);\n producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);\n \n // Create a message\n TextMessage message = session.createTextMessage(text);\n \n // Tell the producer to send the message\n producer.send(message);\n } finally {\n // Clean up\n if (session != null) session.close();\n if (connection != null) connection.close();\n }\n }\n \n public String receiveMessage() throws JMSException {\n \n Connection connection = null;\n Session session = null;\n MessageConsumer consumer = null;\n try {\n connection = connectionFactory.createConnection();\n connection.start();\n \n // Create a Session\n session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);\n \n // Create a MessageConsumer from the Session to the Topic or Queue\n consumer = session.createConsumer(chatQueue);\n \n // Wait for a message\n TextMessage message = (TextMessage) consumer.receive(1000);\n \n return message.getText();\n } finally {\n if (consumer != null) consumer.close();\n if (session != null) session.close();\n if (connection != null) connection.close();\n }\n }\n }\n\n## MessagingBeanTest\n\n package org.superbiz.injection.jms;\n \n import junit.framework.TestCase;\n \n import javax.ejb.embeddable.EJBContainer;\n import javax.naming.Context;\n \n public class MessagingBeanTest extends TestCase {\n \n public void test() throws Exception {\n \n final Context context = EJBContainer.createEJBContainer().getContext();\n \n Messages messages = (Messages) context.lookup(\"java:global/injection-of-connectionfactory/Messages\");\n \n messages.sendMessage(\"Hello World!\");\n messages.sendMessage(\"How are you?\");\n messages.sendMessage(\"Still spinning?\");\n \n assertEquals(messages.receiveMessage(), \"Hello World!\");\n assertEquals(messages.receiveMessage(), \"How are you?\");\n assertEquals(messages.receiveMessage(), \"Still spinning?\");\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.injection.jms.MessagingBeanTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/injection-of-connectionfactory\n INFO - openejb.base = /Users/dblevins/examples/injection-of-connectionfactory\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/injection-of-connectionfactory/target/classes\n INFO - Beginning load: /Users/dblevins/examples/injection-of-connectionfactory/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/injection-of-connectionfactory\n WARN - Method 'lookup' is not available for 'javax.annotation.Resource'. Probably using an older Runtime.\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean Messages: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Configuring Service(id=Default JMS Connection Factory, type=Resource, provider-id=Default JMS Connection Factory)\n INFO - Auto-creating a Resource with id 'Default JMS Connection Factory' of type 'javax.jms.ConnectionFactory for 'Messages'.\n INFO - Configuring Service(id=Default JMS Resource Adapter, type=Resource, provider-id=Default JMS Resource Adapter)\n INFO - Auto-linking resource-ref 'java:comp/env/org.superbiz.injection.jms.Messages/connectionFactory' in bean Messages to Resource(id=Default JMS Connection Factory)\n INFO - Configuring Service(id=org.superbiz.injection.jms.Messages/chatQueue, type=Resource, provider-id=Default Queue)\n INFO - Auto-creating a Resource with id 'org.superbiz.injection.jms.Messages/chatQueue' of type 'javax.jms.Queue for 'Messages'.\n INFO - Auto-linking resource-env-ref 'java:comp/env/org.superbiz.injection.jms.Messages/chatQueue' in bean Messages to Resource(id=org.superbiz.injection.jms.Messages/chatQueue)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.injection.jms.MessagingBeanTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Enterprise application \"/Users/dblevins/examples/injection-of-connectionfactory\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/injection-of-connectionfactory\n INFO - Jndi(name=\"java:global/injection-of-connectionfactory/Messages!org.superbiz.injection.jms.Messages\")\n INFO - Jndi(name=\"java:global/injection-of-connectionfactory/Messages\")\n INFO - Jndi(name=\"java:global/EjbModule1634151355/org.superbiz.injection.jms.MessagingBeanTest!org.superbiz.injection.jms.MessagingBeanTest\")\n INFO - Jndi(name=\"java:global/EjbModule1634151355/org.superbiz.injection.jms.MessagingBeanTest\")\n INFO - Created Ejb(deployment-id=Messages, ejb-name=Messages, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=org.superbiz.injection.jms.MessagingBeanTest, ejb-name=org.superbiz.injection.jms.MessagingBeanTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=Messages, ejb-name=Messages, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=org.superbiz.injection.jms.MessagingBeanTest, ejb-name=org.superbiz.injection.jms.MessagingBeanTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/injection-of-connectionfactory)\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.562 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/injection-of-connectionfactory"
},
{
"name":"testcase-injection",
"readme":"Title: Testcase Injection\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## Movie\n\n package org.superbiz.testinjection;\n \n import javax.persistence.Entity;\n \n @Entity\n public class Movie {\n \n private String director;\n private String title;\n private int year;\n \n public Movie() {\n }\n \n public Movie(String director, String title, int year) {\n this.director = director;\n this.title = title;\n this.year = year;\n }\n \n public String getDirector() {\n return director;\n }\n \n public void setDirector(String director) {\n this.director = director;\n }\n \n public String getTitle() {\n return title;\n }\n \n public void setTitle(String title) {\n this.title = title;\n }\n \n public int getYear() {\n return year;\n }\n \n public void setYear(int year) {\n this.year = year;\n }\n \n }\n\n## Movies\n\n package org.superbiz.testinjection;\n \n import javax.ejb.Stateful;\n import javax.ejb.TransactionAttribute;\n import javax.persistence.EntityManager;\n import javax.persistence.PersistenceContext;\n import javax.persistence.PersistenceContextType;\n import javax.persistence.Query;\n import java.util.List;\n \n import static javax.ejb.TransactionAttributeType.MANDATORY;\n \n //START SNIPPET: code\n @Stateful\n @TransactionAttribute(MANDATORY)\n public class Movies {\n \n @PersistenceContext(unitName = \"movie-unit\", type = PersistenceContextType.TRANSACTION)\n private EntityManager entityManager;\n \n public void addMovie(Movie movie) throws Exception {\n entityManager.persist(movie);\n }\n \n public void deleteMovie(Movie movie) throws Exception {\n entityManager.remove(movie);\n }\n \n public List<Movie> getMovies() throws Exception {\n Query query = entityManager.createQuery(\"SELECT m from Movie as m\");\n return query.getResultList();\n }\n }\n\n## persistence.xml\n\n <persistence xmlns=\"http://java.sun.com/xml/ns/persistence\" version=\"1.0\">\n \n <persistence-unit name=\"movie-unit\">\n <jta-data-source>movieDatabase</jta-data-source>\n <non-jta-data-source>movieDatabaseUnmanaged</non-jta-data-source>\n <class>org.superbiz.testinjection.Movie</class>\n \n <properties>\n <property name=\"openjpa.jdbc.SynchronizeMappings\" value=\"buildSchema(ForeignKeys=true)\"/>\n </properties>\n </persistence-unit>\n </persistence>\n\n## MoviesTest\n\n package org.superbiz.testinjection;\n \n import junit.framework.TestCase;\n \n import javax.annotation.Resource;\n import javax.ejb.EJB;\n import javax.ejb.embeddable.EJBContainer;\n import javax.persistence.EntityManager;\n import javax.persistence.PersistenceContext;\n import javax.transaction.UserTransaction;\n import java.util.List;\n import java.util.Properties;\n \n //START SNIPPET: code\n public class MoviesTest extends TestCase {\n \n @EJB\n private Movies movies;\n \n @Resource\n private UserTransaction userTransaction;\n \n @PersistenceContext\n private EntityManager entityManager;\n \n public void setUp() throws Exception {\n Properties p = new Properties();\n p.put(\"movieDatabase\", \"new://Resource?type=DataSource\");\n p.put(\"movieDatabase.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"movieDatabase.JdbcUrl\", \"jdbc:hsqldb:mem:moviedb\");\n \n EJBContainer.createEJBContainer(p).getContext().bind(\"inject\", this);\n }\n \n public void test() throws Exception {\n \n userTransaction.begin();\n \n try {\n entityManager.persist(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n entityManager.persist(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n entityManager.persist(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n \n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n \n for (Movie movie : list) {\n movies.deleteMovie(movie);\n }\n \n assertEquals(\"Movies.getMovies()\", 0, movies.getMovies().size());\n } finally {\n userTransaction.commit();\n }\n \n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.testinjection.MoviesTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/testcase-injection\n INFO - openejb.base = /Users/dblevins/examples/testcase-injection\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/testcase-injection/target/classes\n INFO - Beginning load: /Users/dblevins/examples/testcase-injection/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/testcase-injection\n WARN - Method 'lookup' is not available for 'javax.annotation.Resource'. Probably using an older Runtime.\n INFO - Configuring Service(id=Default Stateful Container, type=Container, provider-id=Default Stateful Container)\n INFO - Auto-creating a container for bean Movies: Container(type=STATEFUL, id=Default Stateful Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.testinjection.MoviesTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring PersistenceUnit(name=movie-unit)\n INFO - Auto-creating a Resource with id 'movieDatabaseNonJta' of type 'DataSource for 'movie-unit'.\n INFO - Configuring Service(id=movieDatabaseNonJta, type=Resource, provider-id=movieDatabase)\n INFO - Adjusting PersistenceUnit movie-unit <non-jta-data-source> to Resource ID 'movieDatabaseNonJta' from 'movieDatabaseUnmanaged'\n INFO - Enterprise application \"/Users/dblevins/examples/testcase-injection\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/testcase-injection\n INFO - PersistenceUnit(name=movie-unit, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 408ms\n INFO - Jndi(name=\"java:global/testcase-injection/Movies!org.superbiz.testinjection.Movies\")\n INFO - Jndi(name=\"java:global/testcase-injection/Movies\")\n INFO - Jndi(name=\"java:global/EjbModule1583515396/org.superbiz.testinjection.MoviesTest!org.superbiz.testinjection.MoviesTest\")\n INFO - Jndi(name=\"java:global/EjbModule1583515396/org.superbiz.testinjection.MoviesTest\")\n INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Created Ejb(deployment-id=org.superbiz.testinjection.MoviesTest, ejb-name=org.superbiz.testinjection.MoviesTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Started Ejb(deployment-id=org.superbiz.testinjection.MoviesTest, ejb-name=org.superbiz.testinjection.MoviesTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/testcase-injection)\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.24 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/testcase-injection"
},
{
"name":"injection-of-env-entry",
"readme":"Title: Using EnvEntries\n\nThe `@Resource` annotation can be used to inject several things including\nDataSources, Topics, Queues, etc. Most of these are container supplied objects.\n\nIt is possible, however, to supply your own values to be injected via an `<env-entry>`\nin your `ejb-jar.xml` or `web.xml` deployment descriptor. Java EE 6 supported `<env-entry>` types\nare limited to the following:\n\n - java.lang.String\n - java.lang.Integer\n - java.lang.Short\n - java.lang.Float\n - java.lang.Double\n - java.lang.Byte\n - java.lang.Character\n - java.lang.Boolean\n - java.lang.Class\n - java.lang.Enum (any enum)\n\nSee also the [Custom Injection](../custom-injection) exmaple for a TomEE and OpenEJB feature that will let you\nuse more than just the above types as well as declare `<env-entry>` items with a plain properties file.\n\n# Using @Resource for basic properties\n\nThe use of the `@Resource` annotation isn't limited to setters. For\nexample, this annotation could have been used on the corresponding *field*\nlike so:\n\n @Resource\n private int maxLineItems;\n\nA fuller example might look like this:\n\n package org.superbiz.injection.enventry;\n \n import javax.annotation.Resource;\n import javax.ejb.Singleton;\n import java.util.Date;\n \n @Singleton\n public class Configuration {\n \n @Resource\n private String color;\n \n @Resource\n private Shape shape;\n \n @Resource\n private Class strategy;\n \n @Resource(name = \"date\")\n private long date;\n \n public String getColor() {\n return color;\n }\n \n public Shape getShape() {\n return shape;\n }\n \n public Class getStrategy() {\n return strategy;\n }\n \n public Date getDate() {\n return new Date(date);\n }\n }\n\nHere we have an `@Singleton` bean called `Confuration` that has the following properties (`<env-entry>` items)\n\n- String color\n- Shape shape\n- Class strategy\n- long date\n\n## Supplying @Resource values for <env-entry> items in ejb-jar.xml\n\nThe values for our `color`, `shape`, `strategy` and `date` properties are supplied via `<env-entry>` elements in the `ejb-jar.xml` file or the\n`web.xml` file like so:\n\n\n <ejb-jar xmlns=\"http://java.sun.com/xml/ns/javaee\" version=\"3.0\" metadata-complete=\"false\">\n <enterprise-beans>\n <session>\n <ejb-name>Configuration</ejb-name>\n <env-entry>\n <env-entry-name>org.superbiz.injection.enventry.Configuration/color</env-entry-name>\n <env-entry-type>java.lang.String</env-entry-type>\n <env-entry-value>orange</env-entry-value>\n </env-entry>\n <env-entry>\n <env-entry-name>org.superbiz.injection.enventry.Configuration/shape</env-entry-name>\n <env-entry-type>org.superbiz.injection.enventry.Shape</env-entry-type>\n <env-entry-value>TRIANGLE</env-entry-value>\n </env-entry>\n <env-entry>\n <env-entry-name>org.superbiz.injection.enventry.Configuration/strategy</env-entry-name>\n <env-entry-type>java.lang.Class</env-entry-type>\n <env-entry-value>org.superbiz.injection.enventry.Widget</env-entry-value>\n </env-entry>\n <env-entry>\n <description>The name was explicitly set in the annotation so the classname prefix isn't required</description>\n <env-entry-name>date</env-entry-name>\n <env-entry-type>java.lang.Long</env-entry-type>\n <env-entry-value>123456789</env-entry-value>\n </env-entry>\n </session>\n </enterprise-beans>\n </ejb-jar>\n\n\n### Using the @Resource 'name' attribute\n\nNote that `date` was referenced by `name` as:\n\n @Resource(name = \"date\")\n private long date;\n\nWhen the `@Resource(name)` is used, you do not need to specify the full class name of the bean and can do it briefly like so:\n\n <env-entry>\n <description>The name was explicitly set in the annotation so the classname prefix isn't required</description>\n <env-entry-name>date</env-entry-name>\n <env-entry-type>java.lang.Long</env-entry-type>\n <env-entry-value>123456789</env-entry-value>\n </env-entry>\n\nConversly, `color` was not referenced by `name`\n\n @Resource\n private String color;\n\nWhen something is not referenced by `name` in the `@Resource` annotation a default name is created. The format is essentially this:\n\n bean.getClass() + \"/\" + field.getName()\n\nSo the default `name` of the above `color` property ends up being `org.superbiz.injection.enventry.Configuration/color`. This is the name\nwe must use when we attempt to decalre a value for it in xml.\n\n <env-entry>\n <env-entry-name>org.superbiz.injection.enventry.Configuration/color</env-entry-name>\n <env-entry-type>java.lang.String</env-entry-type>\n <env-entry-value>orange</env-entry-value>\n </env-entry>\n\n### @Resource and Enum (Enumerations)\n\nThe `shape` field is actually a custom Java Enum type\n\n package org.superbiz.injection.enventry;\n\n public enum Shape {\n \n CIRCLE,\n TRIANGLE,\n SQUARE\n }\n\nAs of Java EE 6, java.lang.Enum types are allowed as `<env-entry>` items. Declaring one in xml is done using the actual enum's class name like so:\n\n <env-entry>\n <env-entry-name>org.superbiz.injection.enventry.Configuration/shape</env-entry-name>\n <env-entry-type>org.superbiz.injection.enventry.Shape</env-entry-type>\n <env-entry-value>TRIANGLE</env-entry-value>\n </env-entry>\n\nDo not use `<env-entry-type>java.lang.Enum</env-entry-type>` or it will not work!\n\n## ConfigurationTest\n\n package org.superbiz.injection.enventry;\n \n import junit.framework.TestCase;\n \n import javax.ejb.embeddable.EJBContainer;\n import javax.naming.Context;\n import java.util.Date;\n \n public class ConfigurationTest extends TestCase {\n \n \n public void test() throws Exception {\n final Context context = EJBContainer.createEJBContainer().getContext();\n \n final Configuration configuration = (Configuration) context.lookup(\"java:global/injection-of-env-entry/Configuration\");\n \n assertEquals(\"orange\", configuration.getColor());\n \n assertEquals(Shape.TRIANGLE, configuration.getShape());\n \n assertEquals(Widget.class, configuration.getStrategy());\n \n assertEquals(new Date(123456789), configuration.getDate());\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.injection.enventry.ConfigurationTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/injection-of-env-entry\n INFO - openejb.base = /Users/dblevins/examples/injection-of-env-entry\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/injection-of-env-entry/target/classes\n INFO - Beginning load: /Users/dblevins/examples/injection-of-env-entry/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/injection-of-env-entry\n WARN - Method 'lookup' is not available for 'javax.annotation.Resource'. Probably using an older Runtime.\n INFO - Configuring Service(id=Default Singleton Container, type=Container, provider-id=Default Singleton Container)\n INFO - Auto-creating a container for bean Configuration: Container(type=SINGLETON, id=Default Singleton Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.injection.enventry.ConfigurationTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Enterprise application \"/Users/dblevins/examples/injection-of-env-entry\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/injection-of-env-entry\n INFO - Jndi(name=\"java:global/injection-of-env-entry/Configuration!org.superbiz.injection.enventry.Configuration\")\n INFO - Jndi(name=\"java:global/injection-of-env-entry/Configuration\")\n INFO - Jndi(name=\"java:global/EjbModule1355224018/org.superbiz.injection.enventry.ConfigurationTest!org.superbiz.injection.enventry.ConfigurationTest\")\n INFO - Jndi(name=\"java:global/EjbModule1355224018/org.superbiz.injection.enventry.ConfigurationTest\")\n INFO - Created Ejb(deployment-id=org.superbiz.injection.enventry.ConfigurationTest, ejb-name=org.superbiz.injection.enventry.ConfigurationTest, container=Default Managed Container)\n INFO - Created Ejb(deployment-id=Configuration, ejb-name=Configuration, container=Default Singleton Container)\n INFO - Started Ejb(deployment-id=org.superbiz.injection.enventry.ConfigurationTest, ejb-name=org.superbiz.injection.enventry.ConfigurationTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=Configuration, ejb-name=Configuration, container=Default Singleton Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/injection-of-env-entry)\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.664 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/injection-of-env-entry"
},
{
"name":"injection-of-entitymanager",
"readme":"Title: Injection Of Entitymanager\n\nThis example shows use of `@PersistenceContext` to have an `EntityManager` with an\n`EXTENDED` persistence context injected into a `@Stateful bean`. A JPA\n`@Entity` bean is used with the `EntityManager` to create, persist and merge\ndata to a database.\n\n## Creating the JPA Entity\n\nThe entity itself is simply a pojo annotated with `@Entity`. We create one called `Movie` which we can use to hold movie records.\n\n package org.superbiz.injection.jpa;\n\n import javax.persistence.Entity;\n \n @Entity\n public class Movie {\n\n @Id @GeneratedValue\n private long id;\n\n private String director;\n private String title;\n private int year;\n\n public Movie() {\n }\n\n public long getId() {\n return id;\n }\n\n public void setId(long id) {\n this.id = id;\n }\n\n public Movie(String director, String title, int year) {\n this.director = director;\n this.title = title;\n this.year = year;\n }\n\n public String getDirector() {\n return director;\n }\n\n public void setDirector(String director) {\n this.director = director;\n }\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public int getYear() {\n return year;\n }\n\n public void setYear(int year) {\n this.year = year;\n }\n }\n\n## Configure the EntityManager via a persistence.xml file\n\nThe above `Movie` entity can be created, removed, updated or deleted via an `EntityManager` object. The `EntityManager` itself is\nconfigured via a `META-INF/persistence.xml` file that is placed in the same jar as the `Movie` entity.\n\n <persistence xmlns=\"http://java.sun.com/xml/ns/persistence\" version=\"1.0\">\n\n <persistence-unit name=\"movie-unit\">\n <jta-data-source>movieDatabase</jta-data-source>\n <non-jta-data-source>movieDatabaseUnmanaged</non-jta-data-source>\n <class>org.superbiz.injection.jpa.Movie</class>\n\n <properties>\n <property name=\"openjpa.jdbc.SynchronizeMappings\" value=\"buildSchema(ForeignKeys=true)\"/>\n </properties>\n </persistence-unit>\n </persistence>\n\nNotice that the `Movie` entity is listed via a `<class>` element. This is not required, but can help when testing or when the\n`Movie` class is located in a different jar than the jar containing the `persistence.xml` file.\n\n## Injection via @PersistenceContext\n\nThe `EntityManager` itself is created by the container using the information in the `persistence.xml`, so to use it at\nruntime, we simply need to request it be injected into one of our components. We do this via `@PersistenceContext`\n\nThe `@PersistenceContext` annotation can be used on any CDI bean, EJB, Servlet, Servlet Listener, Servlet Filter, or JSF ManagedBean. If you don't use an EJB you will need to use a `UserTransaction` begin and commit transactions manually. A transaction is required for any of the create, update or delete methods of the EntityManager to work.\n\n package org.superbiz.injection.jpa;\n\n import javax.ejb.Stateful;\n import javax.persistence.EntityManager;\n import javax.persistence.PersistenceContext;\n import javax.persistence.PersistenceContextType;\n import javax.persistence.Query;\n import java.util.List;\n \n @Stateful\n public class Movies {\n \n @PersistenceContext(unitName = \"movie-unit\", type = PersistenceContextType.EXTENDED)\n private EntityManager entityManager;\n \n public void addMovie(Movie movie) throws Exception {\n entityManager.persist(movie);\n }\n \n public void deleteMovie(Movie movie) throws Exception {\n entityManager.remove(movie);\n }\n \n public List<Movie> getMovies() throws Exception {\n Query query = entityManager.createQuery(\"SELECT m from Movie as m\");\n return query.getResultList();\n }\n }\n\nThis particular `EntityManager` is injected as an `EXTENDED` persistence context, which simply means that the `EntityManager`\nis created when the `@Stateful` bean is created and destroyed when the `@Stateful` bean is destroyed. Simply put, the\ndata in the `EntityManager` is cached for the lifetime of the `@Stateful` bean.\n\nThe use of `EXTENDED` persistence contexts is **only** available to `@Stateful` beans. See the [JPA Concepts](../../jpa-concepts.html) page for an high level explanation of what a \"persistence context\" really is and how it is significant to JPA.\n\n## MoviesTest\n\nTesting JPA is quite easy, we can simply use the `EJBContainer` API to create a container in our test case.\n\n package org.superbiz.injection.jpa;\n \n import junit.framework.TestCase;\n \n import javax.ejb.embeddable.EJBContainer;\n import javax.naming.Context;\n import java.util.List;\n import java.util.Properties;\n \n //START SNIPPET: code\n public class MoviesTest extends TestCase {\n \n public void test() throws Exception {\n \n final Properties p = new Properties();\n p.put(\"movieDatabase\", \"new://Resource?type=DataSource\");\n p.put(\"movieDatabase.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"movieDatabase.JdbcUrl\", \"jdbc:hsqldb:mem:moviedb\");\n \n final Context context = EJBContainer.createEJBContainer(p).getContext();\n \n Movies movies = (Movies) context.lookup(\"java:global/injection-of-entitymanager/Movies\");\n \n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n movies.addMovie(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n movies.addMovie(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n \n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n \n for (Movie movie : list) {\n movies.deleteMovie(movie);\n }\n \n assertEquals(\"Movies.getMovies()\", 0, movies.getMovies().size());\n }\n }\n\n# Running\n\nWhen we run our test case we should see output similar to the following.\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.injection.jpa.MoviesTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/injection-of-entitymanager\n INFO - openejb.base = /Users/dblevins/examples/injection-of-entitymanager\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/injection-of-entitymanager/target/classes\n INFO - Beginning load: /Users/dblevins/examples/injection-of-entitymanager/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/injection-of-entitymanager\n INFO - Configuring Service(id=Default Stateful Container, type=Container, provider-id=Default Stateful Container)\n INFO - Auto-creating a container for bean Movies: Container(type=STATEFUL, id=Default Stateful Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.injection.jpa.MoviesTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring PersistenceUnit(name=movie-unit)\n INFO - Auto-creating a Resource with id 'movieDatabaseNonJta' of type 'DataSource for 'movie-unit'.\n INFO - Configuring Service(id=movieDatabaseNonJta, type=Resource, provider-id=movieDatabase)\n INFO - Adjusting PersistenceUnit movie-unit <non-jta-data-source> to Resource ID 'movieDatabaseNonJta' from 'movieDatabaseUnmanaged'\n INFO - Enterprise application \"/Users/dblevins/examples/injection-of-entitymanager\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/injection-of-entitymanager\n INFO - PersistenceUnit(name=movie-unit, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 462ms\n INFO - Jndi(name=\"java:global/injection-of-entitymanager/Movies!org.superbiz.injection.jpa.Movies\")\n INFO - Jndi(name=\"java:global/injection-of-entitymanager/Movies\")\n INFO - Jndi(name=\"java:global/EjbModule1461341140/org.superbiz.injection.jpa.MoviesTest!org.superbiz.injection.jpa.MoviesTest\")\n INFO - Jndi(name=\"java:global/EjbModule1461341140/org.superbiz.injection.jpa.MoviesTest\")\n INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Created Ejb(deployment-id=org.superbiz.injection.jpa.MoviesTest, ejb-name=org.superbiz.injection.jpa.MoviesTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Started Ejb(deployment-id=org.superbiz.injection.jpa.MoviesTest, ejb-name=org.superbiz.injection.jpa.MoviesTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/injection-of-entitymanager)\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.301 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/injection-of-entitymanager"
},
{
"name":"injection-of-datasource",
"readme":"Title: Injection Of Datasource\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## Movie\n\n package org.superbiz.injection;\n \n /**\n * @version $Revision: 607077 $ $Date: 2007-12-27 06:55:23 -0800 (Thu, 27 Dec 2007) $\n */\n public class Movie {\n private String director;\n private String title;\n private int year;\n \n public Movie() {\n }\n \n public Movie(String director, String title, int year) {\n this.director = director;\n this.title = title;\n this.year = year;\n }\n \n public String getDirector() {\n return director;\n }\n \n public void setDirector(String director) {\n this.director = director;\n }\n \n public String getTitle() {\n return title;\n }\n \n public void setTitle(String title) {\n this.title = title;\n }\n \n public int getYear() {\n return year;\n }\n \n public void setYear(int year) {\n this.year = year;\n }\n \n }\n\n## Movies\n\n package org.superbiz.injection;\n \n import javax.annotation.PostConstruct;\n import javax.annotation.Resource;\n import javax.ejb.Stateful;\n import javax.sql.DataSource;\n import java.sql.Connection;\n import java.sql.PreparedStatement;\n import java.sql.ResultSet;\n import java.util.ArrayList;\n import java.util.List;\n \n @Stateful\n public class Movies {\n \n /**\n * The field name \"movieDatabase\" matches the DataSource we\n * configure in the TestCase via :\n * p.put(\"movieDatabase\", \"new://Resource?type=DataSource\");\n * <p/>\n * This would also match an equivalent delcaration in an openejb.xml:\n * <Resource id=\"movieDatabase\" type=\"DataSource\"/>\n * <p/>\n * If you'd like the freedom to change the field name without\n * impact on your configuration you can set the \"name\" attribute\n * of the @Resource annotation to \"movieDatabase\" instead.\n */\n @Resource\n private DataSource movieDatabase;\n \n @PostConstruct\n private void construct() throws Exception {\n Connection connection = movieDatabase.getConnection();\n try {\n PreparedStatement stmt = connection.prepareStatement(\"CREATE TABLE movie ( director VARCHAR(255), title VARCHAR(255), year integer)\");\n stmt.execute();\n } finally {\n connection.close();\n }\n }\n \n public void addMovie(Movie movie) throws Exception {\n Connection conn = movieDatabase.getConnection();\n try {\n PreparedStatement sql = conn.prepareStatement(\"INSERT into movie (director, title, year) values (?, ?, ?)\");\n sql.setString(1, movie.getDirector());\n sql.setString(2, movie.getTitle());\n sql.setInt(3, movie.getYear());\n sql.execute();\n } finally {\n conn.close();\n }\n }\n \n public void deleteMovie(Movie movie) throws Exception {\n Connection conn = movieDatabase.getConnection();\n try {\n PreparedStatement sql = conn.prepareStatement(\"DELETE from movie where director = ? AND title = ? AND year = ?\");\n sql.setString(1, movie.getDirector());\n sql.setString(2, movie.getTitle());\n sql.setInt(3, movie.getYear());\n sql.execute();\n } finally {\n conn.close();\n }\n }\n \n public List<Movie> getMovies() throws Exception {\n ArrayList<Movie> movies = new ArrayList<Movie>();\n Connection conn = movieDatabase.getConnection();\n try {\n PreparedStatement sql = conn.prepareStatement(\"SELECT director, title, year from movie\");\n ResultSet set = sql.executeQuery();\n while (set.next()) {\n Movie movie = new Movie();\n movie.setDirector(set.getString(\"director\"));\n movie.setTitle(set.getString(\"title\"));\n movie.setYear(set.getInt(\"year\"));\n movies.add(movie);\n }\n } finally {\n conn.close();\n }\n return movies;\n }\n }\n\n## MoviesTest\n\n package org.superbiz.injection;\n \n import junit.framework.TestCase;\n \n import javax.ejb.embeddable.EJBContainer;\n import javax.naming.Context;\n import java.util.List;\n import java.util.Properties;\n \n //START SNIPPET: code\n public class MoviesTest extends TestCase {\n \n public void test() throws Exception {\n \n Properties p = new Properties();\n p.put(\"movieDatabase\", \"new://Resource?type=DataSource\");\n p.put(\"movieDatabase.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"movieDatabase.JdbcUrl\", \"jdbc:hsqldb:mem:moviedb\");\n \n Context context = EJBContainer.createEJBContainer(p).getContext();\n \n Movies movies = (Movies) context.lookup(\"java:global/injection-of-datasource/Movies\");\n \n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n movies.addMovie(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n movies.addMovie(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n \n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n \n for (Movie movie : list) {\n movies.deleteMovie(movie);\n }\n \n assertEquals(\"Movies.getMovies()\", 0, movies.getMovies().size());\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.injection.MoviesTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/injection-of-datasource\n INFO - openejb.base = /Users/dblevins/examples/injection-of-datasource\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/injection-of-datasource/target/classes\n INFO - Beginning load: /Users/dblevins/examples/injection-of-datasource/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/injection-of-datasource\n WARN - Method 'lookup' is not available for 'javax.annotation.Resource'. Probably using an older Runtime.\n INFO - Configuring Service(id=Default Stateful Container, type=Container, provider-id=Default Stateful Container)\n INFO - Auto-creating a container for bean Movies: Container(type=STATEFUL, id=Default Stateful Container)\n INFO - Auto-linking resource-ref 'java:comp/env/org.superbiz.injection.Movies/movieDatabase' in bean Movies to Resource(id=movieDatabase)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.injection.MoviesTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Enterprise application \"/Users/dblevins/examples/injection-of-datasource\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/injection-of-datasource\n INFO - Jndi(name=\"java:global/injection-of-datasource/Movies!org.superbiz.injection.Movies\")\n INFO - Jndi(name=\"java:global/injection-of-datasource/Movies\")\n INFO - Jndi(name=\"java:global/EjbModule1508028338/org.superbiz.injection.MoviesTest!org.superbiz.injection.MoviesTest\")\n INFO - Jndi(name=\"java:global/EjbModule1508028338/org.superbiz.injection.MoviesTest\")\n INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Created Ejb(deployment-id=org.superbiz.injection.MoviesTest, ejb-name=org.superbiz.injection.MoviesTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Started Ejb(deployment-id=org.superbiz.injection.MoviesTest, ejb-name=org.superbiz.injection.MoviesTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/injection-of-datasource)\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.276 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/injection-of-datasource"
},
{
"name":"injection-of-ejbs",
"readme":"Title: Injection Of Ejbs\n\nThis example shows how to use the @EJB annotation on a bean class to refer to other beans.\n\nThis functionality is often referred as dependency injection (see\nhttp://www.martinfowler.com/articles/injection.html), and has been recently introduced in\nJava EE 5.\n\nIn this particular example, we will create two session stateless beans\n\n * a DataStore session bean\n * a DataReader session bean\n\nThe DataReader bean uses the DataStore to retrieve some informations, and\nwe will see how we can, inside the DataReader bean, get a reference to the\nDataStore bean using the @EJB annotation, thus avoiding the use of the\nJNDI API.\n\n## DataReader\n\n package org.superbiz.injection;\n \n import javax.ejb.EJB;\n import javax.ejb.Stateless;\n \n /**\n * This is an EJB 3.1 style pojo stateless session bean\n * Every stateless session bean implementation must be annotated\n * using the annotation @Stateless\n * This EJB has 2 business interfaces: DataReaderRemote, a remote business\n * interface, and DataReaderLocal, a local business interface\n * <p/>\n * The instance variables 'dataStoreRemote' is annotated with the @EJB annotation:\n * this means that the application server, at runtime, will inject in this instance\n * variable a reference to the EJB DataStoreRemote\n * <p/>\n * The instance variables 'dataStoreLocal' is annotated with the @EJB annotation:\n * this means that the application server, at runtime, will inject in this instance\n * variable a reference to the EJB DataStoreLocal\n */\n //START SNIPPET: code\n @Stateless\n public class DataReader {\n \n @EJB\n private DataStoreRemote dataStoreRemote;\n @EJB\n private DataStoreLocal dataStoreLocal;\n @EJB\n private DataStore dataStore;\n \n public String readDataFromLocalStore() {\n return \"LOCAL:\" + dataStoreLocal.getData();\n }\n \n public String readDataFromLocalBeanStore() {\n return \"LOCALBEAN:\" + dataStore.getData();\n }\n \n public String readDataFromRemoteStore() {\n return \"REMOTE:\" + dataStoreRemote.getData();\n }\n }\n\n## DataStore\n\n package org.superbiz.injection;\n \n import javax.ejb.LocalBean;\n import javax.ejb.Stateless;\n \n /**\n * This is an EJB 3 style pojo stateless session bean\n * Every stateless session bean implementation must be annotated\n * using the annotation @Stateless\n * This EJB has 2 business interfaces: DataStoreRemote, a remote business\n * interface, and DataStoreLocal, a local business interface\n */\n //START SNIPPET: code\n @Stateless\n @LocalBean\n public class DataStore implements DataStoreLocal, DataStoreRemote {\n \n public String getData() {\n return \"42\";\n }\n }\n\n## DataStoreLocal\n\n package org.superbiz.injection;\n \n import javax.ejb.Local;\n \n /**\n * This is an EJB 3 local business interface\n * A local business interface may be annotated with the @Local\n * annotation, but it's optional. A business interface which is\n * not annotated with @Local or @Remote is assumed to be Local\n */\n //START SNIPPET: code\n @Local\n public interface DataStoreLocal {\n \n public String getData();\n }\n\n## DataStoreRemote\n\n package org.superbiz.injection;\n \n import javax.ejb.Remote;\n \n /**\n * This is an EJB 3 remote business interface\n * A remote business interface must be annotated with the @Remote\n * annotation\n */\n //START SNIPPET: code\n @Remote\n public interface DataStoreRemote {\n \n public String getData();\n }\n\n## EjbDependencyTest\n\n package org.superbiz.injection;\n \n import junit.framework.TestCase;\n \n import javax.ejb.embeddable.EJBContainer;\n import javax.naming.Context;\n \n /**\n * A test case for DataReaderImpl ejb, testing both the remote and local interface\n */\n //START SNIPPET: code\n public class EjbDependencyTest extends TestCase {\n \n public void test() throws Exception {\n final Context context = EJBContainer.createEJBContainer().getContext();\n \n DataReader dataReader = (DataReader) context.lookup(\"java:global/injection-of-ejbs/DataReader\");\n \n assertNotNull(dataReader);\n \n assertEquals(\"LOCAL:42\", dataReader.readDataFromLocalStore());\n assertEquals(\"REMOTE:42\", dataReader.readDataFromRemoteStore());\n assertEquals(\"LOCALBEAN:42\", dataReader.readDataFromLocalBeanStore());\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.injection.EjbDependencyTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/injection-of-ejbs\n INFO - openejb.base = /Users/dblevins/examples/injection-of-ejbs\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/injection-of-ejbs/target/classes\n INFO - Beginning load: /Users/dblevins/examples/injection-of-ejbs/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/injection-of-ejbs\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean DataReader: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.injection.EjbDependencyTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Enterprise application \"/Users/dblevins/examples/injection-of-ejbs\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/injection-of-ejbs\n INFO - Jndi(name=\"java:global/injection-of-ejbs/DataReader!org.superbiz.injection.DataReader\")\n INFO - Jndi(name=\"java:global/injection-of-ejbs/DataReader\")\n INFO - Jndi(name=\"java:global/injection-of-ejbs/DataStore!org.superbiz.injection.DataStore\")\n INFO - Jndi(name=\"java:global/injection-of-ejbs/DataStore!org.superbiz.injection.DataStoreLocal\")\n INFO - Jndi(name=\"java:global/injection-of-ejbs/DataStore!org.superbiz.injection.DataStoreRemote\")\n INFO - Jndi(name=\"java:global/injection-of-ejbs/DataStore\")\n INFO - Jndi(name=\"java:global/EjbModule355598874/org.superbiz.injection.EjbDependencyTest!org.superbiz.injection.EjbDependencyTest\")\n INFO - Jndi(name=\"java:global/EjbModule355598874/org.superbiz.injection.EjbDependencyTest\")\n INFO - Created Ejb(deployment-id=DataReader, ejb-name=DataReader, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=DataStore, ejb-name=DataStore, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=org.superbiz.injection.EjbDependencyTest, ejb-name=org.superbiz.injection.EjbDependencyTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=DataReader, ejb-name=DataReader, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=DataStore, ejb-name=DataStore, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=org.superbiz.injection.EjbDependencyTest, ejb-name=org.superbiz.injection.EjbDependencyTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/injection-of-ejbs)\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.225 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/injection-of-ejbs"
},
{
"name":"custom-injection",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/custom-injection"
}
],
"interceptor":[
{
"name":"interceptors",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/interceptors"
},
{
"name":"cdi-interceptors",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/cdi-interceptors"
},
{
"name":"simple-cdi-interceptor",
"readme":"#Simple CDI Interceptor\n\nLet's write a simple application that would allow us to book tickets for a movie show. As with all applications, logging is one cross-cutting concern that we have. \n\n(Relevant snippets are inlined but you can check out the complete code, from the links provided)\n\nHow do we mark which methods are to be intercepted ? Wouldn't it be handy to annotate a method like \n\n @Log\n public void aMethod(){...} \n\nLet's create an annotation that would \"mark\" a method for interception. \n\n @InterceptorBinding\n @Target({ TYPE, METHOD })\n @Retention(RUNTIME)\n public @interface Log {\n }\n\nSure, you haven't missed the @InterceptorBinding annotation above ! Now that our custom annotation is created, lets attach it (or to use a better term for it, \"bind it\" )\nto an interceptor. \n\nSo here's our logging interceptor. An @AroundInvoke method and we are almost done.\n\n @Interceptor\n @Log //binding the interceptor here. now any method annotated with @Log would be intercepted by logMethodEntry\n public class LoggingInterceptor {\n @AroundInvoke\n public Object logMethodEntry(InvocationContext ctx) throws Exception {\n System.out.println(\"Entering method: \" + ctx.getMethod().getName());\n //or logger.info statement \n return ctx.proceed();\n }\n }\n\nNow the @Log annotation we created is bound to this interceptor.\n\nThat done, let's annotate at class-level or method-level and have fun intercepting ! \n\n @Log\n @Stateful\n public class BookShow implements Serializable {\n private static final long serialVersionUID = 6350400892234496909L;\n public List<String> getMoviesList() {\n List<String> moviesAvailable = new ArrayList<String>();\n moviesAvailable.add(\"12 Angry Men\");\n moviesAvailable.add(\"Kings speech\");\n return moviesAvailable;\n }\n public Integer getDiscountedPrice(int ticketPrice) {\n return ticketPrice - 50;\n }\n // assume more methods are present\n }\n\nThe `@Log` annotation applied at class level denotes that all the methods should be intercepted with `LoggingInterceptor`.\n\nBefore we say \"all done\" there's one last thing we are left with ! To enable the interceptors ! \n\nLets quickly put up a [beans.xml file]\n\n <beans>\n <interceptors>\n <class>org.superbiz.cdi.bookshow.interceptors.LoggingInterceptor\n </class>\n </interceptors>\n </beans>\n\n in META-INF\n\n\nThose lines in beans.xml not only \"enable\" the interceptors, but also define the \"order of execution\" of the interceptors.\nBut we'll see that in another example on multiple-cdi-interceptors.\n\nFire up the test, and we should see a 'Entering method: getMoviesList' printed in the console.\n\n#Tests\n Apache OpenEJB 4.0.0-beta-2 build: 20111103-01:00\n http://tomee.apache.org/\n INFO - openejb.home = /media/fthree/Workspace/open4/openejb/examples/cdi-simple-interceptors\n INFO - openejb.base = /media/fthree/Workspace/open4/openejb/examples/cdi-simple-interceptors\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true' \n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /media/fthree/Workspace/open4/openejb/examples/cdi-simple-interceptors/target/classes\n INFO - Beginning load: /media/fthree/Workspace/open4/openejb/examples/cdi-simple-interceptors/target/classes\n INFO - Configuring enterprise application: /media/fthree/Workspace/open4/openejb/examples/cdi-simple-interceptors\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean cdi-simple-interceptors.Comp: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring Service(id=Default Stateful Container, type=Container, provider-id=Default Stateful Container)\n INFO - Auto-creating a container for bean BookShow: Container(type=STATEFUL, id=Default Stateful Container)\n INFO - Enterprise application \"/media/fthree/Workspace/open4/openejb/examples/cdi-simple-interceptors\" loaded.\n INFO - Assembling app: /media/fthree/Workspace/open4/openejb/examples/cdi-simple-interceptors\n INFO - Jndi(name=\"java:global/cdi-simple-interceptors/BookShow!org.superbiz.cdi.bookshow.beans.BookShow\")\n INFO - Jndi(name=\"java:global/cdi-simple-interceptors/BookShow\")\n INFO - Created Ejb(deployment-id=BookShow, ejb-name=BookShow, container=Default Stateful Container)\n INFO - Started Ejb(deployment-id=BookShow, ejb-name=BookShow, container=Default Stateful Container)\n INFO - Deployed Application(path=/media/fthree/Workspace/open4/openejb/examples/cdi-simple-interceptors)\n Entering method: getMoviesList\n",
"url":"https://github.com/apache/tomee/tree/master/examples/simple-cdi-interceptor"
}
],
"interfaces":[
{
"name":"component-interfaces",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/component-interfaces"
}
],
"jaas":[
{
"name":"cdi-ejbcontext-jaas",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/cdi-ejbcontext-jaas"
},
{
"name":"rest-jaas",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/rest-jaas"
}
],
"javamail":[
{
"name":"javamail",
"readme":"Title: Javamail API\n\nThis 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.\n\n#The Code\n\n## A simple REST service using the Javamail API\n\nHere 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\nmore 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.\nYou can find much more detailed information on the [Javamail API here](https://java.net/projects/javamail/pages/Home#Samples)\n\n package org.superbiz.rest;\n\n import javax.mail.Authenticator;\n import javax.mail.Message;\n import javax.mail.MessagingException;\n import javax.mail.PasswordAuthentication;\n import javax.mail.Session;\n import javax.mail.Transport;\n import javax.mail.internet.InternetAddress;\n import javax.mail.internet.MimeMessage;\n import javax.ws.rs.POST;\n import javax.ws.rs.Path;\n import java.util.Date;\n import java.util.Properties;\n\n @Path(\"/email\")\n public class EmailService {\n\n @POST\n public String lowerCase(final String message) {\n\n try {\n\n //Create some properties and get the default Session\n final Properties props = new Properties();\n props.put(\"mail.smtp.host\", \"your.mailserver.host\");\n props.put(\"mail.debug\", \"true\");\n\n final Session session = Session.getInstance(props, new Authenticator() {\n @Override\n protected PasswordAuthentication getPasswordAuthentication() {\n return new PasswordAuthentication(\"MyUsername\", \"MyPassword\");\n }\n });\n\n //Set this just to see some internal logging\n session.setDebug(true);\n\n //Create a message\n final MimeMessage msg = new MimeMessage(session);\n msg.setFrom(new InternetAddress(\"your@email.address\"));\n final InternetAddress[] address = {new InternetAddress(\"general@tomitribe.com\")};\n msg.setRecipients(Message.RecipientType.TO, address);\n msg.setSubject(\"JavaMail API test\");\n msg.setSentDate(new Date());\n msg.setText(message, \"UTF-8\");\n\n\n Transport.send(msg);\n } catch (MessagingException e) {\n return \"Failed to send message: \" + e.getMessage();\n }\n\n return \"Sent\";\n }\n }\n\n# Testing\n\n## Test for the JAXRS service\n\nThe test uses the OpenEJB ApplicationComposer to make it trivial.\n\nThe idea is first to activate the jaxrs services. This is done using @EnableServices annotation.\n\nThen we create on the fly the application simply returning an object representing the web.xml. Here we simply\nuse it to define the context root but you can use it to define your REST Application too. And to complete the\napplication definition we add @Classes annotation to define the set of classes to use in this app.\n\nFinally to test it we use cxf client API to call the REST service post() method.\n\n package org.superbiz.rest;\n\n import org.apache.cxf.jaxrs.client.WebClient;\n import org.apache.openejb.jee.WebApp;\n import org.apache.openejb.junit.ApplicationComposer;\n import org.apache.openejb.testing.Classes;\n import org.apache.openejb.testing.EnableServices;\n import org.apache.openejb.testing.Module;\n import org.junit.Test;\n import org.junit.runner.RunWith;\n\n import java.io.IOException;\n\n import static org.junit.Assert.assertEquals;\n\n @EnableServices(value = \"jaxrs\")\n @RunWith(ApplicationComposer.class)\n public class EmailServiceTest {\n\n @Module\n @Classes(EmailService.class)\n public WebApp app() {\n return new WebApp().contextRoot(\"test\");\n }\n\n @Test\n public void post() throws IOException {\n final String message = WebClient.create(\"http://localhost:4204\").path(\"/test/email/\").post(\"Hello Tomitribe\", String.class);\n assertEquals(\"Failed to send message: Unknown SMTP host: your.mailserver.host\", message);\n }\n }\n\n#Running\n\nRunning the example is fairly simple. In the \"javamail-api\" directory run:\n\n $ mvn clean install\n\nWhich should create output like the following.\n\n INFO - Cannot find the configuration file [conf/openejb.xml]. Will attempt to create one for the beans deployed.\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Creating TransactionManager(id=Default Transaction Manager)\n INFO - Creating SecurityService(id=Default Security Service)\n INFO - Initializing network services\n INFO - Creating ServerService(id=cxf-rs)\n INFO - Creating ServerService(id=httpejbd)\n INFO - Created ServicePool 'httpejbd' with (10) core threads, limited to (200) threads with a queue of (9)\n INFO - Initializing network services\n INFO - ** Bound Services **\n INFO - NAME IP PORT\n INFO - httpejbd 127.0.0.1 4204\n INFO - -------\n INFO - Ready!\n INFO - Configuring enterprise application: D:\\github\\tomee\\examples\\javamail\\EmailServiceTest\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.rest.EmailServiceTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Creating Container(id=Default Managed Container)\n INFO - Using directory D:\\windows\\tmp for stateful session passivation\n INFO - Configuring Service(id=comp/DefaultManagedExecutorService, type=Resource, provider-id=Default Executor Service)\n INFO - Auto-creating a Resource with id 'comp/DefaultManagedExecutorService' of type 'javax.enterprise.concurrent.ManagedExecutorService for 'test'.\n INFO - Configuring Service(id=comp/DefaultManagedScheduledExecutorService, type=Resource, provider-id=Default Scheduled Executor Service)\n INFO - Auto-creating a Resource with id 'comp/DefaultManagedScheduledExecutorService' of type 'javax.enterprise.concurrent.ManagedScheduledExecutorService for 'test'.\n INFO - Configuring Service(id=comp/DefaultManagedThreadFactory, type=Resource, provider-id=Default Managed Thread Factory)\n INFO - Auto-creating a Resource with id 'comp/DefaultManagedThreadFactory' of type 'javax.enterprise.concurrent.ManagedThreadFactory for 'test'.\n INFO - Enterprise application \"D:\\github\\tomee\\examples\\javamail\\EmailServiceTest\" loaded.\n INFO - Creating dedicated application classloader for EmailServiceTest\n INFO - Assembling app: D:\\github\\tomee\\examples\\javamail\\EmailServiceTest\n INFO - Using providers:\n INFO - org.apache.johnzon.jaxrs.JohnzonProvider@2687f956\n INFO - org.apache.cxf.jaxrs.provider.JAXBElementProvider@1ded7b14\n INFO - org.apache.johnzon.jaxrs.JsrProvider@29be7749\n INFO - org.apache.johnzon.jaxrs.WadlDocumentMessageBodyWriter@5f84abe8\n INFO - org.apache.openejb.server.cxf.rs.EJBAccessExceptionMapper@4650a407\n INFO - org.apache.cxf.jaxrs.validation.ValidationExceptionMapper@30135202\n INFO - REST Application: http://127.0.0.1:4204/test/ -> org.apache.openejb.server.rest.InternalApplication\n INFO - Service URI: http://127.0.0.1:4204/test/email -> Pojo org.superbiz.rest.EmailService\n INFO - POST http://127.0.0.1:4204/test/email/ -> String lowerCase(String)\n INFO - Deployed Application(path=D:\\github\\tomee\\examples\\javamail\\EmailServiceTest)\n DEBUG: JavaMail version 1.4ea\n DEBUG: java.io.FileNotFoundException: D:\\java\\jdk8\\jre\\lib\\javamail.providers (The system cannot find the file specified)\n DEBUG: !anyLoaded\n DEBUG: not loading resource: /META-INF/javamail.providers\n DEBUG: successfully loaded resource: /META-INF/javamail.default.providers\n DEBUG: Tables of loaded providers\n 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]}\n 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]}\n DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map\n DEBUG: !anyLoaded\n DEBUG: not loading resource: /META-INF/javamail.address.map\n DEBUG: java.io.FileNotFoundException: D:\\java\\jdk8\\jre\\lib\\javamail.address.map (The system cannot find the file specified)\n DEBUG: setDebug: JavaMail version 1.4ea\n DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]\n DEBUG SMTP: useEhlo true, useAuth false\n DEBUG SMTP: trying to connect to host \"your.mailserver.host\", port 25, isSSL false\n INFO - Undeploying app: D:\\github\\tomee\\examples\\javamail\\EmailServiceTest\n INFO - Stopping network services\n INFO - Stopping server services\n\n\n",
"url":"https://github.com/apache/tomee/tree/master/examples/javamail"
}
],
"jaxws":[
{
"name":"applicationcomposer-jaxws-cdi",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/applicationcomposer-jaxws-cdi"
},
{
"name":"change-jaxws-url",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/change-jaxws-url"
}
],
"jersey":[
{
"name":"tomee-jersey-eclipselink",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/tomee-jersey-eclipselink"
}
],
"jmx":[
{
"name":"resources-jmx-example",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/resources-jmx-example"
}
],
"jpa":[
{
"name":"jpa-eclipselink",
"readme":"Title: JPA Eclipselink\n\nThis 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.\n\n## Creating the JPA Entity\n\nThe entity itself is simply a pojo annotated with `@Entity`. We create one pojo called `Movie` which we can use to hold movie records.\n\n package org.superbiz.eclipselink;\n \n import javax.persistence.Entity;\n import javax.persistence.GeneratedValue;\n import javax.persistence.GenerationType;\n import javax.persistence.Id;\n \n @Entity\n public class Movie {\n \n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private long id;\n \n private String director;\n private String title;\n private int year;\n \n public Movie() {\n }\n \n public Movie(String director, String title, int year) {\n this.director = director;\n this.title = title;\n this.year = year;\n }\n \n public String getDirector() {\n return director;\n }\n \n public void setDirector(String director) {\n this.director = director;\n }\n \n public String getTitle() {\n return title;\n }\n \n public void setTitle(String title) {\n this.title = title;\n }\n \n public int getYear() {\n return year;\n }\n \n public void setYear(int year) {\n this.year = year;\n }\n \n }\n\n## Database Operations\n\nThis is the bean responsible for database operations; it allows us to persist or delete entities.\nFor more information we recommend you to see [injection-of-entitymanager](http://tomee.apache.org/examples-trunk/injection-of-entitymanager/README.html)\n\n\n package org.superbiz.eclipselink;\n \n import javax.ejb.Stateful;\n import javax.persistence.EntityManager;\n import javax.persistence.PersistenceContext;\n import javax.persistence.PersistenceContextType;\n import javax.persistence.Query;\n import java.util.List;\n \n @Stateful\n public class Movies {\n \n @PersistenceContext(unitName = \"movie-unit\", type = PersistenceContextType.EXTENDED)\n private EntityManager entityManager;\n \n public void addMovie(Movie movie) throws Exception {\n entityManager.persist(movie);\n }\n \n public void deleteMovie(Movie movie) throws Exception {\n entityManager.remove(movie);\n }\n \n public List<Movie> getMovies() throws Exception {\n Query query = entityManager.createQuery(\"SELECT m from Movie as m\");\n return query.getResultList();\n }\n }\n\n## Persistence.xml with EclipseLink configuration\n\nThis operation is too easy, just set the `provider` to `org.eclipse.persistence.jpa.PersistenceProvider` and add additional properties to the persistence unit. \nThe example has followed a strategy that allows the creation of tables in a HSQL database.\nFor a complete list of persistence unit properties see [here](http://www.eclipse.org/eclipselink/api/2.4/org/eclipse/persistence/config/PersistenceUnitProperties.html)\n\n <persistence version=\"1.0\"\n xmlns=\"http://java.sun.com/xml/ns/persistence\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd\">\n <persistence-unit name=\"movie-unit\">\n <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>\n <jta-data-source>movieDatabase</jta-data-source>\n <non-jta-data-source>movieDatabaseUnmanaged</non-jta-data-source>\n <properties>\n <property name=\"eclipselink.target-database\" value=\"org.eclipse.persistence.platform.database.HSQLPlatform\"/>\n <property name=\"eclipselink.ddl-generation\" value=\"create-tables\"/>\n <property name=\"eclipselink.ddl-generation.output-mode\" value=\"database\"/>\n </properties>\n </persistence-unit>\n </persistence>\n \n\n## MoviesTest\n\nTesting JPA is quite easy, we can simply use the `EJBContainer` API to create a container in our test case.\n\n package org.superbiz.eclipselink;\n \n import junit.framework.TestCase;\n \n import javax.ejb.embeddable.EJBContainer;\n import javax.naming.Context;\n import java.util.List;\n import java.util.Properties;\n \n /**\n * @version $Revision: 607077 $ $Date: 2007-12-27 06:55:23 -0800 (Thu, 27 Dec 2007) $\n */\n public class MoviesTest extends TestCase {\n \n public void test() throws Exception {\n Properties p = new Properties();\n p.put(\"movieDatabase\", \"new://Resource?type=DataSource\");\n p.put(\"movieDatabase.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"movieDatabase.JdbcUrl\", \"jdbc:hsqldb:mem:moviedb\");\n \n final Context context = EJBContainer.createEJBContainer(p).getContext();\n \n Movies movies = (Movies) context.lookup(\"java:global/jpa-eclipselink/Movies\");\n \n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n movies.addMovie(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n movies.addMovie(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n \n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n \n for (Movie movie : list) {\n movies.deleteMovie(movie);\n }\n \n assertEquals(\"Movies.getMovies()\", 0, movies.getMovies().size());\n }\n }\n\n# Running\n\nWhen we run our test case we should see output similar to the following. \n\n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.eclipselink.MoviesTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/jpa-eclipselink\n INFO - openejb.base = /Users/dblevins/examples/jpa-eclipselink\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/jpa-eclipselink/target/classes\n INFO - Beginning load: /Users/dblevins/examples/jpa-eclipselink/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/jpa-eclipselink\n INFO - Configuring Service(id=Default Stateful Container, type=Container, provider-id=Default Stateful Container)\n INFO - Auto-creating a container for bean Movies: Container(type=STATEFUL, id=Default Stateful Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.eclipselink.MoviesTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring PersistenceUnit(name=movie-unit, provider=org.eclipse.persistence.jpa.PersistenceProvider)\n INFO - Auto-creating a Resource with id 'movieDatabaseNonJta' of type 'DataSource for 'movie-unit'.\n INFO - Configuring Service(id=movieDatabaseNonJta, type=Resource, provider-id=movieDatabase)\n INFO - Adjusting PersistenceUnit movie-unit <non-jta-data-source> to Resource ID 'movieDatabaseNonJta' from 'movieDatabaseUnmanaged'\n INFO - Enterprise application \"/Users/dblevins/examples/jpa-eclipselink\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/jpa-eclipselink\n INFO - PersistenceUnit(name=movie-unit, provider=org.eclipse.persistence.jpa.PersistenceProvider) - provider time 511ms\n INFO - Jndi(name=\"java:global/jpa-eclipselink/Movies!org.superbiz.eclipselink.Movies\")\n INFO - Jndi(name=\"java:global/jpa-eclipselink/Movies\")\n INFO - Jndi(name=\"java:global/EjbModule225280863/org.superbiz.eclipselink.MoviesTest!org.superbiz.eclipselink.MoviesTest\")\n INFO - Jndi(name=\"java:global/EjbModule225280863/org.superbiz.eclipselink.MoviesTest\")\n INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Created Ejb(deployment-id=org.superbiz.eclipselink.MoviesTest, ejb-name=org.superbiz.eclipselink.MoviesTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Started Ejb(deployment-id=org.superbiz.eclipselink.MoviesTest, ejb-name=org.superbiz.eclipselink.MoviesTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/jpa-eclipselink)\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.188 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n ",
"url":"https://github.com/apache/tomee/tree/master/examples/jpa-eclipselink"
},
{
"name":"groovy-jpa",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/groovy-jpa"
},
{
"name":"jpa-enumerated",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/jpa-enumerated"
},
{
"name":"jpa-hibernate",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/jpa-hibernate"
},
{
"name":"arquillian-jpa",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/arquillian-jpa"
},
{
"name":"multi-jpa-provider-testing",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/multi-jpa-provider-testing"
}
],
"jsf":[
{
"name":"jsf-managedBean-and-ejb",
"readme":"Title: JSF Application that uses managed-bean and ejb\n\nThis is a simple web-app showing how to use dependency injection in JSF managed beans using TomEE.\n\nIt contains a Local Stateless session bean `CalculatorImpl` which adds two numbers and returns the result.\nThe application also contains a JSF managed bean `CalculatorBean`, which uses the EJB to add two numbers\nand display the results to the user. The EJB is injected in the managed bean using `@EJB` annotation.\n\n\n## A little note on the setup:\n\nYou could run this in the latest Apache TomEE [snapshot](https://repository.apache.org/content/repositories/snapshots/org/apache/openejb/apache-tomee/)\n\nAs for the libraries, myfaces-api and myfaces-impl are provided in tomee/lib and hence they should not be a part of the\nwar. In maven terms, they would be with scope 'provided'\n\nAlso note that we use servlet 2.5 declaration in web.xml\n \n <web-app xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns=\"http://java.sun.com/xml/ns/javaee\"\n xmlns:web=\"http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee\n http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n version=\"2.5\">\n\nAnd we use 2.0 version of faces-config\n\n <faces-config xmlns=\"http://java.sun.com/xml/ns/javaee\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee\n http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd\"\n version=\"2.0\">\n\n\nThe complete source code is provided below but let's break down to look at some smaller snippets and see how it works.\n\nWe'll first declare the `FacesServlet` in the `web.xml`\n\n <servlet>\n <servlet-name>Faces Servlet</servlet-name>\n <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>\n <load-on-startup>1</load-on-startup>\n </servlet>\n\n`FacesServlet` acts as the master controller.\n\nWe'll then create the `calculator.xhtml` file.\n\n <h:outputText value='Enter first number'/>\n <h:inputText value='#{calculatorBean.x}'/>\n <h:outputText value='Enter second number'/>\n <h:inputText value='#{calculatorBean.y}'/>\n <h:commandButton action=\"#{calculatorBean.add}\" value=\"Add\"/>\n\n\nNotice how we've use the bean here.\nBy default it is the simple class name of the managed bean.\n\nWhen a request comes in, the bean is instantiated and placed in the appropriate scope.\nBy default, the bean is placed in the request scope.\n\n <h:inputText value='#{calculatorBean.x}'/>\n\nHere, getX() method of calculatorBean is invoked and the resulting value is displayed.\nx being a Double, we rightly should see 0.0 displayed.\n\nWhen you change the value and submit the form, these entered values are bound using the setters\nin the bean and then the commandButton-action method is invoked.\n\nIn this case, `CalculatorBean#add()` is invoked.\n\n`Calculator#add()` delegates the work to the ejb, gets the result, stores it\nand then instructs what view is to be rendered.\n\nYou're right. The return value \"success\" is checked up in faces-config navigation-rules\nand the respective page is rendered.\n\nIn our case, `result.xhtml` page is rendered.\n\nThe request scoped `calculatorBean` is available here, and we use EL to display the values.\n\n## Source\n\n## Calculator\n\n package org.superbiz.jsf;\n \n import javax.ejb.Local;\n \n @Local\n public interface Calculator {\n public double add(double x, double y);\n }\n\n\n## CalculatorBean\n\n package org.superbiz.jsf;\n \n import javax.ejb.EJB;\n import javax.faces.bean.ManagedBean;\n\n @ManagedBean\n public class CalculatorBean {\n @EJB\n Calculator calculator;\n private double x;\n private double y;\n private double result;\n \n public double getX() {\n return x;\n }\n \n public void setX(double x) {\n this.x = x;\n }\n \n public double getY() {\n return y;\n }\n \n public void setY(double y) {\n this.y = y;\n }\n \n public double getResult() {\n return result;\n }\n \n public void setResult(double result) {\n this.result = result;\n }\n \n public String add() {\n result = calculator.add(x, y);\n return \"success\";\n }\n }\n\n## CalculatorImpl\n\n package org.superbiz.jsf;\n \n import javax.ejb.Stateless;\n \n @Stateless\n public class CalculatorImpl implements Calculator {\n \n public double add(double x, double y) {\n return x + y;\n }\n }\n\n\n# web.xml\n\n <?xml version=\"1.0\"?>\n\n <web-app xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns=\"http://java.sun.com/xml/ns/javaee\"\n xmlns:web=\"http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee\n http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n version=\"2.5\">\n\n <description>MyProject web.xml</description>\n\n <!-- Faces Servlet -->\n <servlet>\n <servlet-name>Faces Servlet</servlet-name>\n <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>\n <load-on-startup>1</load-on-startup>\n </servlet>\n\n <!-- Faces Servlet Mapping -->\n <servlet-mapping>\n <servlet-name>Faces Servlet</servlet-name>\n <url-pattern>*.jsf</url-pattern>\n </servlet-mapping>\n\n <!-- Welcome files -->\n <welcome-file-list>\n <welcome-file>index.jsp</welcome-file>\n <welcome-file>index.html</welcome-file>\n </welcome-file-list>\n </web-app>\n\n \n##Calculator.xhtml\n\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n <html xmlns=\"http://www.w3.org/1999/xhtml\"\n xmlns:f=\"http://java.sun.com/jsf/core\"\n xmlns:h=\"http://java.sun.com/jsf/html\">\n\n\n <h:body bgcolor=\"white\">\n <f:view>\n <h:form>\n <h:panelGrid columns=\"2\">\n <h:outputText value='Enter first number'/>\n <h:inputText value='#{calculatorBean.x}'/>\n <h:outputText value='Enter second number'/>\n <h:inputText value='#{calculatorBean.y}'/>\n <h:commandButton action=\"#{calculatorBean.add}\" value=\"Add\"/>\n </h:panelGrid>\n </h:form>\n </f:view>\n </h:body>\n </html>\n\n \n##Result.xhtml\n\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n <html xmlns=\"http://www.w3.org/1999/xhtml\"\n xmlns:f=\"http://java.sun.com/jsf/core\"\n xmlns:h=\"http://java.sun.com/jsf/html\">\n\n <h:body>\n <f:view>\n <h:form id=\"mainForm\">\n <h2><h:outputText value=\"Result of adding #{calculatorBean.x} and #{calculatorBean.y} is #{calculatorBean.result }\"/></h2>\n <h:commandLink action=\"back\">\n <h:outputText value=\"Home\"/>\n </h:commandLink>\n </h:form>\n </f:view>\n </h:body>\n </html>\n \n#faces-config.xml\n\n <?xml version=\"1.0\"?>\n <faces-config xmlns=\"http://java.sun.com/xml/ns/javaee\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee\n http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd\"\n version=\"2.0\">\n\n <navigation-rule>\n <from-view-id>/calculator.xhtml</from-view-id>\n <navigation-case>\n <from-outcome>success</from-outcome>\n <to-view-id>/result.xhtml</to-view-id>\n </navigation-case>\n </navigation-rule>\n\n <navigation-rule>\n <from-view-id>/result.xhtml</from-view-id>\n <navigation-case>\n <from-outcome>back</from-outcome>\n <to-view-id>/calculator.xhtml</to-view-id>\n </navigation-case>\n </navigation-rule>\n </faces-config>\n",
"url":"https://github.com/apache/tomee/tree/master/examples/jsf-managedBean-and-ejb"
},
{
"name":"jsf-cdi-and-ejb",
"readme":"Title: JSF-CDI-EJB\n\nThe simple application contains a CDI managed bean `CalculatorBean`, which uses the `Calculator` EJB to add two numbers\nand display the results to the user. The EJB is injected in the managed bean using @Inject annotation.\n\nYou could run this in the latest Apache TomEE [snapshot](https://repository.apache.org/content/repositories/snapshots/org/apache/openejb/apache-tomee/)\n\nThe complete source code is below but lets break down to look at some smaller snippets and see how it works.\n\n\nA little note on the setup:\n\nAs for the libraries, myfaces-api and myfaces-impl are provided in tomee/lib and hence they should not be a part of the\nwar. In maven terms, they would be with scope 'provided'\n\nAlso note that we use servlet 2.5 declaration in web.xml\n<web-app xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns=\"http://java.sun.com/xml/ns/javaee\"\n xmlns:web=\"http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee\n http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n version=\"2.5\">\n\nAnd we use 2.0 version of faces-config\n\n <faces-config xmlns=\"http://java.sun.com/xml/ns/javaee\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee\n http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd\"\n version=\"2.0\">\n\nTo make this a cdi-aware-archive (i.e bean archive) an empty beans.xml is added in WEB-INF\n\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n <beans xmlns=\"http://java.sun.com/xml/ns/javaee\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee\n http://java.sun.com/xml/ns/javaee/beans_1_0.xsd\">\n </beans>\n\nWe'll first declare the FacesServlet in the web.xml\n\n <servlet>\n <servlet-name>Faces Servlet</servlet-name>\n <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>\n <load-on-startup>1</load-on-startup>\n </servlet>\n\nFacesServlet acts as the master controller.\n\nWe'll then create the calculator.xhtml file.\n\n <h:outputText value='Enter first number'/>\n <h:inputText value='#{calculatorBean.x}'/>\n <h:outputText value='Enter second number'/>\n <h:inputText value='#{calculatorBean.y}'/>\n <h:commandButton action=\"#{calculatorBean.add}\" value=\"Add\"/>\n\nNotice how we've used the bean here. By default, the bean name would be the simple name of the bean\nclass with the first letter in lower case.\n\nWe've annotated the `CalculatorBean` with `@RequestScoped`.\nSo when a request comes in, the bean is instantiated and placed in the request scope.\n\n<h:inputText value='#{calculatorBean.x}'/>\n\nHere, getX() method of calculatorBean is invoked and the resulting value is displayed.\nx being a Double, we rightly should see 0.0 displayed.\n\nWhen you change the value and submit the form, these entered values are bound using the setters\nin the bean and then the commandButton-action method is invoked.\n\nIn this case, CalculatorBean#add() is invoked.\n\nCalculator#add() delegates the work to the ejb, gets the result, stores it\nand then returns what view is to be rendered.\n\nThe return value \"success\" is checked up in faces-config navigation-rules\nand the respective page is rendered.\n\nIn our case, 'result.xhtml' page is rendered where\nuse EL and display the result from the request-scoped `calculatorBean`.\n\n#Source Code\n\n## CalculatorBean\n\n import javax.enterprise.context.RequestScoped;\n import javax.inject.Named;\n import javax.inject.Inject;\n\n @RequestScoped\n @Named\n public class CalculatorBean {\n @Inject\n Calculator calculator;\n private double x;\n private double y;\n private double result;\n \n public double getX() {\n return x;\n }\n \n public void setX(double x) {\n this.x = x;\n }\n \n public double getY() {\n return y;\n }\n \n public void setY(double y) {\n this.y = y;\n }\n \n public double getResult() {\n return result;\n }\n \n public void setResult(double result) {\n this.result = result;\n }\n \n public String add() {\n result = calculator.add(x, y);\n return \"success\";\n }\n }\n\n## Calculator\n\n package org.superbiz.jsf;\n \n import javax.ejb.Stateless;\n \n @Stateless\n public class Calculator{\n \n public double add(double x, double y) {\n return x + y;\n }\n }\n\n\n#web.xml\n\n<?xml version=\"1.0\"?>\n\n<web-app xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns=\"http://java.sun.com/xml/ns/javaee\"\n xmlns:web=\"http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee\n http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n version=\"2.5\">\n\n <description>MyProject web.xml</description>\n\n <!-- Faces Servlet -->\n <servlet>\n <servlet-name>Faces Servlet</servlet-name>\n <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>\n <load-on-startup>1</load-on-startup>\n </servlet>\n\n <!-- Faces Servlet Mapping -->\n <servlet-mapping>\n <servlet-name>Faces Servlet</servlet-name>\n <url-pattern>*.jsf</url-pattern>\n </servlet-mapping>\n\n <!-- Welcome files -->\n <welcome-file-list>\n <welcome-file>index.jsp</welcome-file>\n <welcome-file>index.html</welcome-file>\n </welcome-file-list>\n\n</web-app>\n\n\n#Calculator.xhtml\n\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\"\n xmlns:f=\"http://java.sun.com/jsf/core\"\n xmlns:h=\"http://java.sun.com/jsf/html\">\n\n\n<h:body bgcolor=\"white\">\n <f:view>\n <h:form>\n <h:panelGrid columns=\"2\">\n <h:outputText value='Enter first number'/>\n <h:inputText value='#{calculatorBean.x}'/>\n <h:outputText value='Enter second number'/>\n <h:inputText value='#{calculatorBean.y}'/>\n <h:commandButton action=\"#{calculatorBean.add}\" value=\"Add\"/>\n </h:panelGrid>\n </h:form>\n </f:view>\n</h:body>\n</html>\n\n\n #Result.xhtml\n\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\"\n xmlns:f=\"http://java.sun.com/jsf/core\"\n xmlns:h=\"http://java.sun.com/jsf/html\">\n\n<h:body>\n<f:view>\n <h:form id=\"mainForm\">\n <h2><h:outputText value=\"Result of adding #{calculatorBean.x} and #{calculatorBean.y} is #{calculatorBean.result }\"/></h2>\n <h:commandLink action=\"back\">\n <h:outputText value=\"Home\"/>\n </h:commandLink>\n </h:form>\n</f:view>\n</h:body>\n</html>\n\n #faces-config.xml\n\n <?xml version=\"1.0\"?>\n <faces-config xmlns=\"http://java.sun.com/xml/ns/javaee\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee\n http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd\"\n version=\"2.0\">\n\n <navigation-rule>\n <from-view-id>/calculator.xhtml</from-view-id>\n <navigation-case>\n <from-outcome>success</from-outcome>\n <to-view-id>/result.xhtml</to-view-id>\n </navigation-case>\n </navigation-rule>\n\n <navigation-rule>\n <from-view-id>/result.xhtml</from-view-id>\n <navigation-case>\n <from-outcome>back</from-outcome>\n <to-view-id>/calculator.xhtml</to-view-id>\n </navigation-case>\n </navigation-rule>\n </faces-config>",
"url":"https://github.com/apache/tomee/tree/master/examples/jsf-cdi-and-ejb"
}
],
"json":[
{
"name":"rest-xml-json",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/rest-xml-json"
}
],
"lookup":[
{
"name":"lookup-of-ejbs",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/lookup-of-ejbs"
},
{
"name":"client-resource-lookup-preview",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/client-resource-lookup-preview"
},
{
"name":"lookup-of-ejbs-with-descriptor",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/lookup-of-ejbs-with-descriptor"
}
],
"managedBean":[
{
"name":"jsf-managedBean-and-ejb",
"readme":"Title: JSF Application that uses managed-bean and ejb\n\nThis is a simple web-app showing how to use dependency injection in JSF managed beans using TomEE.\n\nIt contains a Local Stateless session bean `CalculatorImpl` which adds two numbers and returns the result.\nThe application also contains a JSF managed bean `CalculatorBean`, which uses the EJB to add two numbers\nand display the results to the user. The EJB is injected in the managed bean using `@EJB` annotation.\n\n\n## A little note on the setup:\n\nYou could run this in the latest Apache TomEE [snapshot](https://repository.apache.org/content/repositories/snapshots/org/apache/openejb/apache-tomee/)\n\nAs for the libraries, myfaces-api and myfaces-impl are provided in tomee/lib and hence they should not be a part of the\nwar. In maven terms, they would be with scope 'provided'\n\nAlso note that we use servlet 2.5 declaration in web.xml\n \n <web-app xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns=\"http://java.sun.com/xml/ns/javaee\"\n xmlns:web=\"http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee\n http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n version=\"2.5\">\n\nAnd we use 2.0 version of faces-config\n\n <faces-config xmlns=\"http://java.sun.com/xml/ns/javaee\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee\n http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd\"\n version=\"2.0\">\n\n\nThe complete source code is provided below but let's break down to look at some smaller snippets and see how it works.\n\nWe'll first declare the `FacesServlet` in the `web.xml`\n\n <servlet>\n <servlet-name>Faces Servlet</servlet-name>\n <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>\n <load-on-startup>1</load-on-startup>\n </servlet>\n\n`FacesServlet` acts as the master controller.\n\nWe'll then create the `calculator.xhtml` file.\n\n <h:outputText value='Enter first number'/>\n <h:inputText value='#{calculatorBean.x}'/>\n <h:outputText value='Enter second number'/>\n <h:inputText value='#{calculatorBean.y}'/>\n <h:commandButton action=\"#{calculatorBean.add}\" value=\"Add\"/>\n\n\nNotice how we've use the bean here.\nBy default it is the simple class name of the managed bean.\n\nWhen a request comes in, the bean is instantiated and placed in the appropriate scope.\nBy default, the bean is placed in the request scope.\n\n <h:inputText value='#{calculatorBean.x}'/>\n\nHere, getX() method of calculatorBean is invoked and the resulting value is displayed.\nx being a Double, we rightly should see 0.0 displayed.\n\nWhen you change the value and submit the form, these entered values are bound using the setters\nin the bean and then the commandButton-action method is invoked.\n\nIn this case, `CalculatorBean#add()` is invoked.\n\n`Calculator#add()` delegates the work to the ejb, gets the result, stores it\nand then instructs what view is to be rendered.\n\nYou're right. The return value \"success\" is checked up in faces-config navigation-rules\nand the respective page is rendered.\n\nIn our case, `result.xhtml` page is rendered.\n\nThe request scoped `calculatorBean` is available here, and we use EL to display the values.\n\n## Source\n\n## Calculator\n\n package org.superbiz.jsf;\n \n import javax.ejb.Local;\n \n @Local\n public interface Calculator {\n public double add(double x, double y);\n }\n\n\n## CalculatorBean\n\n package org.superbiz.jsf;\n \n import javax.ejb.EJB;\n import javax.faces.bean.ManagedBean;\n\n @ManagedBean\n public class CalculatorBean {\n @EJB\n Calculator calculator;\n private double x;\n private double y;\n private double result;\n \n public double getX() {\n return x;\n }\n \n public void setX(double x) {\n this.x = x;\n }\n \n public double getY() {\n return y;\n }\n \n public void setY(double y) {\n this.y = y;\n }\n \n public double getResult() {\n return result;\n }\n \n public void setResult(double result) {\n this.result = result;\n }\n \n public String add() {\n result = calculator.add(x, y);\n return \"success\";\n }\n }\n\n## CalculatorImpl\n\n package org.superbiz.jsf;\n \n import javax.ejb.Stateless;\n \n @Stateless\n public class CalculatorImpl implements Calculator {\n \n public double add(double x, double y) {\n return x + y;\n }\n }\n\n\n# web.xml\n\n <?xml version=\"1.0\"?>\n\n <web-app xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns=\"http://java.sun.com/xml/ns/javaee\"\n xmlns:web=\"http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee\n http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n version=\"2.5\">\n\n <description>MyProject web.xml</description>\n\n <!-- Faces Servlet -->\n <servlet>\n <servlet-name>Faces Servlet</servlet-name>\n <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>\n <load-on-startup>1</load-on-startup>\n </servlet>\n\n <!-- Faces Servlet Mapping -->\n <servlet-mapping>\n <servlet-name>Faces Servlet</servlet-name>\n <url-pattern>*.jsf</url-pattern>\n </servlet-mapping>\n\n <!-- Welcome files -->\n <welcome-file-list>\n <welcome-file>index.jsp</welcome-file>\n <welcome-file>index.html</welcome-file>\n </welcome-file-list>\n </web-app>\n\n \n##Calculator.xhtml\n\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n <html xmlns=\"http://www.w3.org/1999/xhtml\"\n xmlns:f=\"http://java.sun.com/jsf/core\"\n xmlns:h=\"http://java.sun.com/jsf/html\">\n\n\n <h:body bgcolor=\"white\">\n <f:view>\n <h:form>\n <h:panelGrid columns=\"2\">\n <h:outputText value='Enter first number'/>\n <h:inputText value='#{calculatorBean.x}'/>\n <h:outputText value='Enter second number'/>\n <h:inputText value='#{calculatorBean.y}'/>\n <h:commandButton action=\"#{calculatorBean.add}\" value=\"Add\"/>\n </h:panelGrid>\n </h:form>\n </f:view>\n </h:body>\n </html>\n\n \n##Result.xhtml\n\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n <html xmlns=\"http://www.w3.org/1999/xhtml\"\n xmlns:f=\"http://java.sun.com/jsf/core\"\n xmlns:h=\"http://java.sun.com/jsf/html\">\n\n <h:body>\n <f:view>\n <h:form id=\"mainForm\">\n <h2><h:outputText value=\"Result of adding #{calculatorBean.x} and #{calculatorBean.y} is #{calculatorBean.result }\"/></h2>\n <h:commandLink action=\"back\">\n <h:outputText value=\"Home\"/>\n </h:commandLink>\n </h:form>\n </f:view>\n </h:body>\n </html>\n \n#faces-config.xml\n\n <?xml version=\"1.0\"?>\n <faces-config xmlns=\"http://java.sun.com/xml/ns/javaee\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee\n http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd\"\n version=\"2.0\">\n\n <navigation-rule>\n <from-view-id>/calculator.xhtml</from-view-id>\n <navigation-case>\n <from-outcome>success</from-outcome>\n <to-view-id>/result.xhtml</to-view-id>\n </navigation-case>\n </navigation-rule>\n\n <navigation-rule>\n <from-view-id>/result.xhtml</from-view-id>\n <navigation-case>\n <from-outcome>back</from-outcome>\n <to-view-id>/calculator.xhtml</to-view-id>\n </navigation-case>\n </navigation-rule>\n </faces-config>\n",
"url":"https://github.com/apache/tomee/tree/master/examples/jsf-managedBean-and-ejb"
}
],
"mbean":[
{
"name":"dynamic-proxy-to-access-mbean",
"readme":"Title: dynamic-proxy-to-access-mbean\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## Example\n\nAcessing MBean is something simple through the JMX API but it is often technical and not very interesting.\n\nThis example simplify this work simply doing it generically in a proxy.\n\nSo from an user side you simple declare an interface to access your MBeans.\n\nNote: the example implementation uses a local MBeanServer but enhancing the example API\nit is easy to imagine a remote connection with user/password if needed.\n\n## ObjectName API (annotation)\n\nSimply an annotation to get the object\n\n package org.superbiz.dynamic.mbean;\n\n import java.lang.annotation.Retention;\n import java.lang.annotation.Target;\n\n import static java.lang.annotation.ElementType.TYPE;\n import static java.lang.annotation.ElementType.METHOD;\n import static java.lang.annotation.RetentionPolicy.RUNTIME;\n\n @Target({TYPE, METHOD})\n @Retention(RUNTIME)\n public @interface ObjectName {\n String value();\n\n // for remote usage only\n String url() default \"\";\n String user() default \"\";\n String password() default \"\";\n }\n\n## DynamicMBeanHandler (thr proxy implementation)\n\n package org.superbiz.dynamic.mbean;\n\n import javax.annotation.PreDestroy;\n import javax.management.Attribute;\n import javax.management.MBeanAttributeInfo;\n import javax.management.MBeanInfo;\n import javax.management.MBeanServer;\n import javax.management.MBeanServerConnection;\n import javax.management.ObjectName;\n import javax.management.remote.JMXConnector;\n import javax.management.remote.JMXConnectorFactory;\n import javax.management.remote.JMXServiceURL;\n import java.io.IOException;\n import java.lang.management.ManagementFactory;\n import java.lang.reflect.InvocationHandler;\n import java.lang.reflect.Method;\n import java.util.HashMap;\n import java.util.Map;\n import java.util.concurrent.ConcurrentHashMap;\n\n /**\n * Need a @PreDestroy method to disconnect the remote host when used in remote mode.\n */\n public class DynamicMBeanHandler implements InvocationHandler {\n private final Map<Method, ConnectionInfo> infos = new ConcurrentHashMap<Method, ConnectionInfo>();\n\n @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {\n final String methodName = method.getName();\n if (method.getDeclaringClass().equals(Object.class) && \"toString\".equals(methodName)) {\n return getClass().getSimpleName() + \" Proxy\";\n }\n if (method.getAnnotation(PreDestroy.class) != null) {\n return destroy();\n }\n\n final ConnectionInfo info = getConnectionInfo(method);\n final MBeanInfo infos = info.getMBeanInfo();\n if (methodName.startsWith(\"set\") && methodName.length() > 3 && args != null && args.length == 1\n && (Void.TYPE.equals(method.getReturnType()) || Void.class.equals(method.getReturnType()))) {\n final String attributeName = attributeName(infos, methodName, method.getParameterTypes()[0]);\n info.setAttribute(new Attribute(attributeName, args[0]));\n return null;\n } else if (methodName.startsWith(\"get\") && (args == null || args.length == 0) && methodName.length() > 3) {\n final String attributeName = attributeName(infos, methodName, method.getReturnType());\n return info.getAttribute(attributeName);\n }\n // operation\n return info.invoke(methodName, args, getSignature(method));\n }\n\n public Object destroy() {\n for (ConnectionInfo info : infos.values()) {\n info.clean();\n }\n infos.clear();\n return null;\n }\n\n private String[] getSignature(Method method) {\n String[] args = new String[method.getParameterTypes().length];\n for (int i = 0; i < method.getParameterTypes().length; i++) {\n args[i] = method.getParameterTypes()[i].getName();\n }\n return args; // note: null should often work...\n }\n\n private String attributeName(MBeanInfo infos, String methodName, Class<?> type) {\n String found = null;\n String foundBackUp = null; // without checking the type\n final String attributeName = methodName.substring(3, methodName.length());\n final String lowerName = Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4, methodName.length());\n\n for (MBeanAttributeInfo attribute : infos.getAttributes()) {\n final String name = attribute.getName();\n if (attributeName.equals(name)) {\n foundBackUp = attributeName;\n if (attribute.getType().equals(type.getName())) {\n found = name;\n }\n } else if (found == null && ((lowerName.equals(name) && !attributeName.equals(name))\n || lowerName.equalsIgnoreCase(name))) {\n foundBackUp = name;\n if (attribute.getType().equals(type.getName())) {\n found = name;\n }\n }\n }\n\n if (found == null && foundBackUp == null) {\n throw new UnsupportedOperationException(\"cannot find attribute \" + attributeName);\n }\n\n if (found != null) {\n return found;\n }\n return foundBackUp;\n }\n\n private synchronized ConnectionInfo getConnectionInfo(Method method) throws Exception {\n if (!infos.containsKey(method)) {\n synchronized (infos) {\n if (!infos.containsKey(method)) { // double check for synchro\n org.superbiz.dynamic.mbean.ObjectName on = method.getAnnotation(org.superbiz.dynamic.mbean.ObjectName.class);\n if (on == null) {\n Class<?> current = method.getDeclaringClass();\n do {\n on = method.getDeclaringClass().getAnnotation(org.superbiz.dynamic.mbean.ObjectName.class);\n current = current.getSuperclass();\n } while (on == null && current != null);\n if (on == null) {\n throw new UnsupportedOperationException(\"class or method should define the objectName to use for invocation: \" + method.toGenericString());\n }\n }\n final ConnectionInfo info;\n if (on.url().isEmpty()) {\n info = new LocalConnectionInfo();\n ((LocalConnectionInfo) info).server = ManagementFactory.getPlatformMBeanServer(); // could use an id...\n } else {\n info = new RemoteConnectionInfo();\n final Map<String, String[]> environment = new HashMap<String, String[]>();\n if (!on.user().isEmpty()) {\n environment.put(JMXConnector.CREDENTIALS, new String[]{ on.user(), on.password() });\n }\n // ((RemoteConnectionInfo) info).connector = JMXConnectorFactory.newJMXConnector(new JMXServiceURL(on.url()), environment);\n ((RemoteConnectionInfo) info).connector = JMXConnectorFactory.connect(new JMXServiceURL(on.url()), environment);\n\n }\n info.objectName = new ObjectName(on.value());\n\n infos.put(method, info);\n }\n }\n }\n return infos.get(method);\n }\n\n private abstract static class ConnectionInfo {\n protected ObjectName objectName;\n\n public abstract void setAttribute(Attribute attribute) throws Exception;\n public abstract Object getAttribute(String attribute) throws Exception;\n public abstract Object invoke(String operationName, Object params[], String signature[]) throws Exception;\n public abstract MBeanInfo getMBeanInfo() throws Exception;\n public abstract void clean();\n }\n\n private static class LocalConnectionInfo extends ConnectionInfo {\n private MBeanServer server;\n\n @Override public void setAttribute(Attribute attribute) throws Exception {\n server.setAttribute(objectName, attribute);\n }\n\n @Override public Object getAttribute(String attribute) throws Exception {\n return server.getAttribute(objectName, attribute);\n }\n\n @Override\n public Object invoke(String operationName, Object[] params, String[] signature) throws Exception {\n return server.invoke(objectName, operationName, params, signature);\n }\n\n @Override public MBeanInfo getMBeanInfo() throws Exception {\n return server.getMBeanInfo(objectName);\n }\n\n @Override public void clean() {\n // no-op\n }\n }\n\n private static class RemoteConnectionInfo extends ConnectionInfo {\n private JMXConnector connector;\n private MBeanServerConnection connection;\n\n private void before() throws IOException {\n connection = connector.getMBeanServerConnection();\n }\n\n private void after() throws IOException {\n // no-op\n }\n\n @Override public void setAttribute(Attribute attribute) throws Exception {\n before();\n connection.setAttribute(objectName, attribute);\n after();\n }\n\n @Override public Object getAttribute(String attribute) throws Exception {\n before();\n try {\n return connection.getAttribute(objectName, attribute);\n } finally {\n after();\n }\n }\n\n @Override\n public Object invoke(String operationName, Object[] params, String[] signature) throws Exception {\n before();\n try {\n return connection.invoke(objectName, operationName, params, signature);\n } finally {\n after();\n }\n }\n\n @Override public MBeanInfo getMBeanInfo() throws Exception {\n before();\n try {\n return connection.getMBeanInfo(objectName);\n } finally {\n after();\n }\n }\n\n @Override public void clean() {\n try {\n connector.close();\n } catch (IOException e) {\n // no-op\n }\n }\n }\n }\n\n## Dynamic Proxies \n\n### DynamicMBeanClient (the dynamic JMX client)\n\n\tpackage org.superbiz.dynamic.mbean;\n\n\timport org.apache.openejb.api.Proxy;\n\timport org.superbiz.dynamic.mbean.DynamicMBeanHandler;\n\timport org.superbiz.dynamic.mbean.ObjectName;\n\n\timport javax.ejb.Singleton;\n\n\t/**\n\t * @author rmannibucau\n\t */\n\t@Singleton\n\t@Proxy(DynamicMBeanHandler.class)\n\t@ObjectName(DynamicMBeanClient.OBJECT_NAME)\n\tpublic interface DynamicMBeanClient {\n\t\tstatic final String OBJECT_NAME = \"test:group=DynamicMBeanClientTest\";\n\n\t\tint getCounter();\n\t\tvoid setCounter(int i);\n\t\tint length(String aString);\n\t}\n\n### DynamicMBeanClient (the dynamic JMX client)\n package org.superbiz.dynamic.mbean;\n\n import org.apache.openejb.api.Proxy;\n\n import javax.annotation.PreDestroy;\n import javax.ejb.Singleton;\n\n\n @Singleton\n @Proxy(DynamicMBeanHandler.class)\n @ObjectName(value = DynamicRemoteMBeanClient.OBJECT_NAME, url = \"service:jmx:rmi:///jndi/rmi://localhost:8243/jmxrmi\")\n public interface DynamicRemoteMBeanClient {\n static final String OBJECT_NAME = \"test:group=DynamicMBeanClientTest\";\n\n int getCounter();\n void setCounter(int i);\n int length(String aString);\n\n @PreDestroy void clean();\n }\n\n## The MBean used for the test\n\n### SimpleMBean\n\n\tpackage org.superbiz.dynamic.mbean.simple;\n\n\tpublic interface SimpleMBean {\n\t\tint length(String s);\n\n\t\tint getCounter();\n\t\tvoid setCounter(int c);\n\t}\n\n## Simple\n\n\tpackage org.superbiz.dynamic.mbean.simple;\n\n\tpublic class Simple implements SimpleMBean {\n\t\tprivate int counter = 0;\n\n\t\t@Override public int length(String s) {\n\t\t if (s == null) {\n\t\t return 0;\n\t\t }\n\t\t return s.length();\n\t\t}\n\n\t\t@Override public int getCounter() {\n\t\t return counter;\n\t\t}\n\n\t\t@Override public void setCounter(int c) {\n\t\t counter = c;\n\t\t}\n\t}\n\n## DynamicMBeanClientTest (The test)\n\n package org.superbiz.dynamic.mbean;\n\n import org.junit.After;\n import org.junit.AfterClass;\n import org.junit.Before;\n import org.junit.BeforeClass;\n import org.junit.Test;\n import org.superbiz.dynamic.mbean.simple.Simple;\n\n import javax.ejb.EJB;\n import javax.ejb.embeddable.EJBContainer;\n import javax.management.Attribute;\n import javax.management.ObjectName;\n import java.lang.management.ManagementFactory;\n\n import static junit.framework.Assert.assertEquals;\n\n public class DynamicMBeanClientTest {\n private static ObjectName objectName;\n private static EJBContainer container;\n\n @EJB private DynamicMBeanClient localClient;\n @EJB private DynamicRemoteMBeanClient remoteClient;\n\n @BeforeClass public static void start() {\n container = EJBContainer.createEJBContainer();\n }\n\n @Before public void injectAndRegisterMBean() throws Exception {\n container.getContext().bind(\"inject\", this);\n objectName = new ObjectName(DynamicMBeanClient.OBJECT_NAME);\n ManagementFactory.getPlatformMBeanServer().registerMBean(new Simple(), objectName);\n }\n\n @After public void unregisterMBean() throws Exception {\n if (objectName != null) {\n ManagementFactory.getPlatformMBeanServer().unregisterMBean(objectName);\n }\n }\n\n @Test public void localGet() throws Exception {\n assertEquals(0, localClient.getCounter());\n ManagementFactory.getPlatformMBeanServer().setAttribute(objectName, new Attribute(\"Counter\", 5));\n assertEquals(5, localClient.getCounter());\n }\n\n @Test public void localSet() throws Exception {\n assertEquals(0, ((Integer) ManagementFactory.getPlatformMBeanServer().getAttribute(objectName, \"Counter\")).intValue());\n localClient.setCounter(8);\n assertEquals(8, ((Integer) ManagementFactory.getPlatformMBeanServer().getAttribute(objectName, \"Counter\")).intValue());\n }\n\n @Test public void localOperation() {\n assertEquals(7, localClient.length(\"openejb\"));\n }\n\n @Test public void remoteGet() throws Exception {\n assertEquals(0, remoteClient.getCounter());\n ManagementFactory.getPlatformMBeanServer().setAttribute(objectName, new Attribute(\"Counter\", 5));\n assertEquals(5, remoteClient.getCounter());\n }\n\n @Test public void remoteSet() throws Exception {\n assertEquals(0, ((Integer) ManagementFactory.getPlatformMBeanServer().getAttribute(objectName, \"Counter\")).intValue());\n remoteClient.setCounter(8);\n assertEquals(8, ((Integer) ManagementFactory.getPlatformMBeanServer().getAttribute(objectName, \"Counter\")).intValue());\n }\n\n @Test public void remoteOperation() {\n assertEquals(7, remoteClient.length(\"openejb\"));\n }\n\n @AfterClass public static void close() {\n if (container != null) {\n container.close();\n }\n }\n }\n\n",
"url":"https://github.com/apache/tomee/tree/master/examples/dynamic-proxy-to-access-mbean"
},
{
"name":"mbean-auto-registration",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/mbean-auto-registration"
}
],
"mdb":[
{
"name":"simple-mdb-and-cdi",
"readme":"Title: Simple MDB and CDI\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## ChatBean\n\n package org.superbiz.mdb;\n \n import javax.annotation.Resource;\n import javax.ejb.MessageDriven;\n import javax.inject.Inject;\n import javax.jms.Connection;\n import javax.jms.ConnectionFactory;\n import javax.jms.DeliveryMode;\n import javax.jms.JMSException;\n import javax.jms.Message;\n import javax.jms.MessageListener;\n import javax.jms.MessageProducer;\n import javax.jms.Queue;\n import javax.jms.Session;\n import javax.jms.TextMessage;\n \n @MessageDriven\n public class ChatBean implements MessageListener {\n \n @Resource\n private ConnectionFactory connectionFactory;\n \n @Resource(name = \"AnswerQueue\")\n private Queue answerQueue;\n \n @Inject\n private ChatRespondCreator responder;\n \n public void onMessage(Message message) {\n try {\n \n final TextMessage textMessage = (TextMessage) message;\n final String question = textMessage.getText();\n final String response = responder.respond(question);\n \n if (response != null) {\n respond(response);\n }\n } catch (JMSException e) {\n throw new IllegalStateException(e);\n }\n }\n \n private void respond(String text) throws JMSException {\n \n Connection connection = null;\n Session session = null;\n \n try {\n connection = connectionFactory.createConnection();\n connection.start();\n \n // Create a Session\n session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);\n \n // Create a MessageProducer from the Session to the Topic or Queue\n MessageProducer producer = session.createProducer(answerQueue);\n producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);\n \n // Create a message\n TextMessage message = session.createTextMessage(text);\n \n // Tell the producer to send the message\n producer.send(message);\n } finally {\n // Clean up\n if (session != null) session.close();\n if (connection != null) connection.close();\n }\n }\n }\n\n## ChatRespondCreator\n\n package org.superbiz.mdb;\n \n public class ChatRespondCreator {\n public String respond(String question) {\n if (\"Hello World!\".equals(question)) {\n return \"Hello, Test Case!\";\n } else if (\"How are you?\".equals(question)) {\n return \"I'm doing well.\";\n } else if (\"Still spinning?\".equals(question)) {\n return \"Once every day, as usual.\";\n }\n return null;\n }\n }\n\n## beans.xml\n\n <!--\n \n Licensed to the Apache Software Foundation (ASF) under one or more\n contributor license agreements. See the NOTICE file distributed with\n this work for additional information regarding copyright ownership.\n The ASF licenses this file to You under the Apache License, Version 2.0\n (the \"License\"); you may not use this file except in compliance with\n the License. You may obtain a copy of the License at\n \n http://www.apache.org/licenses/LICENSE-2.0\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n -->\n \n <beans/>\n \n\n## ChatBeanTest\n\n package org.superbiz.mdb;\n \n import junit.framework.TestCase;\n \n import javax.annotation.Resource;\n import javax.ejb.embeddable.EJBContainer;\n import javax.jms.Connection;\n import javax.jms.ConnectionFactory;\n import javax.jms.JMSException;\n import javax.jms.MessageConsumer;\n import javax.jms.MessageProducer;\n import javax.jms.Queue;\n import javax.jms.Session;\n import javax.jms.TextMessage;\n \n public class ChatBeanTest extends TestCase {\n \n @Resource\n private ConnectionFactory connectionFactory;\n \n @Resource(name = \"ChatBean\")\n private Queue questionQueue;\n \n @Resource(name = \"AnswerQueue\")\n private Queue answerQueue;\n \n public void test() throws Exception {\n EJBContainer.createEJBContainer().getContext().bind(\"inject\", this);\n \n \n final Connection connection = connectionFactory.createConnection();\n \n connection.start();\n \n final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);\n \n final MessageProducer questions = session.createProducer(questionQueue);\n \n final MessageConsumer answers = session.createConsumer(answerQueue);\n \n \n sendText(\"Hello World!\", questions, session);\n \n assertEquals(\"Hello, Test Case!\", receiveText(answers));\n \n \n sendText(\"How are you?\", questions, session);\n \n assertEquals(\"I'm doing well.\", receiveText(answers));\n \n \n sendText(\"Still spinning?\", questions, session);\n \n assertEquals(\"Once every day, as usual.\", receiveText(answers));\n }\n \n private void sendText(String text, MessageProducer questions, Session session) throws JMSException {\n \n questions.send(session.createTextMessage(text));\n }\n \n private String receiveText(MessageConsumer answers) throws JMSException {\n \n return ((TextMessage) answers.receive(1000)).getText();\n }\n }\n",
"url":"https://github.com/apache/tomee/tree/master/examples/simple-mdb-and-cdi"
},
{
"name":"simple-mdb",
"readme":"Title: Simple MDB\n\nBelow is a fun app, a chat application that uses JMS. We create a message driven bean, by marking our class with `@MessageDriven`. A message driven bean has some similarities with a stateless session bean, in the part that it is pooled too.\n\nWell, lets tell our chat-app to listen for incoming messages. That we do by implementing `MessageListener` and overriding the `onMessage(Message message)`.\n\nThen this app \"listens\" for incoming messages, and the messages picked up are processed by `onMessage(Message message)` method.\n\nThat finishes our message driven bean implementation. The \"processing\" part could be anything that fits your business-requirement.\n\nIn this case, it is to respond to the user. The `respond` method shows how a Message can be sent.\n\nThis sequence diagram shows how a message is sent.\n\n<img src=\"../../resources/mdb-flow.png\" alt=\"\"/>\n\n## ChatBean\n\n package org.superbiz.mdb;\n \n import javax.annotation.Resource;\n import javax.ejb.MessageDriven;\n import javax.jms.Connection;\n import javax.jms.ConnectionFactory;\n import javax.jms.DeliveryMode;\n import javax.jms.JMSException;\n import javax.jms.Message;\n import javax.jms.MessageListener;\n import javax.jms.MessageProducer;\n import javax.jms.Queue;\n import javax.jms.Session;\n import javax.jms.TextMessage;\n \n @MessageDriven\n public class ChatBean implements MessageListener {\n \n @Resource\n private ConnectionFactory connectionFactory;\n \n @Resource(name = \"AnswerQueue\")\n private Queue answerQueue;\n \n public void onMessage(Message message) {\n try {\n \n final TextMessage textMessage = (TextMessage) message;\n final String question = textMessage.getText();\n \n if (\"Hello World!\".equals(question)) {\n \n respond(\"Hello, Test Case!\");\n } else if (\"How are you?\".equals(question)) {\n \n respond(\"I'm doing well.\");\n } else if (\"Still spinning?\".equals(question)) {\n \n respond(\"Once every day, as usual.\");\n }\n } catch (JMSException e) {\n throw new IllegalStateException(e);\n }\n }\n \n private void respond(String text) throws JMSException {\n \n Connection connection = null;\n Session session = null;\n \n try {\n connection = connectionFactory.createConnection();\n connection.start();\n \n // Create a Session\n session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);\n \n // Create a MessageProducer from the Session to the Topic or Queue\n MessageProducer producer = session.createProducer(answerQueue);\n producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);\n \n // Create a message\n TextMessage message = session.createTextMessage(text);\n \n // Tell the producer to send the message\n producer.send(message);\n } finally {\n // Clean up\n if (session != null) session.close();\n if (connection != null) connection.close();\n }\n }\n }\n\n## ChatBeanTest\n\n package org.superbiz.mdb;\n \n import junit.framework.TestCase;\n \n import javax.annotation.Resource;\n import javax.ejb.embeddable.EJBContainer;\n import javax.jms.Connection;\n import javax.jms.ConnectionFactory;\n import javax.jms.JMSException;\n import javax.jms.MessageConsumer;\n import javax.jms.MessageProducer;\n import javax.jms.Queue;\n import javax.jms.Session;\n import javax.jms.TextMessage;\n \n public class ChatBeanTest extends TestCase {\n \n @Resource\n private ConnectionFactory connectionFactory;\n \n @Resource(name = \"ChatBean\")\n private Queue questionQueue;\n \n @Resource(name = \"AnswerQueue\")\n private Queue answerQueue;\n \n public void test() throws Exception {\n EJBContainer.createEJBContainer().getContext().bind(\"inject\", this);\n \n \n final Connection connection = connectionFactory.createConnection();\n \n connection.start();\n \n final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);\n \n final MessageProducer questions = session.createProducer(questionQueue);\n \n final MessageConsumer answers = session.createConsumer(answerQueue);\n \n \n sendText(\"Hello World!\", questions, session);\n \n assertEquals(\"Hello, Test Case!\", receiveText(answers));\n \n \n sendText(\"How are you?\", questions, session);\n \n assertEquals(\"I'm doing well.\", receiveText(answers));\n \n \n sendText(\"Still spinning?\", questions, session);\n \n assertEquals(\"Once every day, as usual.\", receiveText(answers));\n }\n \n private void sendText(String text, MessageProducer questions, Session session) throws JMSException {\n \n questions.send(session.createTextMessage(text));\n }\n \n private String receiveText(MessageConsumer answers) throws JMSException {\n \n return ((TextMessage) answers.receive(1000)).getText();\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.mdb.ChatBeanTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/simple-mdb\n INFO - openejb.base = /Users/dblevins/examples/simple-mdb\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/simple-mdb/target/classes\n INFO - Beginning load: /Users/dblevins/examples/simple-mdb/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/simple-mdb\n WARN - Method 'lookup' is not available for 'javax.annotation.Resource'. Probably using an older Runtime.\n INFO - Auto-configuring a message driven bean ChatBean destination ChatBean to be destinationType javax.jms.Queue\n INFO - Configuring Service(id=Default MDB Container, type=Container, provider-id=Default MDB Container)\n INFO - Auto-creating a container for bean ChatBean: Container(type=MESSAGE, id=Default MDB Container)\n INFO - Configuring Service(id=Default JMS Resource Adapter, type=Resource, provider-id=Default JMS Resource Adapter)\n INFO - Configuring Service(id=Default JMS Connection Factory, type=Resource, provider-id=Default JMS Connection Factory)\n INFO - Auto-creating a Resource with id 'Default JMS Connection Factory' of type 'javax.jms.ConnectionFactory for 'ChatBean'.\n INFO - Auto-linking resource-ref 'java:comp/env/org.superbiz.mdb.ChatBean/connectionFactory' in bean ChatBean to Resource(id=Default JMS Connection Factory)\n INFO - Configuring Service(id=AnswerQueue, type=Resource, provider-id=Default Queue)\n INFO - Auto-creating a Resource with id 'AnswerQueue' of type 'javax.jms.Queue for 'ChatBean'.\n INFO - Auto-linking resource-env-ref 'java:comp/env/AnswerQueue' in bean ChatBean to Resource(id=AnswerQueue)\n INFO - Configuring Service(id=ChatBean, type=Resource, provider-id=Default Queue)\n INFO - Auto-creating a Resource with id 'ChatBean' of type 'javax.jms.Queue for 'ChatBean'.\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.mdb.ChatBeanTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Auto-linking resource-ref 'java:comp/env/org.superbiz.mdb.ChatBeanTest/connectionFactory' in bean org.superbiz.mdb.ChatBeanTest to Resource(id=Default JMS Connection Factory)\n INFO - Auto-linking resource-env-ref 'java:comp/env/AnswerQueue' in bean org.superbiz.mdb.ChatBeanTest to Resource(id=AnswerQueue)\n INFO - Auto-linking resource-env-ref 'java:comp/env/ChatBean' in bean org.superbiz.mdb.ChatBeanTest to Resource(id=ChatBean)\n INFO - Enterprise application \"/Users/dblevins/examples/simple-mdb\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/simple-mdb\n INFO - Jndi(name=\"java:global/EjbModule1515710343/org.superbiz.mdb.ChatBeanTest!org.superbiz.mdb.ChatBeanTest\")\n INFO - Jndi(name=\"java:global/EjbModule1515710343/org.superbiz.mdb.ChatBeanTest\")\n INFO - Created Ejb(deployment-id=org.superbiz.mdb.ChatBeanTest, ejb-name=org.superbiz.mdb.ChatBeanTest, container=Default Managed Container)\n INFO - Created Ejb(deployment-id=ChatBean, ejb-name=ChatBean, container=Default MDB Container)\n INFO - Started Ejb(deployment-id=org.superbiz.mdb.ChatBeanTest, ejb-name=org.superbiz.mdb.ChatBeanTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=ChatBean, ejb-name=ChatBean, container=Default MDB Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/simple-mdb)\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.547 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/simple-mdb"
},
{
"name":"simple-mdb-with-descriptor",
"readme":"Title: Simple MDB with Descriptor\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## ChatBean\n\n package org.superbiz.mdbdesc;\n \n import javax.jms.Connection;\n import javax.jms.ConnectionFactory;\n import javax.jms.DeliveryMode;\n import javax.jms.JMSException;\n import javax.jms.Message;\n import javax.jms.MessageListener;\n import javax.jms.MessageProducer;\n import javax.jms.Queue;\n import javax.jms.Session;\n import javax.jms.TextMessage;\n \n public class ChatBean implements MessageListener {\n \n private ConnectionFactory connectionFactory;\n \n private Queue answerQueue;\n \n public void onMessage(Message message) {\n try {\n \n final TextMessage textMessage = (TextMessage) message;\n final String question = textMessage.getText();\n \n if (\"Hello World!\".equals(question)) {\n \n respond(\"Hello, Test Case!\");\n } else if (\"How are you?\".equals(question)) {\n \n respond(\"I'm doing well.\");\n } else if (\"Still spinning?\".equals(question)) {\n \n respond(\"Once every day, as usual.\");\n }\n } catch (JMSException e) {\n throw new IllegalStateException(e);\n }\n }\n \n private void respond(String text) throws JMSException {\n \n Connection connection = null;\n Session session = null;\n \n try {\n connection = connectionFactory.createConnection();\n connection.start();\n \n // Create a Session\n session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);\n \n // Create a MessageProducer from the Session to the Topic or Queue\n MessageProducer producer = session.createProducer(answerQueue);\n producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);\n \n // Create a message\n TextMessage message = session.createTextMessage(text);\n \n // Tell the producer to send the message\n producer.send(message);\n } finally {\n // Clean up\n if (session != null) session.close();\n if (connection != null) connection.close();\n }\n }\n }\n\n## ejb-jar.xml\n\n <ejb-jar xmlns=\"http://java.sun.com/xml/ns/javaee\" metadata-complete=\"true\">\n <enterprise-beans>\n \n <message-driven>\n \n <ejb-name>ChatBean</ejb-name>\n <ejb-class>org.superbiz.mdbdesc.ChatBean</ejb-class>\n \n <messaging-type>javax.jms.MessageListener</messaging-type>\n \n <activation-config>\n <activation-config-property>\n <activation-config-property-name>destination</activation-config-property-name>\n <activation-config-property-value>ChatBean</activation-config-property-value>\n </activation-config-property>\n <activation-config-property>\n <activation-config-property-name>destinationType</activation-config-property-name>\n <activation-config-property-value>javax.jms.Queue</activation-config-property-value>\n </activation-config-property>\n </activation-config>\n \n <resource-ref>\n <res-ref-name>java:comp/env/org.superbiz.mdbdesc.ChatBean/connectionFactory</res-ref-name>\n <res-type>javax.jms.ConnectionFactory</res-type>\n <injection-target>\n <injection-target-class>org.superbiz.mdbdesc.ChatBean</injection-target-class>\n <injection-target-name>connectionFactory</injection-target-name>\n </injection-target>\n </resource-ref>\n \n <resource-env-ref>\n <resource-env-ref-name>java:comp/env/AnswerQueue</resource-env-ref-name>\n <resource-env-ref-type>javax.jms.Queue</resource-env-ref-type>\n <mapped-name>AnswerQueue</mapped-name>\n <injection-target>\n <injection-target-class>org.superbiz.mdbdesc.ChatBean</injection-target-class>\n <injection-target-name>answerQueue</injection-target-name>\n </injection-target>\n </resource-env-ref>\n \n </message-driven>\n \n </enterprise-beans>\n </ejb-jar>\n \n\n## ChatBeanTest\n\n package org.superbiz.mdb;\n \n import junit.framework.TestCase;\n \n import javax.annotation.Resource;\n import javax.ejb.embeddable.EJBContainer;\n import javax.jms.Connection;\n import javax.jms.ConnectionFactory;\n import javax.jms.JMSException;\n import javax.jms.MessageConsumer;\n import javax.jms.MessageProducer;\n import javax.jms.Queue;\n import javax.jms.Session;\n import javax.jms.TextMessage;\n \n public class ChatBeanTest extends TestCase {\n \n @Resource\n private ConnectionFactory connectionFactory;\n \n @Resource(name = \"ChatBean\")\n private Queue questionQueue;\n \n @Resource(name = \"AnswerQueue\")\n private Queue answerQueue;\n \n public void test() throws Exception {\n \n EJBContainer.createEJBContainer().getContext().bind(\"inject\", this);\n \n final Connection connection = connectionFactory.createConnection();\n \n connection.start();\n \n final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);\n \n final MessageProducer questions = session.createProducer(questionQueue);\n \n final MessageConsumer answers = session.createConsumer(answerQueue);\n \n \n sendText(\"Hello World!\", questions, session);\n \n assertEquals(\"Hello, Test Case!\", receiveText(answers));\n \n \n sendText(\"How are you?\", questions, session);\n \n assertEquals(\"I'm doing well.\", receiveText(answers));\n \n \n sendText(\"Still spinning?\", questions, session);\n \n assertEquals(\"Once every day, as usual.\", receiveText(answers));\n }\n \n private void sendText(String text, MessageProducer questions, Session session) throws JMSException {\n \n questions.send(session.createTextMessage(text));\n }\n \n private String receiveText(MessageConsumer answers) throws JMSException {\n \n return ((TextMessage) answers.receive(1000)).getText();\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.mdb.ChatBeanTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/simple-mdb-with-descriptor\n INFO - openejb.base = /Users/dblevins/examples/simple-mdb-with-descriptor\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/simple-mdb-with-descriptor/target/classes\n INFO - Beginning load: /Users/dblevins/examples/simple-mdb-with-descriptor/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/simple-mdb-with-descriptor\n WARN - Method 'lookup' is not available for 'javax.annotation.Resource'. Probably using an older Runtime.\n INFO - Configuring Service(id=Default MDB Container, type=Container, provider-id=Default MDB Container)\n INFO - Auto-creating a container for bean ChatBean: Container(type=MESSAGE, id=Default MDB Container)\n INFO - Configuring Service(id=Default JMS Resource Adapter, type=Resource, provider-id=Default JMS Resource Adapter)\n INFO - Configuring Service(id=Default JMS Connection Factory, type=Resource, provider-id=Default JMS Connection Factory)\n INFO - Auto-creating a Resource with id 'Default JMS Connection Factory' of type 'javax.jms.ConnectionFactory for 'ChatBean'.\n INFO - Auto-linking resource-ref 'java:comp/env/org.superbiz.mdbdesc.ChatBean/connectionFactory' in bean ChatBean to Resource(id=Default JMS Connection Factory)\n INFO - Configuring Service(id=AnswerQueue, type=Resource, provider-id=Default Queue)\n INFO - Auto-creating a Resource with id 'AnswerQueue' of type 'javax.jms.Queue for 'ChatBean'.\n INFO - Auto-linking resource-env-ref 'java:comp/env/AnswerQueue' in bean ChatBean to Resource(id=AnswerQueue)\n INFO - Configuring Service(id=ChatBean, type=Resource, provider-id=Default Queue)\n INFO - Auto-creating a Resource with id 'ChatBean' of type 'javax.jms.Queue for 'ChatBean'.\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.mdb.ChatBeanTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Auto-linking resource-ref 'java:comp/env/org.superbiz.mdb.ChatBeanTest/connectionFactory' in bean org.superbiz.mdb.ChatBeanTest to Resource(id=Default JMS Connection Factory)\n INFO - Auto-linking resource-env-ref 'java:comp/env/AnswerQueue' in bean org.superbiz.mdb.ChatBeanTest to Resource(id=AnswerQueue)\n INFO - Auto-linking resource-env-ref 'java:comp/env/ChatBean' in bean org.superbiz.mdb.ChatBeanTest to Resource(id=ChatBean)\n INFO - Enterprise application \"/Users/dblevins/examples/simple-mdb-with-descriptor\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/simple-mdb-with-descriptor\n INFO - Jndi(name=\"java:global/EjbModule1842275169/org.superbiz.mdb.ChatBeanTest!org.superbiz.mdb.ChatBeanTest\")\n INFO - Jndi(name=\"java:global/EjbModule1842275169/org.superbiz.mdb.ChatBeanTest\")\n INFO - Created Ejb(deployment-id=org.superbiz.mdb.ChatBeanTest, ejb-name=org.superbiz.mdb.ChatBeanTest, container=Default Managed Container)\n INFO - Created Ejb(deployment-id=ChatBean, ejb-name=ChatBean, container=Default MDB Container)\n INFO - Started Ejb(deployment-id=org.superbiz.mdb.ChatBeanTest, ejb-name=org.superbiz.mdb.ChatBeanTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=ChatBean, ejb-name=ChatBean, container=Default MDB Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/simple-mdb-with-descriptor)\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.914 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/simple-mdb-with-descriptor"
}
],
"meta":[
{
"name":"spring-data-proxy-meta",
"readme":"# Spring Data With Meta sample #\n\nThis example simply simplifies the usage of spring-data sample\nproviding a meta annotation @SpringRepository to do all the dynamic procy EJB job.\n\nIt replaces @Proxy and @Stateless annotations.\n\nIsn't it more comfortable?\n\nTo do it we defined a meta annotation \"Metatype\" and used it.\n\nThe proxy implementation is the same than for spring-data sample.\n",
"url":"https://github.com/apache/tomee/tree/master/examples/spring-data-proxy-meta"
},
{
"name":"testing-security-meta",
"readme":"Title: Testing Security Meta\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## AddPermission\n\n package org.superbiz.injection.secure.api;\n \n import javax.annotation.security.RolesAllowed;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n \n @Metatype\n @Target(ElementType.METHOD)\n @Retention(RetentionPolicy.RUNTIME)\n \n public @interface AddPermission {\n public static interface $ {\n \n @AddPermission\n @RolesAllowed({\"Employee\", \"Manager\"})\n public void method();\n }\n }\n\n## DeletePermission\n\n package org.superbiz.injection.secure.api;\n \n import javax.annotation.security.RolesAllowed;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n \n @Metatype\n @Target(ElementType.METHOD)\n @Retention(RetentionPolicy.RUNTIME)\n \n public @interface DeletePermission {\n public static interface $ {\n \n @DeletePermission\n @RolesAllowed(\"Manager\")\n public void method();\n }\n }\n\n## Metatype\n\n package org.superbiz.injection.secure.api;\n \n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n @Metatype\n @Target(ElementType.ANNOTATION_TYPE)\n @Retention(RetentionPolicy.RUNTIME)\n public @interface Metatype {\n }\n\n## MovieUnit\n\n package org.superbiz.injection.secure.api;\n \n import javax.persistence.PersistenceContext;\n import javax.persistence.PersistenceContextType;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n \n @Metatype\n @Target({ElementType.METHOD, ElementType.FIELD})\n @Retention(RetentionPolicy.RUNTIME)\n \n @PersistenceContext(name = \"movie-unit\", unitName = \"movie-unit\", type = PersistenceContextType.EXTENDED)\n public @interface MovieUnit {\n }\n\n## ReadPermission\n\n package org.superbiz.injection.secure.api;\n \n import javax.annotation.security.PermitAll;\n import javax.ejb.TransactionAttribute;\n import javax.ejb.TransactionAttributeType;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n \n @Metatype\n @Target(ElementType.METHOD)\n @Retention(RetentionPolicy.RUNTIME)\n \n public @interface ReadPermission {\n public static interface $ {\n \n @ReadPermission\n @PermitAll\n @TransactionAttribute(TransactionAttributeType.SUPPORTS)\n public void method();\n }\n }\n\n## RunAsEmployee\n\n package org.superbiz.injection.secure.api;\n \n import javax.annotation.security.RunAs;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n \n @Metatype\n @Target({ElementType.TYPE, ElementType.METHOD})\n @Retention(RetentionPolicy.RUNTIME)\n \n @RunAs(\"Employee\")\n public @interface RunAsEmployee {\n }\n\n## RunAsManager\n\n package org.superbiz.injection.secure.api;\n \n import javax.annotation.security.RunAs;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n \n @Metatype\n @Target({ElementType.TYPE, ElementType.METHOD})\n @Retention(RetentionPolicy.RUNTIME)\n \n @RunAs(\"Manager\")\n public @interface RunAsManager {\n }\n\n## Movie\n\n package org.superbiz.injection.secure;\n \n import javax.persistence.Entity;\n \n @Entity\n public class Movie {\n \n private String director;\n private String title;\n private int year;\n \n public Movie() {\n }\n \n public Movie(String director, String title, int year) {\n this.director = director;\n this.title = title;\n this.year = year;\n }\n \n public String getDirector() {\n return director;\n }\n \n public void setDirector(String director) {\n this.director = director;\n }\n \n public String getTitle() {\n return title;\n }\n \n public void setTitle(String title) {\n this.title = title;\n }\n \n public int getYear() {\n return year;\n }\n \n public void setYear(int year) {\n this.year = year;\n }\n \n }\n\n## Movies\n\n package org.superbiz.injection.secure;\n \n //START SNIPPET: code\n \n import org.superbiz.injection.secure.api.AddPermission;\n import org.superbiz.injection.secure.api.DeletePermission;\n import org.superbiz.injection.secure.api.MovieUnit;\n import org.superbiz.injection.secure.api.ReadPermission;\n \n import javax.ejb.Stateful;\n import javax.persistence.EntityManager;\n import javax.persistence.Query;\n import java.util.List;\n \n @Stateful\n public class Movies {\n \n @MovieUnit\n private EntityManager entityManager;\n \n @AddPermission\n public void addMovie(Movie movie) throws Exception {\n entityManager.persist(movie);\n }\n \n @DeletePermission\n public void deleteMovie(Movie movie) throws Exception {\n entityManager.remove(movie);\n }\n \n @ReadPermission\n public List<Movie> getMovies() throws Exception {\n Query query = entityManager.createQuery(\"SELECT m from Movie as m\");\n return query.getResultList();\n }\n }\n\n## persistence.xml\n\n <persistence xmlns=\"http://java.sun.com/xml/ns/persistence\" version=\"1.0\">\n \n <persistence-unit name=\"movie-unit\">\n <jta-data-source>movieDatabase</jta-data-source>\n <non-jta-data-source>movieDatabaseUnmanaged</non-jta-data-source>\n <class>org.superbiz.injection.secure.Movie</class>\n \n <properties>\n <property name=\"openjpa.jdbc.SynchronizeMappings\" value=\"buildSchema(ForeignKeys=true)\"/>\n </properties>\n </persistence-unit>\n </persistence>\n\n## MovieTest\n\n package org.superbiz.injection.secure;\n \n import junit.framework.TestCase;\n import org.superbiz.injection.secure.api.RunAsEmployee;\n import org.superbiz.injection.secure.api.RunAsManager;\n \n import javax.ejb.EJB;\n import javax.ejb.EJBAccessException;\n import javax.ejb.Stateless;\n import javax.ejb.embeddable.EJBContainer;\n import java.util.List;\n import java.util.Properties;\n import java.util.concurrent.Callable;\n \n //START SNIPPET: code\n \n public class MovieTest extends TestCase {\n \n @EJB\n private Movies movies;\n \n @EJB(beanName = \"ManagerBean\")\n private Caller manager;\n \n @EJB(beanName = \"EmployeeBean\")\n private Caller employee;\n \n protected void setUp() throws Exception {\n Properties p = new Properties();\n p.put(\"movieDatabase\", \"new://Resource?type=DataSource\");\n p.put(\"movieDatabase.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"movieDatabase.JdbcUrl\", \"jdbc:hsqldb:mem:moviedb\");\n \n EJBContainer.createEJBContainer(p).getContext().bind(\"inject\", this);\n }\n \n public void testAsManager() throws Exception {\n manager.call(new Callable() {\n public Object call() throws Exception {\n \n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n movies.addMovie(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n movies.addMovie(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n \n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n \n for (Movie movie : list) {\n movies.deleteMovie(movie);\n }\n \n assertEquals(\"Movies.getMovies()\", 0, movies.getMovies().size());\n return null;\n }\n });\n }\n \n public void testAsEmployee() throws Exception {\n employee.call(new Callable() {\n public Object call() throws Exception {\n \n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n movies.addMovie(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n movies.addMovie(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n \n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n \n for (Movie movie : list) {\n try {\n movies.deleteMovie(movie);\n fail(\"Employees should not be allowed to delete\");\n } catch (EJBAccessException e) {\n // Good, Employees cannot delete things\n }\n }\n \n // The list should still be three movies long\n assertEquals(\"Movies.getMovies()\", 3, movies.getMovies().size());\n return null;\n }\n });\n }\n \n public void testUnauthenticated() throws Exception {\n try {\n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n fail(\"Unauthenticated users should not be able to add movies\");\n } catch (EJBAccessException e) {\n // Good, guests cannot add things\n }\n \n try {\n movies.deleteMovie(null);\n fail(\"Unauthenticated users should not be allowed to delete\");\n } catch (EJBAccessException e) {\n // Good, Unauthenticated users cannot delete things\n }\n \n try {\n // Read access should be allowed\n \n List<Movie> list = movies.getMovies();\n } catch (EJBAccessException e) {\n fail(\"Read access should be allowed\");\n }\n }\n \n public interface Caller {\n public <V> V call(Callable<V> callable) throws Exception;\n }\n \n /**\n * This little bit of magic allows our test code to execute in\n * the desired security scope.\n */\n \n @Stateless\n @RunAsManager\n public static class ManagerBean implements Caller {\n \n public <V> V call(Callable<V> callable) throws Exception {\n return callable.call();\n }\n }\n \n @Stateless\n @RunAsEmployee\n public static class EmployeeBean implements Caller {\n \n public <V> V call(Callable<V> callable) throws Exception {\n return callable.call();\n }\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.injection.secure.MovieTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/testing-security-meta\n INFO - openejb.base = /Users/dblevins/examples/testing-security-meta\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/testing-security-meta/target/classes\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/testing-security-meta/target/test-classes\n INFO - Beginning load: /Users/dblevins/examples/testing-security-meta/target/classes\n INFO - Beginning load: /Users/dblevins/examples/testing-security-meta/target/test-classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/testing-security-meta\n INFO - Configuring Service(id=Default Stateful Container, type=Container, provider-id=Default Stateful Container)\n INFO - Auto-creating a container for bean Movies: Container(type=STATEFUL, id=Default Stateful Container)\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean ManagerBean: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.injection.secure.MovieTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring PersistenceUnit(name=movie-unit)\n INFO - Auto-creating a Resource with id 'movieDatabaseNonJta' of type 'DataSource for 'movie-unit'.\n INFO - Configuring Service(id=movieDatabaseNonJta, type=Resource, provider-id=movieDatabase)\n INFO - Adjusting PersistenceUnit movie-unit <non-jta-data-source> to Resource ID 'movieDatabaseNonJta' from 'movieDatabaseUnmanaged'\n INFO - Enterprise application \"/Users/dblevins/examples/testing-security-meta\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/testing-security-meta\n INFO - PersistenceUnit(name=movie-unit, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 419ms\n INFO - Jndi(name=\"java:global/testing-security-meta/Movies!org.superbiz.injection.secure.Movies\")\n INFO - Jndi(name=\"java:global/testing-security-meta/Movies\")\n INFO - Jndi(name=\"java:global/testing-security-meta/ManagerBean!org.superbiz.injection.secure.MovieTest$Caller\")\n INFO - Jndi(name=\"java:global/testing-security-meta/ManagerBean\")\n INFO - Jndi(name=\"java:global/testing-security-meta/EmployeeBean!org.superbiz.injection.secure.MovieTest$Caller\")\n INFO - Jndi(name=\"java:global/testing-security-meta/EmployeeBean\")\n INFO - Jndi(name=\"java:global/EjbModule53489605/org.superbiz.injection.secure.MovieTest!org.superbiz.injection.secure.MovieTest\")\n INFO - Jndi(name=\"java:global/EjbModule53489605/org.superbiz.injection.secure.MovieTest\")\n INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Created Ejb(deployment-id=ManagerBean, ejb-name=ManagerBean, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=EmployeeBean, ejb-name=EmployeeBean, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=org.superbiz.injection.secure.MovieTest, ejb-name=org.superbiz.injection.secure.MovieTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Started Ejb(deployment-id=ManagerBean, ejb-name=ManagerBean, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=EmployeeBean, ejb-name=EmployeeBean, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=org.superbiz.injection.secure.MovieTest, ejb-name=org.superbiz.injection.secure.MovieTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/testing-security-meta)\n INFO - EJBContainer already initialized. Call ejbContainer.close() to allow reinitialization\n INFO - EJBContainer already initialized. Call ejbContainer.close() to allow reinitialization\n Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.754 sec\n \n Results :\n \n Tests run: 3, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/testing-security-meta"
},
{
"name":"schedule-methods-meta",
"readme":"Title: Schedule Methods Meta\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## BiAnnually\n\n package org.superbiz.corn.meta.api;\n \n import javax.ejb.Schedule;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n @Metatype\n @Target(ElementType.METHOD)\n @Retention(RetentionPolicy.RUNTIME)\n \n public @interface BiAnnually {\n public static interface $ {\n \n @BiAnnually\n @Schedule(second = \"0\", minute = \"0\", hour = \"0\", dayOfMonth = \"1\", month = \"1,6\")\n public void method();\n }\n }\n\n## BiMonthly\n\n package org.superbiz.corn.meta.api;\n \n import javax.ejb.Schedule;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n @Metatype\n @Target(ElementType.METHOD)\n @Retention(RetentionPolicy.RUNTIME)\n \n public @interface BiMonthly {\n public static interface $ {\n \n @BiMonthly\n @Schedule(second = \"0\", minute = \"0\", hour = \"0\", dayOfMonth = \"1,15\")\n public void method();\n }\n }\n\n## Daily\n\n package org.superbiz.corn.meta.api;\n \n import javax.ejb.Schedule;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n @Metatype\n @Target(ElementType.METHOD)\n @Retention(RetentionPolicy.RUNTIME)\n \n public @interface Daily {\n public static interface $ {\n \n @Daily\n @Schedule(second = \"0\", minute = \"0\", hour = \"0\", dayOfMonth = \"*\")\n public void method();\n }\n }\n\n## HarvestTime\n\n package org.superbiz.corn.meta.api;\n \n import javax.ejb.Schedule;\n import javax.ejb.Schedules;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n @Metatype\n @Target(ElementType.METHOD)\n @Retention(RetentionPolicy.RUNTIME)\n \n public @interface HarvestTime {\n public static interface $ {\n \n @HarvestTime\n @Schedules({\n @Schedule(month = \"9\", dayOfMonth = \"20-Last\", minute = \"0\", hour = \"8\"),\n @Schedule(month = \"10\", dayOfMonth = \"1-10\", minute = \"0\", hour = \"8\")\n })\n public void method();\n }\n }\n\n## Hourly\n\n package org.superbiz.corn.meta.api;\n \n import javax.ejb.Schedule;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n @Metatype\n @Target(ElementType.METHOD)\n @Retention(RetentionPolicy.RUNTIME)\n \n public @interface Hourly {\n public static interface $ {\n \n @Hourly\n @Schedule(second = \"0\", minute = \"0\", hour = \"*\")\n public void method();\n }\n }\n\n## Metatype\n\n package org.superbiz.corn.meta.api;\n \n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n @Metatype\n @Target(ElementType.ANNOTATION_TYPE)\n @Retention(RetentionPolicy.RUNTIME)\n public @interface Metatype {\n }\n\n## Organic\n\n package org.superbiz.corn.meta.api;\n \n import javax.ejb.Lock;\n import javax.ejb.LockType;\n import javax.ejb.Singleton;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n @Metatype\n @Target(ElementType.TYPE)\n @Retention(RetentionPolicy.RUNTIME)\n \n @Singleton\n @Lock(LockType.READ)\n public @interface Organic {\n }\n\n## PlantingTime\n\n package org.superbiz.corn.meta.api;\n \n import javax.ejb.Schedule;\n import javax.ejb.Schedules;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n @Metatype\n @Target(ElementType.METHOD)\n @Retention(RetentionPolicy.RUNTIME)\n \n public @interface PlantingTime {\n public static interface $ {\n \n @PlantingTime\n @Schedules({\n @Schedule(month = \"5\", dayOfMonth = \"20-Last\", minute = \"0\", hour = \"8\"),\n @Schedule(month = \"6\", dayOfMonth = \"1-10\", minute = \"0\", hour = \"8\")\n })\n public void method();\n }\n }\n\n## Secondly\n\n package org.superbiz.corn.meta.api;\n \n import javax.ejb.Schedule;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n @Metatype\n @Target(ElementType.METHOD)\n @Retention(RetentionPolicy.RUNTIME)\n \n public @interface Secondly {\n public static interface $ {\n \n @Secondly\n @Schedule(second = \"*\", minute = \"*\", hour = \"*\")\n public void method();\n }\n }\n\n## FarmerBrown\n\n package org.superbiz.corn.meta;\n \n import org.superbiz.corn.meta.api.HarvestTime;\n import org.superbiz.corn.meta.api.Organic;\n import org.superbiz.corn.meta.api.PlantingTime;\n import org.superbiz.corn.meta.api.Secondly;\n \n import java.util.concurrent.atomic.AtomicInteger;\n \n /**\n * This is where we schedule all of Farmer Brown's corn jobs\n *\n * @version $Revision$ $Date$\n */\n @Organic\n public class FarmerBrown {\n \n private final AtomicInteger checks = new AtomicInteger();\n \n @PlantingTime\n private void plantTheCorn() {\n // Dig out the planter!!!\n }\n \n @HarvestTime\n private void harvestTheCorn() {\n // Dig out the combine!!!\n }\n \n @Secondly\n private void checkOnTheDaughters() {\n checks.incrementAndGet();\n }\n \n public int getChecks() {\n return checks.get();\n }\n }\n\n## FarmerBrownTest\n\n package org.superbiz.corn.meta;\n \n import junit.framework.TestCase;\n \n import javax.ejb.embeddable.EJBContainer;\n import javax.naming.Context;\n \n import static java.util.concurrent.TimeUnit.SECONDS;\n \n /**\n * @version $Revision$ $Date$\n */\n public class FarmerBrownTest extends TestCase {\n \n public void test() throws Exception {\n \n final Context context = EJBContainer.createEJBContainer().getContext();\n \n final FarmerBrown farmerBrown = (FarmerBrown) context.lookup(\"java:global/schedule-methods-meta/FarmerBrown\");\n \n // Give Farmer brown a chance to do some work\n Thread.sleep(SECONDS.toMillis(5));\n \n assertTrue(farmerBrown.getChecks() > 4);\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.corn.meta.FarmerBrownTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/schedule-methods-meta\n INFO - openejb.base = /Users/dblevins/examples/schedule-methods-meta\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/schedule-methods-meta/target/classes\n INFO - Beginning load: /Users/dblevins/examples/schedule-methods-meta/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/schedule-methods-meta\n INFO - Configuring Service(id=Default Singleton Container, type=Container, provider-id=Default Singleton Container)\n INFO - Auto-creating a container for bean FarmerBrown: Container(type=SINGLETON, id=Default Singleton Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.corn.meta.FarmerBrownTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Enterprise application \"/Users/dblevins/examples/schedule-methods-meta\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/schedule-methods-meta\n INFO - Jndi(name=\"java:global/schedule-methods-meta/FarmerBrown!org.superbiz.corn.meta.FarmerBrown\")\n INFO - Jndi(name=\"java:global/schedule-methods-meta/FarmerBrown\")\n INFO - Jndi(name=\"java:global/EjbModule1809441479/org.superbiz.corn.meta.FarmerBrownTest!org.superbiz.corn.meta.FarmerBrownTest\")\n INFO - Jndi(name=\"java:global/EjbModule1809441479/org.superbiz.corn.meta.FarmerBrownTest\")\n INFO - Created Ejb(deployment-id=org.superbiz.corn.meta.FarmerBrownTest, ejb-name=org.superbiz.corn.meta.FarmerBrownTest, container=Default Managed Container)\n INFO - Created Ejb(deployment-id=FarmerBrown, ejb-name=FarmerBrown, container=Default Singleton Container)\n INFO - Started Ejb(deployment-id=org.superbiz.corn.meta.FarmerBrownTest, ejb-name=org.superbiz.corn.meta.FarmerBrownTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=FarmerBrown, ejb-name=FarmerBrown, container=Default Singleton Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/schedule-methods-meta)\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 6.166 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/schedule-methods-meta"
},
{
"name":"access-timeout-meta",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/access-timeout-meta"
},
{
"name":"movies-complete-meta",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/movies-complete-meta"
}
],
"methods":[
{
"name":"schedule-methods",
"readme":"Title: Schedule Methods\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## FarmerBrown\n\n package org.superbiz.corn;\n \n import javax.ejb.Lock;\n import javax.ejb.LockType;\n import javax.ejb.Schedule;\n import javax.ejb.Schedules;\n import javax.ejb.Singleton;\n import java.util.concurrent.atomic.AtomicInteger;\n \n /**\n * This is where we schedule all of Farmer Brown's corn jobs\n *\n * @version $Revision$ $Date$\n */\n @Singleton\n @Lock(LockType.READ) // allows timers to execute in parallel\n public class FarmerBrown {\n \n private final AtomicInteger checks = new AtomicInteger();\n \n @Schedules({\n @Schedule(month = \"5\", dayOfMonth = \"20-Last\", minute = \"0\", hour = \"8\"),\n @Schedule(month = \"6\", dayOfMonth = \"1-10\", minute = \"0\", hour = \"8\")\n })\n private void plantTheCorn() {\n // Dig out the planter!!!\n }\n \n @Schedules({\n @Schedule(month = \"9\", dayOfMonth = \"20-Last\", minute = \"0\", hour = \"8\"),\n @Schedule(month = \"10\", dayOfMonth = \"1-10\", minute = \"0\", hour = \"8\")\n })\n private void harvestTheCorn() {\n // Dig out the combine!!!\n }\n \n @Schedule(second = \"*\", minute = \"*\", hour = \"*\")\n private void checkOnTheDaughters() {\n checks.incrementAndGet();\n }\n \n public int getChecks() {\n return checks.get();\n }\n }\n\n## FarmerBrownTest\n\n package org.superbiz.corn;\n \n import junit.framework.TestCase;\n \n import javax.ejb.embeddable.EJBContainer;\n import javax.naming.Context;\n \n import static java.util.concurrent.TimeUnit.SECONDS;\n \n /**\n * @version $Revision$ $Date$\n */\n public class FarmerBrownTest extends TestCase {\n \n public void test() throws Exception {\n \n final Context context = EJBContainer.createEJBContainer().getContext();\n \n final FarmerBrown farmerBrown = (FarmerBrown) context.lookup(\"java:global/schedule-methods/FarmerBrown\");\n \n // Give Farmer brown a chance to do some work\n Thread.sleep(SECONDS.toMillis(5));\n \n assertTrue(farmerBrown.getChecks() > 4);\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.corn.FarmerBrownTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/schedule-methods\n INFO - openejb.base = /Users/dblevins/examples/schedule-methods\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/schedule-methods/target/classes\n INFO - Beginning load: /Users/dblevins/examples/schedule-methods/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/schedule-methods\n INFO - Configuring Service(id=Default Singleton Container, type=Container, provider-id=Default Singleton Container)\n INFO - Auto-creating a container for bean FarmerBrown: Container(type=SINGLETON, id=Default Singleton Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.corn.FarmerBrownTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Enterprise application \"/Users/dblevins/examples/schedule-methods\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/schedule-methods\n INFO - Jndi(name=\"java:global/schedule-methods/FarmerBrown!org.superbiz.corn.FarmerBrown\")\n INFO - Jndi(name=\"java:global/schedule-methods/FarmerBrown\")\n INFO - Jndi(name=\"java:global/EjbModule660493198/org.superbiz.corn.FarmerBrownTest!org.superbiz.corn.FarmerBrownTest\")\n INFO - Jndi(name=\"java:global/EjbModule660493198/org.superbiz.corn.FarmerBrownTest\")\n INFO - Created Ejb(deployment-id=org.superbiz.corn.FarmerBrownTest, ejb-name=org.superbiz.corn.FarmerBrownTest, container=Default Managed Container)\n INFO - Created Ejb(deployment-id=FarmerBrown, ejb-name=FarmerBrown, container=Default Singleton Container)\n INFO - Started Ejb(deployment-id=org.superbiz.corn.FarmerBrownTest, ejb-name=org.superbiz.corn.FarmerBrownTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=FarmerBrown, ejb-name=FarmerBrown, container=Default Singleton Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/schedule-methods)\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 6.121 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/schedule-methods"
},
{
"name":"schedule-methods-meta",
"readme":"Title: Schedule Methods Meta\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## BiAnnually\n\n package org.superbiz.corn.meta.api;\n \n import javax.ejb.Schedule;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n @Metatype\n @Target(ElementType.METHOD)\n @Retention(RetentionPolicy.RUNTIME)\n \n public @interface BiAnnually {\n public static interface $ {\n \n @BiAnnually\n @Schedule(second = \"0\", minute = \"0\", hour = \"0\", dayOfMonth = \"1\", month = \"1,6\")\n public void method();\n }\n }\n\n## BiMonthly\n\n package org.superbiz.corn.meta.api;\n \n import javax.ejb.Schedule;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n @Metatype\n @Target(ElementType.METHOD)\n @Retention(RetentionPolicy.RUNTIME)\n \n public @interface BiMonthly {\n public static interface $ {\n \n @BiMonthly\n @Schedule(second = \"0\", minute = \"0\", hour = \"0\", dayOfMonth = \"1,15\")\n public void method();\n }\n }\n\n## Daily\n\n package org.superbiz.corn.meta.api;\n \n import javax.ejb.Schedule;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n @Metatype\n @Target(ElementType.METHOD)\n @Retention(RetentionPolicy.RUNTIME)\n \n public @interface Daily {\n public static interface $ {\n \n @Daily\n @Schedule(second = \"0\", minute = \"0\", hour = \"0\", dayOfMonth = \"*\")\n public void method();\n }\n }\n\n## HarvestTime\n\n package org.superbiz.corn.meta.api;\n \n import javax.ejb.Schedule;\n import javax.ejb.Schedules;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n @Metatype\n @Target(ElementType.METHOD)\n @Retention(RetentionPolicy.RUNTIME)\n \n public @interface HarvestTime {\n public static interface $ {\n \n @HarvestTime\n @Schedules({\n @Schedule(month = \"9\", dayOfMonth = \"20-Last\", minute = \"0\", hour = \"8\"),\n @Schedule(month = \"10\", dayOfMonth = \"1-10\", minute = \"0\", hour = \"8\")\n })\n public void method();\n }\n }\n\n## Hourly\n\n package org.superbiz.corn.meta.api;\n \n import javax.ejb.Schedule;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n @Metatype\n @Target(ElementType.METHOD)\n @Retention(RetentionPolicy.RUNTIME)\n \n public @interface Hourly {\n public static interface $ {\n \n @Hourly\n @Schedule(second = \"0\", minute = \"0\", hour = \"*\")\n public void method();\n }\n }\n\n## Metatype\n\n package org.superbiz.corn.meta.api;\n \n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n @Metatype\n @Target(ElementType.ANNOTATION_TYPE)\n @Retention(RetentionPolicy.RUNTIME)\n public @interface Metatype {\n }\n\n## Organic\n\n package org.superbiz.corn.meta.api;\n \n import javax.ejb.Lock;\n import javax.ejb.LockType;\n import javax.ejb.Singleton;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n @Metatype\n @Target(ElementType.TYPE)\n @Retention(RetentionPolicy.RUNTIME)\n \n @Singleton\n @Lock(LockType.READ)\n public @interface Organic {\n }\n\n## PlantingTime\n\n package org.superbiz.corn.meta.api;\n \n import javax.ejb.Schedule;\n import javax.ejb.Schedules;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n @Metatype\n @Target(ElementType.METHOD)\n @Retention(RetentionPolicy.RUNTIME)\n \n public @interface PlantingTime {\n public static interface $ {\n \n @PlantingTime\n @Schedules({\n @Schedule(month = \"5\", dayOfMonth = \"20-Last\", minute = \"0\", hour = \"8\"),\n @Schedule(month = \"6\", dayOfMonth = \"1-10\", minute = \"0\", hour = \"8\")\n })\n public void method();\n }\n }\n\n## Secondly\n\n package org.superbiz.corn.meta.api;\n \n import javax.ejb.Schedule;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n @Metatype\n @Target(ElementType.METHOD)\n @Retention(RetentionPolicy.RUNTIME)\n \n public @interface Secondly {\n public static interface $ {\n \n @Secondly\n @Schedule(second = \"*\", minute = \"*\", hour = \"*\")\n public void method();\n }\n }\n\n## FarmerBrown\n\n package org.superbiz.corn.meta;\n \n import org.superbiz.corn.meta.api.HarvestTime;\n import org.superbiz.corn.meta.api.Organic;\n import org.superbiz.corn.meta.api.PlantingTime;\n import org.superbiz.corn.meta.api.Secondly;\n \n import java.util.concurrent.atomic.AtomicInteger;\n \n /**\n * This is where we schedule all of Farmer Brown's corn jobs\n *\n * @version $Revision$ $Date$\n */\n @Organic\n public class FarmerBrown {\n \n private final AtomicInteger checks = new AtomicInteger();\n \n @PlantingTime\n private void plantTheCorn() {\n // Dig out the planter!!!\n }\n \n @HarvestTime\n private void harvestTheCorn() {\n // Dig out the combine!!!\n }\n \n @Secondly\n private void checkOnTheDaughters() {\n checks.incrementAndGet();\n }\n \n public int getChecks() {\n return checks.get();\n }\n }\n\n## FarmerBrownTest\n\n package org.superbiz.corn.meta;\n \n import junit.framework.TestCase;\n \n import javax.ejb.embeddable.EJBContainer;\n import javax.naming.Context;\n \n import static java.util.concurrent.TimeUnit.SECONDS;\n \n /**\n * @version $Revision$ $Date$\n */\n public class FarmerBrownTest extends TestCase {\n \n public void test() throws Exception {\n \n final Context context = EJBContainer.createEJBContainer().getContext();\n \n final FarmerBrown farmerBrown = (FarmerBrown) context.lookup(\"java:global/schedule-methods-meta/FarmerBrown\");\n \n // Give Farmer brown a chance to do some work\n Thread.sleep(SECONDS.toMillis(5));\n \n assertTrue(farmerBrown.getChecks() > 4);\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.corn.meta.FarmerBrownTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/schedule-methods-meta\n INFO - openejb.base = /Users/dblevins/examples/schedule-methods-meta\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/schedule-methods-meta/target/classes\n INFO - Beginning load: /Users/dblevins/examples/schedule-methods-meta/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/schedule-methods-meta\n INFO - Configuring Service(id=Default Singleton Container, type=Container, provider-id=Default Singleton Container)\n INFO - Auto-creating a container for bean FarmerBrown: Container(type=SINGLETON, id=Default Singleton Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.corn.meta.FarmerBrownTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Enterprise application \"/Users/dblevins/examples/schedule-methods-meta\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/schedule-methods-meta\n INFO - Jndi(name=\"java:global/schedule-methods-meta/FarmerBrown!org.superbiz.corn.meta.FarmerBrown\")\n INFO - Jndi(name=\"java:global/schedule-methods-meta/FarmerBrown\")\n INFO - Jndi(name=\"java:global/EjbModule1809441479/org.superbiz.corn.meta.FarmerBrownTest!org.superbiz.corn.meta.FarmerBrownTest\")\n INFO - Jndi(name=\"java:global/EjbModule1809441479/org.superbiz.corn.meta.FarmerBrownTest\")\n INFO - Created Ejb(deployment-id=org.superbiz.corn.meta.FarmerBrownTest, ejb-name=org.superbiz.corn.meta.FarmerBrownTest, container=Default Managed Container)\n INFO - Created Ejb(deployment-id=FarmerBrown, ejb-name=FarmerBrown, container=Default Singleton Container)\n INFO - Started Ejb(deployment-id=org.superbiz.corn.meta.FarmerBrownTest, ejb-name=org.superbiz.corn.meta.FarmerBrownTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=FarmerBrown, ejb-name=FarmerBrown, container=Default Singleton Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/schedule-methods-meta)\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 6.166 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/schedule-methods-meta"
},
{
"name":"async-methods",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/async-methods"
}
],
"mockito":[
{
"name":"rest-applicationcomposer-mockito",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/rest-applicationcomposer-mockito"
}
],
"moviefun":[
{
"name":"moviefun",
"readme":"Title: Movies Complete\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## AddInterceptor\n\n package org.superbiz.injection.tx;\n \n import javax.interceptor.AroundInvoke;\n import javax.interceptor.InvocationContext;\n \n /**\n * @version $Revision$ $Date$\n */\n public class AddInterceptor {\n \n @AroundInvoke\n public Object invoke(InvocationContext context) throws Exception {\n // Log Add\n return context.proceed();\n }\n }\n\n## DeleteInterceptor\n\n package org.superbiz.injection.tx;\n \n import javax.interceptor.AroundInvoke;\n import javax.interceptor.InvocationContext;\n \n /**\n * @version $Revision$ $Date$\n */\n public class DeleteInterceptor {\n \n @AroundInvoke\n public Object invoke(InvocationContext context) throws Exception {\n // Log Delete\n return context.proceed();\n }\n }\n\n## Movie\n\n package org.superbiz.injection.tx;\n \n import javax.persistence.Entity;\n \n @Entity\n public class Movie {\n \n private String director;\n private String title;\n private int year;\n \n public Movie() {\n }\n \n public Movie(String director, String title, int year) {\n this.director = director;\n this.title = title;\n this.year = year;\n }\n \n public String getDirector() {\n return director;\n }\n \n public void setDirector(String director) {\n this.director = director;\n }\n \n public String getTitle() {\n return title;\n }\n \n public void setTitle(String title) {\n this.title = title;\n }\n \n public int getYear() {\n return year;\n }\n \n public void setYear(int year) {\n this.year = year;\n }\n \n }\n\n## Movies\n\n package org.superbiz.injection.tx;\n \n import javax.annotation.security.PermitAll;\n import javax.annotation.security.RolesAllowed;\n import javax.ejb.Stateful;\n import javax.ejb.TransactionAttribute;\n import javax.ejb.TransactionAttributeType;\n import javax.interceptor.Interceptors;\n import javax.persistence.EntityManager;\n import javax.persistence.PersistenceContext;\n import javax.persistence.PersistenceContextType;\n import javax.persistence.Query;\n import java.util.List;\n \n //START SNIPPET: code\n @Stateful\n public class Movies {\n \n @PersistenceContext(unitName = \"movie-unit\", type = PersistenceContextType.TRANSACTION)\n private EntityManager entityManager;\n \n @RolesAllowed({\"Employee\", \"Manager\"})\n @TransactionAttribute(TransactionAttributeType.REQUIRED)\n @Interceptors(AddInterceptor.class)\n public void addMovie(Movie movie) throws Exception {\n entityManager.persist(movie);\n }\n \n @RolesAllowed({\"Manager\"})\n @TransactionAttribute(TransactionAttributeType.MANDATORY)\n @Interceptors(DeleteInterceptor.class)\n public void deleteMovie(Movie movie) throws Exception {\n entityManager.remove(movie);\n }\n \n @PermitAll\n @TransactionAttribute(TransactionAttributeType.SUPPORTS)\n public List<Movie> getMovies() throws Exception {\n Query query = entityManager.createQuery(\"SELECT m from Movie as m\");\n return query.getResultList();\n }\n }\n\n## ReadInterceptor\n\n package org.superbiz.injection.tx;\n \n import javax.interceptor.AroundInvoke;\n import javax.interceptor.InvocationContext;\n \n /**\n * @version $Revision$ $Date$\n */\n public class ReadInterceptor {\n \n @AroundInvoke\n public Object invoke(InvocationContext context) throws Exception {\n // Log Delete\n return context.proceed();\n }\n }\n\n## persistence.xml\n\n <persistence xmlns=\"http://java.sun.com/xml/ns/persistence\" version=\"1.0\">\n \n <persistence-unit name=\"movie-unit\">\n <jta-data-source>movieDatabase</jta-data-source>\n <non-jta-data-source>movieDatabaseUnmanaged</non-jta-data-source>\n <class>org.superbiz.injection.tx.Movie</class>\n \n <properties>\n <property name=\"openjpa.jdbc.SynchronizeMappings\" value=\"buildSchema(ForeignKeys=true)\"/>\n </properties>\n </persistence-unit>\n </persistence>\n\n## MoviesTest\n\n package org.superbiz.injection.tx;\n \n import junit.framework.TestCase;\n \n import javax.annotation.security.RunAs;\n import javax.ejb.EJB;\n import javax.ejb.Stateless;\n import javax.ejb.TransactionAttribute;\n import javax.ejb.TransactionAttributeType;\n import javax.ejb.embeddable.EJBContainer;\n import java.util.List;\n import java.util.Properties;\n import java.util.concurrent.Callable;\n \n import static javax.ejb.TransactionAttributeType.REQUIRES_NEW;\n \n /**\n * See the transaction-rollback example as it does the same thing\n * via UserTransaction and shows more techniques for rollback \n */\n //START SNIPPET: code\n public class MoviesTest extends TestCase {\n \n @EJB\n private Movies movies;\n \n @EJB(beanName = \"TransactionBean\")\n private Caller transactionalCaller;\n \n @EJB(beanName = \"NoTransactionBean\")\n private Caller nonTransactionalCaller;\n \n protected void setUp() throws Exception {\n final Properties p = new Properties();\n p.put(\"movieDatabase\", \"new://Resource?type=DataSource\");\n p.put(\"movieDatabase.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"movieDatabase.JdbcUrl\", \"jdbc:hsqldb:mem:moviedb\");\n \n EJBContainer.createEJBContainer(p).getContext().bind(\"inject\", this);\n }\n \n private void doWork() throws Exception {\n \n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n movies.addMovie(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n movies.addMovie(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n \n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n \n for (Movie movie : list) {\n movies.deleteMovie(movie);\n }\n \n assertEquals(\"Movies.getMovies()\", 0, movies.getMovies().size());\n }\n \n public void testWithTransaction() throws Exception {\n transactionalCaller.call(new Callable() {\n public Object call() throws Exception {\n doWork();\n return null;\n }\n });\n }\n \n public void testWithoutTransaction() throws Exception {\n try {\n nonTransactionalCaller.call(new Callable() {\n public Object call() throws Exception {\n doWork();\n return null;\n }\n });\n fail(\"The Movies bean should be using TransactionAttributeType.MANDATORY\");\n } catch (javax.ejb.EJBException e) {\n // good, our Movies bean is using TransactionAttributeType.MANDATORY as we want\n }\n }\n \n \n public static interface Caller {\n public <V> V call(Callable<V> callable) throws Exception;\n }\n \n /**\n * This little bit of magic allows our test code to execute in\n * the scope of a container controlled transaction.\n */\n @Stateless\n @RunAs(\"Manager\")\n @TransactionAttribute(REQUIRES_NEW)\n public static class TransactionBean implements Caller {\n \n public <V> V call(Callable<V> callable) throws Exception {\n return callable.call();\n }\n }\n \n @Stateless\n @RunAs(\"Manager\")\n @TransactionAttribute(TransactionAttributeType.NEVER)\n public static class NoTransactionBean implements Caller {\n \n public <V> V call(Callable<V> callable) throws Exception {\n return callable.call();\n }\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.injection.tx.MoviesTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/movies-complete\n INFO - openejb.base = /Users/dblevins/examples/movies-complete\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/movies-complete/target/classes\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/movies-complete/target/test-classes\n INFO - Beginning load: /Users/dblevins/examples/movies-complete/target/classes\n INFO - Beginning load: /Users/dblevins/examples/movies-complete/target/test-classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/movies-complete\n INFO - Configuring Service(id=Default Stateful Container, type=Container, provider-id=Default Stateful Container)\n INFO - Auto-creating a container for bean Movies: Container(type=STATEFUL, id=Default Stateful Container)\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean TransactionBean: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.injection.tx.MoviesTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring PersistenceUnit(name=movie-unit)\n INFO - Auto-creating a Resource with id 'movieDatabaseNonJta' of type 'DataSource for 'movie-unit'.\n INFO - Configuring Service(id=movieDatabaseNonJta, type=Resource, provider-id=movieDatabase)\n INFO - Adjusting PersistenceUnit movie-unit <non-jta-data-source> to Resource ID 'movieDatabaseNonJta' from 'movieDatabaseUnmanaged'\n INFO - Enterprise application \"/Users/dblevins/examples/movies-complete\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/movies-complete\n INFO - PersistenceUnit(name=movie-unit, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 402ms\n INFO - Jndi(name=\"java:global/movies-complete/Movies!org.superbiz.injection.tx.Movies\")\n INFO - Jndi(name=\"java:global/movies-complete/Movies\")\n INFO - Jndi(name=\"java:global/movies-complete/TransactionBean!org.superbiz.injection.tx.MoviesTest$Caller\")\n INFO - Jndi(name=\"java:global/movies-complete/TransactionBean\")\n INFO - Jndi(name=\"java:global/movies-complete/NoTransactionBean!org.superbiz.injection.tx.MoviesTest$Caller\")\n INFO - Jndi(name=\"java:global/movies-complete/NoTransactionBean\")\n INFO - Jndi(name=\"java:global/EjbModule1013462002/org.superbiz.injection.tx.MoviesTest!org.superbiz.injection.tx.MoviesTest\")\n INFO - Jndi(name=\"java:global/EjbModule1013462002/org.superbiz.injection.tx.MoviesTest\")\n INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Created Ejb(deployment-id=NoTransactionBean, ejb-name=NoTransactionBean, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=TransactionBean, ejb-name=TransactionBean, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=org.superbiz.injection.tx.MoviesTest, ejb-name=org.superbiz.injection.tx.MoviesTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Started Ejb(deployment-id=NoTransactionBean, ejb-name=NoTransactionBean, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=TransactionBean, ejb-name=TransactionBean, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=org.superbiz.injection.tx.MoviesTest, ejb-name=org.superbiz.injection.tx.MoviesTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/movies-complete)\n INFO - EJBContainer already initialized. Call ejbContainer.close() to allow reinitialization\n Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.418 sec\n \n Results :\n \n Tests run: 2, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/moviefun"
},
{
"name":"moviefun-rest",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/moviefun-rest"
}
],
"movies":[
{
"name":"movies-complete",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/movies-complete"
},
{
"name":"movies-complete-meta",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/movies-complete-meta"
}
],
"mtom":[
{
"name":"mtom",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/mtom"
}
],
"multi":[
{
"name":"multi-jpa-provider-testing",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/multi-jpa-provider-testing"
}
],
"multiple":[
{
"name":"multiple-tomee-arquillian",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/multiple-tomee-arquillian"
},
{
"name":"multiple-arquillian-adapters",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/multiple-arquillian-adapters"
}
],
"myfaces":[
{
"name":"myfaces-codi-demo",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/myfaces-codi-demo"
}
],
"of":[
{
"name":"injection-of-connectionfactory",
"readme":"Title: Injection Of Connectionfactory\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## Messages\n\n package org.superbiz.injection.jms;\n \n import javax.annotation.Resource;\n import javax.ejb.Stateless;\n import javax.jms.Connection;\n import javax.jms.ConnectionFactory;\n import javax.jms.DeliveryMode;\n import javax.jms.JMSException;\n import javax.jms.MessageConsumer;\n import javax.jms.MessageProducer;\n import javax.jms.Queue;\n import javax.jms.Session;\n import javax.jms.TextMessage;\n \n @Stateless\n public class Messages {\n \n @Resource\n private ConnectionFactory connectionFactory;\n \n @Resource\n private Queue chatQueue;\n \n \n public void sendMessage(String text) throws JMSException {\n \n Connection connection = null;\n Session session = null;\n \n try {\n connection = connectionFactory.createConnection();\n connection.start();\n \n // Create a Session\n session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);\n \n // Create a MessageProducer from the Session to the Topic or Queue\n MessageProducer producer = session.createProducer(chatQueue);\n producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);\n \n // Create a message\n TextMessage message = session.createTextMessage(text);\n \n // Tell the producer to send the message\n producer.send(message);\n } finally {\n // Clean up\n if (session != null) session.close();\n if (connection != null) connection.close();\n }\n }\n \n public String receiveMessage() throws JMSException {\n \n Connection connection = null;\n Session session = null;\n MessageConsumer consumer = null;\n try {\n connection = connectionFactory.createConnection();\n connection.start();\n \n // Create a Session\n session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);\n \n // Create a MessageConsumer from the Session to the Topic or Queue\n consumer = session.createConsumer(chatQueue);\n \n // Wait for a message\n TextMessage message = (TextMessage) consumer.receive(1000);\n \n return message.getText();\n } finally {\n if (consumer != null) consumer.close();\n if (session != null) session.close();\n if (connection != null) connection.close();\n }\n }\n }\n\n## MessagingBeanTest\n\n package org.superbiz.injection.jms;\n \n import junit.framework.TestCase;\n \n import javax.ejb.embeddable.EJBContainer;\n import javax.naming.Context;\n \n public class MessagingBeanTest extends TestCase {\n \n public void test() throws Exception {\n \n final Context context = EJBContainer.createEJBContainer().getContext();\n \n Messages messages = (Messages) context.lookup(\"java:global/injection-of-connectionfactory/Messages\");\n \n messages.sendMessage(\"Hello World!\");\n messages.sendMessage(\"How are you?\");\n messages.sendMessage(\"Still spinning?\");\n \n assertEquals(messages.receiveMessage(), \"Hello World!\");\n assertEquals(messages.receiveMessage(), \"How are you?\");\n assertEquals(messages.receiveMessage(), \"Still spinning?\");\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.injection.jms.MessagingBeanTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/injection-of-connectionfactory\n INFO - openejb.base = /Users/dblevins/examples/injection-of-connectionfactory\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/injection-of-connectionfactory/target/classes\n INFO - Beginning load: /Users/dblevins/examples/injection-of-connectionfactory/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/injection-of-connectionfactory\n WARN - Method 'lookup' is not available for 'javax.annotation.Resource'. Probably using an older Runtime.\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean Messages: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Configuring Service(id=Default JMS Connection Factory, type=Resource, provider-id=Default JMS Connection Factory)\n INFO - Auto-creating a Resource with id 'Default JMS Connection Factory' of type 'javax.jms.ConnectionFactory for 'Messages'.\n INFO - Configuring Service(id=Default JMS Resource Adapter, type=Resource, provider-id=Default JMS Resource Adapter)\n INFO - Auto-linking resource-ref 'java:comp/env/org.superbiz.injection.jms.Messages/connectionFactory' in bean Messages to Resource(id=Default JMS Connection Factory)\n INFO - Configuring Service(id=org.superbiz.injection.jms.Messages/chatQueue, type=Resource, provider-id=Default Queue)\n INFO - Auto-creating a Resource with id 'org.superbiz.injection.jms.Messages/chatQueue' of type 'javax.jms.Queue for 'Messages'.\n INFO - Auto-linking resource-env-ref 'java:comp/env/org.superbiz.injection.jms.Messages/chatQueue' in bean Messages to Resource(id=org.superbiz.injection.jms.Messages/chatQueue)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.injection.jms.MessagingBeanTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Enterprise application \"/Users/dblevins/examples/injection-of-connectionfactory\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/injection-of-connectionfactory\n INFO - Jndi(name=\"java:global/injection-of-connectionfactory/Messages!org.superbiz.injection.jms.Messages\")\n INFO - Jndi(name=\"java:global/injection-of-connectionfactory/Messages\")\n INFO - Jndi(name=\"java:global/EjbModule1634151355/org.superbiz.injection.jms.MessagingBeanTest!org.superbiz.injection.jms.MessagingBeanTest\")\n INFO - Jndi(name=\"java:global/EjbModule1634151355/org.superbiz.injection.jms.MessagingBeanTest\")\n INFO - Created Ejb(deployment-id=Messages, ejb-name=Messages, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=org.superbiz.injection.jms.MessagingBeanTest, ejb-name=org.superbiz.injection.jms.MessagingBeanTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=Messages, ejb-name=Messages, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=org.superbiz.injection.jms.MessagingBeanTest, ejb-name=org.superbiz.injection.jms.MessagingBeanTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/injection-of-connectionfactory)\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.562 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/injection-of-connectionfactory"
},
{
"name":"injection-of-env-entry",
"readme":"Title: Using EnvEntries\n\nThe `@Resource` annotation can be used to inject several things including\nDataSources, Topics, Queues, etc. Most of these are container supplied objects.\n\nIt is possible, however, to supply your own values to be injected via an `<env-entry>`\nin your `ejb-jar.xml` or `web.xml` deployment descriptor. Java EE 6 supported `<env-entry>` types\nare limited to the following:\n\n - java.lang.String\n - java.lang.Integer\n - java.lang.Short\n - java.lang.Float\n - java.lang.Double\n - java.lang.Byte\n - java.lang.Character\n - java.lang.Boolean\n - java.lang.Class\n - java.lang.Enum (any enum)\n\nSee also the [Custom Injection](../custom-injection) exmaple for a TomEE and OpenEJB feature that will let you\nuse more than just the above types as well as declare `<env-entry>` items with a plain properties file.\n\n# Using @Resource for basic properties\n\nThe use of the `@Resource` annotation isn't limited to setters. For\nexample, this annotation could have been used on the corresponding *field*\nlike so:\n\n @Resource\n private int maxLineItems;\n\nA fuller example might look like this:\n\n package org.superbiz.injection.enventry;\n \n import javax.annotation.Resource;\n import javax.ejb.Singleton;\n import java.util.Date;\n \n @Singleton\n public class Configuration {\n \n @Resource\n private String color;\n \n @Resource\n private Shape shape;\n \n @Resource\n private Class strategy;\n \n @Resource(name = \"date\")\n private long date;\n \n public String getColor() {\n return color;\n }\n \n public Shape getShape() {\n return shape;\n }\n \n public Class getStrategy() {\n return strategy;\n }\n \n public Date getDate() {\n return new Date(date);\n }\n }\n\nHere we have an `@Singleton` bean called `Confuration` that has the following properties (`<env-entry>` items)\n\n- String color\n- Shape shape\n- Class strategy\n- long date\n\n## Supplying @Resource values for <env-entry> items in ejb-jar.xml\n\nThe values for our `color`, `shape`, `strategy` and `date` properties are supplied via `<env-entry>` elements in the `ejb-jar.xml` file or the\n`web.xml` file like so:\n\n\n <ejb-jar xmlns=\"http://java.sun.com/xml/ns/javaee\" version=\"3.0\" metadata-complete=\"false\">\n <enterprise-beans>\n <session>\n <ejb-name>Configuration</ejb-name>\n <env-entry>\n <env-entry-name>org.superbiz.injection.enventry.Configuration/color</env-entry-name>\n <env-entry-type>java.lang.String</env-entry-type>\n <env-entry-value>orange</env-entry-value>\n </env-entry>\n <env-entry>\n <env-entry-name>org.superbiz.injection.enventry.Configuration/shape</env-entry-name>\n <env-entry-type>org.superbiz.injection.enventry.Shape</env-entry-type>\n <env-entry-value>TRIANGLE</env-entry-value>\n </env-entry>\n <env-entry>\n <env-entry-name>org.superbiz.injection.enventry.Configuration/strategy</env-entry-name>\n <env-entry-type>java.lang.Class</env-entry-type>\n <env-entry-value>org.superbiz.injection.enventry.Widget</env-entry-value>\n </env-entry>\n <env-entry>\n <description>The name was explicitly set in the annotation so the classname prefix isn't required</description>\n <env-entry-name>date</env-entry-name>\n <env-entry-type>java.lang.Long</env-entry-type>\n <env-entry-value>123456789</env-entry-value>\n </env-entry>\n </session>\n </enterprise-beans>\n </ejb-jar>\n\n\n### Using the @Resource 'name' attribute\n\nNote that `date` was referenced by `name` as:\n\n @Resource(name = \"date\")\n private long date;\n\nWhen the `@Resource(name)` is used, you do not need to specify the full class name of the bean and can do it briefly like so:\n\n <env-entry>\n <description>The name was explicitly set in the annotation so the classname prefix isn't required</description>\n <env-entry-name>date</env-entry-name>\n <env-entry-type>java.lang.Long</env-entry-type>\n <env-entry-value>123456789</env-entry-value>\n </env-entry>\n\nConversly, `color` was not referenced by `name`\n\n @Resource\n private String color;\n\nWhen something is not referenced by `name` in the `@Resource` annotation a default name is created. The format is essentially this:\n\n bean.getClass() + \"/\" + field.getName()\n\nSo the default `name` of the above `color` property ends up being `org.superbiz.injection.enventry.Configuration/color`. This is the name\nwe must use when we attempt to decalre a value for it in xml.\n\n <env-entry>\n <env-entry-name>org.superbiz.injection.enventry.Configuration/color</env-entry-name>\n <env-entry-type>java.lang.String</env-entry-type>\n <env-entry-value>orange</env-entry-value>\n </env-entry>\n\n### @Resource and Enum (Enumerations)\n\nThe `shape` field is actually a custom Java Enum type\n\n package org.superbiz.injection.enventry;\n\n public enum Shape {\n \n CIRCLE,\n TRIANGLE,\n SQUARE\n }\n\nAs of Java EE 6, java.lang.Enum types are allowed as `<env-entry>` items. Declaring one in xml is done using the actual enum's class name like so:\n\n <env-entry>\n <env-entry-name>org.superbiz.injection.enventry.Configuration/shape</env-entry-name>\n <env-entry-type>org.superbiz.injection.enventry.Shape</env-entry-type>\n <env-entry-value>TRIANGLE</env-entry-value>\n </env-entry>\n\nDo not use `<env-entry-type>java.lang.Enum</env-entry-type>` or it will not work!\n\n## ConfigurationTest\n\n package org.superbiz.injection.enventry;\n \n import junit.framework.TestCase;\n \n import javax.ejb.embeddable.EJBContainer;\n import javax.naming.Context;\n import java.util.Date;\n \n public class ConfigurationTest extends TestCase {\n \n \n public void test() throws Exception {\n final Context context = EJBContainer.createEJBContainer().getContext();\n \n final Configuration configuration = (Configuration) context.lookup(\"java:global/injection-of-env-entry/Configuration\");\n \n assertEquals(\"orange\", configuration.getColor());\n \n assertEquals(Shape.TRIANGLE, configuration.getShape());\n \n assertEquals(Widget.class, configuration.getStrategy());\n \n assertEquals(new Date(123456789), configuration.getDate());\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.injection.enventry.ConfigurationTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/injection-of-env-entry\n INFO - openejb.base = /Users/dblevins/examples/injection-of-env-entry\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/injection-of-env-entry/target/classes\n INFO - Beginning load: /Users/dblevins/examples/injection-of-env-entry/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/injection-of-env-entry\n WARN - Method 'lookup' is not available for 'javax.annotation.Resource'. Probably using an older Runtime.\n INFO - Configuring Service(id=Default Singleton Container, type=Container, provider-id=Default Singleton Container)\n INFO - Auto-creating a container for bean Configuration: Container(type=SINGLETON, id=Default Singleton Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.injection.enventry.ConfigurationTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Enterprise application \"/Users/dblevins/examples/injection-of-env-entry\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/injection-of-env-entry\n INFO - Jndi(name=\"java:global/injection-of-env-entry/Configuration!org.superbiz.injection.enventry.Configuration\")\n INFO - Jndi(name=\"java:global/injection-of-env-entry/Configuration\")\n INFO - Jndi(name=\"java:global/EjbModule1355224018/org.superbiz.injection.enventry.ConfigurationTest!org.superbiz.injection.enventry.ConfigurationTest\")\n INFO - Jndi(name=\"java:global/EjbModule1355224018/org.superbiz.injection.enventry.ConfigurationTest\")\n INFO - Created Ejb(deployment-id=org.superbiz.injection.enventry.ConfigurationTest, ejb-name=org.superbiz.injection.enventry.ConfigurationTest, container=Default Managed Container)\n INFO - Created Ejb(deployment-id=Configuration, ejb-name=Configuration, container=Default Singleton Container)\n INFO - Started Ejb(deployment-id=org.superbiz.injection.enventry.ConfigurationTest, ejb-name=org.superbiz.injection.enventry.ConfigurationTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=Configuration, ejb-name=Configuration, container=Default Singleton Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/injection-of-env-entry)\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.664 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/injection-of-env-entry"
},
{
"name":"injection-of-entitymanager",
"readme":"Title: Injection Of Entitymanager\n\nThis example shows use of `@PersistenceContext` to have an `EntityManager` with an\n`EXTENDED` persistence context injected into a `@Stateful bean`. A JPA\n`@Entity` bean is used with the `EntityManager` to create, persist and merge\ndata to a database.\n\n## Creating the JPA Entity\n\nThe entity itself is simply a pojo annotated with `@Entity`. We create one called `Movie` which we can use to hold movie records.\n\n package org.superbiz.injection.jpa;\n\n import javax.persistence.Entity;\n \n @Entity\n public class Movie {\n\n @Id @GeneratedValue\n private long id;\n\n private String director;\n private String title;\n private int year;\n\n public Movie() {\n }\n\n public long getId() {\n return id;\n }\n\n public void setId(long id) {\n this.id = id;\n }\n\n public Movie(String director, String title, int year) {\n this.director = director;\n this.title = title;\n this.year = year;\n }\n\n public String getDirector() {\n return director;\n }\n\n public void setDirector(String director) {\n this.director = director;\n }\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public int getYear() {\n return year;\n }\n\n public void setYear(int year) {\n this.year = year;\n }\n }\n\n## Configure the EntityManager via a persistence.xml file\n\nThe above `Movie` entity can be created, removed, updated or deleted via an `EntityManager` object. The `EntityManager` itself is\nconfigured via a `META-INF/persistence.xml` file that is placed in the same jar as the `Movie` entity.\n\n <persistence xmlns=\"http://java.sun.com/xml/ns/persistence\" version=\"1.0\">\n\n <persistence-unit name=\"movie-unit\">\n <jta-data-source>movieDatabase</jta-data-source>\n <non-jta-data-source>movieDatabaseUnmanaged</non-jta-data-source>\n <class>org.superbiz.injection.jpa.Movie</class>\n\n <properties>\n <property name=\"openjpa.jdbc.SynchronizeMappings\" value=\"buildSchema(ForeignKeys=true)\"/>\n </properties>\n </persistence-unit>\n </persistence>\n\nNotice that the `Movie` entity is listed via a `<class>` element. This is not required, but can help when testing or when the\n`Movie` class is located in a different jar than the jar containing the `persistence.xml` file.\n\n## Injection via @PersistenceContext\n\nThe `EntityManager` itself is created by the container using the information in the `persistence.xml`, so to use it at\nruntime, we simply need to request it be injected into one of our components. We do this via `@PersistenceContext`\n\nThe `@PersistenceContext` annotation can be used on any CDI bean, EJB, Servlet, Servlet Listener, Servlet Filter, or JSF ManagedBean. If you don't use an EJB you will need to use a `UserTransaction` begin and commit transactions manually. A transaction is required for any of the create, update or delete methods of the EntityManager to work.\n\n package org.superbiz.injection.jpa;\n\n import javax.ejb.Stateful;\n import javax.persistence.EntityManager;\n import javax.persistence.PersistenceContext;\n import javax.persistence.PersistenceContextType;\n import javax.persistence.Query;\n import java.util.List;\n \n @Stateful\n public class Movies {\n \n @PersistenceContext(unitName = \"movie-unit\", type = PersistenceContextType.EXTENDED)\n private EntityManager entityManager;\n \n public void addMovie(Movie movie) throws Exception {\n entityManager.persist(movie);\n }\n \n public void deleteMovie(Movie movie) throws Exception {\n entityManager.remove(movie);\n }\n \n public List<Movie> getMovies() throws Exception {\n Query query = entityManager.createQuery(\"SELECT m from Movie as m\");\n return query.getResultList();\n }\n }\n\nThis particular `EntityManager` is injected as an `EXTENDED` persistence context, which simply means that the `EntityManager`\nis created when the `@Stateful` bean is created and destroyed when the `@Stateful` bean is destroyed. Simply put, the\ndata in the `EntityManager` is cached for the lifetime of the `@Stateful` bean.\n\nThe use of `EXTENDED` persistence contexts is **only** available to `@Stateful` beans. See the [JPA Concepts](../../jpa-concepts.html) page for an high level explanation of what a \"persistence context\" really is and how it is significant to JPA.\n\n## MoviesTest\n\nTesting JPA is quite easy, we can simply use the `EJBContainer` API to create a container in our test case.\n\n package org.superbiz.injection.jpa;\n \n import junit.framework.TestCase;\n \n import javax.ejb.embeddable.EJBContainer;\n import javax.naming.Context;\n import java.util.List;\n import java.util.Properties;\n \n //START SNIPPET: code\n public class MoviesTest extends TestCase {\n \n public void test() throws Exception {\n \n final Properties p = new Properties();\n p.put(\"movieDatabase\", \"new://Resource?type=DataSource\");\n p.put(\"movieDatabase.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"movieDatabase.JdbcUrl\", \"jdbc:hsqldb:mem:moviedb\");\n \n final Context context = EJBContainer.createEJBContainer(p).getContext();\n \n Movies movies = (Movies) context.lookup(\"java:global/injection-of-entitymanager/Movies\");\n \n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n movies.addMovie(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n movies.addMovie(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n \n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n \n for (Movie movie : list) {\n movies.deleteMovie(movie);\n }\n \n assertEquals(\"Movies.getMovies()\", 0, movies.getMovies().size());\n }\n }\n\n# Running\n\nWhen we run our test case we should see output similar to the following.\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.injection.jpa.MoviesTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/injection-of-entitymanager\n INFO - openejb.base = /Users/dblevins/examples/injection-of-entitymanager\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/injection-of-entitymanager/target/classes\n INFO - Beginning load: /Users/dblevins/examples/injection-of-entitymanager/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/injection-of-entitymanager\n INFO - Configuring Service(id=Default Stateful Container, type=Container, provider-id=Default Stateful Container)\n INFO - Auto-creating a container for bean Movies: Container(type=STATEFUL, id=Default Stateful Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.injection.jpa.MoviesTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring PersistenceUnit(name=movie-unit)\n INFO - Auto-creating a Resource with id 'movieDatabaseNonJta' of type 'DataSource for 'movie-unit'.\n INFO - Configuring Service(id=movieDatabaseNonJta, type=Resource, provider-id=movieDatabase)\n INFO - Adjusting PersistenceUnit movie-unit <non-jta-data-source> to Resource ID 'movieDatabaseNonJta' from 'movieDatabaseUnmanaged'\n INFO - Enterprise application \"/Users/dblevins/examples/injection-of-entitymanager\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/injection-of-entitymanager\n INFO - PersistenceUnit(name=movie-unit, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 462ms\n INFO - Jndi(name=\"java:global/injection-of-entitymanager/Movies!org.superbiz.injection.jpa.Movies\")\n INFO - Jndi(name=\"java:global/injection-of-entitymanager/Movies\")\n INFO - Jndi(name=\"java:global/EjbModule1461341140/org.superbiz.injection.jpa.MoviesTest!org.superbiz.injection.jpa.MoviesTest\")\n INFO - Jndi(name=\"java:global/EjbModule1461341140/org.superbiz.injection.jpa.MoviesTest\")\n INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Created Ejb(deployment-id=org.superbiz.injection.jpa.MoviesTest, ejb-name=org.superbiz.injection.jpa.MoviesTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Started Ejb(deployment-id=org.superbiz.injection.jpa.MoviesTest, ejb-name=org.superbiz.injection.jpa.MoviesTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/injection-of-entitymanager)\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.301 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/injection-of-entitymanager"
},
{
"name":"injection-of-datasource",
"readme":"Title: Injection Of Datasource\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## Movie\n\n package org.superbiz.injection;\n \n /**\n * @version $Revision: 607077 $ $Date: 2007-12-27 06:55:23 -0800 (Thu, 27 Dec 2007) $\n */\n public class Movie {\n private String director;\n private String title;\n private int year;\n \n public Movie() {\n }\n \n public Movie(String director, String title, int year) {\n this.director = director;\n this.title = title;\n this.year = year;\n }\n \n public String getDirector() {\n return director;\n }\n \n public void setDirector(String director) {\n this.director = director;\n }\n \n public String getTitle() {\n return title;\n }\n \n public void setTitle(String title) {\n this.title = title;\n }\n \n public int getYear() {\n return year;\n }\n \n public void setYear(int year) {\n this.year = year;\n }\n \n }\n\n## Movies\n\n package org.superbiz.injection;\n \n import javax.annotation.PostConstruct;\n import javax.annotation.Resource;\n import javax.ejb.Stateful;\n import javax.sql.DataSource;\n import java.sql.Connection;\n import java.sql.PreparedStatement;\n import java.sql.ResultSet;\n import java.util.ArrayList;\n import java.util.List;\n \n @Stateful\n public class Movies {\n \n /**\n * The field name \"movieDatabase\" matches the DataSource we\n * configure in the TestCase via :\n * p.put(\"movieDatabase\", \"new://Resource?type=DataSource\");\n * <p/>\n * This would also match an equivalent delcaration in an openejb.xml:\n * <Resource id=\"movieDatabase\" type=\"DataSource\"/>\n * <p/>\n * If you'd like the freedom to change the field name without\n * impact on your configuration you can set the \"name\" attribute\n * of the @Resource annotation to \"movieDatabase\" instead.\n */\n @Resource\n private DataSource movieDatabase;\n \n @PostConstruct\n private void construct() throws Exception {\n Connection connection = movieDatabase.getConnection();\n try {\n PreparedStatement stmt = connection.prepareStatement(\"CREATE TABLE movie ( director VARCHAR(255), title VARCHAR(255), year integer)\");\n stmt.execute();\n } finally {\n connection.close();\n }\n }\n \n public void addMovie(Movie movie) throws Exception {\n Connection conn = movieDatabase.getConnection();\n try {\n PreparedStatement sql = conn.prepareStatement(\"INSERT into movie (director, title, year) values (?, ?, ?)\");\n sql.setString(1, movie.getDirector());\n sql.setString(2, movie.getTitle());\n sql.setInt(3, movie.getYear());\n sql.execute();\n } finally {\n conn.close();\n }\n }\n \n public void deleteMovie(Movie movie) throws Exception {\n Connection conn = movieDatabase.getConnection();\n try {\n PreparedStatement sql = conn.prepareStatement(\"DELETE from movie where director = ? AND title = ? AND year = ?\");\n sql.setString(1, movie.getDirector());\n sql.setString(2, movie.getTitle());\n sql.setInt(3, movie.getYear());\n sql.execute();\n } finally {\n conn.close();\n }\n }\n \n public List<Movie> getMovies() throws Exception {\n ArrayList<Movie> movies = new ArrayList<Movie>();\n Connection conn = movieDatabase.getConnection();\n try {\n PreparedStatement sql = conn.prepareStatement(\"SELECT director, title, year from movie\");\n ResultSet set = sql.executeQuery();\n while (set.next()) {\n Movie movie = new Movie();\n movie.setDirector(set.getString(\"director\"));\n movie.setTitle(set.getString(\"title\"));\n movie.setYear(set.getInt(\"year\"));\n movies.add(movie);\n }\n } finally {\n conn.close();\n }\n return movies;\n }\n }\n\n## MoviesTest\n\n package org.superbiz.injection;\n \n import junit.framework.TestCase;\n \n import javax.ejb.embeddable.EJBContainer;\n import javax.naming.Context;\n import java.util.List;\n import java.util.Properties;\n \n //START SNIPPET: code\n public class MoviesTest extends TestCase {\n \n public void test() throws Exception {\n \n Properties p = new Properties();\n p.put(\"movieDatabase\", \"new://Resource?type=DataSource\");\n p.put(\"movieDatabase.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"movieDatabase.JdbcUrl\", \"jdbc:hsqldb:mem:moviedb\");\n \n Context context = EJBContainer.createEJBContainer(p).getContext();\n \n Movies movies = (Movies) context.lookup(\"java:global/injection-of-datasource/Movies\");\n \n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n movies.addMovie(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n movies.addMovie(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n \n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n \n for (Movie movie : list) {\n movies.deleteMovie(movie);\n }\n \n assertEquals(\"Movies.getMovies()\", 0, movies.getMovies().size());\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.injection.MoviesTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/injection-of-datasource\n INFO - openejb.base = /Users/dblevins/examples/injection-of-datasource\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/injection-of-datasource/target/classes\n INFO - Beginning load: /Users/dblevins/examples/injection-of-datasource/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/injection-of-datasource\n WARN - Method 'lookup' is not available for 'javax.annotation.Resource'. Probably using an older Runtime.\n INFO - Configuring Service(id=Default Stateful Container, type=Container, provider-id=Default Stateful Container)\n INFO - Auto-creating a container for bean Movies: Container(type=STATEFUL, id=Default Stateful Container)\n INFO - Auto-linking resource-ref 'java:comp/env/org.superbiz.injection.Movies/movieDatabase' in bean Movies to Resource(id=movieDatabase)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.injection.MoviesTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Enterprise application \"/Users/dblevins/examples/injection-of-datasource\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/injection-of-datasource\n INFO - Jndi(name=\"java:global/injection-of-datasource/Movies!org.superbiz.injection.Movies\")\n INFO - Jndi(name=\"java:global/injection-of-datasource/Movies\")\n INFO - Jndi(name=\"java:global/EjbModule1508028338/org.superbiz.injection.MoviesTest!org.superbiz.injection.MoviesTest\")\n INFO - Jndi(name=\"java:global/EjbModule1508028338/org.superbiz.injection.MoviesTest\")\n INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Created Ejb(deployment-id=org.superbiz.injection.MoviesTest, ejb-name=org.superbiz.injection.MoviesTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Started Ejb(deployment-id=org.superbiz.injection.MoviesTest, ejb-name=org.superbiz.injection.MoviesTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/injection-of-datasource)\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.276 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/injection-of-datasource"
},
{
"name":"injection-of-ejbs",
"readme":"Title: Injection Of Ejbs\n\nThis example shows how to use the @EJB annotation on a bean class to refer to other beans.\n\nThis functionality is often referred as dependency injection (see\nhttp://www.martinfowler.com/articles/injection.html), and has been recently introduced in\nJava EE 5.\n\nIn this particular example, we will create two session stateless beans\n\n * a DataStore session bean\n * a DataReader session bean\n\nThe DataReader bean uses the DataStore to retrieve some informations, and\nwe will see how we can, inside the DataReader bean, get a reference to the\nDataStore bean using the @EJB annotation, thus avoiding the use of the\nJNDI API.\n\n## DataReader\n\n package org.superbiz.injection;\n \n import javax.ejb.EJB;\n import javax.ejb.Stateless;\n \n /**\n * This is an EJB 3.1 style pojo stateless session bean\n * Every stateless session bean implementation must be annotated\n * using the annotation @Stateless\n * This EJB has 2 business interfaces: DataReaderRemote, a remote business\n * interface, and DataReaderLocal, a local business interface\n * <p/>\n * The instance variables 'dataStoreRemote' is annotated with the @EJB annotation:\n * this means that the application server, at runtime, will inject in this instance\n * variable a reference to the EJB DataStoreRemote\n * <p/>\n * The instance variables 'dataStoreLocal' is annotated with the @EJB annotation:\n * this means that the application server, at runtime, will inject in this instance\n * variable a reference to the EJB DataStoreLocal\n */\n //START SNIPPET: code\n @Stateless\n public class DataReader {\n \n @EJB\n private DataStoreRemote dataStoreRemote;\n @EJB\n private DataStoreLocal dataStoreLocal;\n @EJB\n private DataStore dataStore;\n \n public String readDataFromLocalStore() {\n return \"LOCAL:\" + dataStoreLocal.getData();\n }\n \n public String readDataFromLocalBeanStore() {\n return \"LOCALBEAN:\" + dataStore.getData();\n }\n \n public String readDataFromRemoteStore() {\n return \"REMOTE:\" + dataStoreRemote.getData();\n }\n }\n\n## DataStore\n\n package org.superbiz.injection;\n \n import javax.ejb.LocalBean;\n import javax.ejb.Stateless;\n \n /**\n * This is an EJB 3 style pojo stateless session bean\n * Every stateless session bean implementation must be annotated\n * using the annotation @Stateless\n * This EJB has 2 business interfaces: DataStoreRemote, a remote business\n * interface, and DataStoreLocal, a local business interface\n */\n //START SNIPPET: code\n @Stateless\n @LocalBean\n public class DataStore implements DataStoreLocal, DataStoreRemote {\n \n public String getData() {\n return \"42\";\n }\n }\n\n## DataStoreLocal\n\n package org.superbiz.injection;\n \n import javax.ejb.Local;\n \n /**\n * This is an EJB 3 local business interface\n * A local business interface may be annotated with the @Local\n * annotation, but it's optional. A business interface which is\n * not annotated with @Local or @Remote is assumed to be Local\n */\n //START SNIPPET: code\n @Local\n public interface DataStoreLocal {\n \n public String getData();\n }\n\n## DataStoreRemote\n\n package org.superbiz.injection;\n \n import javax.ejb.Remote;\n \n /**\n * This is an EJB 3 remote business interface\n * A remote business interface must be annotated with the @Remote\n * annotation\n */\n //START SNIPPET: code\n @Remote\n public interface DataStoreRemote {\n \n public String getData();\n }\n\n## EjbDependencyTest\n\n package org.superbiz.injection;\n \n import junit.framework.TestCase;\n \n import javax.ejb.embeddable.EJBContainer;\n import javax.naming.Context;\n \n /**\n * A test case for DataReaderImpl ejb, testing both the remote and local interface\n */\n //START SNIPPET: code\n public class EjbDependencyTest extends TestCase {\n \n public void test() throws Exception {\n final Context context = EJBContainer.createEJBContainer().getContext();\n \n DataReader dataReader = (DataReader) context.lookup(\"java:global/injection-of-ejbs/DataReader\");\n \n assertNotNull(dataReader);\n \n assertEquals(\"LOCAL:42\", dataReader.readDataFromLocalStore());\n assertEquals(\"REMOTE:42\", dataReader.readDataFromRemoteStore());\n assertEquals(\"LOCALBEAN:42\", dataReader.readDataFromLocalBeanStore());\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.injection.EjbDependencyTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/injection-of-ejbs\n INFO - openejb.base = /Users/dblevins/examples/injection-of-ejbs\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/injection-of-ejbs/target/classes\n INFO - Beginning load: /Users/dblevins/examples/injection-of-ejbs/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/injection-of-ejbs\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean DataReader: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.injection.EjbDependencyTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Enterprise application \"/Users/dblevins/examples/injection-of-ejbs\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/injection-of-ejbs\n INFO - Jndi(name=\"java:global/injection-of-ejbs/DataReader!org.superbiz.injection.DataReader\")\n INFO - Jndi(name=\"java:global/injection-of-ejbs/DataReader\")\n INFO - Jndi(name=\"java:global/injection-of-ejbs/DataStore!org.superbiz.injection.DataStore\")\n INFO - Jndi(name=\"java:global/injection-of-ejbs/DataStore!org.superbiz.injection.DataStoreLocal\")\n INFO - Jndi(name=\"java:global/injection-of-ejbs/DataStore!org.superbiz.injection.DataStoreRemote\")\n INFO - Jndi(name=\"java:global/injection-of-ejbs/DataStore\")\n INFO - Jndi(name=\"java:global/EjbModule355598874/org.superbiz.injection.EjbDependencyTest!org.superbiz.injection.EjbDependencyTest\")\n INFO - Jndi(name=\"java:global/EjbModule355598874/org.superbiz.injection.EjbDependencyTest\")\n INFO - Created Ejb(deployment-id=DataReader, ejb-name=DataReader, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=DataStore, ejb-name=DataStore, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=org.superbiz.injection.EjbDependencyTest, ejb-name=org.superbiz.injection.EjbDependencyTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=DataReader, ejb-name=DataReader, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=DataStore, ejb-name=DataStore, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=org.superbiz.injection.EjbDependencyTest, ejb-name=org.superbiz.injection.EjbDependencyTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/injection-of-ejbs)\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.225 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/injection-of-ejbs"
},
{
"name":"lookup-of-ejbs",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/lookup-of-ejbs"
},
{
"name":"lookup-of-ejbs-with-descriptor",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/lookup-of-ejbs-with-descriptor"
}
],
"on":[
{
"name":"rest-on-ejb",
"readme":"Title: REST on EJB\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## User\n\n package org.superbiz.rest;\n \n import javax.persistence.Entity;\n import javax.persistence.GeneratedValue;\n import javax.persistence.Id;\n import javax.persistence.NamedQueries;\n import javax.persistence.NamedQuery;\n import javax.xml.bind.annotation.XmlRootElement;\n \n @Entity\n @NamedQueries({\n @NamedQuery(name = \"user.list\", query = \"select u from User u\")\n }\n\n## UserService\n\n package org.superbiz.rest;\n \n import javax.ejb.Lock;\n import javax.ejb.LockType;\n import javax.ejb.Singleton;\n import javax.persistence.EntityManager;\n import javax.persistence.PersistenceContext;\n import javax.ws.rs.DELETE;\n import javax.ws.rs.DefaultValue;\n import javax.ws.rs.GET;\n import javax.ws.rs.POST;\n import javax.ws.rs.PUT;\n import javax.ws.rs.Path;\n import javax.ws.rs.PathParam;\n import javax.ws.rs.Produces;\n import javax.ws.rs.QueryParam;\n import javax.ws.rs.core.MediaType;\n import javax.ws.rs.core.Response;\n import java.util.ArrayList;\n import java.util.List;\n \n /**\n * Outputs are copied because of the enhancement of OpenJPA.\n *\n */\n @Singleton\n @Lock(LockType.WRITE)\n @Path(\"/user\")\n @Produces(MediaType.APPLICATION_XML)\n public class UserService {\n @PersistenceContext\n private EntityManager em;\n \n @Path(\"/create\")\n @PUT\n public User create(@QueryParam(\"name\") String name,\n @QueryParam(\"pwd\") String pwd,\n @QueryParam(\"mail\") String mail) {\n User user = new User();\n user.setFullname(name);\n user.setPassword(pwd);\n user.setEmail(mail);\n em.persist(user);\n return user;\n }\n \n @Path(\"/list\")\n @GET\n public List<User> list(@QueryParam(\"first\") @DefaultValue(\"0\") int first,\n @QueryParam(\"max\") @DefaultValue(\"20\") int max) {\n List<User> users = new ArrayList<User>();\n List<User> found = em.createNamedQuery(\"user.list\", User.class).setFirstResult(first).setMaxResults(max).getResultList();\n for (User u : found) {\n users.add(u.copy());\n }\n return users;\n }\n \n @Path(\"/show/{id}\")\n @GET\n public User find(@PathParam(\"id\") long id) {\n User user = em.find(User.class, id);\n if (user == null) {\n return null;\n }\n return user.copy();\n }\n \n @Path(\"/delete/{id}\")\n @DELETE\n public void delete(@PathParam(\"id\") long id) {\n User user = em.find(User.class, id);\n if (user != null) {\n em.remove(user);\n }\n }\n \n @Path(\"/update/{id}\")\n @POST\n public Response update(@PathParam(\"id\") long id,\n @QueryParam(\"name\") String name,\n @QueryParam(\"pwd\") String pwd,\n @QueryParam(\"mail\") String mail) {\n User user = em.find(User.class, id);\n if (user == null) {\n throw new IllegalArgumentException(\"user id \" + id + \" not found\");\n }\n \n user.setFullname(name);\n user.setPassword(pwd);\n user.setEmail(mail);\n em.merge(user);\n \n return Response.ok(user.copy()).build();\n }\n }\n\n## persistence.xml\n\n <persistence version=\"2.0\"\n xmlns=\"http://java.sun.com/xml/ns/persistence\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\n http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd\">\n <persistence-unit name=\"user\">\n <jta-data-source>My DataSource</jta-data-source>\n <non-jta-data-source>My Unmanaged DataSource</non-jta-data-source>\n <class>org.superbiz.rest.User</class>\n <properties>\n <property name=\"openjpa.jdbc.SynchronizeMappings\" value=\"buildSchema(ForeignKeys=true)\"/>\n </properties>\n </persistence-unit>\n </persistence>\n\n## UserServiceTest\n\n package org.superbiz.rest;\n \n import org.apache.cxf.jaxrs.client.WebClient;\n import org.apache.openejb.OpenEjbContainer;\n import org.junit.AfterClass;\n import org.junit.BeforeClass;\n import org.junit.Test;\n \n import javax.ejb.embeddable.EJBContainer;\n import javax.naming.Context;\n import javax.naming.NamingException;\n import javax.ws.rs.core.Response;\n import javax.xml.bind.JAXBContext;\n import javax.xml.bind.Unmarshaller;\n import java.io.InputStream;\n import java.util.ArrayList;\n import java.util.List;\n import java.util.Properties;\n \n import static junit.framework.Assert.assertEquals;\n import static junit.framework.Assert.assertNull;\n import static junit.framework.Assert.fail;\n \n public class UserServiceTest {\n private static Context context;\n private static UserService service;\n private static List<User> users = new ArrayList<User>();\n \n @BeforeClass\n public static void start() throws NamingException {\n Properties properties = new Properties();\n properties.setProperty(OpenEjbContainer.OPENEJB_EMBEDDED_REMOTABLE, \"true\");\n context = EJBContainer.createEJBContainer(properties).getContext();\n \n // create some records\n service = (UserService) context.lookup(\"java:global/rest-on-ejb/UserService\");\n users.add(service.create(\"foo\", \"foopwd\", \"foo@foo.com\"));\n users.add(service.create(\"bar\", \"barpwd\", \"bar@bar.com\"));\n }\n \n @AfterClass\n public static void close() throws NamingException {\n if (context != null) {\n context.close();\n }\n }\n \n @Test\n public void create() {\n int expected = service.list(0, 100).size() + 1;\n Response response = WebClient.create(\"http://localhost:4204\")\n .path(\"/user/create\")\n .query(\"name\", \"dummy\")\n .query(\"pwd\", \"unbreakable\")\n .query(\"mail\", \"foo@bar.fr\")\n .put(null);\n List<User> list = service.list(0, 100);\n for (User u : list) {\n if (!users.contains(u)) {\n service.delete(u.getId());\n return;\n }\n }\n fail(\"user was not added\");\n }\n \n @Test\n public void delete() throws Exception {\n User user = service.create(\"todelete\", \"dontforget\", \"delete@me.com\");\n \n WebClient.create(\"http://localhost:4204\").path(\"/user/delete/\" + user.getId()).delete();\n \n user = service.find(user.getId());\n assertNull(user);\n }\n \n @Test\n public void show() {\n User user = WebClient.create(\"http://localhost:4204\")\n .path(\"/user/show/\" + users.iterator().next().getId())\n .get(User.class);\n assertEquals(\"foo\", user.getFullname());\n assertEquals(\"foopwd\", user.getPassword());\n assertEquals(\"foo@foo.com\", user.getEmail());\n }\n \n @Test\n public void list() throws Exception {\n String users = WebClient.create(\"http://localhost:4204\")\n .path(\"/user/list\")\n .get(String.class);\n assertEquals(\n \"<users>\" +\n \"<user>\" +\n \"<email>foo@foo.com</email>\" +\n \"<fullname>foo</fullname>\" +\n \"<id>1</id>\" +\n \"<password>foopwd</password>\" +\n \"</user>\" +\n \"<user>\" +\n \"<email>bar@bar.com</email>\" +\n \"<fullname>bar</fullname>\" +\n \"<id>2</id>\" +\n \"<password>barpwd</password>\" +\n \"</user>\" +\n \"</users>\", users);\n }\n \n @Test\n public void update() throws Exception {\n User created = service.create(\"name\", \"pwd\", \"mail\");\n Response response = WebClient.create(\"http://localhost:4204\")\n .path(\"/user/update/\" + created.getId())\n .query(\"name\", \"corrected\")\n .query(\"pwd\", \"userpwd\")\n .query(\"mail\", \"it@is.ok\")\n .post(null);\n \n JAXBContext ctx = JAXBContext.newInstance(User.class);\n Unmarshaller unmarshaller = ctx.createUnmarshaller();\n User modified = (User) unmarshaller.unmarshal(InputStream.class.cast(response.getEntity()));\n \n assertEquals(\"corrected\", modified.getFullname());\n assertEquals(\"userpwd\", modified.getPassword());\n assertEquals(\"it@is.ok\", modified.getEmail());\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.rest.UserServiceTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/rest-on-ejb\n INFO - openejb.base = /Users/dblevins/examples/rest-on-ejb\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/rest-on-ejb/target/classes\n INFO - Beginning load: /Users/dblevins/examples/rest-on-ejb/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/rest-on-ejb\n INFO - Configuring Service(id=Default Singleton Container, type=Container, provider-id=Default Singleton Container)\n INFO - Auto-creating a container for bean UserService: Container(type=SINGLETON, id=Default Singleton Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.rest.UserServiceTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring PersistenceUnit(name=user)\n INFO - Configuring Service(id=Default JDBC Database, type=Resource, provider-id=Default JDBC Database)\n INFO - Auto-creating a Resource with id 'Default JDBC Database' of type 'DataSource for 'user'.\n INFO - Configuring Service(id=Default Unmanaged JDBC Database, type=Resource, provider-id=Default Unmanaged JDBC Database)\n INFO - Auto-creating a Resource with id 'Default Unmanaged JDBC Database' of type 'DataSource for 'user'.\n INFO - Adjusting PersistenceUnit user <jta-data-source> to Resource ID 'Default JDBC Database' from 'My DataSource'\n INFO - Adjusting PersistenceUnit user <non-jta-data-source> to Resource ID 'Default Unmanaged JDBC Database' from 'My Unmanaged DataSource'\n INFO - Enterprise application \"/Users/dblevins/examples/rest-on-ejb\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/rest-on-ejb\n INFO - PersistenceUnit(name=user, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 407ms\n INFO - Jndi(name=\"java:global/rest-on-ejb/UserService!org.superbiz.rest.UserService\")\n INFO - Jndi(name=\"java:global/rest-on-ejb/UserService\")\n INFO - Jndi(name=\"java:global/EjbModule1789767313/org.superbiz.rest.UserServiceTest!org.superbiz.rest.UserServiceTest\")\n INFO - Jndi(name=\"java:global/EjbModule1789767313/org.superbiz.rest.UserServiceTest\")\n INFO - Created Ejb(deployment-id=org.superbiz.rest.UserServiceTest, ejb-name=org.superbiz.rest.UserServiceTest, container=Default Managed Container)\n INFO - Created Ejb(deployment-id=UserService, ejb-name=UserService, container=Default Singleton Container)\n INFO - Started Ejb(deployment-id=org.superbiz.rest.UserServiceTest, ejb-name=org.superbiz.rest.UserServiceTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=UserService, ejb-name=UserService, container=Default Singleton Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/rest-on-ejb)\n INFO - Initializing network services\n INFO - Creating ServerService(id=httpejbd)\n INFO - Creating ServerService(id=admin)\n INFO - Creating ServerService(id=ejbd)\n INFO - Creating ServerService(id=ejbds)\n INFO - Creating ServerService(id=cxf-rs)\n INFO - Initializing network services\n ** Starting Services **\n NAME IP PORT \n httpejbd 127.0.0.1 4204 \n admin thread 127.0.0.1 4200 \n ejbd 127.0.0.1 4201 \n ejbd 127.0.0.1 4203 \n -------\n Ready!\n WARN - Query \"select u from User u\" is removed from cache excluded permanently. Query \"select u from User u\" is not cached because it uses pagination..\n Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.102 sec\n \n Results :\n \n Tests run: 5, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/rest-on-ejb"
}
],
"parent":[
{
"name":"polling-parent",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/polling-parent"
}
],
"password":[
{
"name":"datasource-ciphered-password",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/datasource-ciphered-password"
}
],
"persistence":[
{
"name":"reload-persistence-unit-properties",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/reload-persistence-unit-properties"
},
{
"name":"persistence-fragment",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/persistence-fragment"
}
],
"pojo":[
{
"name":"pojo-webservice",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/pojo-webservice"
}
],
"polling":[
{
"name":"polling-parent",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/polling-parent"
}
],
"postconstruct":[
{
"name":"async-postconstruct",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/async-postconstruct"
}
],
"produces":[
{
"name":"cdi-produces-disposes",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/cdi-produces-disposes"
},
{
"name":"cdi-produces-field",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/cdi-produces-field"
}
],
"projectstage":[
{
"name":"projectstage-demo",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/projectstage-demo"
}
],
"properties":[
{
"name":"reload-persistence-unit-properties",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/reload-persistence-unit-properties"
}
],
"provider":[
{
"name":"multi-jpa-provider-testing",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/multi-jpa-provider-testing"
}
],
"proxy":[
{
"name":"spring-data-proxy",
"readme":"# Spring Data sample #\n\nThis example uses OpenEJB hooks to replace an EJB implementation by a proxy\nto uses Spring Data in your preferred container.\n\nIt is pretty simple: simply provide to OpenEJB an InvocationHandler using delegating to spring data\nand that's it!\n\nIt is what is done in org.superbiz.dynamic.SpringDataProxy.\n\nIt contains a little trick: even if it is not annotated \"implementingInterfaceClass\" attribute\nis injected by OpenEJB to get the interface.\n\nThen we simply create the Spring Data repository and delegate to it.\n",
"url":"https://github.com/apache/tomee/tree/master/examples/spring-data-proxy"
},
{
"name":"spring-data-proxy-meta",
"readme":"# Spring Data With Meta sample #\n\nThis example simply simplifies the usage of spring-data sample\nproviding a meta annotation @SpringRepository to do all the dynamic procy EJB job.\n\nIt replaces @Proxy and @Stateless annotations.\n\nIsn't it more comfortable?\n\nTo do it we defined a meta annotation \"Metatype\" and used it.\n\nThe proxy implementation is the same than for spring-data sample.\n",
"url":"https://github.com/apache/tomee/tree/master/examples/spring-data-proxy-meta"
},
{
"name":"dynamic-proxy-to-access-mbean",
"readme":"Title: dynamic-proxy-to-access-mbean\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## Example\n\nAcessing MBean is something simple through the JMX API but it is often technical and not very interesting.\n\nThis example simplify this work simply doing it generically in a proxy.\n\nSo from an user side you simple declare an interface to access your MBeans.\n\nNote: the example implementation uses a local MBeanServer but enhancing the example API\nit is easy to imagine a remote connection with user/password if needed.\n\n## ObjectName API (annotation)\n\nSimply an annotation to get the object\n\n package org.superbiz.dynamic.mbean;\n\n import java.lang.annotation.Retention;\n import java.lang.annotation.Target;\n\n import static java.lang.annotation.ElementType.TYPE;\n import static java.lang.annotation.ElementType.METHOD;\n import static java.lang.annotation.RetentionPolicy.RUNTIME;\n\n @Target({TYPE, METHOD})\n @Retention(RUNTIME)\n public @interface ObjectName {\n String value();\n\n // for remote usage only\n String url() default \"\";\n String user() default \"\";\n String password() default \"\";\n }\n\n## DynamicMBeanHandler (thr proxy implementation)\n\n package org.superbiz.dynamic.mbean;\n\n import javax.annotation.PreDestroy;\n import javax.management.Attribute;\n import javax.management.MBeanAttributeInfo;\n import javax.management.MBeanInfo;\n import javax.management.MBeanServer;\n import javax.management.MBeanServerConnection;\n import javax.management.ObjectName;\n import javax.management.remote.JMXConnector;\n import javax.management.remote.JMXConnectorFactory;\n import javax.management.remote.JMXServiceURL;\n import java.io.IOException;\n import java.lang.management.ManagementFactory;\n import java.lang.reflect.InvocationHandler;\n import java.lang.reflect.Method;\n import java.util.HashMap;\n import java.util.Map;\n import java.util.concurrent.ConcurrentHashMap;\n\n /**\n * Need a @PreDestroy method to disconnect the remote host when used in remote mode.\n */\n public class DynamicMBeanHandler implements InvocationHandler {\n private final Map<Method, ConnectionInfo> infos = new ConcurrentHashMap<Method, ConnectionInfo>();\n\n @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {\n final String methodName = method.getName();\n if (method.getDeclaringClass().equals(Object.class) && \"toString\".equals(methodName)) {\n return getClass().getSimpleName() + \" Proxy\";\n }\n if (method.getAnnotation(PreDestroy.class) != null) {\n return destroy();\n }\n\n final ConnectionInfo info = getConnectionInfo(method);\n final MBeanInfo infos = info.getMBeanInfo();\n if (methodName.startsWith(\"set\") && methodName.length() > 3 && args != null && args.length == 1\n && (Void.TYPE.equals(method.getReturnType()) || Void.class.equals(method.getReturnType()))) {\n final String attributeName = attributeName(infos, methodName, method.getParameterTypes()[0]);\n info.setAttribute(new Attribute(attributeName, args[0]));\n return null;\n } else if (methodName.startsWith(\"get\") && (args == null || args.length == 0) && methodName.length() > 3) {\n final String attributeName = attributeName(infos, methodName, method.getReturnType());\n return info.getAttribute(attributeName);\n }\n // operation\n return info.invoke(methodName, args, getSignature(method));\n }\n\n public Object destroy() {\n for (ConnectionInfo info : infos.values()) {\n info.clean();\n }\n infos.clear();\n return null;\n }\n\n private String[] getSignature(Method method) {\n String[] args = new String[method.getParameterTypes().length];\n for (int i = 0; i < method.getParameterTypes().length; i++) {\n args[i] = method.getParameterTypes()[i].getName();\n }\n return args; // note: null should often work...\n }\n\n private String attributeName(MBeanInfo infos, String methodName, Class<?> type) {\n String found = null;\n String foundBackUp = null; // without checking the type\n final String attributeName = methodName.substring(3, methodName.length());\n final String lowerName = Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4, methodName.length());\n\n for (MBeanAttributeInfo attribute : infos.getAttributes()) {\n final String name = attribute.getName();\n if (attributeName.equals(name)) {\n foundBackUp = attributeName;\n if (attribute.getType().equals(type.getName())) {\n found = name;\n }\n } else if (found == null && ((lowerName.equals(name) && !attributeName.equals(name))\n || lowerName.equalsIgnoreCase(name))) {\n foundBackUp = name;\n if (attribute.getType().equals(type.getName())) {\n found = name;\n }\n }\n }\n\n if (found == null && foundBackUp == null) {\n throw new UnsupportedOperationException(\"cannot find attribute \" + attributeName);\n }\n\n if (found != null) {\n return found;\n }\n return foundBackUp;\n }\n\n private synchronized ConnectionInfo getConnectionInfo(Method method) throws Exception {\n if (!infos.containsKey(method)) {\n synchronized (infos) {\n if (!infos.containsKey(method)) { // double check for synchro\n org.superbiz.dynamic.mbean.ObjectName on = method.getAnnotation(org.superbiz.dynamic.mbean.ObjectName.class);\n if (on == null) {\n Class<?> current = method.getDeclaringClass();\n do {\n on = method.getDeclaringClass().getAnnotation(org.superbiz.dynamic.mbean.ObjectName.class);\n current = current.getSuperclass();\n } while (on == null && current != null);\n if (on == null) {\n throw new UnsupportedOperationException(\"class or method should define the objectName to use for invocation: \" + method.toGenericString());\n }\n }\n final ConnectionInfo info;\n if (on.url().isEmpty()) {\n info = new LocalConnectionInfo();\n ((LocalConnectionInfo) info).server = ManagementFactory.getPlatformMBeanServer(); // could use an id...\n } else {\n info = new RemoteConnectionInfo();\n final Map<String, String[]> environment = new HashMap<String, String[]>();\n if (!on.user().isEmpty()) {\n environment.put(JMXConnector.CREDENTIALS, new String[]{ on.user(), on.password() });\n }\n // ((RemoteConnectionInfo) info).connector = JMXConnectorFactory.newJMXConnector(new JMXServiceURL(on.url()), environment);\n ((RemoteConnectionInfo) info).connector = JMXConnectorFactory.connect(new JMXServiceURL(on.url()), environment);\n\n }\n info.objectName = new ObjectName(on.value());\n\n infos.put(method, info);\n }\n }\n }\n return infos.get(method);\n }\n\n private abstract static class ConnectionInfo {\n protected ObjectName objectName;\n\n public abstract void setAttribute(Attribute attribute) throws Exception;\n public abstract Object getAttribute(String attribute) throws Exception;\n public abstract Object invoke(String operationName, Object params[], String signature[]) throws Exception;\n public abstract MBeanInfo getMBeanInfo() throws Exception;\n public abstract void clean();\n }\n\n private static class LocalConnectionInfo extends ConnectionInfo {\n private MBeanServer server;\n\n @Override public void setAttribute(Attribute attribute) throws Exception {\n server.setAttribute(objectName, attribute);\n }\n\n @Override public Object getAttribute(String attribute) throws Exception {\n return server.getAttribute(objectName, attribute);\n }\n\n @Override\n public Object invoke(String operationName, Object[] params, String[] signature) throws Exception {\n return server.invoke(objectName, operationName, params, signature);\n }\n\n @Override public MBeanInfo getMBeanInfo() throws Exception {\n return server.getMBeanInfo(objectName);\n }\n\n @Override public void clean() {\n // no-op\n }\n }\n\n private static class RemoteConnectionInfo extends ConnectionInfo {\n private JMXConnector connector;\n private MBeanServerConnection connection;\n\n private void before() throws IOException {\n connection = connector.getMBeanServerConnection();\n }\n\n private void after() throws IOException {\n // no-op\n }\n\n @Override public void setAttribute(Attribute attribute) throws Exception {\n before();\n connection.setAttribute(objectName, attribute);\n after();\n }\n\n @Override public Object getAttribute(String attribute) throws Exception {\n before();\n try {\n return connection.getAttribute(objectName, attribute);\n } finally {\n after();\n }\n }\n\n @Override\n public Object invoke(String operationName, Object[] params, String[] signature) throws Exception {\n before();\n try {\n return connection.invoke(objectName, operationName, params, signature);\n } finally {\n after();\n }\n }\n\n @Override public MBeanInfo getMBeanInfo() throws Exception {\n before();\n try {\n return connection.getMBeanInfo(objectName);\n } finally {\n after();\n }\n }\n\n @Override public void clean() {\n try {\n connector.close();\n } catch (IOException e) {\n // no-op\n }\n }\n }\n }\n\n## Dynamic Proxies \n\n### DynamicMBeanClient (the dynamic JMX client)\n\n\tpackage org.superbiz.dynamic.mbean;\n\n\timport org.apache.openejb.api.Proxy;\n\timport org.superbiz.dynamic.mbean.DynamicMBeanHandler;\n\timport org.superbiz.dynamic.mbean.ObjectName;\n\n\timport javax.ejb.Singleton;\n\n\t/**\n\t * @author rmannibucau\n\t */\n\t@Singleton\n\t@Proxy(DynamicMBeanHandler.class)\n\t@ObjectName(DynamicMBeanClient.OBJECT_NAME)\n\tpublic interface DynamicMBeanClient {\n\t\tstatic final String OBJECT_NAME = \"test:group=DynamicMBeanClientTest\";\n\n\t\tint getCounter();\n\t\tvoid setCounter(int i);\n\t\tint length(String aString);\n\t}\n\n### DynamicMBeanClient (the dynamic JMX client)\n package org.superbiz.dynamic.mbean;\n\n import org.apache.openejb.api.Proxy;\n\n import javax.annotation.PreDestroy;\n import javax.ejb.Singleton;\n\n\n @Singleton\n @Proxy(DynamicMBeanHandler.class)\n @ObjectName(value = DynamicRemoteMBeanClient.OBJECT_NAME, url = \"service:jmx:rmi:///jndi/rmi://localhost:8243/jmxrmi\")\n public interface DynamicRemoteMBeanClient {\n static final String OBJECT_NAME = \"test:group=DynamicMBeanClientTest\";\n\n int getCounter();\n void setCounter(int i);\n int length(String aString);\n\n @PreDestroy void clean();\n }\n\n## The MBean used for the test\n\n### SimpleMBean\n\n\tpackage org.superbiz.dynamic.mbean.simple;\n\n\tpublic interface SimpleMBean {\n\t\tint length(String s);\n\n\t\tint getCounter();\n\t\tvoid setCounter(int c);\n\t}\n\n## Simple\n\n\tpackage org.superbiz.dynamic.mbean.simple;\n\n\tpublic class Simple implements SimpleMBean {\n\t\tprivate int counter = 0;\n\n\t\t@Override public int length(String s) {\n\t\t if (s == null) {\n\t\t return 0;\n\t\t }\n\t\t return s.length();\n\t\t}\n\n\t\t@Override public int getCounter() {\n\t\t return counter;\n\t\t}\n\n\t\t@Override public void setCounter(int c) {\n\t\t counter = c;\n\t\t}\n\t}\n\n## DynamicMBeanClientTest (The test)\n\n package org.superbiz.dynamic.mbean;\n\n import org.junit.After;\n import org.junit.AfterClass;\n import org.junit.Before;\n import org.junit.BeforeClass;\n import org.junit.Test;\n import org.superbiz.dynamic.mbean.simple.Simple;\n\n import javax.ejb.EJB;\n import javax.ejb.embeddable.EJBContainer;\n import javax.management.Attribute;\n import javax.management.ObjectName;\n import java.lang.management.ManagementFactory;\n\n import static junit.framework.Assert.assertEquals;\n\n public class DynamicMBeanClientTest {\n private static ObjectName objectName;\n private static EJBContainer container;\n\n @EJB private DynamicMBeanClient localClient;\n @EJB private DynamicRemoteMBeanClient remoteClient;\n\n @BeforeClass public static void start() {\n container = EJBContainer.createEJBContainer();\n }\n\n @Before public void injectAndRegisterMBean() throws Exception {\n container.getContext().bind(\"inject\", this);\n objectName = new ObjectName(DynamicMBeanClient.OBJECT_NAME);\n ManagementFactory.getPlatformMBeanServer().registerMBean(new Simple(), objectName);\n }\n\n @After public void unregisterMBean() throws Exception {\n if (objectName != null) {\n ManagementFactory.getPlatformMBeanServer().unregisterMBean(objectName);\n }\n }\n\n @Test public void localGet() throws Exception {\n assertEquals(0, localClient.getCounter());\n ManagementFactory.getPlatformMBeanServer().setAttribute(objectName, new Attribute(\"Counter\", 5));\n assertEquals(5, localClient.getCounter());\n }\n\n @Test public void localSet() throws Exception {\n assertEquals(0, ((Integer) ManagementFactory.getPlatformMBeanServer().getAttribute(objectName, \"Counter\")).intValue());\n localClient.setCounter(8);\n assertEquals(8, ((Integer) ManagementFactory.getPlatformMBeanServer().getAttribute(objectName, \"Counter\")).intValue());\n }\n\n @Test public void localOperation() {\n assertEquals(7, localClient.length(\"openejb\"));\n }\n\n @Test public void remoteGet() throws Exception {\n assertEquals(0, remoteClient.getCounter());\n ManagementFactory.getPlatformMBeanServer().setAttribute(objectName, new Attribute(\"Counter\", 5));\n assertEquals(5, remoteClient.getCounter());\n }\n\n @Test public void remoteSet() throws Exception {\n assertEquals(0, ((Integer) ManagementFactory.getPlatformMBeanServer().getAttribute(objectName, \"Counter\")).intValue());\n remoteClient.setCounter(8);\n assertEquals(8, ((Integer) ManagementFactory.getPlatformMBeanServer().getAttribute(objectName, \"Counter\")).intValue());\n }\n\n @Test public void remoteOperation() {\n assertEquals(7, remoteClient.length(\"openejb\"));\n }\n\n @AfterClass public static void close() {\n if (container != null) {\n container.close();\n }\n }\n }\n\n",
"url":"https://github.com/apache/tomee/tree/master/examples/dynamic-proxy-to-access-mbean"
}
],
"quartz":[
{
"name":"quartz-app",
"readme":"Title: Quartz Resource Adapter usage\n\nNote this example is somewhat dated. It predates the schedule API which was added to EJB 3.1. Modern applications should use the schedule API which has many, if not all,\nthe same features as Quartz. In fact, Quartz is the engine that drives the `@Schedule` and `ScheduleExpression` support in OpenEJB and TomEE.\n\nDespite being dated from a scheduling perspective it is still an excellent reference for how to plug-in and test a custom Java EE Resource Adapter.\n\n# Project structure\n\nAs `.rar` files do not do well on a standard classpath structure the goal is to effectively \"unwrap\" the `.rar` so that its dependencies are on the classpath and its `ra.xml` file\ncan be found in scanned by OpenEJB.\n\nWe do this by creating a mini maven module to represent the rar in maven terms. The `pom.xml` of the \"rar module\" declares all of the jars that would be inside `.rar` as maven\ndependencies. The `ra.xml` file is added to the project in `src/main/resources/META-INF/ra.xml` where it will be visible to other modules.\n\n quartz-app\n quartz-app/pom.xml\n quartz-app/quartz-beans\n quartz-app/quartz-beans/pom.xml\n quartz-app/quartz-beans/src/main/java/org/superbiz/quartz/JobBean.java\n quartz-app/quartz-beans/src/main/java/org/superbiz/quartz/JobScheduler.java\n quartz-app/quartz-beans/src/main/java/org/superbiz/quartz/QuartzMdb.java\n quartz-app/quartz-beans/src/main/resources/META-INF\n quartz-app/quartz-beans/src/main/resources/META-INF/ejb-jar.xml\n quartz-app/quartz-beans/src/test/java/org/superbiz/quartz/QuartzMdbTest.java\n quartz-app/quartz-ra\n quartz-app/quartz-ra/pom.xml\n quartz-app/quartz-ra/src/main/resources/META-INF\n quartz-app/quartz-ra/src/main/resources/META-INF/ra.xml\n\n## ra.xml\n\nThe connector in question has both inbound and outbound Resource Adapters. The inbound Resource Adapter can be used to drive message driven beans (MDBs)\n\nthe outbound Resource Adapter, `QuartzResourceAdapter`, can be injected into any component via `@Resource` and used to originate and send messages or events.\n\n <connector xmlns=\"http://java.sun.com/xml/ns/j2ee\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/j2ee\n http://java.sun.com/xml/ns/j2ee/connector_1_5.xsd\"\n version=\"1.5\">\n\n <description>Quartz ResourceAdapter</description>\n <display-name>Quartz ResourceAdapter</display-name>\n\n <vendor-name>OpenEJB</vendor-name>\n <eis-type>Quartz Adapter</eis-type>\n <resourceadapter-version>1.0</resourceadapter-version>\n\n <resourceadapter id=\"QuartzResourceAdapter\">\n <resourceadapter-class>org.apache.openejb.resource.quartz.QuartzResourceAdapter</resourceadapter-class>\n\n <inbound-resourceadapter>\n <messageadapter>\n <messagelistener>\n <messagelistener-type>org.quartz.Job</messagelistener-type>\n <activationspec>\n <activationspec-class>org.apache.openejb.resource.quartz.JobSpec</activationspec-class>\n </activationspec>\n </messagelistener>\n </messageadapter>\n </inbound-resourceadapter>\n\n </resourceadapter>\n </connector>\n\n\n# Using the Outbound Resource Adapter\n\nHere we see the outbound resource adapter used in a stateless session bean to schedule a job that will be executed by the MDB\n\n package org.superbiz.quartz;\n\n import org.apache.openejb.resource.quartz.QuartzResourceAdapter;\n import org.quartz.Job;\n import org.quartz.JobDetail;\n import org.quartz.JobExecutionContext;\n import org.quartz.JobExecutionException;\n import org.quartz.Scheduler;\n import org.quartz.SimpleTrigger;\n\n import javax.ejb.Stateless;\n import javax.naming.InitialContext;\n import java.util.Date;\n\n @Stateless\n public class JobBean implements JobScheduler {\n\n @Override\n public Date createJob() throws Exception {\n\n final QuartzResourceAdapter ra = (QuartzResourceAdapter) new InitialContext().lookup(\"java:openejb/Resource/QuartzResourceAdapter\");\n final Scheduler s = ra.getScheduler();\n\n //Add a job type\n final JobDetail jd = new JobDetail(\"job1\", \"group1\", JobBean.MyTestJob.class);\n jd.getJobDataMap().put(\"MyJobKey\", \"MyJobValue\");\n\n //Schedule my 'test' job to run now\n final SimpleTrigger trigger = new SimpleTrigger(\"trigger1\", \"group1\", new Date());\n return s.scheduleJob(jd, trigger);\n }\n\n public static class MyTestJob implements Job {\n\n @Override\n public void execute(JobExecutionContext context) throws JobExecutionException {\n System.out.println(\"This is a simple test job to get: \" + context.getJobDetail().getJobDataMap().get(\"MyJobKey\"));\n }\n }\n }\n\n# Recieving data from the Inbound Resource Adapter\n\n\n package org.superbiz.quartz;\n\n import org.quartz.Job;\n import org.quartz.JobExecutionContext;\n import org.quartz.JobExecutionException;\n\n import javax.ejb.ActivationConfigProperty;\n import javax.ejb.MessageDriven;\n\n @MessageDriven(activationConfig = {\n @ActivationConfigProperty(propertyName = \"cronExpression\", propertyValue = \"* * * * * ?\")})\n public class QuartzMdb implements Job {\n\n @Override\n public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {\n System.out.println(\"Executing Job\");\n }\n }\n\n# Test case\n\n package org.superbiz.quartz;\n\n import org.junit.AfterClass;\n import org.junit.BeforeClass;\n import org.junit.Test;\n\n import javax.naming.Context;\n import javax.naming.InitialContext;\n import java.util.Date;\n import java.util.Properties;\n\n public class QuartzMdbTest {\n\n private static InitialContext initialContext = null;\n\n @BeforeClass\n public static void beforeClass() throws Exception {\n\n if (null == initialContext) {\n Properties properties = new Properties();\n properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, \"org.apache.openejb.core.LocalInitialContextFactory\");\n\n initialContext = new InitialContext(properties);\n }\n }\n\n @AfterClass\n public static void afterClass() throws Exception {\n if (null != initialContext) {\n initialContext.close();\n initialContext = null;\n }\n }\n\n @Test\n public void testLookup() throws Exception {\n\n final JobScheduler jbi = (JobScheduler) initialContext.lookup(\"JobBeanLocal\");\n final Date d = jbi.createJob();\n Thread.sleep(500);\n System.out.println(\"Scheduled test job should have run at: \" + d.toString());\n }\n\n @Test\n public void testMdb() throws Exception {\n // Sleep 3 seconds and give quartz a chance to execute our MDB\n Thread.sleep(3000);\n }\n }\n\n# Running\n\n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.quartz.QuartzMdbTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/quartz-app/quartz-beans\n INFO - openejb.base = /Users/dblevins/examples/quartz-app/quartz-beans\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found ConnectorModule in classpath: /Users/dblevins/examples/quartz-app/quartz-ra/target/quartz-ra-1.0.jar\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/quartz-app/quartz-beans/target/classes\n INFO - Beginning load: /Users/dblevins/examples/quartz-app/quartz-ra/target/quartz-ra-1.0.jar\n INFO - Extracting jar: /Users/dblevins/examples/quartz-app/quartz-ra/target/quartz-ra-1.0.jar\n INFO - Extracted path: /Users/dblevins/examples/quartz-app/quartz-ra/target/quartz-ra-1.0\n INFO - Beginning load: /Users/dblevins/examples/quartz-app/quartz-beans/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/quartz-app/quartz-beans/classpath.ear\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean JobBean: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Configuring Service(id=QuartzResourceAdapter, type=Resource, provider-id=QuartzResourceAdapter)\n INFO - Configuring Service(id=quartz-ra-1.0, type=Container, provider-id=Default MDB Container)\n INFO - Enterprise application \"/Users/dblevins/examples/quartz-app/quartz-beans/classpath.ear\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/quartz-app/quartz-beans/classpath.ear\n INFO - Jndi(name=JobBeanLocal) --> Ejb(deployment-id=JobBean)\n INFO - Jndi(name=global/classpath.ear/quartz-beans/JobBean!org.superbiz.quartz.JobScheduler) --> Ejb(deployment-id=JobBean)\n INFO - Jndi(name=global/classpath.ear/quartz-beans/JobBean) --> Ejb(deployment-id=JobBean)\n INFO - Created Ejb(deployment-id=JobBean, ejb-name=JobBean, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=QuartzMdb, ejb-name=QuartzMdb, container=quartz-ra-1.0)\n Executing Job\n INFO - Started Ejb(deployment-id=JobBean, ejb-name=JobBean, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=QuartzMdb, ejb-name=QuartzMdb, container=quartz-ra-1.0)\n INFO - Deployed Application(path=/Users/dblevins/examples/quartz-app/quartz-beans/classpath.ear)\n This is a simple test job to get: MyJobValue\n Scheduled test job should have run at: Fri Oct 28 17:05:12 PDT 2011\n Executing Job\n Executing Job\n Executing Job\n Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 4.971 sec\n\n Results :\n\n Tests run: 2, Failures: 0, Errors: 0, Skipped: 0\n\n",
"url":"https://github.com/apache/tomee/tree/master/examples/quartz-app"
}
],
"realm":[
{
"name":"cdi-realm",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/cdi-realm"
},
{
"name":"realm-in-tomee",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/realm-in-tomee"
}
],
"redeployment":[
{
"name":"bval-evaluation-redeployment",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/bval-evaluation-redeployment"
}
],
"registration":[
{
"name":"mbean-auto-registration",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/mbean-auto-registration"
}
],
"reload":[
{
"name":"reload-persistence-unit-properties",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/reload-persistence-unit-properties"
}
],
"request":[
{
"name":"cdi-request-scope",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/cdi-request-scope"
}
],
"resource":[
{
"name":"client-resource-lookup-preview",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/client-resource-lookup-preview"
}
],
"resources":[
{
"name":"resources-jmx-example",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/resources-jmx-example"
},
{
"name":"webservice-ws-with-resources-config",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/webservice-ws-with-resources-config"
},
{
"name":"resources-declared-in-webapp",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/resources-declared-in-webapp"
}
],
"rest":[
{
"name":"rest-on-ejb",
"readme":"Title: REST on EJB\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## User\n\n package org.superbiz.rest;\n \n import javax.persistence.Entity;\n import javax.persistence.GeneratedValue;\n import javax.persistence.Id;\n import javax.persistence.NamedQueries;\n import javax.persistence.NamedQuery;\n import javax.xml.bind.annotation.XmlRootElement;\n \n @Entity\n @NamedQueries({\n @NamedQuery(name = \"user.list\", query = \"select u from User u\")\n }\n\n## UserService\n\n package org.superbiz.rest;\n \n import javax.ejb.Lock;\n import javax.ejb.LockType;\n import javax.ejb.Singleton;\n import javax.persistence.EntityManager;\n import javax.persistence.PersistenceContext;\n import javax.ws.rs.DELETE;\n import javax.ws.rs.DefaultValue;\n import javax.ws.rs.GET;\n import javax.ws.rs.POST;\n import javax.ws.rs.PUT;\n import javax.ws.rs.Path;\n import javax.ws.rs.PathParam;\n import javax.ws.rs.Produces;\n import javax.ws.rs.QueryParam;\n import javax.ws.rs.core.MediaType;\n import javax.ws.rs.core.Response;\n import java.util.ArrayList;\n import java.util.List;\n \n /**\n * Outputs are copied because of the enhancement of OpenJPA.\n *\n */\n @Singleton\n @Lock(LockType.WRITE)\n @Path(\"/user\")\n @Produces(MediaType.APPLICATION_XML)\n public class UserService {\n @PersistenceContext\n private EntityManager em;\n \n @Path(\"/create\")\n @PUT\n public User create(@QueryParam(\"name\") String name,\n @QueryParam(\"pwd\") String pwd,\n @QueryParam(\"mail\") String mail) {\n User user = new User();\n user.setFullname(name);\n user.setPassword(pwd);\n user.setEmail(mail);\n em.persist(user);\n return user;\n }\n \n @Path(\"/list\")\n @GET\n public List<User> list(@QueryParam(\"first\") @DefaultValue(\"0\") int first,\n @QueryParam(\"max\") @DefaultValue(\"20\") int max) {\n List<User> users = new ArrayList<User>();\n List<User> found = em.createNamedQuery(\"user.list\", User.class).setFirstResult(first).setMaxResults(max).getResultList();\n for (User u : found) {\n users.add(u.copy());\n }\n return users;\n }\n \n @Path(\"/show/{id}\")\n @GET\n public User find(@PathParam(\"id\") long id) {\n User user = em.find(User.class, id);\n if (user == null) {\n return null;\n }\n return user.copy();\n }\n \n @Path(\"/delete/{id}\")\n @DELETE\n public void delete(@PathParam(\"id\") long id) {\n User user = em.find(User.class, id);\n if (user != null) {\n em.remove(user);\n }\n }\n \n @Path(\"/update/{id}\")\n @POST\n public Response update(@PathParam(\"id\") long id,\n @QueryParam(\"name\") String name,\n @QueryParam(\"pwd\") String pwd,\n @QueryParam(\"mail\") String mail) {\n User user = em.find(User.class, id);\n if (user == null) {\n throw new IllegalArgumentException(\"user id \" + id + \" not found\");\n }\n \n user.setFullname(name);\n user.setPassword(pwd);\n user.setEmail(mail);\n em.merge(user);\n \n return Response.ok(user.copy()).build();\n }\n }\n\n## persistence.xml\n\n <persistence version=\"2.0\"\n xmlns=\"http://java.sun.com/xml/ns/persistence\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\n http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd\">\n <persistence-unit name=\"user\">\n <jta-data-source>My DataSource</jta-data-source>\n <non-jta-data-source>My Unmanaged DataSource</non-jta-data-source>\n <class>org.superbiz.rest.User</class>\n <properties>\n <property name=\"openjpa.jdbc.SynchronizeMappings\" value=\"buildSchema(ForeignKeys=true)\"/>\n </properties>\n </persistence-unit>\n </persistence>\n\n## UserServiceTest\n\n package org.superbiz.rest;\n \n import org.apache.cxf.jaxrs.client.WebClient;\n import org.apache.openejb.OpenEjbContainer;\n import org.junit.AfterClass;\n import org.junit.BeforeClass;\n import org.junit.Test;\n \n import javax.ejb.embeddable.EJBContainer;\n import javax.naming.Context;\n import javax.naming.NamingException;\n import javax.ws.rs.core.Response;\n import javax.xml.bind.JAXBContext;\n import javax.xml.bind.Unmarshaller;\n import java.io.InputStream;\n import java.util.ArrayList;\n import java.util.List;\n import java.util.Properties;\n \n import static junit.framework.Assert.assertEquals;\n import static junit.framework.Assert.assertNull;\n import static junit.framework.Assert.fail;\n \n public class UserServiceTest {\n private static Context context;\n private static UserService service;\n private static List<User> users = new ArrayList<User>();\n \n @BeforeClass\n public static void start() throws NamingException {\n Properties properties = new Properties();\n properties.setProperty(OpenEjbContainer.OPENEJB_EMBEDDED_REMOTABLE, \"true\");\n context = EJBContainer.createEJBContainer(properties).getContext();\n \n // create some records\n service = (UserService) context.lookup(\"java:global/rest-on-ejb/UserService\");\n users.add(service.create(\"foo\", \"foopwd\", \"foo@foo.com\"));\n users.add(service.create(\"bar\", \"barpwd\", \"bar@bar.com\"));\n }\n \n @AfterClass\n public static void close() throws NamingException {\n if (context != null) {\n context.close();\n }\n }\n \n @Test\n public void create() {\n int expected = service.list(0, 100).size() + 1;\n Response response = WebClient.create(\"http://localhost:4204\")\n .path(\"/user/create\")\n .query(\"name\", \"dummy\")\n .query(\"pwd\", \"unbreakable\")\n .query(\"mail\", \"foo@bar.fr\")\n .put(null);\n List<User> list = service.list(0, 100);\n for (User u : list) {\n if (!users.contains(u)) {\n service.delete(u.getId());\n return;\n }\n }\n fail(\"user was not added\");\n }\n \n @Test\n public void delete() throws Exception {\n User user = service.create(\"todelete\", \"dontforget\", \"delete@me.com\");\n \n WebClient.create(\"http://localhost:4204\").path(\"/user/delete/\" + user.getId()).delete();\n \n user = service.find(user.getId());\n assertNull(user);\n }\n \n @Test\n public void show() {\n User user = WebClient.create(\"http://localhost:4204\")\n .path(\"/user/show/\" + users.iterator().next().getId())\n .get(User.class);\n assertEquals(\"foo\", user.getFullname());\n assertEquals(\"foopwd\", user.getPassword());\n assertEquals(\"foo@foo.com\", user.getEmail());\n }\n \n @Test\n public void list() throws Exception {\n String users = WebClient.create(\"http://localhost:4204\")\n .path(\"/user/list\")\n .get(String.class);\n assertEquals(\n \"<users>\" +\n \"<user>\" +\n \"<email>foo@foo.com</email>\" +\n \"<fullname>foo</fullname>\" +\n \"<id>1</id>\" +\n \"<password>foopwd</password>\" +\n \"</user>\" +\n \"<user>\" +\n \"<email>bar@bar.com</email>\" +\n \"<fullname>bar</fullname>\" +\n \"<id>2</id>\" +\n \"<password>barpwd</password>\" +\n \"</user>\" +\n \"</users>\", users);\n }\n \n @Test\n public void update() throws Exception {\n User created = service.create(\"name\", \"pwd\", \"mail\");\n Response response = WebClient.create(\"http://localhost:4204\")\n .path(\"/user/update/\" + created.getId())\n .query(\"name\", \"corrected\")\n .query(\"pwd\", \"userpwd\")\n .query(\"mail\", \"it@is.ok\")\n .post(null);\n \n JAXBContext ctx = JAXBContext.newInstance(User.class);\n Unmarshaller unmarshaller = ctx.createUnmarshaller();\n User modified = (User) unmarshaller.unmarshal(InputStream.class.cast(response.getEntity()));\n \n assertEquals(\"corrected\", modified.getFullname());\n assertEquals(\"userpwd\", modified.getPassword());\n assertEquals(\"it@is.ok\", modified.getEmail());\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.rest.UserServiceTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/rest-on-ejb\n INFO - openejb.base = /Users/dblevins/examples/rest-on-ejb\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/rest-on-ejb/target/classes\n INFO - Beginning load: /Users/dblevins/examples/rest-on-ejb/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/rest-on-ejb\n INFO - Configuring Service(id=Default Singleton Container, type=Container, provider-id=Default Singleton Container)\n INFO - Auto-creating a container for bean UserService: Container(type=SINGLETON, id=Default Singleton Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.rest.UserServiceTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring PersistenceUnit(name=user)\n INFO - Configuring Service(id=Default JDBC Database, type=Resource, provider-id=Default JDBC Database)\n INFO - Auto-creating a Resource with id 'Default JDBC Database' of type 'DataSource for 'user'.\n INFO - Configuring Service(id=Default Unmanaged JDBC Database, type=Resource, provider-id=Default Unmanaged JDBC Database)\n INFO - Auto-creating a Resource with id 'Default Unmanaged JDBC Database' of type 'DataSource for 'user'.\n INFO - Adjusting PersistenceUnit user <jta-data-source> to Resource ID 'Default JDBC Database' from 'My DataSource'\n INFO - Adjusting PersistenceUnit user <non-jta-data-source> to Resource ID 'Default Unmanaged JDBC Database' from 'My Unmanaged DataSource'\n INFO - Enterprise application \"/Users/dblevins/examples/rest-on-ejb\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/rest-on-ejb\n INFO - PersistenceUnit(name=user, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 407ms\n INFO - Jndi(name=\"java:global/rest-on-ejb/UserService!org.superbiz.rest.UserService\")\n INFO - Jndi(name=\"java:global/rest-on-ejb/UserService\")\n INFO - Jndi(name=\"java:global/EjbModule1789767313/org.superbiz.rest.UserServiceTest!org.superbiz.rest.UserServiceTest\")\n INFO - Jndi(name=\"java:global/EjbModule1789767313/org.superbiz.rest.UserServiceTest\")\n INFO - Created Ejb(deployment-id=org.superbiz.rest.UserServiceTest, ejb-name=org.superbiz.rest.UserServiceTest, container=Default Managed Container)\n INFO - Created Ejb(deployment-id=UserService, ejb-name=UserService, container=Default Singleton Container)\n INFO - Started Ejb(deployment-id=org.superbiz.rest.UserServiceTest, ejb-name=org.superbiz.rest.UserServiceTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=UserService, ejb-name=UserService, container=Default Singleton Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/rest-on-ejb)\n INFO - Initializing network services\n INFO - Creating ServerService(id=httpejbd)\n INFO - Creating ServerService(id=admin)\n INFO - Creating ServerService(id=ejbd)\n INFO - Creating ServerService(id=ejbds)\n INFO - Creating ServerService(id=cxf-rs)\n INFO - Initializing network services\n ** Starting Services **\n NAME IP PORT \n httpejbd 127.0.0.1 4204 \n admin thread 127.0.0.1 4200 \n ejbd 127.0.0.1 4201 \n ejbd 127.0.0.1 4203 \n -------\n Ready!\n WARN - Query \"select u from User u\" is removed from cache excluded permanently. Query \"select u from User u\" is not cached because it uses pagination..\n Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.102 sec\n \n Results :\n \n Tests run: 5, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/rest-on-ejb"
},
{
"name":"simple-rest",
"readme":"Title: Simple REST\n\nDefining a REST service is pretty easy, simply ad @Path annotation to a class then define on methods\nthe HTTP method to use (@GET, @POST, ...).\n\n#The Code\n\n## The REST service: @Path, @GET, @POST\n\nHere we see a bean that uses the Bean-Managed Concurrency option as well as the @Startup annotation which causes the bean to be instantiated by the container when the application starts. Singleton beans with @ConcurrencyManagement(BEAN) are responsible for their own thread-safety. The bean shown is a simple properties \"registry\" and provides a place where options could be set and retrieved by all beans in the application.\n\n package org.superbiz.rest;\n\n import javax.ws.rs.GET;\n import javax.ws.rs.POST;\n import javax.ws.rs.Path;\n\n @Path(\"/greeting\")\n public class GreetingService {\n @GET\n public String message() {\n return \"Hi REST!\";\n }\n\n @POST\n public String lowerCase(final String message) {\n return \"Hi REST!\".toLowerCase();\n }\n }\n\n# Testing\n\n## Test for the JAXRS service\n\nThe test uses the OpenEJB ApplicationComposer to make it trivial.\n\nThe idea is first to activate the jaxrs services. This is done using @EnableServices annotation.\n\nThen we create on the fly the application simply returning an object representing the web.xml. Here we simply\nuse it to define the context root but you can use it to define your REST Application too. And to complete the\napplication definition we add @Classes annotation to define the set of classes to use in this app.\n\nFinally to test it we use cxf client API to call the REST service in get() and post() methods.\n\n package org.superbiz.rest;\n\n import org.apache.cxf.jaxrs.client.WebClient;\n import org.apache.openejb.jee.SingletonBean;\n import org.apache.openejb.junit.ApplicationComposer;\n import org.apache.openejb.junit.EnableServices;\n import org.apache.openejb.junit.Module;\n import org.junit.Test;\n import org.junit.runner.RunWith;\n\n import java.io.IOException;\n\n import static org.junit.Assert.assertEquals;\n\n @EnableServices(value = \"jaxrs\")\n @RunWith(ApplicationComposer.class)\n public class GreetingServiceTest {\n @Module\n public SingletonBean app() {\n return (SingletonBean) new SingletonBean(GreetingService.class).localBean();\n }\n\n @Test\n public void get() throws IOException {\n final String message = WebClient.create(\"http://localhost:4204\").path(\"/GreetingServiceTest/greeting/\").get(String.class);\n assertEquals(\"Hi REST!\", message);\n }\n\n @Test\n public void post() throws IOException {\n final String message = WebClient.create(\"http://localhost:4204\").path(\"/GreetingServiceTest/greeting/\").post(\"Hi REST!\", String.class);\n assertEquals(\"hi rest!\", message);\n }\n }\n\n#Running\n\nRunning the example is fairly simple. In the \"simple-rest\" directory run:\n\n $ mvn clean install\n\nWhich should create output like the following.\n\n INFO - Cannot find the configuration file [conf/openejb.xml]. Will attempt to create one for the beans deployed.\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Creating TransactionManager(id=Default Transaction Manager)\n INFO - Creating SecurityService(id=Default Security Service)\n INFO - Initializing network services\n INFO - Creating ServerService(id=httpejbd)\n INFO - Creating ServerService(id=cxf-rs)\n INFO - Initializing network services\n INFO - Starting service httpejbd\n INFO - Started service httpejbd\n INFO - Starting service cxf-rs\n INFO - Started service cxf-rs\n INFO - ** Bound Services **\n INFO - NAME IP PORT\n INFO - httpejbd 127.0.0.1 4204\n INFO - -------\n INFO - Ready!\n INFO - Configuring enterprise application: /opt/dev/openejb/openejb-trunk/examples/GreetingServiceTest\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.rest.GreetingServiceTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Creating Container(id=Default Managed Container)\n INFO - Using directory /tmp for stateful session passivation\n INFO - Enterprise application \"/opt/dev/openejb/openejb-trunk/examples/GreetingServiceTest\" loaded.\n INFO - Assembling app: /opt/dev/openejb/openejb-trunk/examples/GreetingServiceTest\n INFO - Existing thread singleton service in SystemInstance() null\n INFO - Created new singletonService org.apache.openejb.cdi.ThreadSingletonServiceImpl@12c9b196\n INFO - Succeeded in installing singleton service\n INFO - OpenWebBeans Container is starting...\n INFO - Adding OpenWebBeansPlugin : [CdiPlugin]\n INFO - All injection points are validated successfully.\n INFO - OpenWebBeans Container has started, it took 11 ms.\n INFO - Deployed Application(path=/opt/dev/openejb/openejb-trunk/examples/GreetingServiceTest)\n INFO - Setting the server's publish address to be http://127.0.0.1:4204/test\n INFO - REST Service: http://127.0.0.1:4204/test/greeting/.* -> Pojo org.superbiz.rest.GreetingService\n INFO - Undeploying app: /opt/dev/openejb/openejb-trunk/examples/GreetingServiceTest\n INFO - Stopping network services\n INFO - Stopping server services\n Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.004 sec\n\n Results :\n\n Tests run: 2, Failures: 0, Errors: 0, Skipped: 0\n\n",
"url":"https://github.com/apache/tomee/tree/master/examples/simple-rest"
},
{
"name":"moviefun-rest",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/moviefun-rest"
},
{
"name":"rest-applicationcomposer",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/rest-applicationcomposer"
},
{
"name":"rest-example",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/rest-example"
},
{
"name":"rest-example-with-application",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/rest-example-with-application"
},
{
"name":"rest-cdi",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/rest-cdi"
},
{
"name":"rest-applicationcomposer-mockito",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/rest-applicationcomposer-mockito"
},
{
"name":"rest-jaas",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/rest-jaas"
},
{
"name":"rest-xml-json",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/rest-xml-json"
}
],
"rollback":[
{
"name":"transaction-rollback",
"readme":"Title: Transaction Rollback\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## CustomRuntimeException\n\n package org.superbiz.txrollback;\n \n import javax.ejb.ApplicationException;\n \n @ApplicationException\n public class CustomRuntimeException extends RuntimeException {\n \n public CustomRuntimeException() {\n }\n \n public CustomRuntimeException(String s) {\n super(s);\n }\n \n public CustomRuntimeException(String s, Throwable throwable) {\n super(s, throwable);\n }\n \n public CustomRuntimeException(Throwable throwable) {\n super(throwable);\n }\n }\n\n## Movie\n\n package org.superbiz.txrollback;\n \n import javax.persistence.Entity;\n import javax.persistence.GeneratedValue;\n import javax.persistence.GenerationType;\n import javax.persistence.Id;\n \n @Entity(name = \"Movie\")\n public class Movie {\n \n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private long id;\n \n private String director;\n private String title;\n private int year;\n \n public Movie() {\n }\n \n public Movie(String director, String title, int year) {\n this.director = director;\n this.title = title;\n this.year = year;\n }\n \n public String getDirector() {\n return director;\n }\n \n public void setDirector(String director) {\n this.director = director;\n }\n \n public String getTitle() {\n return title;\n }\n \n public void setTitle(String title) {\n this.title = title;\n }\n \n public int getYear() {\n return year;\n }\n \n public void setYear(int year) {\n this.year = year;\n }\n \n }\n\n## Movies\n\n package org.superbiz.txrollback;\n \n import javax.annotation.Resource;\n import javax.ejb.SessionContext;\n import javax.ejb.Stateless;\n import javax.persistence.EntityManager;\n import javax.persistence.PersistenceContext;\n import javax.persistence.PersistenceContextType;\n import javax.persistence.Query;\n import java.util.List;\n \n //START SNIPPET: code\n @Stateless\n public class Movies {\n \n @PersistenceContext(unitName = \"movie-unit\", type = PersistenceContextType.TRANSACTION)\n private EntityManager entityManager;\n \n @Resource\n private SessionContext sessionContext;\n \n public void addMovie(Movie movie) throws Exception {\n entityManager.persist(movie);\n }\n \n public void deleteMovie(Movie movie) throws Exception {\n entityManager.remove(movie);\n }\n \n public List<Movie> getMovies() throws Exception {\n Query query = entityManager.createQuery(\"SELECT m from Movie as m\");\n return query.getResultList();\n }\n \n public void callSetRollbackOnly() {\n sessionContext.setRollbackOnly();\n }\n \n public void throwUncheckedException() {\n throw new RuntimeException(\"Throwing unchecked exceptions will rollback a transaction\");\n }\n \n public void throwApplicationException() {\n throw new CustomRuntimeException(\"This is marked @ApplicationException, so no TX rollback\");\n }\n }\n\n## persistence.xml\n\n <persistence xmlns=\"http://java.sun.com/xml/ns/persistence\" version=\"1.0\">\n \n <persistence-unit name=\"movie-unit\">\n <jta-data-source>movieDatabase</jta-data-source>\n <non-jta-data-source>movieDatabaseUnmanaged</non-jta-data-source>\n <class>org.superbiz.testinjection.MoviesTest.Movie</class>\n \n <properties>\n <property name=\"openjpa.jdbc.SynchronizeMappings\" value=\"buildSchema(ForeignKeys=true)\"/>\n </properties>\n </persistence-unit>\n </persistence>\n\n## MoviesTest\n\n package org.superbiz.txrollback;\n \n import junit.framework.TestCase;\n \n import javax.annotation.Resource;\n import javax.ejb.EJB;\n import javax.ejb.embeddable.EJBContainer;\n import javax.persistence.EntityManager;\n import javax.persistence.PersistenceContext;\n import javax.transaction.RollbackException;\n import javax.transaction.UserTransaction;\n import java.util.List;\n import java.util.Properties;\n \n //START SNIPPET: code\n public class MoviesTest extends TestCase {\n \n @EJB\n private Movies movies;\n \n @Resource\n private UserTransaction userTransaction;\n \n @PersistenceContext\n private EntityManager entityManager;\n \n private EJBContainer ejbContainer;\n \n public void setUp() throws Exception {\n Properties p = new Properties();\n p.put(\"movieDatabase\", \"new://Resource?type=DataSource\");\n p.put(\"movieDatabase.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"movieDatabase.JdbcUrl\", \"jdbc:hsqldb:mem:moviedb\" + System.currentTimeMillis());\n \n ejbContainer = EJBContainer.createEJBContainer(p);\n ejbContainer.getContext().bind(\"inject\", this);\n }\n \n @Override\n protected void tearDown() throws Exception {\n ejbContainer.close();\n }\n \n /**\n * Standard successful transaction scenario. The data created inside\n * the transaction is visible after the transaction completes.\n * <p/>\n * Note that UserTransaction is only usable by Bean-Managed Transaction\n * beans, which can be specified with @TransactionManagement(BEAN)\n */\n public void testCommit() throws Exception {\n \n userTransaction.begin();\n \n try {\n entityManager.persist(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n entityManager.persist(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n entityManager.persist(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n \n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n } finally {\n userTransaction.commit();\n }\n \n // Transaction was committed\n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n }\n \n /**\n * Standard transaction rollback scenario. The data created inside\n * the transaction is not visible after the transaction completes.\n */\n public void testUserTransactionRollback() throws Exception {\n \n userTransaction.begin();\n \n try {\n entityManager.persist(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n entityManager.persist(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n entityManager.persist(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n \n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n } finally {\n userTransaction.rollback();\n }\n \n // Transaction was rolled back\n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 0, list.size());\n }\n \n /**\n * Transaction is marked for rollback inside the bean via\n * calling the javax.ejb.SessionContext.setRollbackOnly() method\n * <p/>\n * This is the cleanest way to make a transaction rollback.\n */\n public void testMarkedRollback() throws Exception {\n \n userTransaction.begin();\n \n try {\n entityManager.persist(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n entityManager.persist(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n entityManager.persist(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n \n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n \n movies.callSetRollbackOnly();\n } finally {\n try {\n userTransaction.commit();\n fail(\"A RollbackException should have been thrown\");\n } catch (RollbackException e) {\n // Pass\n }\n }\n \n // Transaction was rolled back\n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 0, list.size());\n }\n \n /**\n * Throwing an unchecked exception from a bean will cause\n * the container to call setRollbackOnly() and discard the\n * bean instance from further use without calling any @PreDestroy\n * methods on the bean instance.\n */\n public void testExceptionBasedRollback() throws Exception {\n \n userTransaction.begin();\n \n try {\n entityManager.persist(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n entityManager.persist(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n entityManager.persist(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n \n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n \n try {\n movies.throwUncheckedException();\n } catch (RuntimeException e) {\n // Good, this will cause the tx to rollback\n }\n } finally {\n try {\n userTransaction.commit();\n fail(\"A RollbackException should have been thrown\");\n } catch (RollbackException e) {\n // Pass\n }\n }\n \n // Transaction was rolled back\n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 0, list.size());\n }\n \n /**\n * It is still possible to throw unchecked (runtime) exceptions\n * without dooming the transaction by marking the exception\n * with the @ApplicationException annotation or in the ejb-jar.xml\n * deployment descriptor via the <application-exception> tag\n */\n public void testCommit2() throws Exception {\n \n userTransaction.begin();\n \n try {\n entityManager.persist(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n entityManager.persist(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n entityManager.persist(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n \n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n \n try {\n movies.throwApplicationException();\n } catch (RuntimeException e) {\n // This will *not* cause the tx to rollback\n // because it is marked as an @ApplicationException\n }\n } finally {\n userTransaction.commit();\n }\n \n // Transaction was committed\n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.txrollback.MoviesTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/transaction-rollback\n INFO - openejb.base = /Users/dblevins/examples/transaction-rollback\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/transaction-rollback/target/classes\n INFO - Beginning load: /Users/dblevins/examples/transaction-rollback/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/transaction-rollback\n WARN - Method 'lookup' is not available for 'javax.annotation.Resource'. Probably using an older Runtime.\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean Movies: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.txrollback.MoviesTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring PersistenceUnit(name=movie-unit)\n INFO - Auto-creating a Resource with id 'movieDatabaseNonJta' of type 'DataSource for 'movie-unit'.\n INFO - Configuring Service(id=movieDatabaseNonJta, type=Resource, provider-id=movieDatabase)\n INFO - Adjusting PersistenceUnit movie-unit <non-jta-data-source> to Resource ID 'movieDatabaseNonJta' from 'movieDatabaseUnmanaged'\n INFO - Enterprise application \"/Users/dblevins/examples/transaction-rollback\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/transaction-rollback\n INFO - PersistenceUnit(name=movie-unit, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 412ms\n INFO - Jndi(name=\"java:global/transaction-rollback/Movies!org.superbiz.txrollback.Movies\")\n INFO - Jndi(name=\"java:global/transaction-rollback/Movies\")\n INFO - Jndi(name=\"java:global/EjbModule1718375554/org.superbiz.txrollback.MoviesTest!org.superbiz.txrollback.MoviesTest\")\n INFO - Jndi(name=\"java:global/EjbModule1718375554/org.superbiz.txrollback.MoviesTest\")\n INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=org.superbiz.txrollback.MoviesTest, ejb-name=org.superbiz.txrollback.MoviesTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=org.superbiz.txrollback.MoviesTest, ejb-name=org.superbiz.txrollback.MoviesTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/transaction-rollback)\n WARN - The class \"org.superbiz.testinjection.MoviesTest.Movie\" listed in the openjpa.MetaDataFactory configuration property could not be loaded by sun.misc.Launcher$AppClassLoader@39172e08; ignoring.\n WARN - The class \"org.superbiz.testinjection.MoviesTest.Movie\" listed in the openjpa.MetaDataFactory configuration property could not be loaded by sun.misc.Launcher$AppClassLoader@39172e08; ignoring.\n WARN - The class \"org.superbiz.testinjection.MoviesTest.Movie\" listed in the openjpa.MetaDataFactory configuration property could not be loaded by sun.misc.Launcher$AppClassLoader@39172e08; ignoring.\n INFO - Undeploying app: /Users/dblevins/examples/transaction-rollback\n INFO - Closing DataSource: movieDatabase\n INFO - Closing DataSource: movieDatabaseNonJta\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/transaction-rollback\n INFO - openejb.base = /Users/dblevins/examples/transaction-rollback\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/transaction-rollback/target/classes\n INFO - Beginning load: /Users/dblevins/examples/transaction-rollback/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/transaction-rollback\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean Movies: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.txrollback.MoviesTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring PersistenceUnit(name=movie-unit)\n INFO - Auto-creating a Resource with id 'movieDatabaseNonJta' of type 'DataSource for 'movie-unit'.\n INFO - Configuring Service(id=movieDatabaseNonJta, type=Resource, provider-id=movieDatabase)\n INFO - Adjusting PersistenceUnit movie-unit <non-jta-data-source> to Resource ID 'movieDatabaseNonJta' from 'movieDatabaseUnmanaged'\n INFO - Enterprise application \"/Users/dblevins/examples/transaction-rollback\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/transaction-rollback\n INFO - PersistenceUnit(name=movie-unit, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 5ms\n INFO - Jndi(name=\"java:global/transaction-rollback/Movies!org.superbiz.txrollback.Movies\")\n INFO - Jndi(name=\"java:global/transaction-rollback/Movies\")\n INFO - Jndi(name=\"java:global/EjbModule935567559/org.superbiz.txrollback.MoviesTest!org.superbiz.txrollback.MoviesTest\")\n INFO - Jndi(name=\"java:global/EjbModule935567559/org.superbiz.txrollback.MoviesTest\")\n INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=org.superbiz.txrollback.MoviesTest, ejb-name=org.superbiz.txrollback.MoviesTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=org.superbiz.txrollback.MoviesTest, ejb-name=org.superbiz.txrollback.MoviesTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/transaction-rollback)\n WARN - The class \"org.superbiz.testinjection.MoviesTest.Movie\" listed in the openjpa.MetaDataFactory configuration property could not be loaded by sun.misc.Launcher$AppClassLoader@39172e08; ignoring.\n WARN - The class \"org.superbiz.testinjection.MoviesTest.Movie\" listed in the openjpa.MetaDataFactory configuration property could not be loaded by sun.misc.Launcher$AppClassLoader@39172e08; ignoring.\n WARN - The class \"org.superbiz.testinjection.MoviesTest.Movie\" listed in the openjpa.MetaDataFactory configuration property could not be loaded by sun.misc.Launcher$AppClassLoader@39172e08; ignoring.\n INFO - Undeploying app: /Users/dblevins/examples/transaction-rollback\n INFO - Closing DataSource: movieDatabase\n INFO - Closing DataSource: movieDatabaseNonJta\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/transaction-rollback\n INFO - openejb.base = /Users/dblevins/examples/transaction-rollback\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/transaction-rollback/target/classes\n INFO - Beginning load: /Users/dblevins/examples/transaction-rollback/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/transaction-rollback\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean Movies: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.txrollback.MoviesTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring PersistenceUnit(name=movie-unit)\n INFO - Auto-creating a Resource with id 'movieDatabaseNonJta' of type 'DataSource for 'movie-unit'.\n INFO - Configuring Service(id=movieDatabaseNonJta, type=Resource, provider-id=movieDatabase)\n INFO - Adjusting PersistenceUnit movie-unit <non-jta-data-source> to Resource ID 'movieDatabaseNonJta' from 'movieDatabaseUnmanaged'\n INFO - Enterprise application \"/Users/dblevins/examples/transaction-rollback\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/transaction-rollback\n INFO - PersistenceUnit(name=movie-unit, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 5ms\n INFO - Jndi(name=\"java:global/transaction-rollback/Movies!org.superbiz.txrollback.Movies\")\n INFO - Jndi(name=\"java:global/transaction-rollback/Movies\")\n INFO - Jndi(name=\"java:global/EjbModule1961109485/org.superbiz.txrollback.MoviesTest!org.superbiz.txrollback.MoviesTest\")\n INFO - Jndi(name=\"java:global/EjbModule1961109485/org.superbiz.txrollback.MoviesTest\")\n INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=org.superbiz.txrollback.MoviesTest, ejb-name=org.superbiz.txrollback.MoviesTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=org.superbiz.txrollback.MoviesTest, ejb-name=org.superbiz.txrollback.MoviesTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/transaction-rollback)\n WARN - The class \"org.superbiz.testinjection.MoviesTest.Movie\" listed in the openjpa.MetaDataFactory configuration property could not be loaded by sun.misc.Launcher$AppClassLoader@39172e08; ignoring.\n WARN - The class \"org.superbiz.testinjection.MoviesTest.Movie\" listed in the openjpa.MetaDataFactory configuration property could not be loaded by sun.misc.Launcher$AppClassLoader@39172e08; ignoring.\n WARN - The class \"org.superbiz.testinjection.MoviesTest.Movie\" listed in the openjpa.MetaDataFactory configuration property could not be loaded by sun.misc.Launcher$AppClassLoader@39172e08; ignoring.\n INFO - Undeploying app: /Users/dblevins/examples/transaction-rollback\n INFO - Closing DataSource: movieDatabase\n INFO - Closing DataSource: movieDatabaseNonJta\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/transaction-rollback\n INFO - openejb.base = /Users/dblevins/examples/transaction-rollback\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/transaction-rollback/target/classes\n INFO - Beginning load: /Users/dblevins/examples/transaction-rollback/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/transaction-rollback\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean Movies: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.txrollback.MoviesTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring PersistenceUnit(name=movie-unit)\n INFO - Auto-creating a Resource with id 'movieDatabaseNonJta' of type 'DataSource for 'movie-unit'.\n INFO - Configuring Service(id=movieDatabaseNonJta, type=Resource, provider-id=movieDatabase)\n INFO - Adjusting PersistenceUnit movie-unit <non-jta-data-source> to Resource ID 'movieDatabaseNonJta' from 'movieDatabaseUnmanaged'\n INFO - Enterprise application \"/Users/dblevins/examples/transaction-rollback\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/transaction-rollback\n INFO - PersistenceUnit(name=movie-unit, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 5ms\n INFO - Jndi(name=\"java:global/transaction-rollback/Movies!org.superbiz.txrollback.Movies\")\n INFO - Jndi(name=\"java:global/transaction-rollback/Movies\")\n INFO - Jndi(name=\"java:global/EjbModule419651577/org.superbiz.txrollback.MoviesTest!org.superbiz.txrollback.MoviesTest\")\n INFO - Jndi(name=\"java:global/EjbModule419651577/org.superbiz.txrollback.MoviesTest\")\n INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=org.superbiz.txrollback.MoviesTest, ejb-name=org.superbiz.txrollback.MoviesTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=org.superbiz.txrollback.MoviesTest, ejb-name=org.superbiz.txrollback.MoviesTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/transaction-rollback)\n WARN - The class \"org.superbiz.testinjection.MoviesTest.Movie\" listed in the openjpa.MetaDataFactory configuration property could not be loaded by sun.misc.Launcher$AppClassLoader@39172e08; ignoring.\n WARN - The class \"org.superbiz.testinjection.MoviesTest.Movie\" listed in the openjpa.MetaDataFactory configuration property could not be loaded by sun.misc.Launcher$AppClassLoader@39172e08; ignoring.\n WARN - The class \"org.superbiz.testinjection.MoviesTest.Movie\" listed in the openjpa.MetaDataFactory configuration property could not be loaded by sun.misc.Launcher$AppClassLoader@39172e08; ignoring.\n INFO - Undeploying app: /Users/dblevins/examples/transaction-rollback\n INFO - Closing DataSource: movieDatabase\n INFO - Closing DataSource: movieDatabaseNonJta\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/transaction-rollback\n INFO - openejb.base = /Users/dblevins/examples/transaction-rollback\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/transaction-rollback/target/classes\n INFO - Beginning load: /Users/dblevins/examples/transaction-rollback/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/transaction-rollback\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean Movies: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.txrollback.MoviesTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring PersistenceUnit(name=movie-unit)\n INFO - Auto-creating a Resource with id 'movieDatabaseNonJta' of type 'DataSource for 'movie-unit'.\n INFO - Configuring Service(id=movieDatabaseNonJta, type=Resource, provider-id=movieDatabase)\n INFO - Adjusting PersistenceUnit movie-unit <non-jta-data-source> to Resource ID 'movieDatabaseNonJta' from 'movieDatabaseUnmanaged'\n INFO - Enterprise application \"/Users/dblevins/examples/transaction-rollback\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/transaction-rollback\n INFO - PersistenceUnit(name=movie-unit, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 4ms\n INFO - Jndi(name=\"java:global/transaction-rollback/Movies!org.superbiz.txrollback.Movies\")\n INFO - Jndi(name=\"java:global/transaction-rollback/Movies\")\n INFO - Jndi(name=\"java:global/EjbModule15169271/org.superbiz.txrollback.MoviesTest!org.superbiz.txrollback.MoviesTest\")\n INFO - Jndi(name=\"java:global/EjbModule15169271/org.superbiz.txrollback.MoviesTest\")\n INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=org.superbiz.txrollback.MoviesTest, ejb-name=org.superbiz.txrollback.MoviesTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=org.superbiz.txrollback.MoviesTest, ejb-name=org.superbiz.txrollback.MoviesTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/transaction-rollback)\n WARN - The class \"org.superbiz.testinjection.MoviesTest.Movie\" listed in the openjpa.MetaDataFactory configuration property could not be loaded by sun.misc.Launcher$AppClassLoader@39172e08; ignoring.\n WARN - The class \"org.superbiz.testinjection.MoviesTest.Movie\" listed in the openjpa.MetaDataFactory configuration property could not be loaded by sun.misc.Launcher$AppClassLoader@39172e08; ignoring.\n WARN - The class \"org.superbiz.testinjection.MoviesTest.Movie\" listed in the openjpa.MetaDataFactory configuration property could not be loaded by sun.misc.Launcher$AppClassLoader@39172e08; ignoring.\n INFO - Undeploying app: /Users/dblevins/examples/transaction-rollback\n INFO - Closing DataSource: movieDatabase\n INFO - Closing DataSource: movieDatabaseNonJta\n Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.586 sec\n \n Results :\n \n Tests run: 5, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/transaction-rollback"
}
],
"routing":[
{
"name":"dynamic-datasource-routing",
"readme":"Title: Dynamic Datasource Routing\n\nThe TomEE dynamic datasource api aims to allow to use multiple data sources as one from an application point of view.\n\nIt can be useful for technical reasons (load balancing for example) or more generally\nfunctionnal reasons (filtering, aggregation, enriching...). However please note you can choose\nonly one datasource by transaction. It means the goal of this feature is not to switch more than\nonce of datasource in a transaction. The following code will not work:\n\n @Stateless\n public class MyEJB {\n @Resource private MyRouter router;\n @PersistenceContext private EntityManager em;\n\n public void workWithDataSources() {\n router.setDataSource(\"ds1\");\n em.persist(new MyEntity());\n\n router.setDataSource(\"ds2\"); // same transaction -> this invocation doesn't work\n em.persist(new MyEntity());\n }\n }\n\nIn this example the implementation simply use a datasource from its name and needs to be set before using any JPA\noperation in the transaction (to keep the logic simple in the example).\n\n# The implementation of the Router\n\nOur router has two configuration parameters:\n* a list of jndi names representing datasources to use\n* a default datasource to use\n\n## Router implementation\n\nThe interface Router (`org.apache.openejb.resource.jdbc.Router`) has only one method to implement, `public DataSource getDataSource()`\n\nOur `DeterminedRouter` implementation uses a ThreadLocal to manage the currently used datasource. Keep in mind JPA used more than once the getDatasource() method\nfor one operation. To change the datasource in one transaction is dangerous and should be avoid.\n\n package org.superbiz.dynamicdatasourcerouting;\n\n import org.apache.openejb.resource.jdbc.AbstractRouter;\n\n import javax.naming.NamingException;\n import javax.sql.DataSource;\n import java.util.Map;\n import java.util.concurrent.ConcurrentHashMap;\n\n public class DeterminedRouter extends AbstractRouter {\n private String dataSourceNames;\n private String defaultDataSourceName;\n private Map<String, DataSource> dataSources = null;\n private ThreadLocal<DataSource> currentDataSource = new ThreadLocal<DataSource>();\n\n /**\n * @param datasourceList datasource resource name, separator is a space\n */\n public void setDataSourceNames(String datasourceList) {\n dataSourceNames = datasourceList;\n }\n\n /**\n * lookup datasource in openejb resources\n */\n private void init() {\n dataSources = new ConcurrentHashMap<String, DataSource>();\n for (String ds : dataSourceNames.split(\" \")) {\n try {\n Object o = getOpenEJBResource(ds);\n if (o instanceof DataSource) {\n dataSources.put(ds, DataSource.class.cast(o));\n }\n } catch (NamingException e) {\n // ignored\n }\n }\n }\n\n /**\n * @return the user selected data source if it is set\n * or the default one\n * @throws IllegalArgumentException if the data source is not found\n */\n @Override\n public DataSource getDataSource() {\n // lazy init of routed datasources\n if (dataSources == null) {\n init();\n }\n\n // if no datasource is selected use the default one\n if (currentDataSource.get() == null) {\n if (dataSources.containsKey(defaultDataSourceName)) {\n return dataSources.get(defaultDataSourceName);\n\n } else {\n throw new IllegalArgumentException(\"you have to specify at least one datasource\");\n }\n }\n\n // the developper set the datasource to use\n return currentDataSource.get();\n }\n\n /**\n *\n * @param datasourceName data source name\n */\n public void setDataSource(String datasourceName) {\n if (dataSources == null) {\n init();\n }\n if (!dataSources.containsKey(datasourceName)) {\n throw new IllegalArgumentException(\"data source called \" + datasourceName + \" can't be found.\");\n }\n DataSource ds = dataSources.get(datasourceName);\n currentDataSource.set(ds);\n }\n\n /**\n * reset the data source\n */\n public void clear() {\n currentDataSource.remove();\n }\n\n public void setDefaultDataSourceName(String name) {\n this.defaultDataSourceName = name;\n }\n }\n\n## Declaring the implementation\n\nTo be able to use your router as a resource you need to provide a service configuration. It is done in a file\nyou can find in META-INF/org.router/ and called service-jar.xml\n(for your implementation you can of course change the package name).\n\nIt contains the following code:\n\n <ServiceJar>\n <ServiceProvider id=\"DeterminedRouter\" <!-- the name you want to use -->\n service=\"Resource\"\n type=\"org.apache.openejb.resource.jdbc.Router\"\n class-name=\"org.superbiz.dynamicdatasourcerouting.DeterminedRouter\"> <!-- implementation class -->\n\n # the parameters\n\n DataSourceNames\n DefaultDataSourceName\n </ServiceProvider>\n </ServiceJar>\n\n\n# Using the Router\n\nHere we have a `RoutedPersister` stateless bean which uses our `DeterminedRouter`\n\n package org.superbiz.dynamicdatasourcerouting;\n\n import javax.annotation.Resource;\n import javax.ejb.Stateless;\n import javax.persistence.EntityManager;\n import javax.persistence.PersistenceContext;\n\n @Stateless\n public class RoutedPersister {\n @PersistenceContext(unitName = \"router\")\n private EntityManager em;\n\n @Resource(name = \"My Router\", type = DeterminedRouter.class)\n private DeterminedRouter router;\n\n public void persist(int id, String name, String ds) {\n router.setDataSource(ds);\n em.persist(new Person(id, name));\n }\n }\n\n# The test\n\nIn test mode and using property style configuration the foolowing configuration is used:\n\n public class DynamicDataSourceTest {\n @Test\n public void route() throws Exception {\n String[] databases = new String[]{\"database1\", \"database2\", \"database3\"};\n\n Properties properties = new Properties();\n properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, LocalInitialContextFactory.class.getName());\n\n // resources\n // datasources\n for (int i = 1; i <= databases.length; i++) {\n String dbName = databases[i - 1];\n properties.setProperty(dbName, \"new://Resource?type=DataSource\");\n dbName += \".\";\n properties.setProperty(dbName + \"JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n properties.setProperty(dbName + \"JdbcUrl\", \"jdbc:hsqldb:mem:db\" + i);\n properties.setProperty(dbName + \"UserName\", \"sa\");\n properties.setProperty(dbName + \"Password\", \"\");\n properties.setProperty(dbName + \"JtaManaged\", \"true\");\n }\n\n // router\n properties.setProperty(\"My Router\", \"new://Resource?provider=org.router:DeterminedRouter&type=\" + DeterminedRouter.class.getName());\n properties.setProperty(\"My Router.DatasourceNames\", \"database1 database2 database3\");\n properties.setProperty(\"My Router.DefaultDataSourceName\", \"database1\");\n\n // routed datasource\n properties.setProperty(\"Routed Datasource\", \"new://Resource?provider=RoutedDataSource&type=\" + Router.class.getName());\n properties.setProperty(\"Routed Datasource.Router\", \"My Router\");\n\n Context ctx = EJBContainer.createEJBContainer(properties).getContext();\n RoutedPersister ejb = (RoutedPersister) ctx.lookup(\"java:global/dynamic-datasource-routing/RoutedPersister\");\n for (int i = 0; i < 18; i++) {\n // persisting a person on database db -> kind of manual round robin\n String name = \"record \" + i;\n String db = databases[i % 3];\n ejb.persist(i, name, db);\n }\n\n // assert database records number using jdbc\n for (int i = 1; i <= databases.length; i++) {\n Connection connection = DriverManager.getConnection(\"jdbc:hsqldb:mem:db\" + i, \"sa\", \"\");\n Statement st = connection.createStatement();\n ResultSet rs = st.executeQuery(\"select count(*) from PERSON\");\n rs.next();\n assertEquals(6, rs.getInt(1));\n st.close();\n connection.close();\n }\n\n ctx.close();\n }\n }\n\n# Configuration via openejb.xml\n\nThe testcase above uses properties for configuration. The identical way to do it via the `conf/openejb.xml` is as follows:\n\n <!-- Router and datasource -->\n <Resource id=\"My Router\" type=\"org.apache.openejb.router.test.DynamicDataSourceTest$DeterminedRouter\" provider=\"org.routertest:DeterminedRouter\">\n DatasourceNames = database1 database2 database3\n DefaultDataSourceName = database1\n </Resource>\n <Resource id=\"Routed Datasource\" type=\"org.apache.openejb.resource.jdbc.Router\" provider=\"RoutedDataSource\">\n Router = My Router\n </Resource>\n\n <!-- real datasources -->\n <Resource id=\"database1\" type=\"DataSource\">\n JdbcDriver = org.hsqldb.jdbcDriver\n JdbcUrl = jdbc:hsqldb:mem:db1\n UserName = sa\n Password\n JtaManaged = true\n </Resource>\n <Resource id=\"database2\" type=\"DataSource\">\n JdbcDriver = org.hsqldb.jdbcDriver\n JdbcUrl = jdbc:hsqldb:mem:db2\n UserName = sa\n Password\n JtaManaged = true\n </Resource>\n <Resource id=\"database3\" type=\"DataSource\">\n JdbcDriver = org.hsqldb.jdbcDriver\n JdbcUrl = jdbc:hsqldb:mem:db3\n UserName = sa\n Password\n JtaManaged = true\n </Resource>\n\n\n\n\n## Some hack for OpenJPA\n\nUsing more than one datasource behind one EntityManager means the databases are already created. If it is not the case,\nthe JPA provider has to create the datasource at boot time.\n\nHibernate do it so if you declare your databases it will work. However with OpenJPA\n(the default JPA provider for OpenEJB), the creation is lazy and it happens only once so when you'll switch of database\nit will no more work.\n\nOf course OpenEJB provides @Singleton and @Startup features of Java EE 6 and we can do a bean just making a simple find,\neven on none existing entities, just to force the database creation:\n\n @Startup\n @Singleton\n public class BoostrapUtility {\n // inject all real databases\n\n @PersistenceContext(unitName = \"db1\")\n private EntityManager em1;\n\n @PersistenceContext(unitName = \"db2\")\n private EntityManager em2;\n\n @PersistenceContext(unitName = \"db3\")\n private EntityManager em3;\n\n // force database creation\n\n @PostConstruct\n @TransactionAttribute(TransactionAttributeType.SUPPORTS)\n public void initDatabase() {\n em1.find(Person.class, 0);\n em2.find(Person.class, 0);\n em3.find(Person.class, 0);\n }\n }\n\n## Using the routed datasource\n\nNow you configured the way you want to route your JPA operation, you registered the resources and you initialized\nyour databases you can use it and see how it is simple:\n\n @Stateless\n public class RoutedPersister {\n // injection of the \"proxied\" datasource\n @PersistenceContext(unitName = \"router\")\n private EntityManager em;\n\n // injection of the router you need it to configured the database\n @Resource(name = \"My Router\", type = DeterminedRouter.class)\n private DeterminedRouter router;\n\n public void persist(int id, String name, String ds) {\n router.setDataSource(ds); // configuring the database for the current transaction\n em.persist(new Person(id, name)); // will use ds database automatically\n }\n }\n\n# Running\n\n\n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.dynamicdatasourcerouting.DynamicDataSourceTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/dynamic-datasource-routing\n INFO - openejb.base = /Users/dblevins/examples/dynamic-datasource-routing\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=My Router, type=Resource, provider-id=DeterminedRouter)\n INFO - Configuring Service(id=database3, type=Resource, provider-id=Default JDBC Database)\n INFO - Configuring Service(id=database2, type=Resource, provider-id=Default JDBC Database)\n INFO - Configuring Service(id=Routed Datasource, type=Resource, provider-id=RoutedDataSource)\n INFO - Configuring Service(id=database1, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/dynamic-datasource-routing/target/classes\n INFO - Beginning load: /Users/dblevins/examples/dynamic-datasource-routing/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/dynamic-datasource-routing\n WARN - Method 'lookup' is not available for 'javax.annotation.Resource'. Probably using an older Runtime.\n INFO - Configuring Service(id=Default Singleton Container, type=Container, provider-id=Default Singleton Container)\n INFO - Auto-creating a container for bean BoostrapUtility: Container(type=SINGLETON, id=Default Singleton Container)\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean RoutedPersister: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Auto-linking resource-ref 'java:comp/env/My Router' in bean RoutedPersister to Resource(id=My Router)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.dynamicdatasourcerouting.DynamicDataSourceTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring PersistenceUnit(name=router)\n INFO - Configuring PersistenceUnit(name=db1)\n INFO - Auto-creating a Resource with id 'database1NonJta' of type 'DataSource for 'db1'.\n INFO - Configuring Service(id=database1NonJta, type=Resource, provider-id=database1)\n INFO - Adjusting PersistenceUnit db1 <non-jta-data-source> to Resource ID 'database1NonJta' from 'null'\n INFO - Configuring PersistenceUnit(name=db2)\n INFO - Auto-creating a Resource with id 'database2NonJta' of type 'DataSource for 'db2'.\n INFO - Configuring Service(id=database2NonJta, type=Resource, provider-id=database2)\n INFO - Adjusting PersistenceUnit db2 <non-jta-data-source> to Resource ID 'database2NonJta' from 'null'\n INFO - Configuring PersistenceUnit(name=db3)\n INFO - Auto-creating a Resource with id 'database3NonJta' of type 'DataSource for 'db3'.\n INFO - Configuring Service(id=database3NonJta, type=Resource, provider-id=database3)\n INFO - Adjusting PersistenceUnit db3 <non-jta-data-source> to Resource ID 'database3NonJta' from 'null'\n INFO - Enterprise application \"/Users/dblevins/examples/dynamic-datasource-routing\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/dynamic-datasource-routing\n INFO - PersistenceUnit(name=router, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 504ms\n INFO - PersistenceUnit(name=db1, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 11ms\n INFO - PersistenceUnit(name=db2, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 7ms\n INFO - PersistenceUnit(name=db3, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 6ms\n INFO - Jndi(name=\"java:global/dynamic-datasource-routing/BoostrapUtility!org.superbiz.dynamicdatasourcerouting.BoostrapUtility\")\n INFO - Jndi(name=\"java:global/dynamic-datasource-routing/BoostrapUtility\")\n INFO - Jndi(name=\"java:global/dynamic-datasource-routing/RoutedPersister!org.superbiz.dynamicdatasourcerouting.RoutedPersister\")\n INFO - Jndi(name=\"java:global/dynamic-datasource-routing/RoutedPersister\")\n INFO - Jndi(name=\"java:global/EjbModule1519652738/org.superbiz.dynamicdatasourcerouting.DynamicDataSourceTest!org.superbiz.dynamicdatasourcerouting.DynamicDataSourceTest\")\n INFO - Jndi(name=\"java:global/EjbModule1519652738/org.superbiz.dynamicdatasourcerouting.DynamicDataSourceTest\")\n INFO - Created Ejb(deployment-id=RoutedPersister, ejb-name=RoutedPersister, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=org.superbiz.dynamicdatasourcerouting.DynamicDataSourceTest, ejb-name=org.superbiz.dynamicdatasourcerouting.DynamicDataSourceTest, container=Default Managed Container)\n INFO - Created Ejb(deployment-id=BoostrapUtility, ejb-name=BoostrapUtility, container=Default Singleton Container)\n INFO - Started Ejb(deployment-id=RoutedPersister, ejb-name=RoutedPersister, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=org.superbiz.dynamicdatasourcerouting.DynamicDataSourceTest, ejb-name=org.superbiz.dynamicdatasourcerouting.DynamicDataSourceTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=BoostrapUtility, ejb-name=BoostrapUtility, container=Default Singleton Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/dynamic-datasource-routing)\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.504 sec\n\n Results :\n\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n\n",
"url":"https://github.com/apache/tomee/tree/master/examples/dynamic-datasource-routing"
}
],
"scala":[
{
"name":"scala-basic",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/scala-basic"
}
],
"schedule":[
{
"name":"schedule-methods",
"readme":"Title: Schedule Methods\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## FarmerBrown\n\n package org.superbiz.corn;\n \n import javax.ejb.Lock;\n import javax.ejb.LockType;\n import javax.ejb.Schedule;\n import javax.ejb.Schedules;\n import javax.ejb.Singleton;\n import java.util.concurrent.atomic.AtomicInteger;\n \n /**\n * This is where we schedule all of Farmer Brown's corn jobs\n *\n * @version $Revision$ $Date$\n */\n @Singleton\n @Lock(LockType.READ) // allows timers to execute in parallel\n public class FarmerBrown {\n \n private final AtomicInteger checks = new AtomicInteger();\n \n @Schedules({\n @Schedule(month = \"5\", dayOfMonth = \"20-Last\", minute = \"0\", hour = \"8\"),\n @Schedule(month = \"6\", dayOfMonth = \"1-10\", minute = \"0\", hour = \"8\")\n })\n private void plantTheCorn() {\n // Dig out the planter!!!\n }\n \n @Schedules({\n @Schedule(month = \"9\", dayOfMonth = \"20-Last\", minute = \"0\", hour = \"8\"),\n @Schedule(month = \"10\", dayOfMonth = \"1-10\", minute = \"0\", hour = \"8\")\n })\n private void harvestTheCorn() {\n // Dig out the combine!!!\n }\n \n @Schedule(second = \"*\", minute = \"*\", hour = \"*\")\n private void checkOnTheDaughters() {\n checks.incrementAndGet();\n }\n \n public int getChecks() {\n return checks.get();\n }\n }\n\n## FarmerBrownTest\n\n package org.superbiz.corn;\n \n import junit.framework.TestCase;\n \n import javax.ejb.embeddable.EJBContainer;\n import javax.naming.Context;\n \n import static java.util.concurrent.TimeUnit.SECONDS;\n \n /**\n * @version $Revision$ $Date$\n */\n public class FarmerBrownTest extends TestCase {\n \n public void test() throws Exception {\n \n final Context context = EJBContainer.createEJBContainer().getContext();\n \n final FarmerBrown farmerBrown = (FarmerBrown) context.lookup(\"java:global/schedule-methods/FarmerBrown\");\n \n // Give Farmer brown a chance to do some work\n Thread.sleep(SECONDS.toMillis(5));\n \n assertTrue(farmerBrown.getChecks() > 4);\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.corn.FarmerBrownTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/schedule-methods\n INFO - openejb.base = /Users/dblevins/examples/schedule-methods\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/schedule-methods/target/classes\n INFO - Beginning load: /Users/dblevins/examples/schedule-methods/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/schedule-methods\n INFO - Configuring Service(id=Default Singleton Container, type=Container, provider-id=Default Singleton Container)\n INFO - Auto-creating a container for bean FarmerBrown: Container(type=SINGLETON, id=Default Singleton Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.corn.FarmerBrownTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Enterprise application \"/Users/dblevins/examples/schedule-methods\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/schedule-methods\n INFO - Jndi(name=\"java:global/schedule-methods/FarmerBrown!org.superbiz.corn.FarmerBrown\")\n INFO - Jndi(name=\"java:global/schedule-methods/FarmerBrown\")\n INFO - Jndi(name=\"java:global/EjbModule660493198/org.superbiz.corn.FarmerBrownTest!org.superbiz.corn.FarmerBrownTest\")\n INFO - Jndi(name=\"java:global/EjbModule660493198/org.superbiz.corn.FarmerBrownTest\")\n INFO - Created Ejb(deployment-id=org.superbiz.corn.FarmerBrownTest, ejb-name=org.superbiz.corn.FarmerBrownTest, container=Default Managed Container)\n INFO - Created Ejb(deployment-id=FarmerBrown, ejb-name=FarmerBrown, container=Default Singleton Container)\n INFO - Started Ejb(deployment-id=org.superbiz.corn.FarmerBrownTest, ejb-name=org.superbiz.corn.FarmerBrownTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=FarmerBrown, ejb-name=FarmerBrown, container=Default Singleton Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/schedule-methods)\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 6.121 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/schedule-methods"
},
{
"name":"schedule-methods-meta",
"readme":"Title: Schedule Methods Meta\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## BiAnnually\n\n package org.superbiz.corn.meta.api;\n \n import javax.ejb.Schedule;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n @Metatype\n @Target(ElementType.METHOD)\n @Retention(RetentionPolicy.RUNTIME)\n \n public @interface BiAnnually {\n public static interface $ {\n \n @BiAnnually\n @Schedule(second = \"0\", minute = \"0\", hour = \"0\", dayOfMonth = \"1\", month = \"1,6\")\n public void method();\n }\n }\n\n## BiMonthly\n\n package org.superbiz.corn.meta.api;\n \n import javax.ejb.Schedule;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n @Metatype\n @Target(ElementType.METHOD)\n @Retention(RetentionPolicy.RUNTIME)\n \n public @interface BiMonthly {\n public static interface $ {\n \n @BiMonthly\n @Schedule(second = \"0\", minute = \"0\", hour = \"0\", dayOfMonth = \"1,15\")\n public void method();\n }\n }\n\n## Daily\n\n package org.superbiz.corn.meta.api;\n \n import javax.ejb.Schedule;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n @Metatype\n @Target(ElementType.METHOD)\n @Retention(RetentionPolicy.RUNTIME)\n \n public @interface Daily {\n public static interface $ {\n \n @Daily\n @Schedule(second = \"0\", minute = \"0\", hour = \"0\", dayOfMonth = \"*\")\n public void method();\n }\n }\n\n## HarvestTime\n\n package org.superbiz.corn.meta.api;\n \n import javax.ejb.Schedule;\n import javax.ejb.Schedules;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n @Metatype\n @Target(ElementType.METHOD)\n @Retention(RetentionPolicy.RUNTIME)\n \n public @interface HarvestTime {\n public static interface $ {\n \n @HarvestTime\n @Schedules({\n @Schedule(month = \"9\", dayOfMonth = \"20-Last\", minute = \"0\", hour = \"8\"),\n @Schedule(month = \"10\", dayOfMonth = \"1-10\", minute = \"0\", hour = \"8\")\n })\n public void method();\n }\n }\n\n## Hourly\n\n package org.superbiz.corn.meta.api;\n \n import javax.ejb.Schedule;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n @Metatype\n @Target(ElementType.METHOD)\n @Retention(RetentionPolicy.RUNTIME)\n \n public @interface Hourly {\n public static interface $ {\n \n @Hourly\n @Schedule(second = \"0\", minute = \"0\", hour = \"*\")\n public void method();\n }\n }\n\n## Metatype\n\n package org.superbiz.corn.meta.api;\n \n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n @Metatype\n @Target(ElementType.ANNOTATION_TYPE)\n @Retention(RetentionPolicy.RUNTIME)\n public @interface Metatype {\n }\n\n## Organic\n\n package org.superbiz.corn.meta.api;\n \n import javax.ejb.Lock;\n import javax.ejb.LockType;\n import javax.ejb.Singleton;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n @Metatype\n @Target(ElementType.TYPE)\n @Retention(RetentionPolicy.RUNTIME)\n \n @Singleton\n @Lock(LockType.READ)\n public @interface Organic {\n }\n\n## PlantingTime\n\n package org.superbiz.corn.meta.api;\n \n import javax.ejb.Schedule;\n import javax.ejb.Schedules;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n @Metatype\n @Target(ElementType.METHOD)\n @Retention(RetentionPolicy.RUNTIME)\n \n public @interface PlantingTime {\n public static interface $ {\n \n @PlantingTime\n @Schedules({\n @Schedule(month = \"5\", dayOfMonth = \"20-Last\", minute = \"0\", hour = \"8\"),\n @Schedule(month = \"6\", dayOfMonth = \"1-10\", minute = \"0\", hour = \"8\")\n })\n public void method();\n }\n }\n\n## Secondly\n\n package org.superbiz.corn.meta.api;\n \n import javax.ejb.Schedule;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n @Metatype\n @Target(ElementType.METHOD)\n @Retention(RetentionPolicy.RUNTIME)\n \n public @interface Secondly {\n public static interface $ {\n \n @Secondly\n @Schedule(second = \"*\", minute = \"*\", hour = \"*\")\n public void method();\n }\n }\n\n## FarmerBrown\n\n package org.superbiz.corn.meta;\n \n import org.superbiz.corn.meta.api.HarvestTime;\n import org.superbiz.corn.meta.api.Organic;\n import org.superbiz.corn.meta.api.PlantingTime;\n import org.superbiz.corn.meta.api.Secondly;\n \n import java.util.concurrent.atomic.AtomicInteger;\n \n /**\n * This is where we schedule all of Farmer Brown's corn jobs\n *\n * @version $Revision$ $Date$\n */\n @Organic\n public class FarmerBrown {\n \n private final AtomicInteger checks = new AtomicInteger();\n \n @PlantingTime\n private void plantTheCorn() {\n // Dig out the planter!!!\n }\n \n @HarvestTime\n private void harvestTheCorn() {\n // Dig out the combine!!!\n }\n \n @Secondly\n private void checkOnTheDaughters() {\n checks.incrementAndGet();\n }\n \n public int getChecks() {\n return checks.get();\n }\n }\n\n## FarmerBrownTest\n\n package org.superbiz.corn.meta;\n \n import junit.framework.TestCase;\n \n import javax.ejb.embeddable.EJBContainer;\n import javax.naming.Context;\n \n import static java.util.concurrent.TimeUnit.SECONDS;\n \n /**\n * @version $Revision$ $Date$\n */\n public class FarmerBrownTest extends TestCase {\n \n public void test() throws Exception {\n \n final Context context = EJBContainer.createEJBContainer().getContext();\n \n final FarmerBrown farmerBrown = (FarmerBrown) context.lookup(\"java:global/schedule-methods-meta/FarmerBrown\");\n \n // Give Farmer brown a chance to do some work\n Thread.sleep(SECONDS.toMillis(5));\n \n assertTrue(farmerBrown.getChecks() > 4);\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.corn.meta.FarmerBrownTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/schedule-methods-meta\n INFO - openejb.base = /Users/dblevins/examples/schedule-methods-meta\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/schedule-methods-meta/target/classes\n INFO - Beginning load: /Users/dblevins/examples/schedule-methods-meta/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/schedule-methods-meta\n INFO - Configuring Service(id=Default Singleton Container, type=Container, provider-id=Default Singleton Container)\n INFO - Auto-creating a container for bean FarmerBrown: Container(type=SINGLETON, id=Default Singleton Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.corn.meta.FarmerBrownTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Enterprise application \"/Users/dblevins/examples/schedule-methods-meta\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/schedule-methods-meta\n INFO - Jndi(name=\"java:global/schedule-methods-meta/FarmerBrown!org.superbiz.corn.meta.FarmerBrown\")\n INFO - Jndi(name=\"java:global/schedule-methods-meta/FarmerBrown\")\n INFO - Jndi(name=\"java:global/EjbModule1809441479/org.superbiz.corn.meta.FarmerBrownTest!org.superbiz.corn.meta.FarmerBrownTest\")\n INFO - Jndi(name=\"java:global/EjbModule1809441479/org.superbiz.corn.meta.FarmerBrownTest\")\n INFO - Created Ejb(deployment-id=org.superbiz.corn.meta.FarmerBrownTest, ejb-name=org.superbiz.corn.meta.FarmerBrownTest, container=Default Managed Container)\n INFO - Created Ejb(deployment-id=FarmerBrown, ejb-name=FarmerBrown, container=Default Singleton Container)\n INFO - Started Ejb(deployment-id=org.superbiz.corn.meta.FarmerBrownTest, ejb-name=org.superbiz.corn.meta.FarmerBrownTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=FarmerBrown, ejb-name=FarmerBrown, container=Default Singleton Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/schedule-methods-meta)\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 6.166 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/schedule-methods-meta"
},
{
"name":"schedule-expression",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/schedule-expression"
},
{
"name":"schedule-events",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/schedule-events"
}
],
"scope":[
{
"name":"cdi-application-scope",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/cdi-application-scope"
},
{
"name":"cdi-request-scope",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/cdi-request-scope"
},
{
"name":"cdi-session-scope",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/cdi-session-scope"
}
],
"security":[
{
"name":"testing-security",
"readme":"Title: Testing Security\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## Movie\n\n package org.superbiz.injection.secure;\n \n import javax.persistence.Entity;\n \n @Entity\n public class Movie {\n \n private String director;\n private String title;\n private int year;\n \n public Movie() {\n }\n \n public Movie(String director, String title, int year) {\n this.director = director;\n this.title = title;\n this.year = year;\n }\n \n public String getDirector() {\n return director;\n }\n \n public void setDirector(String director) {\n this.director = director;\n }\n \n public String getTitle() {\n return title;\n }\n \n public void setTitle(String title) {\n this.title = title;\n }\n \n public int getYear() {\n return year;\n }\n \n public void setYear(int year) {\n this.year = year;\n }\n \n }\n\n## Movies\n\n package org.superbiz.injection.secure;\n \n //START SNIPPET: code\n \n import javax.annotation.security.PermitAll;\n import javax.annotation.security.RolesAllowed;\n import javax.ejb.Stateful;\n import javax.ejb.TransactionAttribute;\n import javax.ejb.TransactionAttributeType;\n import javax.persistence.EntityManager;\n import javax.persistence.PersistenceContext;\n import javax.persistence.PersistenceContextType;\n import javax.persistence.Query;\n import java.util.List;\n \n @Stateful\n public class Movies {\n \n @PersistenceContext(unitName = \"movie-unit\", type = PersistenceContextType.EXTENDED)\n private EntityManager entityManager;\n \n @RolesAllowed({\"Employee\", \"Manager\"})\n public void addMovie(Movie movie) throws Exception {\n entityManager.persist(movie);\n }\n \n @RolesAllowed({\"Manager\"})\n public void deleteMovie(Movie movie) throws Exception {\n entityManager.remove(movie);\n }\n \n @PermitAll\n @TransactionAttribute(TransactionAttributeType.SUPPORTS)\n public List<Movie> getMovies() throws Exception {\n Query query = entityManager.createQuery(\"SELECT m from Movie as m\");\n return query.getResultList();\n }\n }\n\n## persistence.xml\n\n <persistence xmlns=\"http://java.sun.com/xml/ns/persistence\" version=\"1.0\">\n \n <persistence-unit name=\"movie-unit\">\n <jta-data-source>movieDatabase</jta-data-source>\n <non-jta-data-source>movieDatabaseUnmanaged</non-jta-data-source>\n <class>org.superbiz.injection.secure.Movie</class>\n \n <properties>\n <property name=\"openjpa.jdbc.SynchronizeMappings\" value=\"buildSchema(ForeignKeys=true)\"/>\n </properties>\n </persistence-unit>\n </persistence>\n\n## MovieTest\n\n package org.superbiz.injection.secure;\n \n import junit.framework.TestCase;\n \n import javax.annotation.security.RunAs;\n import javax.ejb.EJB;\n import javax.ejb.EJBAccessException;\n import javax.ejb.Stateless;\n import javax.ejb.embeddable.EJBContainer;\n import java.util.List;\n import java.util.Properties;\n import java.util.concurrent.Callable;\n \n //START SNIPPET: code\n \n public class MovieTest extends TestCase {\n \n @EJB\n private Movies movies;\n \n @EJB(name = \"ManagerBean\")\n private Caller manager;\n \n @EJB(name = \"EmployeeBean\")\n private Caller employee;\n \n protected void setUp() throws Exception {\n Properties p = new Properties();\n p.put(\"movieDatabase\", \"new://Resource?type=DataSource\");\n p.put(\"movieDatabase.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"movieDatabase.JdbcUrl\", \"jdbc:hsqldb:mem:moviedb\");\n \n EJBContainer.createEJBContainer(p).getContext().bind(\"inject\", this);\n }\n \n public void testAsManager() throws Exception {\n manager.call(new Callable() {\n public Object call() throws Exception {\n \n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n movies.addMovie(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n movies.addMovie(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n \n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n \n for (Movie movie : list) {\n movies.deleteMovie(movie);\n }\n \n assertEquals(\"Movies.getMovies()\", 0, movies.getMovies().size());\n return null;\n }\n });\n }\n \n public void testAsEmployee() throws Exception {\n employee.call(new Callable() {\n public Object call() throws Exception {\n \n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n movies.addMovie(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n movies.addMovie(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n \n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n \n for (Movie movie : list) {\n try {\n movies.deleteMovie(movie);\n fail(\"Employees should not be allowed to delete\");\n } catch (EJBAccessException e) {\n // Good, Employees cannot delete things\n }\n }\n \n // The list should still be three movies long\n assertEquals(\"Movies.getMovies()\", 3, movies.getMovies().size());\n return null;\n }\n });\n }\n \n public void testUnauthenticated() throws Exception {\n try {\n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n fail(\"Unauthenticated users should not be able to add movies\");\n } catch (EJBAccessException e) {\n // Good, guests cannot add things\n }\n \n try {\n movies.deleteMovie(null);\n fail(\"Unauthenticated users should not be allowed to delete\");\n } catch (EJBAccessException e) {\n // Good, Unauthenticated users cannot delete things\n }\n \n try {\n // Read access should be allowed\n \n List<Movie> list = movies.getMovies();\n } catch (EJBAccessException e) {\n fail(\"Read access should be allowed\");\n }\n }\n \n \n public static interface Caller {\n public <V> V call(Callable<V> callable) throws Exception;\n }\n \n /**\n * This little bit of magic allows our test code to execute in\n * the desired security scope.\n */\n \n @Stateless\n @RunAs(\"Manager\")\n public static class ManagerBean implements Caller {\n \n public <V> V call(Callable<V> callable) throws Exception {\n return callable.call();\n }\n }\n \n @Stateless\n @RunAs(\"Employee\")\n public static class EmployeeBean implements Caller {\n \n public <V> V call(Callable<V> callable) throws Exception {\n return callable.call();\n }\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.injection.secure.MovieTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/testing-security\n INFO - openejb.base = /Users/dblevins/examples/testing-security\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/testing-security/target/classes\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/testing-security/target/test-classes\n INFO - Beginning load: /Users/dblevins/examples/testing-security/target/classes\n INFO - Beginning load: /Users/dblevins/examples/testing-security/target/test-classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/testing-security\n INFO - Configuring Service(id=Default Stateful Container, type=Container, provider-id=Default Stateful Container)\n INFO - Auto-creating a container for bean Movies: Container(type=STATEFUL, id=Default Stateful Container)\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean ManagerBean: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.injection.secure.MovieTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring PersistenceUnit(name=movie-unit)\n INFO - Auto-creating a Resource with id 'movieDatabaseNonJta' of type 'DataSource for 'movie-unit'.\n INFO - Configuring Service(id=movieDatabaseNonJta, type=Resource, provider-id=movieDatabase)\n INFO - Adjusting PersistenceUnit movie-unit <non-jta-data-source> to Resource ID 'movieDatabaseNonJta' from 'movieDatabaseUnmanaged'\n INFO - Enterprise application \"/Users/dblevins/examples/testing-security\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/testing-security\n INFO - PersistenceUnit(name=movie-unit, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 405ms\n INFO - Jndi(name=\"java:global/testing-security/Movies!org.superbiz.injection.secure.Movies\")\n INFO - Jndi(name=\"java:global/testing-security/Movies\")\n INFO - Jndi(name=\"java:global/testing-security/ManagerBean!org.superbiz.injection.secure.MovieTest$Caller\")\n INFO - Jndi(name=\"java:global/testing-security/ManagerBean\")\n INFO - Jndi(name=\"java:global/testing-security/EmployeeBean!org.superbiz.injection.secure.MovieTest$Caller\")\n INFO - Jndi(name=\"java:global/testing-security/EmployeeBean\")\n INFO - Jndi(name=\"java:global/EjbModule26174809/org.superbiz.injection.secure.MovieTest!org.superbiz.injection.secure.MovieTest\")\n INFO - Jndi(name=\"java:global/EjbModule26174809/org.superbiz.injection.secure.MovieTest\")\n INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Created Ejb(deployment-id=ManagerBean, ejb-name=ManagerBean, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=EmployeeBean, ejb-name=EmployeeBean, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=org.superbiz.injection.secure.MovieTest, ejb-name=org.superbiz.injection.secure.MovieTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Started Ejb(deployment-id=ManagerBean, ejb-name=ManagerBean, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=EmployeeBean, ejb-name=EmployeeBean, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=org.superbiz.injection.secure.MovieTest, ejb-name=org.superbiz.injection.secure.MovieTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/testing-security)\n INFO - EJBContainer already initialized. Call ejbContainer.close() to allow reinitialization\n INFO - EJBContainer already initialized. Call ejbContainer.close() to allow reinitialization\n Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.574 sec\n \n Results :\n \n Tests run: 3, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/testing-security"
},
{
"name":"testing-security-meta",
"readme":"Title: Testing Security Meta\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## AddPermission\n\n package org.superbiz.injection.secure.api;\n \n import javax.annotation.security.RolesAllowed;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n \n @Metatype\n @Target(ElementType.METHOD)\n @Retention(RetentionPolicy.RUNTIME)\n \n public @interface AddPermission {\n public static interface $ {\n \n @AddPermission\n @RolesAllowed({\"Employee\", \"Manager\"})\n public void method();\n }\n }\n\n## DeletePermission\n\n package org.superbiz.injection.secure.api;\n \n import javax.annotation.security.RolesAllowed;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n \n @Metatype\n @Target(ElementType.METHOD)\n @Retention(RetentionPolicy.RUNTIME)\n \n public @interface DeletePermission {\n public static interface $ {\n \n @DeletePermission\n @RolesAllowed(\"Manager\")\n public void method();\n }\n }\n\n## Metatype\n\n package org.superbiz.injection.secure.api;\n \n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n @Metatype\n @Target(ElementType.ANNOTATION_TYPE)\n @Retention(RetentionPolicy.RUNTIME)\n public @interface Metatype {\n }\n\n## MovieUnit\n\n package org.superbiz.injection.secure.api;\n \n import javax.persistence.PersistenceContext;\n import javax.persistence.PersistenceContextType;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n \n @Metatype\n @Target({ElementType.METHOD, ElementType.FIELD})\n @Retention(RetentionPolicy.RUNTIME)\n \n @PersistenceContext(name = \"movie-unit\", unitName = \"movie-unit\", type = PersistenceContextType.EXTENDED)\n public @interface MovieUnit {\n }\n\n## ReadPermission\n\n package org.superbiz.injection.secure.api;\n \n import javax.annotation.security.PermitAll;\n import javax.ejb.TransactionAttribute;\n import javax.ejb.TransactionAttributeType;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n \n @Metatype\n @Target(ElementType.METHOD)\n @Retention(RetentionPolicy.RUNTIME)\n \n public @interface ReadPermission {\n public static interface $ {\n \n @ReadPermission\n @PermitAll\n @TransactionAttribute(TransactionAttributeType.SUPPORTS)\n public void method();\n }\n }\n\n## RunAsEmployee\n\n package org.superbiz.injection.secure.api;\n \n import javax.annotation.security.RunAs;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n \n @Metatype\n @Target({ElementType.TYPE, ElementType.METHOD})\n @Retention(RetentionPolicy.RUNTIME)\n \n @RunAs(\"Employee\")\n public @interface RunAsEmployee {\n }\n\n## RunAsManager\n\n package org.superbiz.injection.secure.api;\n \n import javax.annotation.security.RunAs;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n \n @Metatype\n @Target({ElementType.TYPE, ElementType.METHOD})\n @Retention(RetentionPolicy.RUNTIME)\n \n @RunAs(\"Manager\")\n public @interface RunAsManager {\n }\n\n## Movie\n\n package org.superbiz.injection.secure;\n \n import javax.persistence.Entity;\n \n @Entity\n public class Movie {\n \n private String director;\n private String title;\n private int year;\n \n public Movie() {\n }\n \n public Movie(String director, String title, int year) {\n this.director = director;\n this.title = title;\n this.year = year;\n }\n \n public String getDirector() {\n return director;\n }\n \n public void setDirector(String director) {\n this.director = director;\n }\n \n public String getTitle() {\n return title;\n }\n \n public void setTitle(String title) {\n this.title = title;\n }\n \n public int getYear() {\n return year;\n }\n \n public void setYear(int year) {\n this.year = year;\n }\n \n }\n\n## Movies\n\n package org.superbiz.injection.secure;\n \n //START SNIPPET: code\n \n import org.superbiz.injection.secure.api.AddPermission;\n import org.superbiz.injection.secure.api.DeletePermission;\n import org.superbiz.injection.secure.api.MovieUnit;\n import org.superbiz.injection.secure.api.ReadPermission;\n \n import javax.ejb.Stateful;\n import javax.persistence.EntityManager;\n import javax.persistence.Query;\n import java.util.List;\n \n @Stateful\n public class Movies {\n \n @MovieUnit\n private EntityManager entityManager;\n \n @AddPermission\n public void addMovie(Movie movie) throws Exception {\n entityManager.persist(movie);\n }\n \n @DeletePermission\n public void deleteMovie(Movie movie) throws Exception {\n entityManager.remove(movie);\n }\n \n @ReadPermission\n public List<Movie> getMovies() throws Exception {\n Query query = entityManager.createQuery(\"SELECT m from Movie as m\");\n return query.getResultList();\n }\n }\n\n## persistence.xml\n\n <persistence xmlns=\"http://java.sun.com/xml/ns/persistence\" version=\"1.0\">\n \n <persistence-unit name=\"movie-unit\">\n <jta-data-source>movieDatabase</jta-data-source>\n <non-jta-data-source>movieDatabaseUnmanaged</non-jta-data-source>\n <class>org.superbiz.injection.secure.Movie</class>\n \n <properties>\n <property name=\"openjpa.jdbc.SynchronizeMappings\" value=\"buildSchema(ForeignKeys=true)\"/>\n </properties>\n </persistence-unit>\n </persistence>\n\n## MovieTest\n\n package org.superbiz.injection.secure;\n \n import junit.framework.TestCase;\n import org.superbiz.injection.secure.api.RunAsEmployee;\n import org.superbiz.injection.secure.api.RunAsManager;\n \n import javax.ejb.EJB;\n import javax.ejb.EJBAccessException;\n import javax.ejb.Stateless;\n import javax.ejb.embeddable.EJBContainer;\n import java.util.List;\n import java.util.Properties;\n import java.util.concurrent.Callable;\n \n //START SNIPPET: code\n \n public class MovieTest extends TestCase {\n \n @EJB\n private Movies movies;\n \n @EJB(beanName = \"ManagerBean\")\n private Caller manager;\n \n @EJB(beanName = \"EmployeeBean\")\n private Caller employee;\n \n protected void setUp() throws Exception {\n Properties p = new Properties();\n p.put(\"movieDatabase\", \"new://Resource?type=DataSource\");\n p.put(\"movieDatabase.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"movieDatabase.JdbcUrl\", \"jdbc:hsqldb:mem:moviedb\");\n \n EJBContainer.createEJBContainer(p).getContext().bind(\"inject\", this);\n }\n \n public void testAsManager() throws Exception {\n manager.call(new Callable() {\n public Object call() throws Exception {\n \n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n movies.addMovie(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n movies.addMovie(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n \n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n \n for (Movie movie : list) {\n movies.deleteMovie(movie);\n }\n \n assertEquals(\"Movies.getMovies()\", 0, movies.getMovies().size());\n return null;\n }\n });\n }\n \n public void testAsEmployee() throws Exception {\n employee.call(new Callable() {\n public Object call() throws Exception {\n \n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n movies.addMovie(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n movies.addMovie(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n \n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n \n for (Movie movie : list) {\n try {\n movies.deleteMovie(movie);\n fail(\"Employees should not be allowed to delete\");\n } catch (EJBAccessException e) {\n // Good, Employees cannot delete things\n }\n }\n \n // The list should still be three movies long\n assertEquals(\"Movies.getMovies()\", 3, movies.getMovies().size());\n return null;\n }\n });\n }\n \n public void testUnauthenticated() throws Exception {\n try {\n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n fail(\"Unauthenticated users should not be able to add movies\");\n } catch (EJBAccessException e) {\n // Good, guests cannot add things\n }\n \n try {\n movies.deleteMovie(null);\n fail(\"Unauthenticated users should not be allowed to delete\");\n } catch (EJBAccessException e) {\n // Good, Unauthenticated users cannot delete things\n }\n \n try {\n // Read access should be allowed\n \n List<Movie> list = movies.getMovies();\n } catch (EJBAccessException e) {\n fail(\"Read access should be allowed\");\n }\n }\n \n public interface Caller {\n public <V> V call(Callable<V> callable) throws Exception;\n }\n \n /**\n * This little bit of magic allows our test code to execute in\n * the desired security scope.\n */\n \n @Stateless\n @RunAsManager\n public static class ManagerBean implements Caller {\n \n public <V> V call(Callable<V> callable) throws Exception {\n return callable.call();\n }\n }\n \n @Stateless\n @RunAsEmployee\n public static class EmployeeBean implements Caller {\n \n public <V> V call(Callable<V> callable) throws Exception {\n return callable.call();\n }\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.injection.secure.MovieTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/testing-security-meta\n INFO - openejb.base = /Users/dblevins/examples/testing-security-meta\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/testing-security-meta/target/classes\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/testing-security-meta/target/test-classes\n INFO - Beginning load: /Users/dblevins/examples/testing-security-meta/target/classes\n INFO - Beginning load: /Users/dblevins/examples/testing-security-meta/target/test-classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/testing-security-meta\n INFO - Configuring Service(id=Default Stateful Container, type=Container, provider-id=Default Stateful Container)\n INFO - Auto-creating a container for bean Movies: Container(type=STATEFUL, id=Default Stateful Container)\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean ManagerBean: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.injection.secure.MovieTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring PersistenceUnit(name=movie-unit)\n INFO - Auto-creating a Resource with id 'movieDatabaseNonJta' of type 'DataSource for 'movie-unit'.\n INFO - Configuring Service(id=movieDatabaseNonJta, type=Resource, provider-id=movieDatabase)\n INFO - Adjusting PersistenceUnit movie-unit <non-jta-data-source> to Resource ID 'movieDatabaseNonJta' from 'movieDatabaseUnmanaged'\n INFO - Enterprise application \"/Users/dblevins/examples/testing-security-meta\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/testing-security-meta\n INFO - PersistenceUnit(name=movie-unit, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 419ms\n INFO - Jndi(name=\"java:global/testing-security-meta/Movies!org.superbiz.injection.secure.Movies\")\n INFO - Jndi(name=\"java:global/testing-security-meta/Movies\")\n INFO - Jndi(name=\"java:global/testing-security-meta/ManagerBean!org.superbiz.injection.secure.MovieTest$Caller\")\n INFO - Jndi(name=\"java:global/testing-security-meta/ManagerBean\")\n INFO - Jndi(name=\"java:global/testing-security-meta/EmployeeBean!org.superbiz.injection.secure.MovieTest$Caller\")\n INFO - Jndi(name=\"java:global/testing-security-meta/EmployeeBean\")\n INFO - Jndi(name=\"java:global/EjbModule53489605/org.superbiz.injection.secure.MovieTest!org.superbiz.injection.secure.MovieTest\")\n INFO - Jndi(name=\"java:global/EjbModule53489605/org.superbiz.injection.secure.MovieTest\")\n INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Created Ejb(deployment-id=ManagerBean, ejb-name=ManagerBean, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=EmployeeBean, ejb-name=EmployeeBean, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=org.superbiz.injection.secure.MovieTest, ejb-name=org.superbiz.injection.secure.MovieTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Started Ejb(deployment-id=ManagerBean, ejb-name=ManagerBean, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=EmployeeBean, ejb-name=EmployeeBean, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=org.superbiz.injection.secure.MovieTest, ejb-name=org.superbiz.injection.secure.MovieTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/testing-security-meta)\n INFO - EJBContainer already initialized. Call ejbContainer.close() to allow reinitialization\n INFO - EJBContainer already initialized. Call ejbContainer.close() to allow reinitialization\n Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.754 sec\n \n Results :\n \n Tests run: 3, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/testing-security-meta"
},
{
"name":"testing-security-3",
"readme":"Title: Testing Security 3\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## Movie\n\n package org.superbiz.injection.secure;\n \n import javax.persistence.Entity;\n \n @Entity\n public class Movie {\n \n private String director;\n private String title;\n private int year;\n \n public Movie() {\n }\n \n public Movie(String director, String title, int year) {\n this.director = director;\n this.title = title;\n this.year = year;\n }\n \n public String getDirector() {\n return director;\n }\n \n public void setDirector(String director) {\n this.director = director;\n }\n \n public String getTitle() {\n return title;\n }\n \n public void setTitle(String title) {\n this.title = title;\n }\n \n public int getYear() {\n return year;\n }\n \n public void setYear(int year) {\n this.year = year;\n }\n \n }\n\n## Movies\n\n package org.superbiz.injection.secure;\n \n //START SNIPPET: code\n \n import javax.annotation.security.PermitAll;\n import javax.annotation.security.RolesAllowed;\n import javax.ejb.Stateful;\n import javax.ejb.TransactionAttribute;\n import javax.ejb.TransactionAttributeType;\n import javax.persistence.EntityManager;\n import javax.persistence.PersistenceContext;\n import javax.persistence.PersistenceContextType;\n import javax.persistence.Query;\n import java.util.List;\n \n @Stateful\n public class Movies {\n \n @PersistenceContext(unitName = \"movie-unit\", type = PersistenceContextType.EXTENDED)\n private EntityManager entityManager;\n \n @RolesAllowed({\"Employee\", \"Manager\"})\n public void addMovie(Movie movie) throws Exception {\n entityManager.persist(movie);\n }\n \n @RolesAllowed({\"Manager\"})\n public void deleteMovie(Movie movie) throws Exception {\n entityManager.remove(movie);\n }\n \n @PermitAll\n @TransactionAttribute(TransactionAttributeType.SUPPORTS)\n public List<Movie> getMovies() throws Exception {\n Query query = entityManager.createQuery(\"SELECT m from Movie as m\");\n return query.getResultList();\n }\n }\n\n## MyLoginProvider\n\n package org.superbiz.injection.secure;\n\n import org.apache.openejb.core.security.jaas.LoginProvider;\n\n import javax.security.auth.login.FailedLoginException;\n import java.util.Arrays;\n import java.util.List;\n\n public class MyLoginProvider implements LoginProvider {\n\n\n @Override\n public List<String> authenticate(String user, String password) throws FailedLoginException {\n if (\"paul\".equals(user) && \"michelle\".equals(password)) {\n return Arrays.asList(\"Manager\", \"rockstar\", \"beatle\");\n }\n\n if (\"eddie\".equals(user) && \"jump\".equals(password)) {\n return Arrays.asList(\"Employee\", \"rockstar\", \"vanhalen\");\n }\n\n throw new FailedLoginException(\"Bad user or password!\");\n }\n }\n\n## org.apache.openejb.core.security.jaas.LoginProvider\n\n org.superbiz.injection.secure.MyLoginProvider\n\n## persistence.xml\n\n <persistence xmlns=\"http://java.sun.com/xml/ns/persistence\" version=\"1.0\">\n \n <persistence-unit name=\"movie-unit\">\n <jta-data-source>movieDatabase</jta-data-source>\n <non-jta-data-source>movieDatabaseUnmanaged</non-jta-data-source>\n <class>org.superbiz.injection.secure.Movie</class>\n \n <properties>\n <property name=\"openjpa.jdbc.SynchronizeMappings\" value=\"buildSchema(ForeignKeys=true)\"/>\n </properties>\n </persistence-unit>\n </persistence>\n\n## MovieTest\n\n package org.superbiz.injection.secure;\n\n import junit.framework.TestCase;\n\n import javax.ejb.EJB;\n import javax.ejb.EJBAccessException;\n import javax.ejb.embeddable.EJBContainer;\n import javax.naming.Context;\n import javax.naming.InitialContext;\n import javax.naming.NamingException;\n import java.util.List;\n import java.util.Properties;\n\n public class MovieTest extends TestCase {\n\n @EJB\n private Movies movies;\n\n private Context getContext(String user, String pass) throws NamingException {\n Properties p = new Properties();\n p.put(Context.INITIAL_CONTEXT_FACTORY, \"org.apache.openejb.core.LocalInitialContextFactory\");\n p.setProperty(\"openejb.authentication.realmName\", \"ServiceProviderLogin\");\n p.put(Context.SECURITY_PRINCIPAL, user);\n p.put(Context.SECURITY_CREDENTIALS, pass);\n\n return new InitialContext(p);\n }\n\n protected void setUp() throws Exception {\n Properties p = new Properties();\n p.put(\"movieDatabase\", \"new://Resource?type=DataSource\");\n p.put(\"movieDatabase.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"movieDatabase.JdbcUrl\", \"jdbc:hsqldb:mem:moviedb\");\n\n EJBContainer.createEJBContainer(p).getContext().bind(\"inject\", this);\n }\n\n public void testAsManager() throws Exception {\n final Context context = getContext(\"paul\", \"michelle\");\n\n try {\n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n movies.addMovie(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n movies.addMovie(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n\n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n\n for (Movie movie : list) {\n movies.deleteMovie(movie);\n }\n\n assertEquals(\"Movies.getMovies()\", 0, movies.getMovies().size());\n } finally {\n context.close();\n }\n }\n\n public void testAsEmployee() throws Exception {\n final Context context = getContext(\"eddie\", \"jump\");\n\n try {\n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n movies.addMovie(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n movies.addMovie(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n\n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n\n for (Movie movie : list) {\n try {\n movies.deleteMovie(movie);\n fail(\"Employees should not be allowed to delete\");\n } catch (EJBAccessException e) {\n // Good, Employees cannot delete things\n }\n }\n\n // The list should still be three movies long\n assertEquals(\"Movies.getMovies()\", 3, movies.getMovies().size());\n } finally {\n context.close();\n }\n }\n\n public void testUnauthenticated() throws Exception {\n try {\n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n fail(\"Unauthenticated users should not be able to add movies\");\n } catch (EJBAccessException e) {\n // Good, guests cannot add things\n }\n\n try {\n movies.deleteMovie(null);\n fail(\"Unauthenticated users should not be allowed to delete\");\n } catch (EJBAccessException e) {\n // Good, Unauthenticated users cannot delete things\n }\n\n try {\n // Read access should be allowed\n\n List<Movie> list = movies.getMovies();\n\n } catch (EJBAccessException e) {\n fail(\"Read access should be allowed\");\n }\n\n }\n\n public void testLoginFailure() throws NamingException {\n try {\n getContext(\"eddie\", \"panama\");\n fail(\"supposed to have a login failure here\");\n } catch (javax.naming.AuthenticationException e) {\n //expected\n }\n\n try {\n getContext(\"jimmy\", \"foxylady\");\n fail(\"supposed to have a login failure here\");\n } catch (javax.naming.AuthenticationException e) {\n //expected\n }\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.injection.secure.MovieTest\n INFO - ********************************************************************************\n INFO - OpenEJB http://tomee.apache.org/\n INFO - Startup: Fri Jul 20 08:42:53 EDT 2012\n INFO - Copyright 1999-2012 (C) Apache OpenEJB Project, All Rights Reserved.\n INFO - Version: 4.1.0\n INFO - Build date: 20120720\n INFO - Build time: 08:33\n INFO - ********************************************************************************\n INFO - openejb.home = /home/boto/dev/ws/openejb_trunk/openejb/examples/testing-security-3\n INFO - openejb.base = /home/boto/dev/ws/openejb_trunk/openejb/examples/testing-security-3\n INFO - Created new singletonService org.apache.openejb.cdi.ThreadSingletonServiceImpl@38ee6681\n INFO - Succeeded in installing singleton service\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Cannot find the configuration file [conf/openejb.xml]. Will attempt to create one for the beans deployed.\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Creating TransactionManager(id=Default Transaction Manager)\n INFO - Creating SecurityService(id=Default Security Service)\n INFO - Creating Resource(id=movieDatabase)\n INFO - Beginning load: /home/boto/dev/ws/openejb_trunk/openejb/examples/testing-security-3/target/classes\n INFO - Configuring enterprise application: /home/boto/dev/ws/openejb_trunk/openejb/examples/testing-security-3\n INFO - Auto-deploying ejb Movies: EjbDeployment(deployment-id=Movies)\n INFO - Configuring Service(id=Default Stateful Container, type=Container, provider-id=Default Stateful Container)\n INFO - Auto-creating a container for bean Movies: Container(type=STATEFUL, id=Default Stateful Container)\n INFO - Creating Container(id=Default Stateful Container)\n INFO - Using directory /tmp for stateful session passivation\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.injection.secure.MovieTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Creating Container(id=Default Managed Container)\n INFO - Using directory /tmp for stateful session passivation\n INFO - Configuring PersistenceUnit(name=movie-unit)\n INFO - Auto-creating a Resource with id 'movieDatabaseNonJta' of type 'DataSource for 'movie-unit'.\n INFO - Configuring Service(id=movieDatabaseNonJta, type=Resource, provider-id=movieDatabase)\n INFO - Creating Resource(id=movieDatabaseNonJta)\n INFO - Adjusting PersistenceUnit movie-unit <non-jta-data-source> to Resource ID 'movieDatabaseNonJta' from 'movieDatabaseUnmanaged'\n INFO - Enterprise application \"/home/boto/dev/ws/openejb_trunk/openejb/examples/testing-security-3\" loaded.\n INFO - Assembling app: /home/boto/dev/ws/openejb_trunk/openejb/examples/testing-security-3\n SEVERE - JAVA AGENT NOT INSTALLED. The JPA Persistence Provider requested installation of a ClassFileTransformer which requires a JavaAgent. See http://tomee.apache.org/3.0/javaagent.html\n INFO - PersistenceUnit(name=movie-unit, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 268ms\n INFO - Jndi(name=\"java:global/testing-security-3/Movies!org.superbiz.injection.secure.Movies\")\n INFO - Jndi(name=\"java:global/testing-security-3/Movies\")\n INFO - Existing thread singleton service in SystemInstance() org.apache.openejb.cdi.ThreadSingletonServiceImpl@38ee6681\n INFO - OpenWebBeans Container is starting...\n INFO - Adding OpenWebBeansPlugin : [CdiPlugin]\n INFO - All injection points are validated successfully.\n INFO - OpenWebBeans Container has started, it took 170 ms.\n INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Deployed Application(path=/home/boto/dev/ws/openejb_trunk/openejb/examples/testing-security-3)\n 20-Jul-2012 8:42:55 AM null openjpa.Runtime\n INFO: Starting OpenJPA 2.2.0\n 20-Jul-2012 8:42:56 AM null openjpa.jdbc.JDBC\n INFO: Using dictionary class \"org.apache.openjpa.jdbc.sql.HSQLDictionary\" (HSQL Database Engine 2.2.8 ,HSQL Database Engine Driver 2.2.8).\n 20-Jul-2012 8:42:57 AM null openjpa.Enhance\n INFO: Creating subclass and redefining methods for \"[class org.superbiz.injection.secure.Movie]\". This means that your application will be less efficient than it would if you ran the OpenJPA enhancer.\n INFO - Logging in\n INFO - Logging out\n INFO - EJBContainer already initialized. Call ejbContainer.close() to allow reinitialization\n INFO - Logging in\n INFO - Logging out\n INFO - EJBContainer already initialized. Call ejbContainer.close() to allow reinitialization\n Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 6.069 sec\n\n Results :\n\n Tests run: 3, Failures: 0, Errors: 0, Skipped: 0\n\n",
"url":"https://github.com/apache/tomee/tree/master/examples/testing-security-3"
},
{
"name":"testing-security-4",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/testing-security-4"
},
{
"name":"webservice-security",
"readme":"Title: Webservice Security\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## CalculatorImpl\n\n package org.superbiz.calculator;\n \n import javax.annotation.security.DeclareRoles;\n import javax.annotation.security.RolesAllowed;\n import javax.ejb.Stateless;\n import javax.jws.WebService;\n \n /**\n * This is an EJB 3 style pojo stateless session bean\n * Every stateless session bean implementation must be annotated\n * using the annotation @Stateless\n * This EJB has a single interface: CalculatorWs a webservice interface.\n */\n //START SNIPPET: code\n @DeclareRoles(value = {\"Administrator\"})\n @Stateless\n @WebService(\n portName = \"CalculatorPort\",\n serviceName = \"CalculatorWsService\",\n targetNamespace = \"http://superbiz.org/wsdl\",\n endpointInterface = \"org.superbiz.calculator.CalculatorWs\")\n public class CalculatorImpl implements CalculatorWs, CalculatorRemote {\n \n @RolesAllowed(value = {\"Administrator\"})\n public int sum(int add1, int add2) {\n return add1 + add2;\n }\n \n @RolesAllowed(value = {\"Administrator\"})\n public int multiply(int mul1, int mul2) {\n return mul1 * mul2;\n }\n }\n\n## CalculatorRemote\n\n package org.superbiz.calculator;\n \n import javax.ejb.Remote;\n \n @Remote\n public interface CalculatorRemote {\n \n public int sum(int add1, int add2);\n \n public int multiply(int mul1, int mul2);\n }\n\n## CalculatorWs\n\n package org.superbiz.calculator;\n \n import javax.jws.WebService;\n \n //END SNIPPET: code\n \n /**\n * This is an EJB 3 webservice interface\n * A webservice interface must be annotated with the @Local\n * annotation.\n */\n //START SNIPPET: code\n @WebService(targetNamespace = \"http://superbiz.org/wsdl\")\n public interface CalculatorWs {\n \n public int sum(int add1, int add2);\n \n public int multiply(int mul1, int mul2);\n }\n\n## ejb-jar.xml\n\n <ejb-jar/>\n\n## openejb-jar.xml\n\n <openejb-jar xmlns=\"http://tomee.apache.org/xml/ns/openejb-jar-2.2\">\n <enterprise-beans>\n <session>\n <ejb-name>CalculatorImpl</ejb-name>\n <web-service-security>\n <security-realm-name/>\n <transport-guarantee>NONE</transport-guarantee>\n <auth-method>BASIC</auth-method>\n </web-service-security>\n </session>\n </enterprise-beans>\n </openejb-jar>\n\n## CalculatorTest\n\n package org.superbiz.calculator;\n \n import junit.framework.TestCase;\n \n import javax.naming.Context;\n import javax.naming.InitialContext;\n import javax.xml.namespace.QName;\n import javax.xml.ws.BindingProvider;\n import javax.xml.ws.Service;\n import java.net.URL;\n import java.util.Properties;\n \n public class CalculatorTest extends TestCase {\n \n //START SNIPPET: setup\n private InitialContext initialContext;\n \n protected void setUp() throws Exception {\n Properties properties = new Properties();\n properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, \"org.apache.openejb.core.LocalInitialContextFactory\");\n properties.setProperty(\"openejb.embedded.remotable\", \"true\");\n \n initialContext = new InitialContext(properties);\n }\n //END SNIPPET: setup\n \n /**\n * Create a webservice client using wsdl url\n *\n * @throws Exception\n */\n //START SNIPPET: webservice\n public void testCalculatorViaWsInterface() throws Exception {\n URL url = new URL(\"http://127.0.0.1:4204/CalculatorImpl?wsdl\");\n QName calcServiceQName = new QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService\");\n Service calcService = Service.create(url, calcServiceQName);\n assertNotNull(calcService);\n \n CalculatorWs calc = calcService.getPort(CalculatorWs.class);\n ((BindingProvider) calc).getRequestContext().put(BindingProvider.USERNAME_PROPERTY, \"jane\");\n ((BindingProvider) calc).getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, \"waterfall\");\n assertEquals(10, calc.sum(4, 6));\n assertEquals(12, calc.multiply(3, 4));\n }\n //END SNIPPET: webservice\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.calculator.CalculatorTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/webservice-security\n INFO - openejb.base = /Users/dblevins/examples/webservice-security\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/webservice-security/target/classes\n INFO - Beginning load: /Users/dblevins/examples/webservice-security/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/webservice-security/classpath.ear\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean CalculatorImpl: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Enterprise application \"/Users/dblevins/examples/webservice-security/classpath.ear\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/webservice-security/classpath.ear\n INFO - Jndi(name=CalculatorImplRemote) --> Ejb(deployment-id=CalculatorImpl)\n INFO - Jndi(name=global/classpath.ear/webservice-security/CalculatorImpl!org.superbiz.calculator.CalculatorRemote) --> Ejb(deployment-id=CalculatorImpl)\n INFO - Jndi(name=global/classpath.ear/webservice-security/CalculatorImpl) --> Ejb(deployment-id=CalculatorImpl)\n INFO - Created Ejb(deployment-id=CalculatorImpl, ejb-name=CalculatorImpl, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=CalculatorImpl, ejb-name=CalculatorImpl, container=Default Stateless Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/webservice-security/classpath.ear)\n INFO - Initializing network services\n INFO - Creating ServerService(id=httpejbd)\n INFO - Creating ServerService(id=cxf)\n INFO - Creating ServerService(id=admin)\n INFO - Creating ServerService(id=ejbd)\n INFO - Creating ServerService(id=ejbds)\n INFO - Initializing network services\n ** Starting Services **\n NAME IP PORT \n httpejbd 127.0.0.1 4204 \n admin thread 127.0.0.1 4200 \n ejbd 127.0.0.1 4201 \n ejbd 127.0.0.1 4203 \n -------\n Ready!\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.481 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/webservice-security"
},
{
"name":"webservice-ws-security",
"readme":"Title: Webservice Ws Security\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## CalculatorImpl\n\n package org.superbiz.calculator;\n \n import javax.annotation.security.DeclareRoles;\n import javax.annotation.security.RolesAllowed;\n import javax.ejb.Stateless;\n import javax.jws.WebService;\n \n /**\n * This is an EJB 3 style pojo stateless session bean\n * Every stateless session bean implementation must be annotated\n * using the annotation @Stateless\n * This EJB has a single interface: CalculatorWs a webservice interface.\n */\n //START SNIPPET: code\n @DeclareRoles(value = {\"Administrator\"})\n @Stateless\n @WebService(\n portName = \"CalculatorPort\",\n serviceName = \"CalculatorWsService\",\n targetNamespace = \"http://superbiz.org/wsdl\",\n endpointInterface = \"org.superbiz.calculator.CalculatorWs\")\n public class CalculatorImpl implements CalculatorWs, CalculatorRemote {\n \n @RolesAllowed(value = {\"Administrator\"})\n public int sum(int add1, int add2) {\n return add1 + add2;\n }\n \n public int multiply(int mul1, int mul2) {\n return mul1 * mul2;\n }\n }\n\n## CalculatorRemote\n\n package org.superbiz.calculator;\n \n import javax.ejb.Remote;\n \n @Remote\n public interface CalculatorRemote {\n \n public int sum(int add1, int add2);\n \n public int multiply(int mul1, int mul2);\n }\n\n## CalculatorWs\n\n package org.superbiz.calculator;\n \n import javax.jws.WebService;\n \n //END SNIPPET: code\n \n /**\n * This is an EJB 3 webservice interface\n * A webservice interface must be annotated with the @Local\n * annotation.\n */\n //START SNIPPET: code\n @WebService(targetNamespace = \"http://superbiz.org/wsdl\")\n public interface CalculatorWs {\n \n public int sum(int add1, int add2);\n \n public int multiply(int mul1, int mul2);\n }\n\n## ejb-jar.xml\n\n <ejb-jar xmlns=\"http://java.sun.com/xml/ns/javaee\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd\"\n version=\"3.0\" id=\"simple\" metadata-complete=\"false\">\n \n <enterprise-beans>\n \n <session>\n <ejb-name>CalculatorImplTimestamp1way</ejb-name>\n <service-endpoint>org.superbiz.calculator.CalculatorWs</service-endpoint>\n <ejb-class>org.superbiz.calculator.CalculatorImpl</ejb-class>\n <session-type>Stateless</session-type>\n <transaction-type>Container</transaction-type>\n </session>\n \n <session>\n <ejb-name>CalculatorImplTimestamp2ways</ejb-name>\n <service-endpoint>org.superbiz.calculator.CalculatorWs</service-endpoint>\n <ejb-class>org.superbiz.calculator.CalculatorImpl</ejb-class>\n <session-type>Stateless</session-type>\n <transaction-type>Container</transaction-type>\n </session>\n \n <session>\n <ejb-name>CalculatorImplUsernameTokenPlainPassword</ejb-name>\n <service-endpoint>org.superbiz.calculator.CalculatorWs</service-endpoint>\n <ejb-class>org.superbiz.calculator.CalculatorImpl</ejb-class>\n <session-type>Stateless</session-type>\n <transaction-type>Container</transaction-type>\n </session>\n \n <session>\n <ejb-name>CalculatorImplUsernameTokenHashedPassword</ejb-name>\n <service-endpoint>org.superbiz.calculator.CalculatorWs</service-endpoint>\n <ejb-class>org.superbiz.calculator.CalculatorImpl</ejb-class>\n <session-type>Stateless</session-type>\n <transaction-type>Container</transaction-type>\n </session>\n \n <session>\n <ejb-name>CalculatorImplUsernameTokenPlainPasswordEncrypt</ejb-name>\n <service-endpoint>org.superbiz.calculator.CalculatorWs</service-endpoint>\n <ejb-class>org.superbiz.calculator.CalculatorImpl</ejb-class>\n <session-type>Stateless</session-type>\n <transaction-type>Container</transaction-type>\n </session>\n \n <session>\n <ejb-name>CalculatorImplSign</ejb-name>\n <service-endpoint>org.superbiz.calculator.CalculatorWs</service-endpoint>\n <ejb-class>org.superbiz.calculator.CalculatorImpl</ejb-class>\n <session-type>Stateless</session-type>\n <transaction-type>Container</transaction-type>\n </session>\n \n <session>\n <ejb-name>CalculatorImplEncrypt2ways</ejb-name>\n <service-endpoint>org.superbiz.calculator.CalculatorWs</service-endpoint>\n <ejb-class>org.superbiz.calculator.CalculatorImpl</ejb-class>\n <session-type>Stateless</session-type>\n <transaction-type>Container</transaction-type>\n </session>\n \n <session>\n <ejb-name>CalculatorImplSign2ways</ejb-name>\n <service-endpoint>org.superbiz.calculator.CalculatorWs</service-endpoint>\n <ejb-class>org.superbiz.calculator.CalculatorImpl</ejb-class>\n <session-type>Stateless</session-type>\n <transaction-type>Container</transaction-type>\n </session>\n \n <session>\n <ejb-name>CalculatorImplEncryptAndSign2ways</ejb-name>\n <service-endpoint>org.superbiz.calculator.CalculatorWs</service-endpoint>\n <ejb-class>org.superbiz.calculator.CalculatorImpl</ejb-class>\n <session-type>Stateless</session-type>\n <transaction-type>Container</transaction-type>\n </session>\n \n </enterprise-beans>\n \n </ejb-jar>\n \n\n## openejb-jar.xml\n\n <openejb-jar xmlns=\"http://www.openejb.org/openejb-jar/1.1\">\n \n <ejb-deployment ejb-name=\"CalculatorImpl\">\n <properties>\n # webservice.security.realm\n # webservice.security.securityRealm\n # webservice.security.transportGarantee = NONE\n webservice.security.authMethod = WS-SECURITY\n wss4j.in.action = UsernameToken\n wss4j.in.passwordType = PasswordText\n wss4j.in.passwordCallbackClass = org.superbiz.calculator.CustomPasswordHandler\n \n # automatically added\n wss4j.in.validator.{http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd}UsernameToken = org.apache.openejb.server.cxf.OpenEJBLoginValidator\n </properties>\n </ejb-deployment>\n <ejb-deployment ejb-name=\"CalculatorImplTimestamp1way\">\n <properties>\n webservice.security.authMethod = WS-SECURITY\n wss4j.in.action = Timestamp\n </properties>\n </ejb-deployment>\n <ejb-deployment ejb-name=\"CalculatorImplTimestamp2ways\">\n <properties>\n webservice.security.authMethod = WS-SECURITY\n wss4j.in.action = Timestamp\n wss4j.out.action = Timestamp\n </properties>\n </ejb-deployment>\n <ejb-deployment ejb-name=\"CalculatorImplUsernameTokenPlainPassword\">\n <properties>\n webservice.security.authMethod = WS-SECURITY\n wss4j.in.action = UsernameToken\n wss4j.in.passwordType = PasswordText\n wss4j.in.passwordCallbackClass=org.superbiz.calculator.CustomPasswordHandler\n </properties>\n </ejb-deployment>\n <ejb-deployment ejb-name=\"CalculatorImplUsernameTokenHashedPassword\">\n <properties>\n webservice.security.authMethod = WS-SECURITY\n wss4j.in.action = UsernameToken\n wss4j.in.passwordType = PasswordDigest\n wss4j.in.passwordCallbackClass=org.superbiz.calculator.CustomPasswordHandler\n </properties>\n </ejb-deployment>\n <ejb-deployment ejb-name=\"CalculatorImplUsernameTokenPlainPasswordEncrypt\">\n <properties>\n webservice.security.authMethod = WS-SECURITY\n wss4j.in.action = UsernameToken Encrypt\n wss4j.in.passwordType = PasswordText\n wss4j.in.passwordCallbackClass=org.superbiz.calculator.CustomPasswordHandler\n wss4j.in.decryptionPropFile = META-INF/CalculatorImplUsernameTokenPlainPasswordEncrypt-server.properties\n </properties>\n </ejb-deployment>\n <ejb-deployment ejb-name=\"CalculatorImplSign\">\n <properties>\n webservice.security.authMethod = WS-SECURITY\n wss4j.in.action = Signature\n wss4j.in.passwordCallbackClass=org.superbiz.calculator.CustomPasswordHandler\n wss4j.in.signaturePropFile = META-INF/CalculatorImplSign-server.properties\n </properties>\n </ejb-deployment>\n \n </openejb-jar>\n \n\n## webservices.xml\n\n <webservices xmlns=\"http://java.sun.com/xml/ns/j2ee\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/j2ee\n http://www.ibm.com/webservices/xsd/j2ee_web_services_1_1.xsd\"\n xmlns:ger=\"http://ciaows.org/wsdl\" version=\"1.1\">\n \n <webservice-description>\n <webservice-description-name>CalculatorWsService</webservice-description-name>\n <port-component>\n <port-component-name>CalculatorImplTimestamp1way</port-component-name>\n <wsdl-port>CalculatorImplTimestamp1way</wsdl-port>\n <service-endpoint-interface>org.superbiz.calculator.CalculatorWs</service-endpoint-interface>\n <service-impl-bean>\n <ejb-link>CalculatorImplTimestamp1way</ejb-link>\n </service-impl-bean>\n </port-component>\n <port-component>\n <port-component-name>CalculatorImplTimestamp2ways</port-component-name>\n <wsdl-port>CalculatorImplTimestamp2ways</wsdl-port>\n <service-endpoint-interface>org.superbiz.calculator.CalculatorWs</service-endpoint-interface>\n <service-impl-bean>\n <ejb-link>CalculatorImplTimestamp2ways</ejb-link>\n </service-impl-bean>\n </port-component>\n <port-component>\n <port-component-name>CalculatorImplUsernameTokenPlainPassword</port-component-name>\n <wsdl-port>CalculatorImplUsernameTokenPlainPassword</wsdl-port>\n <service-endpoint-interface>org.superbiz.calculator.CalculatorWs</service-endpoint-interface>\n <service-impl-bean>\n <ejb-link>CalculatorImplUsernameTokenPlainPassword</ejb-link>\n </service-impl-bean>\n </port-component>\n <port-component>\n <port-component-name>CalculatorImplUsernameTokenHashedPassword</port-component-name>\n <wsdl-port>CalculatorImplUsernameTokenHashedPassword</wsdl-port>\n <service-endpoint-interface>org.superbiz.calculator.CalculatorWs</service-endpoint-interface>\n <service-impl-bean>\n <ejb-link>CalculatorImplUsernameTokenHashedPassword</ejb-link>\n </service-impl-bean>\n </port-component>\n <port-component>\n <port-component-name>CalculatorImplUsernameTokenPlainPasswordEncrypt</port-component-name>\n <wsdl-port>CalculatorImplUsernameTokenPlainPasswordEncrypt</wsdl-port>\n <service-endpoint-interface>org.superbiz.calculator.CalculatorWs</service-endpoint-interface>\n <service-impl-bean>\n <ejb-link>CalculatorImplUsernameTokenPlainPasswordEncrypt</ejb-link>\n </service-impl-bean>\n </port-component>\n </webservice-description>\n \n </webservices>\n \n\n## CalculatorTest\n\n package org.superbiz.calculator;\n \n import junit.framework.TestCase;\n import org.apache.cxf.binding.soap.saaj.SAAJInInterceptor;\n import org.apache.cxf.binding.soap.saaj.SAAJOutInterceptor;\n import org.apache.cxf.endpoint.Client;\n import org.apache.cxf.endpoint.Endpoint;\n import org.apache.cxf.frontend.ClientProxy;\n import org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor;\n import org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor;\n import org.apache.ws.security.WSConstants;\n import org.apache.ws.security.WSPasswordCallback;\n import org.apache.ws.security.handler.WSHandlerConstants;\n \n import javax.naming.Context;\n import javax.naming.InitialContext;\n import javax.security.auth.callback.Callback;\n import javax.security.auth.callback.CallbackHandler;\n import javax.security.auth.callback.UnsupportedCallbackException;\n import javax.xml.namespace.QName;\n import javax.xml.ws.Service;\n import javax.xml.ws.soap.SOAPBinding;\n import java.io.IOException;\n import java.net.URL;\n import java.util.HashMap;\n import java.util.Map;\n import java.util.Properties;\n \n public class CalculatorTest extends TestCase {\n \n //START SNIPPET: setup\n protected void setUp() throws Exception {\n Properties properties = new Properties();\n properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, \"org.apache.openejb.core.LocalInitialContextFactory\");\n properties.setProperty(\"openejb.embedded.remotable\", \"true\");\n \n new InitialContext(properties);\n }\n //END SNIPPET: setup\n \n //START SNIPPET: webservice\n public void testCalculatorViaWsInterface() throws Exception {\n Service calcService = Service.create(new URL(\"http://127.0.0.1:4204/CalculatorImpl?wsdl\"),\n new QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService\"));\n assertNotNull(calcService);\n \n CalculatorWs calc = calcService.getPort(CalculatorWs.class);\n \n Client client = ClientProxy.getClient(calc);\n Endpoint endpoint = client.getEndpoint();\n endpoint.getOutInterceptors().add(new SAAJOutInterceptor());\n \n Map<String, Object> outProps = new HashMap<String, Object>();\n outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);\n outProps.put(WSHandlerConstants.USER, \"jane\");\n outProps.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT);\n outProps.put(WSHandlerConstants.PW_CALLBACK_REF, new CallbackHandler() {\n \n public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {\n WSPasswordCallback pc = (WSPasswordCallback) callbacks[0];\n pc.setPassword(\"waterfall\");\n }\n });\n \n WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps);\n endpoint.getOutInterceptors().add(wssOut);\n \n assertEquals(10, calc.sum(4, 6));\n }\n \n public void testCalculatorViaWsInterfaceWithTimestamp1way() throws Exception {\n Service calcService = Service.create(new URL(\"http://127.0.0.1:4204/CalculatorImplTimestamp1way?wsdl\"),\n new QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService\"));\n assertNotNull(calcService);\n \n // for debugging (ie. TCPMon)\n calcService.addPort(new QName(\"http://superbiz.org/wsdl\",\n \"CalculatorWsService2\"), SOAPBinding.SOAP12HTTP_BINDING,\n \"http://127.0.0.1:8204/CalculatorImplTimestamp1way\");\n \n // CalculatorWs calc = calcService.getPort(\n // \tnew QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService2\"),\n //\t\tCalculatorWs.class);\n \n CalculatorWs calc = calcService.getPort(CalculatorWs.class);\n \n Client client = ClientProxy.getClient(calc);\n Endpoint endpoint = client.getEndpoint();\n endpoint.getOutInterceptors().add(new SAAJOutInterceptor());\n \n Map<String, Object> outProps = new HashMap<String, Object>();\n outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.TIMESTAMP);\n WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps);\n endpoint.getOutInterceptors().add(wssOut);\n \n assertEquals(12, calc.multiply(3, 4));\n }\n \n public void testCalculatorViaWsInterfaceWithTimestamp2ways() throws Exception {\n Service calcService = Service.create(new URL(\"http://127.0.0.1:4204/CalculatorImplTimestamp2ways?wsdl\"),\n new QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService\"));\n assertNotNull(calcService);\n \n // for debugging (ie. TCPMon)\n calcService.addPort(new QName(\"http://superbiz.org/wsdl\",\n \"CalculatorWsService2\"), SOAPBinding.SOAP12HTTP_BINDING,\n \"http://127.0.0.1:8204/CalculatorImplTimestamp2ways\");\n \n // CalculatorWs calc = calcService.getPort(\n // \tnew QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService2\"),\n //\t\tCalculatorWs.class);\n \n CalculatorWs calc = calcService.getPort(CalculatorWs.class);\n \n Client client = ClientProxy.getClient(calc);\n Endpoint endpoint = client.getEndpoint();\n endpoint.getOutInterceptors().add(new SAAJOutInterceptor());\n endpoint.getInInterceptors().add(new SAAJInInterceptor());\n \n Map<String, Object> outProps = new HashMap<String, Object>();\n outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.TIMESTAMP);\n WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps);\n endpoint.getOutInterceptors().add(wssOut);\n \n Map<String, Object> inProps = new HashMap<String, Object>();\n inProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.TIMESTAMP);\n WSS4JInInterceptor wssIn = new WSS4JInInterceptor(inProps);\n endpoint.getInInterceptors().add(wssIn);\n \n assertEquals(12, calc.multiply(3, 4));\n }\n \n public void testCalculatorViaWsInterfaceWithUsernameTokenPlainPassword() throws Exception {\n Service calcService = Service.create(new URL(\"http://127.0.0.1:4204/CalculatorImplUsernameTokenPlainPassword?wsdl\"),\n new QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService\"));\n assertNotNull(calcService);\n \n // for debugging (ie. TCPMon)\n calcService.addPort(new QName(\"http://superbiz.org/wsdl\",\n \"CalculatorWsService2\"), SOAPBinding.SOAP12HTTP_BINDING,\n \"http://127.0.0.1:8204/CalculatorImplUsernameTokenPlainPassword\");\n \n // CalculatorWs calc = calcService.getPort(\n // \tnew QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService2\"),\n // \tCalculatorWs.class);\n \n CalculatorWs calc = calcService.getPort(CalculatorWs.class);\n \n Client client = ClientProxy.getClient(calc);\n Endpoint endpoint = client.getEndpoint();\n endpoint.getOutInterceptors().add(new SAAJOutInterceptor());\n \n Map<String, Object> outProps = new HashMap<String, Object>();\n outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);\n outProps.put(WSHandlerConstants.USER, \"jane\");\n outProps.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT);\n outProps.put(WSHandlerConstants.PW_CALLBACK_REF, new CallbackHandler() {\n \n @Override\n public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {\n WSPasswordCallback pc = (WSPasswordCallback) callbacks[0];\n pc.setPassword(\"waterfall\");\n }\n });\n \n WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps);\n endpoint.getOutInterceptors().add(wssOut);\n \n assertEquals(10, calc.sum(4, 6));\n }\n \n public void testCalculatorViaWsInterfaceWithUsernameTokenHashedPassword() throws Exception {\n Service calcService = Service.create(new URL(\"http://127.0.0.1:4204/CalculatorImplUsernameTokenHashedPassword?wsdl\"),\n new QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService\"));\n assertNotNull(calcService);\n \n // for debugging (ie. TCPMon)\n calcService.addPort(new QName(\"http://superbiz.org/wsdl\",\n \"CalculatorWsService2\"), SOAPBinding.SOAP12HTTP_BINDING,\n \"http://127.0.0.1:8204/CalculatorImplUsernameTokenHashedPassword\");\n \n // CalculatorWs calc = calcService.getPort(\n // \tnew QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService2\"),\n // \tCalculatorWs.class);\n \n CalculatorWs calc = calcService.getPort(CalculatorWs.class);\n \n Client client = ClientProxy.getClient(calc);\n Endpoint endpoint = client.getEndpoint();\n endpoint.getOutInterceptors().add(new SAAJOutInterceptor());\n \n Map<String, Object> outProps = new HashMap<String, Object>();\n outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);\n outProps.put(WSHandlerConstants.USER, \"jane\");\n outProps.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_DIGEST);\n outProps.put(WSHandlerConstants.PW_CALLBACK_REF, new CallbackHandler() {\n \n @Override\n public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {\n WSPasswordCallback pc = (WSPasswordCallback) callbacks[0];\n pc.setPassword(\"waterfall\");\n }\n });\n \n WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps);\n endpoint.getOutInterceptors().add(wssOut);\n \n assertEquals(10, calc.sum(4, 6));\n }\n \n public void testCalculatorViaWsInterfaceWithUsernameTokenPlainPasswordEncrypt() throws Exception {\n Service calcService = Service.create(new URL(\"http://127.0.0.1:4204/CalculatorImplUsernameTokenPlainPasswordEncrypt?wsdl\"),\n new QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService\"));\n assertNotNull(calcService);\n \n // for debugging (ie. TCPMon)\n calcService.addPort(new QName(\"http://superbiz.org/wsdl\",\n \"CalculatorWsService2\"), SOAPBinding.SOAP12HTTP_BINDING,\n \"http://127.0.0.1:8204/CalculatorImplUsernameTokenPlainPasswordEncrypt\");\n \n // CalculatorWs calc = calcService.getPort(\n // \tnew QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService2\"),\n // \tCalculatorWs.class);\n \n CalculatorWs calc = calcService.getPort(CalculatorWs.class);\n \n Client client = ClientProxy.getClient(calc);\n Endpoint endpoint = client.getEndpoint();\n endpoint.getOutInterceptors().add(new SAAJOutInterceptor());\n \n Map<String, Object> outProps = new HashMap<String, Object>();\n outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN\n + \" \" + WSHandlerConstants.ENCRYPT);\n outProps.put(WSHandlerConstants.USER, \"jane\");\n outProps.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT);\n outProps.put(WSHandlerConstants.PW_CALLBACK_REF, new CallbackHandler() {\n \n @Override\n public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {\n WSPasswordCallback pc = (WSPasswordCallback) callbacks[0];\n pc.setPassword(\"waterfall\");\n }\n });\n outProps.put(WSHandlerConstants.ENC_PROP_FILE, \"META-INF/CalculatorImplUsernameTokenPlainPasswordEncrypt-client.properties\");\n outProps.put(WSHandlerConstants.ENCRYPTION_USER, \"serveralias\");\n \n WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps);\n endpoint.getOutInterceptors().add(wssOut);\n \n assertEquals(10, calc.sum(4, 6));\n }\n \n public void testCalculatorViaWsInterfaceWithSign() throws Exception {\n Service calcService = Service.create(new URL(\"http://127.0.0.1:4204/CalculatorImplSign?wsdl\"),\n new QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService\"));\n assertNotNull(calcService);\n \n // for debugging (ie. TCPMon)\n calcService.addPort(new QName(\"http://superbiz.org/wsdl\",\n \"CalculatorWsService2\"), SOAPBinding.SOAP12HTTP_BINDING,\n \"http://127.0.0.1:8204/CalculatorImplSign\");\n \n // CalculatorWs calc = calcService.getPort(\n //\tnew QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService2\"),\n //\tCalculatorWs.class);\n \n CalculatorWs calc = calcService.getPort(CalculatorWs.class);\n \n Client client = ClientProxy.getClient(calc);\n Endpoint endpoint = client.getEndpoint();\n endpoint.getOutInterceptors().add(new SAAJOutInterceptor());\n \n Map<String, Object> outProps = new HashMap<String, Object>();\n outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.SIGNATURE);\n outProps.put(WSHandlerConstants.USER, \"clientalias\");\n outProps.put(WSHandlerConstants.PW_CALLBACK_REF, new CallbackHandler() {\n \n @Override\n public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {\n WSPasswordCallback pc = (WSPasswordCallback) callbacks[0];\n pc.setPassword(\"clientPassword\");\n }\n });\n outProps.put(WSHandlerConstants.SIG_PROP_FILE, \"META-INF/CalculatorImplSign-client.properties\");\n outProps.put(WSHandlerConstants.SIG_KEY_ID, \"IssuerSerial\");\n \n WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps);\n endpoint.getOutInterceptors().add(wssOut);\n \n assertEquals(24, calc.multiply(4, 6));\n }\n //END SNIPPET: webservice\n }\n\n## CustomPasswordHandler\n\n package org.superbiz.calculator;\n \n import org.apache.ws.security.WSPasswordCallback;\n \n import javax.security.auth.callback.Callback;\n import javax.security.auth.callback.CallbackHandler;\n import javax.security.auth.callback.UnsupportedCallbackException;\n import java.io.IOException;\n \n public class CustomPasswordHandler implements CallbackHandler {\n @Override\n public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {\n WSPasswordCallback pc = (WSPasswordCallback) callbacks[0];\n \n if (pc.getUsage() == WSPasswordCallback.USERNAME_TOKEN) {\n // TODO get the password from the users.properties if possible\n pc.setPassword(\"waterfall\");\n } else if (pc.getUsage() == WSPasswordCallback.DECRYPT) {\n pc.setPassword(\"serverPassword\");\n } else if (pc.getUsage() == WSPasswordCallback.SIGNATURE) {\n pc.setPassword(\"serverPassword\");\n }\n }\n }\n\n# Running\n\n \n generate keys:\n \n do.sun.jdk:\n [echo] *** Running on a Sun JDK ***\n [echo] generate server keys\n [java] Certificate stored in file </Users/dblevins/examples/webservice-ws-security/target/classes/META-INF/serverKey.rsa>\n [echo] generate client keys\n [java] Certificate stored in file </Users/dblevins/examples/webservice-ws-security/target/test-classes/META-INF/clientKey.rsa>\n [echo] import client/server public keys in client/server keystores\n [java] Certificate was added to keystore\n [java] Certificate was added to keystore\n \n do.ibm.jdk:\n \n run:\n [echo] Running JDK specific keystore creation target\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.calculator.CalculatorTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/webservice-ws-security\n INFO - openejb.base = /Users/dblevins/examples/webservice-ws-security\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/webservice-ws-security/target/classes\n INFO - Beginning load: /Users/dblevins/examples/webservice-ws-security/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/webservice-ws-security/classpath.ear\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean CalculatorImplTimestamp1way: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Enterprise application \"/Users/dblevins/examples/webservice-ws-security/classpath.ear\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/webservice-ws-security/classpath.ear\n INFO - Jndi(name=CalculatorImplTimestamp1wayRemote) --> Ejb(deployment-id=CalculatorImplTimestamp1way)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplTimestamp1way!org.superbiz.calculator.CalculatorRemote) --> Ejb(deployment-id=CalculatorImplTimestamp1way)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplTimestamp1way) --> Ejb(deployment-id=CalculatorImplTimestamp1way)\n INFO - Jndi(name=CalculatorImplTimestamp2waysRemote) --> Ejb(deployment-id=CalculatorImplTimestamp2ways)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplTimestamp2ways!org.superbiz.calculator.CalculatorRemote) --> Ejb(deployment-id=CalculatorImplTimestamp2ways)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplTimestamp2ways) --> Ejb(deployment-id=CalculatorImplTimestamp2ways)\n INFO - Jndi(name=CalculatorImplUsernameTokenPlainPasswordRemote) --> Ejb(deployment-id=CalculatorImplUsernameTokenPlainPassword)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplUsernameTokenPlainPassword!org.superbiz.calculator.CalculatorRemote) --> Ejb(deployment-id=CalculatorImplUsernameTokenPlainPassword)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplUsernameTokenPlainPassword) --> Ejb(deployment-id=CalculatorImplUsernameTokenPlainPassword)\n INFO - Jndi(name=CalculatorImplUsernameTokenHashedPasswordRemote) --> Ejb(deployment-id=CalculatorImplUsernameTokenHashedPassword)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplUsernameTokenHashedPassword!org.superbiz.calculator.CalculatorRemote) --> Ejb(deployment-id=CalculatorImplUsernameTokenHashedPassword)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplUsernameTokenHashedPassword) --> Ejb(deployment-id=CalculatorImplUsernameTokenHashedPassword)\n INFO - Jndi(name=CalculatorImplUsernameTokenPlainPasswordEncryptRemote) --> Ejb(deployment-id=CalculatorImplUsernameTokenPlainPasswordEncrypt)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplUsernameTokenPlainPasswordEncrypt!org.superbiz.calculator.CalculatorRemote) --> Ejb(deployment-id=CalculatorImplUsernameTokenPlainPasswordEncrypt)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplUsernameTokenPlainPasswordEncrypt) --> Ejb(deployment-id=CalculatorImplUsernameTokenPlainPasswordEncrypt)\n INFO - Jndi(name=CalculatorImplSignRemote) --> Ejb(deployment-id=CalculatorImplSign)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplSign!org.superbiz.calculator.CalculatorRemote) --> Ejb(deployment-id=CalculatorImplSign)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplSign) --> Ejb(deployment-id=CalculatorImplSign)\n INFO - Jndi(name=CalculatorImplEncrypt2waysRemote) --> Ejb(deployment-id=CalculatorImplEncrypt2ways)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplEncrypt2ways!org.superbiz.calculator.CalculatorRemote) --> Ejb(deployment-id=CalculatorImplEncrypt2ways)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplEncrypt2ways) --> Ejb(deployment-id=CalculatorImplEncrypt2ways)\n INFO - Jndi(name=CalculatorImplSign2waysRemote) --> Ejb(deployment-id=CalculatorImplSign2ways)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplSign2ways!org.superbiz.calculator.CalculatorRemote) --> Ejb(deployment-id=CalculatorImplSign2ways)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplSign2ways) --> Ejb(deployment-id=CalculatorImplSign2ways)\n INFO - Jndi(name=CalculatorImplEncryptAndSign2waysRemote) --> Ejb(deployment-id=CalculatorImplEncryptAndSign2ways)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplEncryptAndSign2ways!org.superbiz.calculator.CalculatorRemote) --> Ejb(deployment-id=CalculatorImplEncryptAndSign2ways)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplEncryptAndSign2ways) --> Ejb(deployment-id=CalculatorImplEncryptAndSign2ways)\n INFO - Jndi(name=CalculatorImplRemote) --> Ejb(deployment-id=CalculatorImpl)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImpl!org.superbiz.calculator.CalculatorRemote) --> Ejb(deployment-id=CalculatorImpl)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImpl) --> Ejb(deployment-id=CalculatorImpl)\n INFO - Created Ejb(deployment-id=CalculatorImplUsernameTokenHashedPassword, ejb-name=CalculatorImplUsernameTokenHashedPassword, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=CalculatorImpl, ejb-name=CalculatorImpl, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=CalculatorImplSign, ejb-name=CalculatorImplSign, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=CalculatorImplEncryptAndSign2ways, ejb-name=CalculatorImplEncryptAndSign2ways, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=CalculatorImplTimestamp1way, ejb-name=CalculatorImplTimestamp1way, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=CalculatorImplSign2ways, ejb-name=CalculatorImplSign2ways, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=CalculatorImplEncrypt2ways, ejb-name=CalculatorImplEncrypt2ways, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=CalculatorImplUsernameTokenPlainPassword, ejb-name=CalculatorImplUsernameTokenPlainPassword, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=CalculatorImplTimestamp2ways, ejb-name=CalculatorImplTimestamp2ways, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=CalculatorImplUsernameTokenPlainPasswordEncrypt, ejb-name=CalculatorImplUsernameTokenPlainPasswordEncrypt, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=CalculatorImplUsernameTokenHashedPassword, ejb-name=CalculatorImplUsernameTokenHashedPassword, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=CalculatorImpl, ejb-name=CalculatorImpl, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=CalculatorImplSign, ejb-name=CalculatorImplSign, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=CalculatorImplEncryptAndSign2ways, ejb-name=CalculatorImplEncryptAndSign2ways, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=CalculatorImplTimestamp1way, ejb-name=CalculatorImplTimestamp1way, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=CalculatorImplSign2ways, ejb-name=CalculatorImplSign2ways, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=CalculatorImplEncrypt2ways, ejb-name=CalculatorImplEncrypt2ways, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=CalculatorImplUsernameTokenPlainPassword, ejb-name=CalculatorImplUsernameTokenPlainPassword, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=CalculatorImplTimestamp2ways, ejb-name=CalculatorImplTimestamp2ways, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=CalculatorImplUsernameTokenPlainPasswordEncrypt, ejb-name=CalculatorImplUsernameTokenPlainPasswordEncrypt, container=Default Stateless Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/webservice-ws-security/classpath.ear)\n INFO - Initializing network services\n INFO - Creating ServerService(id=httpejbd)\n INFO - Creating ServerService(id=cxf)\n INFO - Creating ServerService(id=admin)\n INFO - Creating ServerService(id=ejbd)\n INFO - Creating ServerService(id=ejbds)\n INFO - Initializing network services\n ** Starting Services **\n NAME IP PORT \n httpejbd 127.0.0.1 4204 \n admin thread 127.0.0.1 4200 \n ejbd 127.0.0.1 4201 \n ejbd 127.0.0.1 4203 \n -------\n Ready!\n Tests run: 7, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 4.582 sec\n \n Results :\n \n Tests run: 7, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/webservice-ws-security"
},
{
"name":"testing-security-2",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/testing-security-2"
}
],
"server":[
{
"name":"server-events",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/server-events"
}
],
"session":[
{
"name":"cdi-session-scope",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/cdi-session-scope"
}
],
"singleton":[
{
"name":"simple-singleton",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/simple-singleton"
}
],
"spock":[
{
"name":"groovy-spock",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/groovy-spock"
}
],
"spring":[
{
"name":"spring-data-proxy",
"readme":"# Spring Data sample #\n\nThis example uses OpenEJB hooks to replace an EJB implementation by a proxy\nto uses Spring Data in your preferred container.\n\nIt is pretty simple: simply provide to OpenEJB an InvocationHandler using delegating to spring data\nand that's it!\n\nIt is what is done in org.superbiz.dynamic.SpringDataProxy.\n\nIt contains a little trick: even if it is not annotated \"implementingInterfaceClass\" attribute\nis injected by OpenEJB to get the interface.\n\nThen we simply create the Spring Data repository and delegate to it.\n",
"url":"https://github.com/apache/tomee/tree/master/examples/spring-data-proxy"
},
{
"name":"spring-data-proxy-meta",
"readme":"# Spring Data With Meta sample #\n\nThis example simply simplifies the usage of spring-data sample\nproviding a meta annotation @SpringRepository to do all the dynamic procy EJB job.\n\nIt replaces @Proxy and @Stateless annotations.\n\nIsn't it more comfortable?\n\nTo do it we defined a meta annotation \"Metatype\" and used it.\n\nThe proxy implementation is the same than for spring-data sample.\n",
"url":"https://github.com/apache/tomee/tree/master/examples/spring-data-proxy-meta"
}
],
"stateful":[
{
"name":"telephone-stateful",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/telephone-stateful"
},
{
"name":"simple-stateful-callbacks",
"readme":"Title: Simple Stateful with callback methods\n\nThis example shows how to create a stateful session bean that uses the @PrePassivate, @PostActivate, @PostConstruct, @PreDestroy and @AroundInvoke annotations.\n\n## CallbackCounter\n\n package org.superbiz.counter;\n\n import javax.annotation.PostConstruct;\n import javax.annotation.PreDestroy;\n import javax.ejb.PostActivate;\n import javax.ejb.PrePassivate;\n import javax.ejb.Stateful;\n import javax.ejb.StatefulTimeout;\n import javax.interceptor.AroundInvoke;\n import javax.interceptor.InvocationContext;\n import java.io.Serializable;\n import java.util.concurrent.TimeUnit;\n\n @Stateful\n @StatefulTimeout(value = 1, unit = TimeUnit.SECONDS)\n public class CallbackCounter implements Serializable {\n\n private int count = 0;\n\n @PrePassivate\n public void prePassivate() {\n ExecutionChannel.getInstance().notifyObservers(\"prePassivate\");\n }\n\n @PostActivate\n public void postActivate() {\n ExecutionChannel.getInstance().notifyObservers(\"postActivate\");\n }\n\n @PostConstruct\n public void postConstruct() {\n ExecutionChannel.getInstance().notifyObservers(\"postConstruct\");\n }\n\n @PreDestroy\n public void preDestroy() {\n ExecutionChannel.getInstance().notifyObservers(\"preDestroy\");\n }\n\n @AroundInvoke\n public Object intercept(InvocationContext ctx) throws Exception {\n ExecutionChannel.getInstance().notifyObservers(ctx.getMethod().getName());\n return ctx.proceed();\n }\n\n public int count() {\n return count;\n }\n\n public int increment() {\n return ++count;\n }\n\n public int reset() {\n return (count = 0);\n }\n }\n\n## ExecutionChannel\n\n package org.superbiz.counter;\n\n import java.util.ArrayList;\n import java.util.List;\n\n public class ExecutionChannel {\n private static final ExecutionChannel INSTANCE = new ExecutionChannel();\n\n private final List<ExecutionObserver> observers = new ArrayList<ExecutionObserver>();\n\n public static ExecutionChannel getInstance() {\n return INSTANCE;\n }\n\n public void addObserver(ExecutionObserver observer) {\n this.observers.add(observer);\n }\n\n public void notifyObservers(Object value) {\n for (ExecutionObserver observer : this.observers) {\n observer.onExecution(value);\n }\n }\n }\n\n## ExecutionObserver\n\n package org.superbiz.counter;\n\n public interface ExecutionObserver {\n\n void onExecution(Object value);\n\n }\n\n## CounterCallbacksTest\n\n package org.superbiz.counter;\n\n import junit.framework.Assert;\n import org.junit.Test;\n\n import javax.ejb.embeddable.EJBContainer;\n import javax.naming.Context;\n import javax.naming.InitialContext;\n import javax.naming.NamingException;\n import java.util.*;\n\n public class CounterCallbacksTest implements ExecutionObserver {\n private static List<Object> received = new ArrayList<Object>();\n\n public Context getContext() throws NamingException {\n final Properties p = new Properties();\n p.put(Context.INITIAL_CONTEXT_FACTORY, \"org.apache.openejb.core.LocalInitialContextFactory\");\n return new InitialContext(p);\n\n }\n\n @Test\n public void test() throws Exception {\n final Map<String, Object> p = new HashMap<String, Object>();\n p.put(\"MySTATEFUL\", \"new://Container?type=STATEFUL\");\n p.put(\"MySTATEFUL.Capacity\", \"2\"); //How many instances of Stateful beans can our server hold in memory?\n p.put(\"MySTATEFUL.Frequency\", \"1\"); //Interval in seconds between checks\n p.put(\"MySTATEFUL.BulkPassivate\", \"0\"); //No bulkPassivate - just passivate entities whenever it is needed\n final EJBContainer container = EJBContainer.createEJBContainer(p);\n\n //this is going to track the execution\n ExecutionChannel.getInstance().addObserver(this);\n\n {\n final Context context = getContext();\n\n CallbackCounter counterA = (CallbackCounter) context.lookup(\"java:global/simple-stateful-callbacks/CallbackCounter\");\n Assert.assertNotNull(counterA);\n Assert.assertEquals(\"postConstruct\", received.remove(0));\n\n Assert.assertEquals(0, counterA.count());\n Assert.assertEquals(\"count\", received.remove(0));\n\n Assert.assertEquals(1, counterA.increment());\n Assert.assertEquals(\"increment\", received.remove(0));\n\n Assert.assertEquals(0, counterA.reset());\n Assert.assertEquals(\"reset\", received.remove(0));\n\n Assert.assertEquals(1, counterA.increment());\n Assert.assertEquals(\"increment\", received.remove(0));\n\n System.out.println(\"Waiting 2 seconds...\");\n Thread.sleep(2000);\n\n Assert.assertEquals(\"preDestroy\", received.remove(0));\n\n try {\n counterA.increment();\n Assert.fail(\"The ejb is not supposed to be there.\");\n } catch (javax.ejb.NoSuchEJBException e) {\n //excepted\n }\n\n context.close();\n }\n\n {\n final Context context = getContext();\n\n CallbackCounter counterA = (CallbackCounter) context.lookup(\"java:global/simple-stateful-callbacks/CallbackCounter\");\n Assert.assertEquals(\"postConstruct\", received.remove(0));\n\n Assert.assertEquals(1, counterA.increment());\n Assert.assertEquals(\"increment\", received.remove(0));\n\n ((CallbackCounter) context.lookup(\"java:global/simple-stateful-callbacks/CallbackCounter\")).count();\n Assert.assertEquals(\"postConstruct\", received.remove(0));\n Assert.assertEquals(\"count\", received.remove(0));\n\n ((CallbackCounter) context.lookup(\"java:global/simple-stateful-callbacks/CallbackCounter\")).count();\n Assert.assertEquals(\"postConstruct\", received.remove(0));\n Assert.assertEquals(\"count\", received.remove(0));\n\n System.out.println(\"Waiting 2 seconds...\");\n Thread.sleep(2000);\n Assert.assertEquals(\"prePassivate\", received.remove(0));\n\n context.close();\n }\n container.close();\n\n Assert.assertEquals(\"preDestroy\", received.remove(0));\n Assert.assertEquals(\"preDestroy\", received.remove(0));\n\n Assert.assertTrue(received.toString(), received.isEmpty());\n }\n\n @Override\n public void onExecution(Object value) {\n System.out.println(\"Test step -> \" + value);\n received.add(value);\n }\n }\n\n# Running\n\n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.counter.CounterCallbacksTest\n INFO - ********************************************************************************\n INFO - OpenEJB http://tomee.apache.org/\n INFO - Startup: Sat Jul 21 08:18:28 EDT 2012\n INFO - Copyright 1999-2012 (C) Apache OpenEJB Project, All Rights Reserved.\n INFO - Version: 4.1.0\n INFO - Build date: 20120721\n INFO - Build time: 04:06\n INFO - ********************************************************************************\n INFO - openejb.home = /home/boto/dev/ws/openejb_trunk/openejb/examples/simple-stateful-callbacks\n INFO - openejb.base = /home/boto/dev/ws/openejb_trunk/openejb/examples/simple-stateful-callbacks\n INFO - Created new singletonService org.apache.openejb.cdi.ThreadSingletonServiceImpl@527736bd\n INFO - Succeeded in installing singleton service\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Cannot find the configuration file [conf/openejb.xml]. Will attempt to create one for the beans deployed.\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=MySTATEFUL, type=Container, provider-id=Default Stateful Container)\n INFO - Creating TransactionManager(id=Default Transaction Manager)\n INFO - Creating SecurityService(id=Default Security Service)\n INFO - Creating Container(id=MySTATEFUL)\n INFO - Using directory /tmp for stateful session passivation\n INFO - Beginning load: /home/boto/dev/ws/openejb_trunk/openejb/examples/simple-stateful-callbacks/target/classes\n INFO - Configuring enterprise application: /home/boto/dev/ws/openejb_trunk/openejb/examples/simple-stateful-callbacks\n INFO - Auto-deploying ejb CallbackCounter: EjbDeployment(deployment-id=CallbackCounter)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.counter.CounterCallbacksTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Creating Container(id=Default Managed Container)\n INFO - Using directory /tmp for stateful session passivation\n INFO - Enterprise application \"/home/boto/dev/ws/openejb_trunk/openejb/examples/simple-stateful-callbacks\" loaded.\n INFO - Assembling app: /home/boto/dev/ws/openejb_trunk/openejb/examples/simple-stateful-callbacks\n INFO - Jndi(name=\"java:global/simple-stateful-callbacks/CallbackCounter!org.superbiz.counter.CallbackCounter\")\n INFO - Jndi(name=\"java:global/simple-stateful-callbacks/CallbackCounter\")\n INFO - Existing thread singleton service in SystemInstance() org.apache.openejb.cdi.ThreadSingletonServiceImpl@527736bd\n INFO - OpenWebBeans Container is starting...\n INFO - Adding OpenWebBeansPlugin : [CdiPlugin]\n INFO - All injection points are validated successfully.\n INFO - OpenWebBeans Container has started, it took 225 ms.\n INFO - Created Ejb(deployment-id=CallbackCounter, ejb-name=CallbackCounter, container=MySTATEFUL)\n INFO - Started Ejb(deployment-id=CallbackCounter, ejb-name=CallbackCounter, container=MySTATEFUL)\n INFO - Deployed Application(path=/home/boto/dev/ws/openejb_trunk/openejb/examples/simple-stateful-callbacks)\n Test step -> postConstruct\n Test step -> count\n Test step -> increment\n Test step -> reset\n Test step -> increment\n Waiting 2 seconds...\n Test step -> preDestroy\n INFO - Removing the timed-out stateful session bean instance 583c10bfdbd326ba:57f94a9b:138a9798adf:-8000\n INFO - Activation failed: file not found /tmp/583c10bfdbd326ba=57f94a9b=138a9798adf=-8000\n Test step -> postConstruct\n Test step -> increment\n Test step -> postConstruct\n Test step -> count\n Test step -> postConstruct\n Test step -> count\n Waiting 2 seconds...\n Test step -> prePassivate\n INFO - Passivating to file /tmp/583c10bfdbd326ba=57f94a9b=138a9798adf=-7fff\n Test step -> preDestroy\n INFO - Removing the timed-out stateful session bean instance 583c10bfdbd326ba:57f94a9b:138a9798adf:-7ffe\n Test step -> preDestroy\n INFO - Removing the timed-out stateful session bean instance 583c10bfdbd326ba:57f94a9b:138a9798adf:-7ffd\n INFO - Undeploying app: /home/boto/dev/ws/openejb_trunk/openejb/examples/simple-stateful-callbacks\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 7.487 sec\n\n Results :\n\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n\n [INFO] ------------------------------------------------------------------------\n [INFO] BUILD SUCCESS\n [INFO] ------------------------------------------------------------------------\n [INFO] Total time: 15.803s\n [INFO] Finished at: Sat Jul 21 08:18:35 EDT 2012\n [INFO] Final Memory: 11M/247M\n [INFO] ------------------------------------------------------------------------\n\n\n",
"url":"https://github.com/apache/tomee/tree/master/examples/simple-stateful-callbacks"
},
{
"name":"simple-stateful",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/simple-stateful"
}
],
"stateless":[
{
"name":"simple-stateless-with-descriptor",
"readme":"Title: Simple Stateless with Descriptor\n\nThis test is similar to simple-stateless, with two major differences. In this case all the classes are regular POJOs without annotations.\nThe EJB-specific metadata is provided via an XML descriptor. The second difference is the explicite use of Local and Remote interfaces. \n\n## CalculatorImpl\n\n package org.superbiz.calculator;\n \n /**\n * This is an EJB 3 stateless session bean, configured using an EJB 3\n * deployment descriptor as opposed to using annotations.\n * This EJB has 2 business interfaces: CalculatorRemote, a remote business\n * interface, and CalculatorLocal, a local business interface\n */\n public class CalculatorImpl implements CalculatorRemote, CalculatorLocal {\n \n public int sum(int add1, int add2) {\n return add1 + add2;\n }\n \n public int multiply(int mul1, int mul2) {\n return mul1 * mul2;\n }\n }\n\n## CalculatorLocal\n\n package org.superbiz.calculator;\n \n /**\n * This is an EJB 3 local business interface\n * This interface is specified using the business-local tag in the deployment descriptor\n */\n public interface CalculatorLocal {\n \n public int sum(int add1, int add2);\n \n public int multiply(int mul1, int mul2);\n }\n\n## CalculatorRemote\n\n package org.superbiz.calculator;\n \n \n /**\n * This is an EJB 3 remote business interface\n * This interface is specified using the business-local tag in the deployment descriptor\n */\n public interface CalculatorRemote {\n \n public int sum(int add1, int add2);\n \n public int multiply(int mul1, int mul2);\n }\n\n## ejb-jar.xml\n\nThe XML descriptor defines the EJB class and both local and remote interfaces.\n\n <ejb-jar xmlns=\"http://java.sun.com/xml/ns/javaee\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd\"\n version=\"3.0\">\n <enterprise-beans>\n <session>\n <ejb-name>CalculatorImpl</ejb-name>\n <business-local>org.superbiz.calculator.CalculatorLocal</business-local>\n <business-remote>org.superbiz.calculator.CalculatorRemote</business-remote>\n <ejb-class>org.superbiz.calculator.CalculatorImpl</ejb-class>\n <session-type>Stateless</session-type>\n <transaction-type>Container</transaction-type>\n </session>\n </enterprise-beans>\n </ejb-jar>\n\n \n\n## CalculatorTest\n\nTwo tests obtain a Local and Remote interface to the bean instance. This time an `InitialContext` object is directly created, \nas opposed to getting the context from `EJBContainer`, as we did in the previous example. \n\n package org.superbiz.calculator;\n \n import junit.framework.TestCase;\n \n import javax.naming.Context;\n import javax.naming.InitialContext;\n import java.util.Properties;\n \n public class CalculatorTest extends TestCase {\n \n private InitialContext initialContext;\n \n protected void setUp() throws Exception {\n Properties properties = new Properties();\n properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, \"org.apache.openejb.core.LocalInitialContextFactory\");\n \n initialContext = new InitialContext(properties);\n }\n\n /**\n * Lookup the Calculator bean via its remote home interface\n *\n * @throws Exception\n */\n public void testCalculatorViaRemoteInterface() throws Exception {\n Object object = initialContext.lookup(\"CalculatorImplRemote\");\n \n assertNotNull(object);\n assertTrue(object instanceof CalculatorRemote);\n CalculatorRemote calc = (CalculatorRemote) object;\n assertEquals(10, calc.sum(4, 6));\n assertEquals(12, calc.multiply(3, 4));\n }\n\n /**\n * Lookup the Calculator bean via its local home interface\n *\n * @throws Exception\n */\n public void testCalculatorViaLocalInterface() throws Exception {\n Object object = initialContext.lookup(\"CalculatorImplLocal\");\n \n assertNotNull(object);\n assertTrue(object instanceof CalculatorLocal);\n CalculatorLocal calc = (CalculatorLocal) object;\n assertEquals(10, calc.sum(4, 6));\n assertEquals(12, calc.multiply(3, 4));\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.calculator.CalculatorTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/simple-stateless-with-descriptor\n INFO - openejb.base = /Users/dblevins/examples/simple-stateless-with-descriptor\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/simple-stateless-with-descriptor/target/classes\n INFO - Beginning load: /Users/dblevins/examples/simple-stateless-with-descriptor/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/simple-stateless-with-descriptor/classpath.ear\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean CalculatorImpl: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Enterprise application \"/Users/dblevins/examples/simple-stateless-with-descriptor/classpath.ear\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/simple-stateless-with-descriptor/classpath.ear\n INFO - Jndi(name=CalculatorImplLocal) --> Ejb(deployment-id=CalculatorImpl)\n INFO - Jndi(name=global/classpath.ear/simple-stateless-with-descriptor/CalculatorImpl!org.superbiz.calculator.CalculatorLocal) --> Ejb(deployment-id=CalculatorImpl)\n INFO - Jndi(name=CalculatorImplRemote) --> Ejb(deployment-id=CalculatorImpl)\n INFO - Jndi(name=global/classpath.ear/simple-stateless-with-descriptor/CalculatorImpl!org.superbiz.calculator.CalculatorRemote) --> Ejb(deployment-id=CalculatorImpl)\n INFO - Jndi(name=global/classpath.ear/simple-stateless-with-descriptor/CalculatorImpl) --> Ejb(deployment-id=CalculatorImpl)\n INFO - Created Ejb(deployment-id=CalculatorImpl, ejb-name=CalculatorImpl, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=CalculatorImpl, ejb-name=CalculatorImpl, container=Default Stateless Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/simple-stateless-with-descriptor/classpath.ear)\n Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.475 sec\n \n Results :\n \n Tests run: 2, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/simple-stateless-with-descriptor"
},
{
"name":"simple-stateless",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/simple-stateless"
},
{
"name":"simple-stateless-callbacks",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/simple-stateless-callbacks"
}
],
"stereotypes":[
{
"name":"cdi-alternative-and-stereotypes",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/cdi-alternative-and-stereotypes"
}
],
"struts":[
{
"name":"struts",
"readme":"Title: Struts\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## AddUser\n\n package org.superbiz.struts;\n \n import javax.naming.Context;\n import javax.naming.InitialContext;\n import java.util.Properties;\n \n \n public class AddUser {\n \n private int id;\n private String firstName;\n private String lastName;\n private String errorMessage;\n \n \n public String getFirstName() {\n return firstName;\n }\n \n public void setFirstName(String firstName) {\n this.firstName = firstName;\n }\n \n public String getLastName() {\n return lastName;\n }\n \n public void setLastName(String lastName) {\n this.lastName = lastName;\n }\n \n public String getErrorMessage() {\n return errorMessage;\n }\n \n public void setErrorMessage(String errorMessage) {\n this.errorMessage = errorMessage;\n }\n \n public int getId() {\n return id;\n }\n \n public void setId(int id) {\n this.id = id;\n }\n \n public String execute() {\n \n try {\n UserService service = null;\n Properties props = new Properties();\n props.put(Context.INITIAL_CONTEXT_FACTORY,\n \"org.apache.openejb.core.LocalInitialContextFactory\");\n Context ctx = new InitialContext(props);\n service = (UserService) ctx.lookup(\"UserServiceImplLocal\");\n service.add(new User(id, firstName, lastName));\n } catch (Exception e) {\n this.errorMessage = e.getMessage();\n return \"failure\";\n }\n \n return \"success\";\n }\n }\n\n## AddUserForm\n\n package org.superbiz.struts;\n \n import com.opensymphony.xwork2.ActionSupport;\n \n \n public class AddUserForm extends ActionSupport {\n }\n\n## FindUser\n\n package org.superbiz.struts;\n \n import javax.naming.Context;\n import javax.naming.InitialContext;\n import java.util.Properties;\n \n public class FindUser {\n \n private int id;\n private String errorMessage;\n private User user;\n \n public User getUser() {\n return user;\n }\n \n public void setUser(User user) {\n this.user = user;\n }\n \n public String getErrorMessage() {\n return errorMessage;\n }\n \n public void setErrorMessage(String errorMessage) {\n this.errorMessage = errorMessage;\n }\n \n public int getId() {\n return id;\n }\n \n public void setId(int id) {\n this.id = id;\n }\n \n public String execute() {\n \n try {\n UserService service = null;\n Properties props = new Properties();\n props.put(Context.INITIAL_CONTEXT_FACTORY,\n \"org.apache.openejb.core.LocalInitialContextFactory\");\n Context ctx = new InitialContext(props);\n service = (UserService) ctx.lookup(\"UserServiceImplLocal\");\n this.user = service.find(id);\n } catch (Exception e) {\n this.errorMessage = e.getMessage();\n return \"failure\";\n }\n \n return \"success\";\n }\n }\n\n## FindUserForm\n\n package org.superbiz.struts;\n \n import com.opensymphony.xwork2.ActionSupport;\n \n \n public class FindUserForm extends ActionSupport {\n }\n\n## ListAllUsers\n\n package org.superbiz.struts;\n \n import javax.naming.Context;\n import javax.naming.InitialContext;\n import java.util.List;\n import java.util.Properties;\n \n public class ListAllUsers {\n \n private int id;\n private String errorMessage;\n private List<User> users;\n \n public List<User> getUsers() {\n return users;\n }\n \n public void setUsers(List<User> users) {\n this.users = users;\n }\n \n public String getErrorMessage() {\n return errorMessage;\n }\n \n public void setErrorMessage(String errorMessage) {\n this.errorMessage = errorMessage;\n }\n \n public int getId() {\n return id;\n }\n \n public void setId(int id) {\n this.id = id;\n }\n \n public String execute() {\n \n try {\n UserService service = null;\n Properties props = new Properties();\n props.put(Context.INITIAL_CONTEXT_FACTORY,\n \"org.apache.openejb.core.LocalInitialContextFactory\");\n Context ctx = new InitialContext(props);\n service = (UserService) ctx.lookup(\"UserServiceImplLocal\");\n this.users = service.findAll();\n } catch (Exception e) {\n this.errorMessage = e.getMessage();\n return \"failure\";\n }\n \n return \"success\";\n }\n }\n\n## User\n\n package org.superbiz.struts;\n \n import javax.persistence.Entity;\n import javax.persistence.Id;\n import javax.persistence.Table;\n import java.io.Serializable;\n \n @Entity\n @Table(name = \"USER\")\n public class User implements Serializable {\n private long id;\n private String firstName;\n private String lastName;\n \n public User(long id, String firstName, String lastName) {\n super();\n this.id = id;\n this.firstName = firstName;\n this.lastName = lastName;\n }\n \n public User() {\n }\n \n @Id\n public long getId() {\n return id;\n }\n \n public void setId(long id) {\n this.id = id;\n }\n \n public String getFirstName() {\n return firstName;\n }\n \n public void setFirstName(String firstName) {\n this.firstName = firstName;\n }\n \n public String getLastName() {\n return lastName;\n }\n \n public void setLastName(String lastName) {\n this.lastName = lastName;\n }\n }\n\n## UserService\n\n package org.superbiz.struts;\n \n import java.util.List;\n \n public interface UserService {\n public void add(User user);\n \n public User find(int id);\n \n public List<User> findAll();\n }\n\n## UserServiceImpl\n\n package org.superbiz.struts;\n \n import javax.ejb.Stateless;\n import javax.persistence.EntityManager;\n import javax.persistence.PersistenceContext;\n import java.util.List;\n \n @Stateless\n public class UserServiceImpl implements UserService {\n \n @PersistenceContext(unitName = \"user\")\n private EntityManager manager;\n \n public void add(User user) {\n manager.persist(user);\n }\n \n public User find(int id) {\n return manager.find(User.class, id);\n }\n \n public List<User> findAll() {\n return manager.createQuery(\"select u from User u\").getResultList();\n }\n }\n\n## persistence.xml\n\n </persistence-unit>\n \n -->\n </persistence>\n\n## struts.xml\n\n <struts>\n <constant name=\"struts.devMode\" value=\"true\"></constant>\n <package name=\"default\" namespace=\"/\" extends=\"struts-default\">\n <action name=\"addUserForm\" class=\"org.superbiz.struts.AddUserForm\">\n <result>/addUserForm.jsp</result>\n </action>\n <action name=\"addUser\" class=\"org.superbiz.struts.AddUser\">\n <result name=\"success\">/addedUser.jsp</result>\n <result name='failure'>/addUserForm.jsp</result>\n </action>\n <action name=\"findUserForm\" class=\"org.superbiz.struts.FindUserForm\">\n <result>/findUserForm.jsp</result>\n </action>\n <action name=\"findUser\" class=\"org.superbiz.struts.FindUser\">\n <result name='success'>/displayUser.jsp</result>\n <result name='failure'>/findUserForm.jsp</result>\n </action>\n <action name=\"listAllUsers\" class=\"org.superbiz.struts.ListAllUsers\">\n <result>/displayUsers.jsp</result>\n </action>\n \n </package>\n </struts>\n\n## decorators.xml\n\n <decorators defaultdir=\"/decorators\">\n <decorator name=\"main\" page=\"layout.jsp\">\n <pattern>/*</pattern>\n </decorator>\n </decorators>\n\n## web.xml\n\n <web-app xmlns=\"http://java.sun.com/xml/ns/javaee\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n version=\"2.5\">\n <display-name>Learn EJB3 and Struts2</display-name>\n <filter>\n <filter-name>struts2</filter-name>\n <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>\n <init-param>\n <param-name>actionPackages</param-name>\n <param-value>com.lq</param-value>\n </init-param>\n </filter>\n <filter>\n <filter-name>struts-cleanup</filter-name>\n <filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class>\n </filter>\n <filter>\n <filter-name>sitemesh</filter-name>\n <filter-class>com.opensymphony.module.sitemesh.filter.PageFilter</filter-class>\n </filter>\n <filter-mapping>\n <filter-name>struts-cleanup</filter-name>\n <url-pattern>/*</url-pattern>\n </filter-mapping>\n <filter-mapping>\n <filter-name>sitemesh</filter-name>\n <url-pattern>/*</url-pattern>\n </filter-mapping>\n <filter-mapping>\n <filter-name>struts2</filter-name>\n <url-pattern>/*</url-pattern>\n </filter-mapping>\n <welcome-file-list>\n <welcome-file>index.jsp</welcome-file>\n </welcome-file-list>\n <jsp-config>\n <jsp-property-group>\n <description>JSP configuration of all the JSP's</description>\n <url-pattern>*.jsp</url-pattern>\n <include-prelude>/prelude.jspf</include-prelude>\n </jsp-property-group>\n </jsp-config>\n </web-app>\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/struts"
}
],
"telephone":[
{
"name":"telephone-stateful",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/telephone-stateful"
}
],
"testcase":[
{
"name":"testcase-injection",
"readme":"Title: Testcase Injection\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## Movie\n\n package org.superbiz.testinjection;\n \n import javax.persistence.Entity;\n \n @Entity\n public class Movie {\n \n private String director;\n private String title;\n private int year;\n \n public Movie() {\n }\n \n public Movie(String director, String title, int year) {\n this.director = director;\n this.title = title;\n this.year = year;\n }\n \n public String getDirector() {\n return director;\n }\n \n public void setDirector(String director) {\n this.director = director;\n }\n \n public String getTitle() {\n return title;\n }\n \n public void setTitle(String title) {\n this.title = title;\n }\n \n public int getYear() {\n return year;\n }\n \n public void setYear(int year) {\n this.year = year;\n }\n \n }\n\n## Movies\n\n package org.superbiz.testinjection;\n \n import javax.ejb.Stateful;\n import javax.ejb.TransactionAttribute;\n import javax.persistence.EntityManager;\n import javax.persistence.PersistenceContext;\n import javax.persistence.PersistenceContextType;\n import javax.persistence.Query;\n import java.util.List;\n \n import static javax.ejb.TransactionAttributeType.MANDATORY;\n \n //START SNIPPET: code\n @Stateful\n @TransactionAttribute(MANDATORY)\n public class Movies {\n \n @PersistenceContext(unitName = \"movie-unit\", type = PersistenceContextType.TRANSACTION)\n private EntityManager entityManager;\n \n public void addMovie(Movie movie) throws Exception {\n entityManager.persist(movie);\n }\n \n public void deleteMovie(Movie movie) throws Exception {\n entityManager.remove(movie);\n }\n \n public List<Movie> getMovies() throws Exception {\n Query query = entityManager.createQuery(\"SELECT m from Movie as m\");\n return query.getResultList();\n }\n }\n\n## persistence.xml\n\n <persistence xmlns=\"http://java.sun.com/xml/ns/persistence\" version=\"1.0\">\n \n <persistence-unit name=\"movie-unit\">\n <jta-data-source>movieDatabase</jta-data-source>\n <non-jta-data-source>movieDatabaseUnmanaged</non-jta-data-source>\n <class>org.superbiz.testinjection.Movie</class>\n \n <properties>\n <property name=\"openjpa.jdbc.SynchronizeMappings\" value=\"buildSchema(ForeignKeys=true)\"/>\n </properties>\n </persistence-unit>\n </persistence>\n\n## MoviesTest\n\n package org.superbiz.testinjection;\n \n import junit.framework.TestCase;\n \n import javax.annotation.Resource;\n import javax.ejb.EJB;\n import javax.ejb.embeddable.EJBContainer;\n import javax.persistence.EntityManager;\n import javax.persistence.PersistenceContext;\n import javax.transaction.UserTransaction;\n import java.util.List;\n import java.util.Properties;\n \n //START SNIPPET: code\n public class MoviesTest extends TestCase {\n \n @EJB\n private Movies movies;\n \n @Resource\n private UserTransaction userTransaction;\n \n @PersistenceContext\n private EntityManager entityManager;\n \n public void setUp() throws Exception {\n Properties p = new Properties();\n p.put(\"movieDatabase\", \"new://Resource?type=DataSource\");\n p.put(\"movieDatabase.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"movieDatabase.JdbcUrl\", \"jdbc:hsqldb:mem:moviedb\");\n \n EJBContainer.createEJBContainer(p).getContext().bind(\"inject\", this);\n }\n \n public void test() throws Exception {\n \n userTransaction.begin();\n \n try {\n entityManager.persist(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n entityManager.persist(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n entityManager.persist(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n \n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n \n for (Movie movie : list) {\n movies.deleteMovie(movie);\n }\n \n assertEquals(\"Movies.getMovies()\", 0, movies.getMovies().size());\n } finally {\n userTransaction.commit();\n }\n \n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.testinjection.MoviesTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/testcase-injection\n INFO - openejb.base = /Users/dblevins/examples/testcase-injection\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/testcase-injection/target/classes\n INFO - Beginning load: /Users/dblevins/examples/testcase-injection/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/testcase-injection\n WARN - Method 'lookup' is not available for 'javax.annotation.Resource'. Probably using an older Runtime.\n INFO - Configuring Service(id=Default Stateful Container, type=Container, provider-id=Default Stateful Container)\n INFO - Auto-creating a container for bean Movies: Container(type=STATEFUL, id=Default Stateful Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.testinjection.MoviesTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring PersistenceUnit(name=movie-unit)\n INFO - Auto-creating a Resource with id 'movieDatabaseNonJta' of type 'DataSource for 'movie-unit'.\n INFO - Configuring Service(id=movieDatabaseNonJta, type=Resource, provider-id=movieDatabase)\n INFO - Adjusting PersistenceUnit movie-unit <non-jta-data-source> to Resource ID 'movieDatabaseNonJta' from 'movieDatabaseUnmanaged'\n INFO - Enterprise application \"/Users/dblevins/examples/testcase-injection\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/testcase-injection\n INFO - PersistenceUnit(name=movie-unit, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 408ms\n INFO - Jndi(name=\"java:global/testcase-injection/Movies!org.superbiz.testinjection.Movies\")\n INFO - Jndi(name=\"java:global/testcase-injection/Movies\")\n INFO - Jndi(name=\"java:global/EjbModule1583515396/org.superbiz.testinjection.MoviesTest!org.superbiz.testinjection.MoviesTest\")\n INFO - Jndi(name=\"java:global/EjbModule1583515396/org.superbiz.testinjection.MoviesTest\")\n INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Created Ejb(deployment-id=org.superbiz.testinjection.MoviesTest, ejb-name=org.superbiz.testinjection.MoviesTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Started Ejb(deployment-id=org.superbiz.testinjection.MoviesTest, ejb-name=org.superbiz.testinjection.MoviesTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/testcase-injection)\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.24 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/testcase-injection"
}
],
"testing":[
{
"name":"testing-security",
"readme":"Title: Testing Security\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## Movie\n\n package org.superbiz.injection.secure;\n \n import javax.persistence.Entity;\n \n @Entity\n public class Movie {\n \n private String director;\n private String title;\n private int year;\n \n public Movie() {\n }\n \n public Movie(String director, String title, int year) {\n this.director = director;\n this.title = title;\n this.year = year;\n }\n \n public String getDirector() {\n return director;\n }\n \n public void setDirector(String director) {\n this.director = director;\n }\n \n public String getTitle() {\n return title;\n }\n \n public void setTitle(String title) {\n this.title = title;\n }\n \n public int getYear() {\n return year;\n }\n \n public void setYear(int year) {\n this.year = year;\n }\n \n }\n\n## Movies\n\n package org.superbiz.injection.secure;\n \n //START SNIPPET: code\n \n import javax.annotation.security.PermitAll;\n import javax.annotation.security.RolesAllowed;\n import javax.ejb.Stateful;\n import javax.ejb.TransactionAttribute;\n import javax.ejb.TransactionAttributeType;\n import javax.persistence.EntityManager;\n import javax.persistence.PersistenceContext;\n import javax.persistence.PersistenceContextType;\n import javax.persistence.Query;\n import java.util.List;\n \n @Stateful\n public class Movies {\n \n @PersistenceContext(unitName = \"movie-unit\", type = PersistenceContextType.EXTENDED)\n private EntityManager entityManager;\n \n @RolesAllowed({\"Employee\", \"Manager\"})\n public void addMovie(Movie movie) throws Exception {\n entityManager.persist(movie);\n }\n \n @RolesAllowed({\"Manager\"})\n public void deleteMovie(Movie movie) throws Exception {\n entityManager.remove(movie);\n }\n \n @PermitAll\n @TransactionAttribute(TransactionAttributeType.SUPPORTS)\n public List<Movie> getMovies() throws Exception {\n Query query = entityManager.createQuery(\"SELECT m from Movie as m\");\n return query.getResultList();\n }\n }\n\n## persistence.xml\n\n <persistence xmlns=\"http://java.sun.com/xml/ns/persistence\" version=\"1.0\">\n \n <persistence-unit name=\"movie-unit\">\n <jta-data-source>movieDatabase</jta-data-source>\n <non-jta-data-source>movieDatabaseUnmanaged</non-jta-data-source>\n <class>org.superbiz.injection.secure.Movie</class>\n \n <properties>\n <property name=\"openjpa.jdbc.SynchronizeMappings\" value=\"buildSchema(ForeignKeys=true)\"/>\n </properties>\n </persistence-unit>\n </persistence>\n\n## MovieTest\n\n package org.superbiz.injection.secure;\n \n import junit.framework.TestCase;\n \n import javax.annotation.security.RunAs;\n import javax.ejb.EJB;\n import javax.ejb.EJBAccessException;\n import javax.ejb.Stateless;\n import javax.ejb.embeddable.EJBContainer;\n import java.util.List;\n import java.util.Properties;\n import java.util.concurrent.Callable;\n \n //START SNIPPET: code\n \n public class MovieTest extends TestCase {\n \n @EJB\n private Movies movies;\n \n @EJB(name = \"ManagerBean\")\n private Caller manager;\n \n @EJB(name = \"EmployeeBean\")\n private Caller employee;\n \n protected void setUp() throws Exception {\n Properties p = new Properties();\n p.put(\"movieDatabase\", \"new://Resource?type=DataSource\");\n p.put(\"movieDatabase.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"movieDatabase.JdbcUrl\", \"jdbc:hsqldb:mem:moviedb\");\n \n EJBContainer.createEJBContainer(p).getContext().bind(\"inject\", this);\n }\n \n public void testAsManager() throws Exception {\n manager.call(new Callable() {\n public Object call() throws Exception {\n \n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n movies.addMovie(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n movies.addMovie(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n \n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n \n for (Movie movie : list) {\n movies.deleteMovie(movie);\n }\n \n assertEquals(\"Movies.getMovies()\", 0, movies.getMovies().size());\n return null;\n }\n });\n }\n \n public void testAsEmployee() throws Exception {\n employee.call(new Callable() {\n public Object call() throws Exception {\n \n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n movies.addMovie(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n movies.addMovie(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n \n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n \n for (Movie movie : list) {\n try {\n movies.deleteMovie(movie);\n fail(\"Employees should not be allowed to delete\");\n } catch (EJBAccessException e) {\n // Good, Employees cannot delete things\n }\n }\n \n // The list should still be three movies long\n assertEquals(\"Movies.getMovies()\", 3, movies.getMovies().size());\n return null;\n }\n });\n }\n \n public void testUnauthenticated() throws Exception {\n try {\n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n fail(\"Unauthenticated users should not be able to add movies\");\n } catch (EJBAccessException e) {\n // Good, guests cannot add things\n }\n \n try {\n movies.deleteMovie(null);\n fail(\"Unauthenticated users should not be allowed to delete\");\n } catch (EJBAccessException e) {\n // Good, Unauthenticated users cannot delete things\n }\n \n try {\n // Read access should be allowed\n \n List<Movie> list = movies.getMovies();\n } catch (EJBAccessException e) {\n fail(\"Read access should be allowed\");\n }\n }\n \n \n public static interface Caller {\n public <V> V call(Callable<V> callable) throws Exception;\n }\n \n /**\n * This little bit of magic allows our test code to execute in\n * the desired security scope.\n */\n \n @Stateless\n @RunAs(\"Manager\")\n public static class ManagerBean implements Caller {\n \n public <V> V call(Callable<V> callable) throws Exception {\n return callable.call();\n }\n }\n \n @Stateless\n @RunAs(\"Employee\")\n public static class EmployeeBean implements Caller {\n \n public <V> V call(Callable<V> callable) throws Exception {\n return callable.call();\n }\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.injection.secure.MovieTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/testing-security\n INFO - openejb.base = /Users/dblevins/examples/testing-security\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/testing-security/target/classes\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/testing-security/target/test-classes\n INFO - Beginning load: /Users/dblevins/examples/testing-security/target/classes\n INFO - Beginning load: /Users/dblevins/examples/testing-security/target/test-classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/testing-security\n INFO - Configuring Service(id=Default Stateful Container, type=Container, provider-id=Default Stateful Container)\n INFO - Auto-creating a container for bean Movies: Container(type=STATEFUL, id=Default Stateful Container)\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean ManagerBean: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.injection.secure.MovieTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring PersistenceUnit(name=movie-unit)\n INFO - Auto-creating a Resource with id 'movieDatabaseNonJta' of type 'DataSource for 'movie-unit'.\n INFO - Configuring Service(id=movieDatabaseNonJta, type=Resource, provider-id=movieDatabase)\n INFO - Adjusting PersistenceUnit movie-unit <non-jta-data-source> to Resource ID 'movieDatabaseNonJta' from 'movieDatabaseUnmanaged'\n INFO - Enterprise application \"/Users/dblevins/examples/testing-security\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/testing-security\n INFO - PersistenceUnit(name=movie-unit, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 405ms\n INFO - Jndi(name=\"java:global/testing-security/Movies!org.superbiz.injection.secure.Movies\")\n INFO - Jndi(name=\"java:global/testing-security/Movies\")\n INFO - Jndi(name=\"java:global/testing-security/ManagerBean!org.superbiz.injection.secure.MovieTest$Caller\")\n INFO - Jndi(name=\"java:global/testing-security/ManagerBean\")\n INFO - Jndi(name=\"java:global/testing-security/EmployeeBean!org.superbiz.injection.secure.MovieTest$Caller\")\n INFO - Jndi(name=\"java:global/testing-security/EmployeeBean\")\n INFO - Jndi(name=\"java:global/EjbModule26174809/org.superbiz.injection.secure.MovieTest!org.superbiz.injection.secure.MovieTest\")\n INFO - Jndi(name=\"java:global/EjbModule26174809/org.superbiz.injection.secure.MovieTest\")\n INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Created Ejb(deployment-id=ManagerBean, ejb-name=ManagerBean, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=EmployeeBean, ejb-name=EmployeeBean, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=org.superbiz.injection.secure.MovieTest, ejb-name=org.superbiz.injection.secure.MovieTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Started Ejb(deployment-id=ManagerBean, ejb-name=ManagerBean, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=EmployeeBean, ejb-name=EmployeeBean, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=org.superbiz.injection.secure.MovieTest, ejb-name=org.superbiz.injection.secure.MovieTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/testing-security)\n INFO - EJBContainer already initialized. Call ejbContainer.close() to allow reinitialization\n INFO - EJBContainer already initialized. Call ejbContainer.close() to allow reinitialization\n Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.574 sec\n \n Results :\n \n Tests run: 3, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/testing-security"
},
{
"name":"testing-security-meta",
"readme":"Title: Testing Security Meta\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## AddPermission\n\n package org.superbiz.injection.secure.api;\n \n import javax.annotation.security.RolesAllowed;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n \n @Metatype\n @Target(ElementType.METHOD)\n @Retention(RetentionPolicy.RUNTIME)\n \n public @interface AddPermission {\n public static interface $ {\n \n @AddPermission\n @RolesAllowed({\"Employee\", \"Manager\"})\n public void method();\n }\n }\n\n## DeletePermission\n\n package org.superbiz.injection.secure.api;\n \n import javax.annotation.security.RolesAllowed;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n \n @Metatype\n @Target(ElementType.METHOD)\n @Retention(RetentionPolicy.RUNTIME)\n \n public @interface DeletePermission {\n public static interface $ {\n \n @DeletePermission\n @RolesAllowed(\"Manager\")\n public void method();\n }\n }\n\n## Metatype\n\n package org.superbiz.injection.secure.api;\n \n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n @Metatype\n @Target(ElementType.ANNOTATION_TYPE)\n @Retention(RetentionPolicy.RUNTIME)\n public @interface Metatype {\n }\n\n## MovieUnit\n\n package org.superbiz.injection.secure.api;\n \n import javax.persistence.PersistenceContext;\n import javax.persistence.PersistenceContextType;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n \n @Metatype\n @Target({ElementType.METHOD, ElementType.FIELD})\n @Retention(RetentionPolicy.RUNTIME)\n \n @PersistenceContext(name = \"movie-unit\", unitName = \"movie-unit\", type = PersistenceContextType.EXTENDED)\n public @interface MovieUnit {\n }\n\n## ReadPermission\n\n package org.superbiz.injection.secure.api;\n \n import javax.annotation.security.PermitAll;\n import javax.ejb.TransactionAttribute;\n import javax.ejb.TransactionAttributeType;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n \n @Metatype\n @Target(ElementType.METHOD)\n @Retention(RetentionPolicy.RUNTIME)\n \n public @interface ReadPermission {\n public static interface $ {\n \n @ReadPermission\n @PermitAll\n @TransactionAttribute(TransactionAttributeType.SUPPORTS)\n public void method();\n }\n }\n\n## RunAsEmployee\n\n package org.superbiz.injection.secure.api;\n \n import javax.annotation.security.RunAs;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n \n @Metatype\n @Target({ElementType.TYPE, ElementType.METHOD})\n @Retention(RetentionPolicy.RUNTIME)\n \n @RunAs(\"Employee\")\n public @interface RunAsEmployee {\n }\n\n## RunAsManager\n\n package org.superbiz.injection.secure.api;\n \n import javax.annotation.security.RunAs;\n import java.lang.annotation.ElementType;\n import java.lang.annotation.Retention;\n import java.lang.annotation.RetentionPolicy;\n import java.lang.annotation.Target;\n \n \n @Metatype\n @Target({ElementType.TYPE, ElementType.METHOD})\n @Retention(RetentionPolicy.RUNTIME)\n \n @RunAs(\"Manager\")\n public @interface RunAsManager {\n }\n\n## Movie\n\n package org.superbiz.injection.secure;\n \n import javax.persistence.Entity;\n \n @Entity\n public class Movie {\n \n private String director;\n private String title;\n private int year;\n \n public Movie() {\n }\n \n public Movie(String director, String title, int year) {\n this.director = director;\n this.title = title;\n this.year = year;\n }\n \n public String getDirector() {\n return director;\n }\n \n public void setDirector(String director) {\n this.director = director;\n }\n \n public String getTitle() {\n return title;\n }\n \n public void setTitle(String title) {\n this.title = title;\n }\n \n public int getYear() {\n return year;\n }\n \n public void setYear(int year) {\n this.year = year;\n }\n \n }\n\n## Movies\n\n package org.superbiz.injection.secure;\n \n //START SNIPPET: code\n \n import org.superbiz.injection.secure.api.AddPermission;\n import org.superbiz.injection.secure.api.DeletePermission;\n import org.superbiz.injection.secure.api.MovieUnit;\n import org.superbiz.injection.secure.api.ReadPermission;\n \n import javax.ejb.Stateful;\n import javax.persistence.EntityManager;\n import javax.persistence.Query;\n import java.util.List;\n \n @Stateful\n public class Movies {\n \n @MovieUnit\n private EntityManager entityManager;\n \n @AddPermission\n public void addMovie(Movie movie) throws Exception {\n entityManager.persist(movie);\n }\n \n @DeletePermission\n public void deleteMovie(Movie movie) throws Exception {\n entityManager.remove(movie);\n }\n \n @ReadPermission\n public List<Movie> getMovies() throws Exception {\n Query query = entityManager.createQuery(\"SELECT m from Movie as m\");\n return query.getResultList();\n }\n }\n\n## persistence.xml\n\n <persistence xmlns=\"http://java.sun.com/xml/ns/persistence\" version=\"1.0\">\n \n <persistence-unit name=\"movie-unit\">\n <jta-data-source>movieDatabase</jta-data-source>\n <non-jta-data-source>movieDatabaseUnmanaged</non-jta-data-source>\n <class>org.superbiz.injection.secure.Movie</class>\n \n <properties>\n <property name=\"openjpa.jdbc.SynchronizeMappings\" value=\"buildSchema(ForeignKeys=true)\"/>\n </properties>\n </persistence-unit>\n </persistence>\n\n## MovieTest\n\n package org.superbiz.injection.secure;\n \n import junit.framework.TestCase;\n import org.superbiz.injection.secure.api.RunAsEmployee;\n import org.superbiz.injection.secure.api.RunAsManager;\n \n import javax.ejb.EJB;\n import javax.ejb.EJBAccessException;\n import javax.ejb.Stateless;\n import javax.ejb.embeddable.EJBContainer;\n import java.util.List;\n import java.util.Properties;\n import java.util.concurrent.Callable;\n \n //START SNIPPET: code\n \n public class MovieTest extends TestCase {\n \n @EJB\n private Movies movies;\n \n @EJB(beanName = \"ManagerBean\")\n private Caller manager;\n \n @EJB(beanName = \"EmployeeBean\")\n private Caller employee;\n \n protected void setUp() throws Exception {\n Properties p = new Properties();\n p.put(\"movieDatabase\", \"new://Resource?type=DataSource\");\n p.put(\"movieDatabase.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"movieDatabase.JdbcUrl\", \"jdbc:hsqldb:mem:moviedb\");\n \n EJBContainer.createEJBContainer(p).getContext().bind(\"inject\", this);\n }\n \n public void testAsManager() throws Exception {\n manager.call(new Callable() {\n public Object call() throws Exception {\n \n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n movies.addMovie(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n movies.addMovie(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n \n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n \n for (Movie movie : list) {\n movies.deleteMovie(movie);\n }\n \n assertEquals(\"Movies.getMovies()\", 0, movies.getMovies().size());\n return null;\n }\n });\n }\n \n public void testAsEmployee() throws Exception {\n employee.call(new Callable() {\n public Object call() throws Exception {\n \n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n movies.addMovie(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n movies.addMovie(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n \n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n \n for (Movie movie : list) {\n try {\n movies.deleteMovie(movie);\n fail(\"Employees should not be allowed to delete\");\n } catch (EJBAccessException e) {\n // Good, Employees cannot delete things\n }\n }\n \n // The list should still be three movies long\n assertEquals(\"Movies.getMovies()\", 3, movies.getMovies().size());\n return null;\n }\n });\n }\n \n public void testUnauthenticated() throws Exception {\n try {\n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n fail(\"Unauthenticated users should not be able to add movies\");\n } catch (EJBAccessException e) {\n // Good, guests cannot add things\n }\n \n try {\n movies.deleteMovie(null);\n fail(\"Unauthenticated users should not be allowed to delete\");\n } catch (EJBAccessException e) {\n // Good, Unauthenticated users cannot delete things\n }\n \n try {\n // Read access should be allowed\n \n List<Movie> list = movies.getMovies();\n } catch (EJBAccessException e) {\n fail(\"Read access should be allowed\");\n }\n }\n \n public interface Caller {\n public <V> V call(Callable<V> callable) throws Exception;\n }\n \n /**\n * This little bit of magic allows our test code to execute in\n * the desired security scope.\n */\n \n @Stateless\n @RunAsManager\n public static class ManagerBean implements Caller {\n \n public <V> V call(Callable<V> callable) throws Exception {\n return callable.call();\n }\n }\n \n @Stateless\n @RunAsEmployee\n public static class EmployeeBean implements Caller {\n \n public <V> V call(Callable<V> callable) throws Exception {\n return callable.call();\n }\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.injection.secure.MovieTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/testing-security-meta\n INFO - openejb.base = /Users/dblevins/examples/testing-security-meta\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/testing-security-meta/target/classes\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/testing-security-meta/target/test-classes\n INFO - Beginning load: /Users/dblevins/examples/testing-security-meta/target/classes\n INFO - Beginning load: /Users/dblevins/examples/testing-security-meta/target/test-classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/testing-security-meta\n INFO - Configuring Service(id=Default Stateful Container, type=Container, provider-id=Default Stateful Container)\n INFO - Auto-creating a container for bean Movies: Container(type=STATEFUL, id=Default Stateful Container)\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean ManagerBean: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.injection.secure.MovieTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring PersistenceUnit(name=movie-unit)\n INFO - Auto-creating a Resource with id 'movieDatabaseNonJta' of type 'DataSource for 'movie-unit'.\n INFO - Configuring Service(id=movieDatabaseNonJta, type=Resource, provider-id=movieDatabase)\n INFO - Adjusting PersistenceUnit movie-unit <non-jta-data-source> to Resource ID 'movieDatabaseNonJta' from 'movieDatabaseUnmanaged'\n INFO - Enterprise application \"/Users/dblevins/examples/testing-security-meta\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/testing-security-meta\n INFO - PersistenceUnit(name=movie-unit, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 419ms\n INFO - Jndi(name=\"java:global/testing-security-meta/Movies!org.superbiz.injection.secure.Movies\")\n INFO - Jndi(name=\"java:global/testing-security-meta/Movies\")\n INFO - Jndi(name=\"java:global/testing-security-meta/ManagerBean!org.superbiz.injection.secure.MovieTest$Caller\")\n INFO - Jndi(name=\"java:global/testing-security-meta/ManagerBean\")\n INFO - Jndi(name=\"java:global/testing-security-meta/EmployeeBean!org.superbiz.injection.secure.MovieTest$Caller\")\n INFO - Jndi(name=\"java:global/testing-security-meta/EmployeeBean\")\n INFO - Jndi(name=\"java:global/EjbModule53489605/org.superbiz.injection.secure.MovieTest!org.superbiz.injection.secure.MovieTest\")\n INFO - Jndi(name=\"java:global/EjbModule53489605/org.superbiz.injection.secure.MovieTest\")\n INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Created Ejb(deployment-id=ManagerBean, ejb-name=ManagerBean, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=EmployeeBean, ejb-name=EmployeeBean, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=org.superbiz.injection.secure.MovieTest, ejb-name=org.superbiz.injection.secure.MovieTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Started Ejb(deployment-id=ManagerBean, ejb-name=ManagerBean, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=EmployeeBean, ejb-name=EmployeeBean, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=org.superbiz.injection.secure.MovieTest, ejb-name=org.superbiz.injection.secure.MovieTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/testing-security-meta)\n INFO - EJBContainer already initialized. Call ejbContainer.close() to allow reinitialization\n INFO - EJBContainer already initialized. Call ejbContainer.close() to allow reinitialization\n Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.754 sec\n \n Results :\n \n Tests run: 3, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/testing-security-meta"
},
{
"name":"testing-security-3",
"readme":"Title: Testing Security 3\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## Movie\n\n package org.superbiz.injection.secure;\n \n import javax.persistence.Entity;\n \n @Entity\n public class Movie {\n \n private String director;\n private String title;\n private int year;\n \n public Movie() {\n }\n \n public Movie(String director, String title, int year) {\n this.director = director;\n this.title = title;\n this.year = year;\n }\n \n public String getDirector() {\n return director;\n }\n \n public void setDirector(String director) {\n this.director = director;\n }\n \n public String getTitle() {\n return title;\n }\n \n public void setTitle(String title) {\n this.title = title;\n }\n \n public int getYear() {\n return year;\n }\n \n public void setYear(int year) {\n this.year = year;\n }\n \n }\n\n## Movies\n\n package org.superbiz.injection.secure;\n \n //START SNIPPET: code\n \n import javax.annotation.security.PermitAll;\n import javax.annotation.security.RolesAllowed;\n import javax.ejb.Stateful;\n import javax.ejb.TransactionAttribute;\n import javax.ejb.TransactionAttributeType;\n import javax.persistence.EntityManager;\n import javax.persistence.PersistenceContext;\n import javax.persistence.PersistenceContextType;\n import javax.persistence.Query;\n import java.util.List;\n \n @Stateful\n public class Movies {\n \n @PersistenceContext(unitName = \"movie-unit\", type = PersistenceContextType.EXTENDED)\n private EntityManager entityManager;\n \n @RolesAllowed({\"Employee\", \"Manager\"})\n public void addMovie(Movie movie) throws Exception {\n entityManager.persist(movie);\n }\n \n @RolesAllowed({\"Manager\"})\n public void deleteMovie(Movie movie) throws Exception {\n entityManager.remove(movie);\n }\n \n @PermitAll\n @TransactionAttribute(TransactionAttributeType.SUPPORTS)\n public List<Movie> getMovies() throws Exception {\n Query query = entityManager.createQuery(\"SELECT m from Movie as m\");\n return query.getResultList();\n }\n }\n\n## MyLoginProvider\n\n package org.superbiz.injection.secure;\n\n import org.apache.openejb.core.security.jaas.LoginProvider;\n\n import javax.security.auth.login.FailedLoginException;\n import java.util.Arrays;\n import java.util.List;\n\n public class MyLoginProvider implements LoginProvider {\n\n\n @Override\n public List<String> authenticate(String user, String password) throws FailedLoginException {\n if (\"paul\".equals(user) && \"michelle\".equals(password)) {\n return Arrays.asList(\"Manager\", \"rockstar\", \"beatle\");\n }\n\n if (\"eddie\".equals(user) && \"jump\".equals(password)) {\n return Arrays.asList(\"Employee\", \"rockstar\", \"vanhalen\");\n }\n\n throw new FailedLoginException(\"Bad user or password!\");\n }\n }\n\n## org.apache.openejb.core.security.jaas.LoginProvider\n\n org.superbiz.injection.secure.MyLoginProvider\n\n## persistence.xml\n\n <persistence xmlns=\"http://java.sun.com/xml/ns/persistence\" version=\"1.0\">\n \n <persistence-unit name=\"movie-unit\">\n <jta-data-source>movieDatabase</jta-data-source>\n <non-jta-data-source>movieDatabaseUnmanaged</non-jta-data-source>\n <class>org.superbiz.injection.secure.Movie</class>\n \n <properties>\n <property name=\"openjpa.jdbc.SynchronizeMappings\" value=\"buildSchema(ForeignKeys=true)\"/>\n </properties>\n </persistence-unit>\n </persistence>\n\n## MovieTest\n\n package org.superbiz.injection.secure;\n\n import junit.framework.TestCase;\n\n import javax.ejb.EJB;\n import javax.ejb.EJBAccessException;\n import javax.ejb.embeddable.EJBContainer;\n import javax.naming.Context;\n import javax.naming.InitialContext;\n import javax.naming.NamingException;\n import java.util.List;\n import java.util.Properties;\n\n public class MovieTest extends TestCase {\n\n @EJB\n private Movies movies;\n\n private Context getContext(String user, String pass) throws NamingException {\n Properties p = new Properties();\n p.put(Context.INITIAL_CONTEXT_FACTORY, \"org.apache.openejb.core.LocalInitialContextFactory\");\n p.setProperty(\"openejb.authentication.realmName\", \"ServiceProviderLogin\");\n p.put(Context.SECURITY_PRINCIPAL, user);\n p.put(Context.SECURITY_CREDENTIALS, pass);\n\n return new InitialContext(p);\n }\n\n protected void setUp() throws Exception {\n Properties p = new Properties();\n p.put(\"movieDatabase\", \"new://Resource?type=DataSource\");\n p.put(\"movieDatabase.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"movieDatabase.JdbcUrl\", \"jdbc:hsqldb:mem:moviedb\");\n\n EJBContainer.createEJBContainer(p).getContext().bind(\"inject\", this);\n }\n\n public void testAsManager() throws Exception {\n final Context context = getContext(\"paul\", \"michelle\");\n\n try {\n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n movies.addMovie(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n movies.addMovie(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n\n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n\n for (Movie movie : list) {\n movies.deleteMovie(movie);\n }\n\n assertEquals(\"Movies.getMovies()\", 0, movies.getMovies().size());\n } finally {\n context.close();\n }\n }\n\n public void testAsEmployee() throws Exception {\n final Context context = getContext(\"eddie\", \"jump\");\n\n try {\n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n movies.addMovie(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n movies.addMovie(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n\n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n\n for (Movie movie : list) {\n try {\n movies.deleteMovie(movie);\n fail(\"Employees should not be allowed to delete\");\n } catch (EJBAccessException e) {\n // Good, Employees cannot delete things\n }\n }\n\n // The list should still be three movies long\n assertEquals(\"Movies.getMovies()\", 3, movies.getMovies().size());\n } finally {\n context.close();\n }\n }\n\n public void testUnauthenticated() throws Exception {\n try {\n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n fail(\"Unauthenticated users should not be able to add movies\");\n } catch (EJBAccessException e) {\n // Good, guests cannot add things\n }\n\n try {\n movies.deleteMovie(null);\n fail(\"Unauthenticated users should not be allowed to delete\");\n } catch (EJBAccessException e) {\n // Good, Unauthenticated users cannot delete things\n }\n\n try {\n // Read access should be allowed\n\n List<Movie> list = movies.getMovies();\n\n } catch (EJBAccessException e) {\n fail(\"Read access should be allowed\");\n }\n\n }\n\n public void testLoginFailure() throws NamingException {\n try {\n getContext(\"eddie\", \"panama\");\n fail(\"supposed to have a login failure here\");\n } catch (javax.naming.AuthenticationException e) {\n //expected\n }\n\n try {\n getContext(\"jimmy\", \"foxylady\");\n fail(\"supposed to have a login failure here\");\n } catch (javax.naming.AuthenticationException e) {\n //expected\n }\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.injection.secure.MovieTest\n INFO - ********************************************************************************\n INFO - OpenEJB http://tomee.apache.org/\n INFO - Startup: Fri Jul 20 08:42:53 EDT 2012\n INFO - Copyright 1999-2012 (C) Apache OpenEJB Project, All Rights Reserved.\n INFO - Version: 4.1.0\n INFO - Build date: 20120720\n INFO - Build time: 08:33\n INFO - ********************************************************************************\n INFO - openejb.home = /home/boto/dev/ws/openejb_trunk/openejb/examples/testing-security-3\n INFO - openejb.base = /home/boto/dev/ws/openejb_trunk/openejb/examples/testing-security-3\n INFO - Created new singletonService org.apache.openejb.cdi.ThreadSingletonServiceImpl@38ee6681\n INFO - Succeeded in installing singleton service\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Cannot find the configuration file [conf/openejb.xml]. Will attempt to create one for the beans deployed.\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Creating TransactionManager(id=Default Transaction Manager)\n INFO - Creating SecurityService(id=Default Security Service)\n INFO - Creating Resource(id=movieDatabase)\n INFO - Beginning load: /home/boto/dev/ws/openejb_trunk/openejb/examples/testing-security-3/target/classes\n INFO - Configuring enterprise application: /home/boto/dev/ws/openejb_trunk/openejb/examples/testing-security-3\n INFO - Auto-deploying ejb Movies: EjbDeployment(deployment-id=Movies)\n INFO - Configuring Service(id=Default Stateful Container, type=Container, provider-id=Default Stateful Container)\n INFO - Auto-creating a container for bean Movies: Container(type=STATEFUL, id=Default Stateful Container)\n INFO - Creating Container(id=Default Stateful Container)\n INFO - Using directory /tmp for stateful session passivation\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.injection.secure.MovieTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Creating Container(id=Default Managed Container)\n INFO - Using directory /tmp for stateful session passivation\n INFO - Configuring PersistenceUnit(name=movie-unit)\n INFO - Auto-creating a Resource with id 'movieDatabaseNonJta' of type 'DataSource for 'movie-unit'.\n INFO - Configuring Service(id=movieDatabaseNonJta, type=Resource, provider-id=movieDatabase)\n INFO - Creating Resource(id=movieDatabaseNonJta)\n INFO - Adjusting PersistenceUnit movie-unit <non-jta-data-source> to Resource ID 'movieDatabaseNonJta' from 'movieDatabaseUnmanaged'\n INFO - Enterprise application \"/home/boto/dev/ws/openejb_trunk/openejb/examples/testing-security-3\" loaded.\n INFO - Assembling app: /home/boto/dev/ws/openejb_trunk/openejb/examples/testing-security-3\n SEVERE - JAVA AGENT NOT INSTALLED. The JPA Persistence Provider requested installation of a ClassFileTransformer which requires a JavaAgent. See http://tomee.apache.org/3.0/javaagent.html\n INFO - PersistenceUnit(name=movie-unit, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 268ms\n INFO - Jndi(name=\"java:global/testing-security-3/Movies!org.superbiz.injection.secure.Movies\")\n INFO - Jndi(name=\"java:global/testing-security-3/Movies\")\n INFO - Existing thread singleton service in SystemInstance() org.apache.openejb.cdi.ThreadSingletonServiceImpl@38ee6681\n INFO - OpenWebBeans Container is starting...\n INFO - Adding OpenWebBeansPlugin : [CdiPlugin]\n INFO - All injection points are validated successfully.\n INFO - OpenWebBeans Container has started, it took 170 ms.\n INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Deployed Application(path=/home/boto/dev/ws/openejb_trunk/openejb/examples/testing-security-3)\n 20-Jul-2012 8:42:55 AM null openjpa.Runtime\n INFO: Starting OpenJPA 2.2.0\n 20-Jul-2012 8:42:56 AM null openjpa.jdbc.JDBC\n INFO: Using dictionary class \"org.apache.openjpa.jdbc.sql.HSQLDictionary\" (HSQL Database Engine 2.2.8 ,HSQL Database Engine Driver 2.2.8).\n 20-Jul-2012 8:42:57 AM null openjpa.Enhance\n INFO: Creating subclass and redefining methods for \"[class org.superbiz.injection.secure.Movie]\". This means that your application will be less efficient than it would if you ran the OpenJPA enhancer.\n INFO - Logging in\n INFO - Logging out\n INFO - EJBContainer already initialized. Call ejbContainer.close() to allow reinitialization\n INFO - Logging in\n INFO - Logging out\n INFO - EJBContainer already initialized. Call ejbContainer.close() to allow reinitialization\n Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 6.069 sec\n\n Results :\n\n Tests run: 3, Failures: 0, Errors: 0, Skipped: 0\n\n",
"url":"https://github.com/apache/tomee/tree/master/examples/testing-security-3"
},
{
"name":"testing-security-4",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/testing-security-4"
},
{
"name":"ear-testing",
"readme":"Title: EAR Testing\n\nThe goal of this example is to demonstrate how maven projects might be organized in a more real world style and how testing with OpenEJB can fit into that structure.\n\nThis example takes the basic moviefun code we us in many of examples and splits it into two modules:\n\n - `business-logic`\n - `business-model`\n\nAs the names imply, we keep our `@Entity` beans in the `business-model` module and our session beans in the `business-logic` model. The tests located and run from the business logic module.\n\n ear-testing\n ear-testing/business-logic\n ear-testing/business-logic/pom.xml\n ear-testing/business-logic/src/main/java/org/superbiz/logic/Movies.java\n ear-testing/business-logic/src/main/java/org/superbiz/logic/MoviesImpl.java\n ear-testing/business-logic/src/main/resources\n ear-testing/business-logic/src/main/resources/META-INF\n ear-testing/business-logic/src/main/resources/META-INF/ejb-jar.xml\n ear-testing/business-logic/src/test/java/org/superbiz/logic/MoviesTest.java\n ear-testing/business-model\n ear-testing/business-model/pom.xml\n ear-testing/business-model/src/main/java/org/superbiz/model/Movie.java\n ear-testing/business-model/src/main/resources/META-INF/persistence.xml\n ear-testing/pom.xml\n\n# Project configuration\n\nThe parent pom, trimmed to the minimum, looks like so:\n\n <project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n\n <modelVersion>4.0.0</modelVersion>\n <groupId>org.superbiz</groupId>\n <artifactId>myear</artifactId>\n <version>1.1.0-SNAPSHOT</version>\n\n <packaging>pom</packaging>\n\n <modules>\n <module>business-model</module>\n <module>business-logic</module>\n </modules>\n\n <dependencyManagement>\n <dependencies>\n <dependency>\n <groupId>org.apache.openejb</groupId>\n <artifactId>javaee-api</artifactId>\n <version>6.0-2</version>\n </dependency>\n <dependency>\n <groupId>junit</groupId>\n <artifactId>junit</artifactId>\n <version>4.8.1</version>\n </dependency>\n </dependencies>\n </dependencyManagement>\n </project>\n\nThe `business-model/pom.xml` as follows:\n\n <project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n <parent>\n <groupId>org.superbiz</groupId>\n <artifactId>myear</artifactId>\n <version>1.1.0-SNAPSHOT</version>\n </parent>\n\n <modelVersion>4.0.0</modelVersion>\n\n <artifactId>business-model</artifactId>\n <packaging>jar</packaging>\n\n <dependencies>\n <dependency>\n <groupId>org.apache.openejb</groupId>\n <artifactId>javaee-api</artifactId>\n <scope>provided</scope>\n </dependency>\n <dependency>\n <groupId>junit</groupId>\n <artifactId>junit</artifactId>\n <scope>test</scope>\n </dependency>\n\n </dependencies>\n\n </project>\n\nAnd finally, the `business-logic/pom.xml` which is setup to support embedded testing with OpenEJB:\n\n <project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n <parent>\n <groupId>org.superbiz</groupId>\n <artifactId>myear</artifactId>\n <version>1.1.0-SNAPSHOT</version>\n </parent>\n\n <modelVersion>4.0.0</modelVersion>\n\n <artifactId>business-logic</artifactId>\n <packaging>jar</packaging>\n\n <dependencies>\n <dependency>\n <groupId>org.superbiz</groupId>\n <artifactId>business-model</artifactId>\n <version>${project.version}</version>\n </dependency>\n <dependency>\n <groupId>org.apache.openejb</groupId>\n <artifactId>javaee-api</artifactId>\n <scope>provided</scope>\n </dependency>\n <dependency>\n <groupId>junit</groupId>\n <artifactId>junit</artifactId>\n <scope>test</scope>\n </dependency>\n <!--\n The <scope>test</scope> guarantees that non of your runtime\n code is dependent on any OpenEJB classes.\n -->\n <dependency>\n <groupId>org.apache.openejb</groupId>\n <artifactId>openejb-core</artifactId>\n <version>7.0.0-SNAPSHOT</version>\n <scope>test</scope>\n </dependency>\n </dependencies>\n </project>\n\n# TestCode\n\nThe test code is the same as always:\n\n public class MoviesTest extends TestCase {\n\n public void test() throws Exception {\n Properties p = new Properties();\n p.put(Context.INITIAL_CONTEXT_FACTORY, \"org.apache.openejb.core.LocalInitialContextFactory\");\n\n p.put(\"openejb.deployments.classpath.ear\", \"true\");\n\n p.put(\"movieDatabase\", \"new://Resource?type=DataSource\");\n p.put(\"movieDatabase.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"movieDatabase.JdbcUrl\", \"jdbc:hsqldb:mem:moviedb\");\n\n p.put(\"movieDatabaseUnmanaged\", \"new://Resource?type=DataSource\");\n p.put(\"movieDatabaseUnmanaged.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"movieDatabaseUnmanaged.JdbcUrl\", \"jdbc:hsqldb:mem:moviedb\");\n p.put(\"movieDatabaseUnmanaged.JtaManaged\", \"false\");\n\n Context context = new InitialContext(p);\n\n Movies movies = (Movies) context.lookup(\"MoviesLocal\");\n\n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n movies.addMovie(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n movies.addMovie(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n\n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n\n for (Movie movie : list) {\n movies.deleteMovie(movie);\n }\n\n assertEquals(\"Movies.getMovies()\", 0, movies.getMovies().size());\n }\n }\n\n\n# Running\n\n\n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.logic.MoviesTest\n Apache OpenEJB 7.0.0-SNAPSHOT build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/ear-testing/business-logic\n INFO - openejb.base = /Users/dblevins/examples/ear-testing/business-logic\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=movieDatabaseUnmanaged, type=Resource, provider-id=Default JDBC Database)\n INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Found PersistenceModule in classpath: /Users/dblevins/examples/ear-testing/business-model/target/business-model-1.0.jar\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/ear-testing/business-logic/target/classes\n INFO - Using 'openejb.deployments.classpath.ear=true'\n INFO - Beginning load: /Users/dblevins/examples/ear-testing/business-model/target/business-model-1.0.jar\n INFO - Beginning load: /Users/dblevins/examples/ear-testing/business-logic/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/ear-testing/business-logic/classpath.ear\n INFO - Configuring Service(id=Default Stateful Container, type=Container, provider-id=Default Stateful Container)\n INFO - Auto-creating a container for bean Movies: Container(type=STATEFUL, id=Default Stateful Container)\n INFO - Configuring PersistenceUnit(name=movie-unit)\n INFO - Enterprise application \"/Users/dblevins/examples/ear-testing/business-logic/classpath.ear\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/ear-testing/business-logic/classpath.ear\n INFO - PersistenceUnit(name=movie-unit, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 415ms\n INFO - Jndi(name=MoviesLocal) --> Ejb(deployment-id=Movies)\n INFO - Jndi(name=global/classpath.ear/business-logic/Movies!org.superbiz.logic.Movies) --> Ejb(deployment-id=Movies)\n INFO - Jndi(name=global/classpath.ear/business-logic/Movies) --> Ejb(deployment-id=Movies)\n INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/ear-testing/business-logic/classpath.ear)\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.393 sec\n\n Results :\n\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n",
"url":"https://github.com/apache/tomee/tree/master/examples/ear-testing"
},
{
"name":"testing-transactions",
"readme":"Title: Testing Transactions\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## Movie\n\n package org.superbiz.injection.tx;\n \n import javax.persistence.Entity;\n \n @Entity\n public class Movie {\n \n private String director;\n private String title;\n private int year;\n \n public Movie() {\n }\n \n public Movie(String director, String title, int year) {\n this.director = director;\n this.title = title;\n this.year = year;\n }\n \n public String getDirector() {\n return director;\n }\n \n public void setDirector(String director) {\n this.director = director;\n }\n \n public String getTitle() {\n return title;\n }\n \n public void setTitle(String title) {\n this.title = title;\n }\n \n public int getYear() {\n return year;\n }\n \n public void setYear(int year) {\n this.year = year;\n }\n \n }\n\n## Movies\n\n package org.superbiz.injection.tx;\n \n import javax.ejb.Stateful;\n import javax.ejb.TransactionAttribute;\n import javax.persistence.EntityManager;\n import javax.persistence.PersistenceContext;\n import javax.persistence.PersistenceContextType;\n import javax.persistence.Query;\n import java.util.List;\n \n import static javax.ejb.TransactionAttributeType.MANDATORY;\n \n //START SNIPPET: code\n @Stateful(name = \"Movies\")\n @TransactionAttribute(MANDATORY)\n public class Movies {\n \n @PersistenceContext(unitName = \"movie-unit\", type = PersistenceContextType.TRANSACTION)\n private EntityManager entityManager;\n \n public void addMovie(Movie movie) throws Exception {\n entityManager.persist(movie);\n }\n \n public void deleteMovie(Movie movie) throws Exception {\n entityManager.remove(movie);\n }\n \n public List<Movie> getMovies() throws Exception {\n Query query = entityManager.createQuery(\"SELECT m from Movie as m\");\n return query.getResultList();\n }\n }\n\n## persistence.xml\n\n <persistence xmlns=\"http://java.sun.com/xml/ns/persistence\" version=\"1.0\">\n \n <persistence-unit name=\"movie-unit\">\n <jta-data-source>movieDatabase</jta-data-source>\n <non-jta-data-source>movieDatabaseUnmanaged</non-jta-data-source>\n <class>org.superbiz.injection.tx.Movie</class>\n \n <properties>\n <property name=\"openjpa.jdbc.SynchronizeMappings\" value=\"buildSchema(ForeignKeys=true)\"/>\n </properties>\n </persistence-unit>\n </persistence>\n\n## MoviesTest\n\n package org.superbiz.injection.tx;\n \n import junit.framework.TestCase;\n \n import javax.ejb.EJB;\n import javax.ejb.Stateless;\n import javax.ejb.TransactionAttribute;\n import javax.ejb.embeddable.EJBContainer;\n import java.util.List;\n import java.util.Properties;\n import java.util.concurrent.Callable;\n \n import static javax.ejb.TransactionAttributeType.REQUIRES_NEW;\n \n /**\n * See the transaction-rollback example as it does the same thing\n * via UserTransaction and shows more techniques for rollback \n */\n //START SNIPPET: code\n public class MoviesTest extends TestCase {\n \n @EJB\n private Movies movies;\n \n @EJB\n private Caller transactionalCaller;\n \n protected void setUp() throws Exception {\n final Properties p = new Properties();\n p.put(\"movieDatabase\", \"new://Resource?type=DataSource\");\n p.put(\"movieDatabase.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"movieDatabase.JdbcUrl\", \"jdbc:hsqldb:mem:moviedb\");\n \n EJBContainer.createEJBContainer(p).getContext().bind(\"inject\", this);\n }\n \n private void doWork() throws Exception {\n \n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n movies.addMovie(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n movies.addMovie(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n \n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n \n for (Movie movie : list) {\n movies.deleteMovie(movie);\n }\n \n assertEquals(\"Movies.getMovies()\", 0, movies.getMovies().size());\n }\n \n public void testWithTransaction() throws Exception {\n transactionalCaller.call(new Callable() {\n public Object call() throws Exception {\n doWork();\n return null;\n }\n });\n }\n \n public void testWithoutTransaction() throws Exception {\n try {\n doWork();\n fail(\"The Movies bean should be using TransactionAttributeType.MANDATORY\");\n } catch (javax.ejb.EJBTransactionRequiredException e) {\n // good, our Movies bean is using TransactionAttributeType.MANDATORY as we want\n }\n }\n \n \n public static interface Caller {\n public <V> V call(Callable<V> callable) throws Exception;\n }\n \n /**\n * This little bit of magic allows our test code to execute in\n * the scope of a container controlled transaction.\n */\n @Stateless\n @TransactionAttribute(REQUIRES_NEW)\n public static class TransactionBean implements Caller {\n \n public <V> V call(Callable<V> callable) throws Exception {\n return callable.call();\n }\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.injection.tx.MoviesTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/testing-transactions\n INFO - openejb.base = /Users/dblevins/examples/testing-transactions\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/testing-transactions/target/classes\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/testing-transactions/target/test-classes\n INFO - Beginning load: /Users/dblevins/examples/testing-transactions/target/classes\n INFO - Beginning load: /Users/dblevins/examples/testing-transactions/target/test-classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/testing-transactions\n INFO - Configuring Service(id=Default Stateful Container, type=Container, provider-id=Default Stateful Container)\n INFO - Auto-creating a container for bean Movies: Container(type=STATEFUL, id=Default Stateful Container)\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean TransactionBean: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.injection.tx.MoviesTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring PersistenceUnit(name=movie-unit)\n INFO - Auto-creating a Resource with id 'movieDatabaseNonJta' of type 'DataSource for 'movie-unit'.\n INFO - Configuring Service(id=movieDatabaseNonJta, type=Resource, provider-id=movieDatabase)\n INFO - Adjusting PersistenceUnit movie-unit <non-jta-data-source> to Resource ID 'movieDatabaseNonJta' from 'movieDatabaseUnmanaged'\n INFO - Enterprise application \"/Users/dblevins/examples/testing-transactions\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/testing-transactions\n INFO - PersistenceUnit(name=movie-unit, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 406ms\n INFO - Jndi(name=\"java:global/testing-transactions/Movies!org.superbiz.injection.tx.Movies\")\n INFO - Jndi(name=\"java:global/testing-transactions/Movies\")\n INFO - Jndi(name=\"java:global/testing-transactions/TransactionBean!org.superbiz.injection.tx.MoviesTest$Caller\")\n INFO - Jndi(name=\"java:global/testing-transactions/TransactionBean\")\n INFO - Jndi(name=\"java:global/EjbModule2036741132/org.superbiz.injection.tx.MoviesTest!org.superbiz.injection.tx.MoviesTest\")\n INFO - Jndi(name=\"java:global/EjbModule2036741132/org.superbiz.injection.tx.MoviesTest\")\n INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Created Ejb(deployment-id=TransactionBean, ejb-name=TransactionBean, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=org.superbiz.injection.tx.MoviesTest, ejb-name=org.superbiz.injection.tx.MoviesTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Started Ejb(deployment-id=TransactionBean, ejb-name=TransactionBean, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=org.superbiz.injection.tx.MoviesTest, ejb-name=org.superbiz.injection.tx.MoviesTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/testing-transactions)\n INFO - EJBContainer already initialized. Call ejbContainer.close() to allow reinitialization\n Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.403 sec\n \n Results :\n \n Tests run: 2, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/testing-transactions"
},
{
"name":"testing-transactions-bmt",
"readme":"Title: Testing Transactions BMT\n\nShows how to begin, commit and rollback transactions using a UserTransaction via a Stateful Bean.\n\n## Movie\n\n package org.superbiz.injection.tx;\n\n import javax.persistence.Entity;\n import javax.persistence.GeneratedValue;\n import javax.persistence.Id;\n\n @Entity\n public class Movie {\n\n @Id\n @GeneratedValue\n private Long id;\n private String director;\n private String title;\n private int year;\n\n public Movie(String director, String title, int year) {\n this.director = director;\n this.title = title;\n this.year = year;\n }\n\n public Movie() {\n\n }\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getDirector() {\n return director;\n }\n\n public void setDirector(String director) {\n this.director = director;\n }\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public int getYear() {\n return year;\n }\n\n public void setYear(int year) {\n this.year = year;\n }\n }\n\n## Movies\n\n package org.superbiz.injection.tx;\n\n import javax.annotation.Resource;\n import javax.ejb.Stateful;\n import javax.ejb.TransactionManagement;\n import javax.ejb.TransactionManagementType;\n import javax.persistence.EntityManager;\n import javax.persistence.PersistenceContext;\n import javax.persistence.PersistenceContextType;\n import javax.persistence.Query;\n import javax.transaction.UserTransaction;\n\n @Stateful(name = \"Movies\")\n @TransactionManagement(TransactionManagementType.BEAN)\n public class Movies {\n\n @PersistenceContext(unitName = \"movie-unit\", type = PersistenceContextType.TRANSACTION)\n private EntityManager entityManager;\n\n @Resource\n private UserTransaction userTransaction;\n\n public void addMovie(Movie movie) throws Exception {\n try {\n userTransaction.begin();\n entityManager.persist(movie);\n\n //For some dummy reason, this db can have only 5 titles. :O)\n if (countMovies() > 5) {\n userTransaction.rollback();\n } else {\n userTransaction.commit();\n }\n\n\n } catch (Exception e) {\n e.printStackTrace();\n userTransaction.rollback();\n }\n }\n\n public Long countMovies() throws Exception {\n Query query = entityManager.createQuery(\"SELECT COUNT(m) FROM Movie m\");\n return Long.class.cast(query.getSingleResult());\n }\n }\n\n\n## persistence.xml\n\n <persistence xmlns=\"http://java.sun.com/xml/ns/persistence\" version=\"1.0\">\n\n <persistence-unit name=\"movie-unit\">\n <jta-data-source>movieDatabase</jta-data-source>\n <non-jta-data-source>movieDatabaseUnmanaged</non-jta-data-source>\n <class>org.superbiz.injection.tx.Movie</class>\n\n <properties>\n <property name=\"openjpa.jdbc.SynchronizeMappings\" value=\"buildSchema(ForeignKeys=true)\"/>\n </properties>\n </persistence-unit>\n </persistence>\n\n## MoviesTest\n\n package org.superbiz.injection.tx;\n\n import org.junit.Assert;\n import org.junit.Test;\n\n import javax.ejb.EJB;\n import javax.ejb.embeddable.EJBContainer;\n import java.util.Properties;\n\n public class MoviesTest {\n\n @EJB\n private Movies movies;\n\n @Test\n public void testMe() throws Exception {\n final Properties p = new Properties();\n p.put(\"movieDatabase\", \"new://Resource?type=DataSource\");\n p.put(\"movieDatabase.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"movieDatabase.JdbcUrl\", \"jdbc:hsqldb:mem:moviedb\");\n\n EJBContainer.createEJBContainer(p).getContext().bind(\"inject\", this);\n\n movies.addMovie(new Movie(\"Asif Kapadia\", \"Senna\", 2010));\n movies.addMovie(new Movie(\"José Padilha\", \"Tropa de Elite\", 2007));\n movies.addMovie(new Movie(\"Andy Wachowski/Lana Wachowski\", \"The Matrix\", 1999));\n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n movies.addMovie(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n movies.addMovie(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n\n Assert.assertEquals(5L, movies.countMovies().longValue());\n }\n\n }\n\n\n# Running\n\n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.injection.tx.MoviesTest\n INFO - ********************************************************************************\n INFO - OpenEJB http://tomee.apache.org/\n INFO - Startup: Sat Jul 21 16:39:28 EDT 2012\n INFO - Copyright 1999-2012 (C) Apache OpenEJB Project, All Rights Reserved.\n INFO - Version: 4.1.0\n INFO - Build date: 20120721\n INFO - Build time: 12:06\n INFO - ********************************************************************************\n INFO - openejb.home = /home/boto/dev/ws/openejb_trunk/openejb/examples/testing-transactions-bmt\n INFO - openejb.base = /home/boto/dev/ws/openejb_trunk/openejb/examples/testing-transactions-bmt\n INFO - Created new singletonService org.apache.openejb.cdi.ThreadSingletonServiceImpl@3f3f210f\n INFO - Succeeded in installing singleton service\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Cannot find the configuration file [conf/openejb.xml]. Will attempt to create one for the beans deployed.\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Creating TransactionManager(id=Default Transaction Manager)\n INFO - Creating SecurityService(id=Default Security Service)\n INFO - Creating Resource(id=movieDatabase)\n INFO - Beginning load: /home/boto/dev/ws/openejb_trunk/openejb/examples/testing-transactions-bmt/target/classes\n INFO - Configuring enterprise application: /home/boto/dev/ws/openejb_trunk/openejb/examples/testing-transactions-bmt\n WARNING - Method 'lookup' is not available for 'javax.annotation.Resource'. Probably using an older Runtime.\n INFO - Auto-deploying ejb Movies: EjbDeployment(deployment-id=Movies)\n INFO - Configuring Service(id=Default Stateful Container, type=Container, provider-id=Default Stateful Container)\n INFO - Auto-creating a container for bean Movies: Container(type=STATEFUL, id=Default Stateful Container)\n INFO - Creating Container(id=Default Stateful Container)\n INFO - Using directory /tmp for stateful session passivation\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.injection.tx.MoviesTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Creating Container(id=Default Managed Container)\n INFO - Using directory /tmp for stateful session passivation\n INFO - Configuring PersistenceUnit(name=movie-unit)\n INFO - Auto-creating a Resource with id 'movieDatabaseNonJta' of type 'DataSource for 'movie-unit'.\n INFO - Configuring Service(id=movieDatabaseNonJta, type=Resource, provider-id=movieDatabase)\n INFO - Creating Resource(id=movieDatabaseNonJta)\n INFO - Adjusting PersistenceUnit movie-unit <non-jta-data-source> to Resource ID 'movieDatabaseNonJta' from 'movieDatabaseUnmanaged'\n INFO - Enterprise application \"/home/boto/dev/ws/openejb_trunk/openejb/examples/testing-transactions-bmt\" loaded.\n INFO - Assembling app: /home/boto/dev/ws/openejb_trunk/openejb/examples/testing-transactions-bmt\n SEVERE - JAVA AGENT NOT INSTALLED. The JPA Persistence Provider requested installation of a ClassFileTransformer which requires a JavaAgent. See http://tomee.apache.org/3.0/javaagent.html\n INFO - PersistenceUnit(name=movie-unit, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 399ms\n INFO - Jndi(name=\"java:global/testing-transactions-bmt/Movies!org.superbiz.injection.tx.Movies\")\n INFO - Jndi(name=\"java:global/testing-transactions-bmt/Movies\")\n INFO - Existing thread singleton service in SystemInstance() org.apache.openejb.cdi.ThreadSingletonServiceImpl@3f3f210f\n INFO - OpenWebBeans Container is starting...\n INFO - Adding OpenWebBeansPlugin : [CdiPlugin]\n INFO - All injection points are validated successfully.\n INFO - OpenWebBeans Container has started, it took 157 ms.\n INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Deployed Application(path=/home/boto/dev/ws/openejb_trunk/openejb/examples/testing-transactions-bmt)\n INFO - Started user transaction org.apache.geronimo.transaction.manager.TransactionImpl@709a1411\n 21-Jul-2012 4:39:32 PM null openjpa.Runtime\n INFO: Starting OpenJPA 2.2.0\n 21-Jul-2012 4:39:32 PM null openjpa.jdbc.JDBC\n INFO: Using dictionary class \"org.apache.openjpa.jdbc.sql.HSQLDictionary\" (HSQL Database Engine 2.2.8 ,HSQL Database Engine Driver 2.2.8).\n 21-Jul-2012 4:39:33 PM null openjpa.Enhance\n INFO: Creating subclass and redefining methods for \"[class org.superbiz.injection.tx.Movie]\". This means that your application will be less efficient than it would if you ran the OpenJPA enhancer.\n INFO - Committing user transaction org.apache.geronimo.transaction.manager.TransactionImpl@709a1411\n INFO - Started user transaction org.apache.geronimo.transaction.manager.TransactionImpl@2bb64b70\n INFO - Committing user transaction org.apache.geronimo.transaction.manager.TransactionImpl@2bb64b70\n INFO - Started user transaction org.apache.geronimo.transaction.manager.TransactionImpl@627b5c\n INFO - Committing user transaction org.apache.geronimo.transaction.manager.TransactionImpl@627b5c\n INFO - Started user transaction org.apache.geronimo.transaction.manager.TransactionImpl@2f031310\n INFO - Committing user transaction org.apache.geronimo.transaction.manager.TransactionImpl@2f031310\n INFO - Started user transaction org.apache.geronimo.transaction.manager.TransactionImpl@4df2a9da\n INFO - Committing user transaction org.apache.geronimo.transaction.manager.TransactionImpl@4df2a9da\n INFO - Started user transaction org.apache.geronimo.transaction.manager.TransactionImpl@3fa9b4a4\n INFO - Rolling back user transaction org.apache.geronimo.transaction.manager.TransactionImpl@3fa9b4a4\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 7.471 sec\n\n Results :\n\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n",
"url":"https://github.com/apache/tomee/tree/master/examples/testing-transactions-bmt"
},
{
"name":"testing-security-2",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/testing-security-2"
},
{
"name":"multi-jpa-provider-testing",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/multi-jpa-provider-testing"
}
],
"timeout":[
{
"name":"access-timeout-meta",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/access-timeout-meta"
},
{
"name":"access-timeout",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/access-timeout"
}
],
"tomee":[
{
"name":"tomee-jersey-eclipselink",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/tomee-jersey-eclipselink"
},
{
"name":"realm-in-tomee",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/realm-in-tomee"
},
{
"name":"multiple-tomee-arquillian",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/multiple-tomee-arquillian"
}
],
"transaction":[
{
"name":"transaction-rollback",
"readme":"Title: Transaction Rollback\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## CustomRuntimeException\n\n package org.superbiz.txrollback;\n \n import javax.ejb.ApplicationException;\n \n @ApplicationException\n public class CustomRuntimeException extends RuntimeException {\n \n public CustomRuntimeException() {\n }\n \n public CustomRuntimeException(String s) {\n super(s);\n }\n \n public CustomRuntimeException(String s, Throwable throwable) {\n super(s, throwable);\n }\n \n public CustomRuntimeException(Throwable throwable) {\n super(throwable);\n }\n }\n\n## Movie\n\n package org.superbiz.txrollback;\n \n import javax.persistence.Entity;\n import javax.persistence.GeneratedValue;\n import javax.persistence.GenerationType;\n import javax.persistence.Id;\n \n @Entity(name = \"Movie\")\n public class Movie {\n \n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private long id;\n \n private String director;\n private String title;\n private int year;\n \n public Movie() {\n }\n \n public Movie(String director, String title, int year) {\n this.director = director;\n this.title = title;\n this.year = year;\n }\n \n public String getDirector() {\n return director;\n }\n \n public void setDirector(String director) {\n this.director = director;\n }\n \n public String getTitle() {\n return title;\n }\n \n public void setTitle(String title) {\n this.title = title;\n }\n \n public int getYear() {\n return year;\n }\n \n public void setYear(int year) {\n this.year = year;\n }\n \n }\n\n## Movies\n\n package org.superbiz.txrollback;\n \n import javax.annotation.Resource;\n import javax.ejb.SessionContext;\n import javax.ejb.Stateless;\n import javax.persistence.EntityManager;\n import javax.persistence.PersistenceContext;\n import javax.persistence.PersistenceContextType;\n import javax.persistence.Query;\n import java.util.List;\n \n //START SNIPPET: code\n @Stateless\n public class Movies {\n \n @PersistenceContext(unitName = \"movie-unit\", type = PersistenceContextType.TRANSACTION)\n private EntityManager entityManager;\n \n @Resource\n private SessionContext sessionContext;\n \n public void addMovie(Movie movie) throws Exception {\n entityManager.persist(movie);\n }\n \n public void deleteMovie(Movie movie) throws Exception {\n entityManager.remove(movie);\n }\n \n public List<Movie> getMovies() throws Exception {\n Query query = entityManager.createQuery(\"SELECT m from Movie as m\");\n return query.getResultList();\n }\n \n public void callSetRollbackOnly() {\n sessionContext.setRollbackOnly();\n }\n \n public void throwUncheckedException() {\n throw new RuntimeException(\"Throwing unchecked exceptions will rollback a transaction\");\n }\n \n public void throwApplicationException() {\n throw new CustomRuntimeException(\"This is marked @ApplicationException, so no TX rollback\");\n }\n }\n\n## persistence.xml\n\n <persistence xmlns=\"http://java.sun.com/xml/ns/persistence\" version=\"1.0\">\n \n <persistence-unit name=\"movie-unit\">\n <jta-data-source>movieDatabase</jta-data-source>\n <non-jta-data-source>movieDatabaseUnmanaged</non-jta-data-source>\n <class>org.superbiz.testinjection.MoviesTest.Movie</class>\n \n <properties>\n <property name=\"openjpa.jdbc.SynchronizeMappings\" value=\"buildSchema(ForeignKeys=true)\"/>\n </properties>\n </persistence-unit>\n </persistence>\n\n## MoviesTest\n\n package org.superbiz.txrollback;\n \n import junit.framework.TestCase;\n \n import javax.annotation.Resource;\n import javax.ejb.EJB;\n import javax.ejb.embeddable.EJBContainer;\n import javax.persistence.EntityManager;\n import javax.persistence.PersistenceContext;\n import javax.transaction.RollbackException;\n import javax.transaction.UserTransaction;\n import java.util.List;\n import java.util.Properties;\n \n //START SNIPPET: code\n public class MoviesTest extends TestCase {\n \n @EJB\n private Movies movies;\n \n @Resource\n private UserTransaction userTransaction;\n \n @PersistenceContext\n private EntityManager entityManager;\n \n private EJBContainer ejbContainer;\n \n public void setUp() throws Exception {\n Properties p = new Properties();\n p.put(\"movieDatabase\", \"new://Resource?type=DataSource\");\n p.put(\"movieDatabase.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"movieDatabase.JdbcUrl\", \"jdbc:hsqldb:mem:moviedb\" + System.currentTimeMillis());\n \n ejbContainer = EJBContainer.createEJBContainer(p);\n ejbContainer.getContext().bind(\"inject\", this);\n }\n \n @Override\n protected void tearDown() throws Exception {\n ejbContainer.close();\n }\n \n /**\n * Standard successful transaction scenario. The data created inside\n * the transaction is visible after the transaction completes.\n * <p/>\n * Note that UserTransaction is only usable by Bean-Managed Transaction\n * beans, which can be specified with @TransactionManagement(BEAN)\n */\n public void testCommit() throws Exception {\n \n userTransaction.begin();\n \n try {\n entityManager.persist(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n entityManager.persist(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n entityManager.persist(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n \n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n } finally {\n userTransaction.commit();\n }\n \n // Transaction was committed\n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n }\n \n /**\n * Standard transaction rollback scenario. The data created inside\n * the transaction is not visible after the transaction completes.\n */\n public void testUserTransactionRollback() throws Exception {\n \n userTransaction.begin();\n \n try {\n entityManager.persist(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n entityManager.persist(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n entityManager.persist(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n \n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n } finally {\n userTransaction.rollback();\n }\n \n // Transaction was rolled back\n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 0, list.size());\n }\n \n /**\n * Transaction is marked for rollback inside the bean via\n * calling the javax.ejb.SessionContext.setRollbackOnly() method\n * <p/>\n * This is the cleanest way to make a transaction rollback.\n */\n public void testMarkedRollback() throws Exception {\n \n userTransaction.begin();\n \n try {\n entityManager.persist(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n entityManager.persist(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n entityManager.persist(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n \n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n \n movies.callSetRollbackOnly();\n } finally {\n try {\n userTransaction.commit();\n fail(\"A RollbackException should have been thrown\");\n } catch (RollbackException e) {\n // Pass\n }\n }\n \n // Transaction was rolled back\n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 0, list.size());\n }\n \n /**\n * Throwing an unchecked exception from a bean will cause\n * the container to call setRollbackOnly() and discard the\n * bean instance from further use without calling any @PreDestroy\n * methods on the bean instance.\n */\n public void testExceptionBasedRollback() throws Exception {\n \n userTransaction.begin();\n \n try {\n entityManager.persist(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n entityManager.persist(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n entityManager.persist(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n \n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n \n try {\n movies.throwUncheckedException();\n } catch (RuntimeException e) {\n // Good, this will cause the tx to rollback\n }\n } finally {\n try {\n userTransaction.commit();\n fail(\"A RollbackException should have been thrown\");\n } catch (RollbackException e) {\n // Pass\n }\n }\n \n // Transaction was rolled back\n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 0, list.size());\n }\n \n /**\n * It is still possible to throw unchecked (runtime) exceptions\n * without dooming the transaction by marking the exception\n * with the @ApplicationException annotation or in the ejb-jar.xml\n * deployment descriptor via the <application-exception> tag\n */\n public void testCommit2() throws Exception {\n \n userTransaction.begin();\n \n try {\n entityManager.persist(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n entityManager.persist(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n entityManager.persist(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n \n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n \n try {\n movies.throwApplicationException();\n } catch (RuntimeException e) {\n // This will *not* cause the tx to rollback\n // because it is marked as an @ApplicationException\n }\n } finally {\n userTransaction.commit();\n }\n \n // Transaction was committed\n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.txrollback.MoviesTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/transaction-rollback\n INFO - openejb.base = /Users/dblevins/examples/transaction-rollback\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/transaction-rollback/target/classes\n INFO - Beginning load: /Users/dblevins/examples/transaction-rollback/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/transaction-rollback\n WARN - Method 'lookup' is not available for 'javax.annotation.Resource'. Probably using an older Runtime.\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean Movies: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.txrollback.MoviesTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring PersistenceUnit(name=movie-unit)\n INFO - Auto-creating a Resource with id 'movieDatabaseNonJta' of type 'DataSource for 'movie-unit'.\n INFO - Configuring Service(id=movieDatabaseNonJta, type=Resource, provider-id=movieDatabase)\n INFO - Adjusting PersistenceUnit movie-unit <non-jta-data-source> to Resource ID 'movieDatabaseNonJta' from 'movieDatabaseUnmanaged'\n INFO - Enterprise application \"/Users/dblevins/examples/transaction-rollback\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/transaction-rollback\n INFO - PersistenceUnit(name=movie-unit, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 412ms\n INFO - Jndi(name=\"java:global/transaction-rollback/Movies!org.superbiz.txrollback.Movies\")\n INFO - Jndi(name=\"java:global/transaction-rollback/Movies\")\n INFO - Jndi(name=\"java:global/EjbModule1718375554/org.superbiz.txrollback.MoviesTest!org.superbiz.txrollback.MoviesTest\")\n INFO - Jndi(name=\"java:global/EjbModule1718375554/org.superbiz.txrollback.MoviesTest\")\n INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=org.superbiz.txrollback.MoviesTest, ejb-name=org.superbiz.txrollback.MoviesTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=org.superbiz.txrollback.MoviesTest, ejb-name=org.superbiz.txrollback.MoviesTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/transaction-rollback)\n WARN - The class \"org.superbiz.testinjection.MoviesTest.Movie\" listed in the openjpa.MetaDataFactory configuration property could not be loaded by sun.misc.Launcher$AppClassLoader@39172e08; ignoring.\n WARN - The class \"org.superbiz.testinjection.MoviesTest.Movie\" listed in the openjpa.MetaDataFactory configuration property could not be loaded by sun.misc.Launcher$AppClassLoader@39172e08; ignoring.\n WARN - The class \"org.superbiz.testinjection.MoviesTest.Movie\" listed in the openjpa.MetaDataFactory configuration property could not be loaded by sun.misc.Launcher$AppClassLoader@39172e08; ignoring.\n INFO - Undeploying app: /Users/dblevins/examples/transaction-rollback\n INFO - Closing DataSource: movieDatabase\n INFO - Closing DataSource: movieDatabaseNonJta\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/transaction-rollback\n INFO - openejb.base = /Users/dblevins/examples/transaction-rollback\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/transaction-rollback/target/classes\n INFO - Beginning load: /Users/dblevins/examples/transaction-rollback/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/transaction-rollback\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean Movies: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.txrollback.MoviesTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring PersistenceUnit(name=movie-unit)\n INFO - Auto-creating a Resource with id 'movieDatabaseNonJta' of type 'DataSource for 'movie-unit'.\n INFO - Configuring Service(id=movieDatabaseNonJta, type=Resource, provider-id=movieDatabase)\n INFO - Adjusting PersistenceUnit movie-unit <non-jta-data-source> to Resource ID 'movieDatabaseNonJta' from 'movieDatabaseUnmanaged'\n INFO - Enterprise application \"/Users/dblevins/examples/transaction-rollback\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/transaction-rollback\n INFO - PersistenceUnit(name=movie-unit, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 5ms\n INFO - Jndi(name=\"java:global/transaction-rollback/Movies!org.superbiz.txrollback.Movies\")\n INFO - Jndi(name=\"java:global/transaction-rollback/Movies\")\n INFO - Jndi(name=\"java:global/EjbModule935567559/org.superbiz.txrollback.MoviesTest!org.superbiz.txrollback.MoviesTest\")\n INFO - Jndi(name=\"java:global/EjbModule935567559/org.superbiz.txrollback.MoviesTest\")\n INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=org.superbiz.txrollback.MoviesTest, ejb-name=org.superbiz.txrollback.MoviesTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=org.superbiz.txrollback.MoviesTest, ejb-name=org.superbiz.txrollback.MoviesTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/transaction-rollback)\n WARN - The class \"org.superbiz.testinjection.MoviesTest.Movie\" listed in the openjpa.MetaDataFactory configuration property could not be loaded by sun.misc.Launcher$AppClassLoader@39172e08; ignoring.\n WARN - The class \"org.superbiz.testinjection.MoviesTest.Movie\" listed in the openjpa.MetaDataFactory configuration property could not be loaded by sun.misc.Launcher$AppClassLoader@39172e08; ignoring.\n WARN - The class \"org.superbiz.testinjection.MoviesTest.Movie\" listed in the openjpa.MetaDataFactory configuration property could not be loaded by sun.misc.Launcher$AppClassLoader@39172e08; ignoring.\n INFO - Undeploying app: /Users/dblevins/examples/transaction-rollback\n INFO - Closing DataSource: movieDatabase\n INFO - Closing DataSource: movieDatabaseNonJta\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/transaction-rollback\n INFO - openejb.base = /Users/dblevins/examples/transaction-rollback\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/transaction-rollback/target/classes\n INFO - Beginning load: /Users/dblevins/examples/transaction-rollback/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/transaction-rollback\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean Movies: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.txrollback.MoviesTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring PersistenceUnit(name=movie-unit)\n INFO - Auto-creating a Resource with id 'movieDatabaseNonJta' of type 'DataSource for 'movie-unit'.\n INFO - Configuring Service(id=movieDatabaseNonJta, type=Resource, provider-id=movieDatabase)\n INFO - Adjusting PersistenceUnit movie-unit <non-jta-data-source> to Resource ID 'movieDatabaseNonJta' from 'movieDatabaseUnmanaged'\n INFO - Enterprise application \"/Users/dblevins/examples/transaction-rollback\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/transaction-rollback\n INFO - PersistenceUnit(name=movie-unit, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 5ms\n INFO - Jndi(name=\"java:global/transaction-rollback/Movies!org.superbiz.txrollback.Movies\")\n INFO - Jndi(name=\"java:global/transaction-rollback/Movies\")\n INFO - Jndi(name=\"java:global/EjbModule1961109485/org.superbiz.txrollback.MoviesTest!org.superbiz.txrollback.MoviesTest\")\n INFO - Jndi(name=\"java:global/EjbModule1961109485/org.superbiz.txrollback.MoviesTest\")\n INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=org.superbiz.txrollback.MoviesTest, ejb-name=org.superbiz.txrollback.MoviesTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=org.superbiz.txrollback.MoviesTest, ejb-name=org.superbiz.txrollback.MoviesTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/transaction-rollback)\n WARN - The class \"org.superbiz.testinjection.MoviesTest.Movie\" listed in the openjpa.MetaDataFactory configuration property could not be loaded by sun.misc.Launcher$AppClassLoader@39172e08; ignoring.\n WARN - The class \"org.superbiz.testinjection.MoviesTest.Movie\" listed in the openjpa.MetaDataFactory configuration property could not be loaded by sun.misc.Launcher$AppClassLoader@39172e08; ignoring.\n WARN - The class \"org.superbiz.testinjection.MoviesTest.Movie\" listed in the openjpa.MetaDataFactory configuration property could not be loaded by sun.misc.Launcher$AppClassLoader@39172e08; ignoring.\n INFO - Undeploying app: /Users/dblevins/examples/transaction-rollback\n INFO - Closing DataSource: movieDatabase\n INFO - Closing DataSource: movieDatabaseNonJta\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/transaction-rollback\n INFO - openejb.base = /Users/dblevins/examples/transaction-rollback\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/transaction-rollback/target/classes\n INFO - Beginning load: /Users/dblevins/examples/transaction-rollback/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/transaction-rollback\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean Movies: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.txrollback.MoviesTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring PersistenceUnit(name=movie-unit)\n INFO - Auto-creating a Resource with id 'movieDatabaseNonJta' of type 'DataSource for 'movie-unit'.\n INFO - Configuring Service(id=movieDatabaseNonJta, type=Resource, provider-id=movieDatabase)\n INFO - Adjusting PersistenceUnit movie-unit <non-jta-data-source> to Resource ID 'movieDatabaseNonJta' from 'movieDatabaseUnmanaged'\n INFO - Enterprise application \"/Users/dblevins/examples/transaction-rollback\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/transaction-rollback\n INFO - PersistenceUnit(name=movie-unit, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 5ms\n INFO - Jndi(name=\"java:global/transaction-rollback/Movies!org.superbiz.txrollback.Movies\")\n INFO - Jndi(name=\"java:global/transaction-rollback/Movies\")\n INFO - Jndi(name=\"java:global/EjbModule419651577/org.superbiz.txrollback.MoviesTest!org.superbiz.txrollback.MoviesTest\")\n INFO - Jndi(name=\"java:global/EjbModule419651577/org.superbiz.txrollback.MoviesTest\")\n INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=org.superbiz.txrollback.MoviesTest, ejb-name=org.superbiz.txrollback.MoviesTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=org.superbiz.txrollback.MoviesTest, ejb-name=org.superbiz.txrollback.MoviesTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/transaction-rollback)\n WARN - The class \"org.superbiz.testinjection.MoviesTest.Movie\" listed in the openjpa.MetaDataFactory configuration property could not be loaded by sun.misc.Launcher$AppClassLoader@39172e08; ignoring.\n WARN - The class \"org.superbiz.testinjection.MoviesTest.Movie\" listed in the openjpa.MetaDataFactory configuration property could not be loaded by sun.misc.Launcher$AppClassLoader@39172e08; ignoring.\n WARN - The class \"org.superbiz.testinjection.MoviesTest.Movie\" listed in the openjpa.MetaDataFactory configuration property could not be loaded by sun.misc.Launcher$AppClassLoader@39172e08; ignoring.\n INFO - Undeploying app: /Users/dblevins/examples/transaction-rollback\n INFO - Closing DataSource: movieDatabase\n INFO - Closing DataSource: movieDatabaseNonJta\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/transaction-rollback\n INFO - openejb.base = /Users/dblevins/examples/transaction-rollback\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/transaction-rollback/target/classes\n INFO - Beginning load: /Users/dblevins/examples/transaction-rollback/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/transaction-rollback\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean Movies: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.txrollback.MoviesTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring PersistenceUnit(name=movie-unit)\n INFO - Auto-creating a Resource with id 'movieDatabaseNonJta' of type 'DataSource for 'movie-unit'.\n INFO - Configuring Service(id=movieDatabaseNonJta, type=Resource, provider-id=movieDatabase)\n INFO - Adjusting PersistenceUnit movie-unit <non-jta-data-source> to Resource ID 'movieDatabaseNonJta' from 'movieDatabaseUnmanaged'\n INFO - Enterprise application \"/Users/dblevins/examples/transaction-rollback\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/transaction-rollback\n INFO - PersistenceUnit(name=movie-unit, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 4ms\n INFO - Jndi(name=\"java:global/transaction-rollback/Movies!org.superbiz.txrollback.Movies\")\n INFO - Jndi(name=\"java:global/transaction-rollback/Movies\")\n INFO - Jndi(name=\"java:global/EjbModule15169271/org.superbiz.txrollback.MoviesTest!org.superbiz.txrollback.MoviesTest\")\n INFO - Jndi(name=\"java:global/EjbModule15169271/org.superbiz.txrollback.MoviesTest\")\n INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=org.superbiz.txrollback.MoviesTest, ejb-name=org.superbiz.txrollback.MoviesTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=org.superbiz.txrollback.MoviesTest, ejb-name=org.superbiz.txrollback.MoviesTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/transaction-rollback)\n WARN - The class \"org.superbiz.testinjection.MoviesTest.Movie\" listed in the openjpa.MetaDataFactory configuration property could not be loaded by sun.misc.Launcher$AppClassLoader@39172e08; ignoring.\n WARN - The class \"org.superbiz.testinjection.MoviesTest.Movie\" listed in the openjpa.MetaDataFactory configuration property could not be loaded by sun.misc.Launcher$AppClassLoader@39172e08; ignoring.\n WARN - The class \"org.superbiz.testinjection.MoviesTest.Movie\" listed in the openjpa.MetaDataFactory configuration property could not be loaded by sun.misc.Launcher$AppClassLoader@39172e08; ignoring.\n INFO - Undeploying app: /Users/dblevins/examples/transaction-rollback\n INFO - Closing DataSource: movieDatabase\n INFO - Closing DataSource: movieDatabaseNonJta\n Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.586 sec\n \n Results :\n \n Tests run: 5, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/transaction-rollback"
}
],
"transactions":[
{
"name":"testing-transactions",
"readme":"Title: Testing Transactions\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## Movie\n\n package org.superbiz.injection.tx;\n \n import javax.persistence.Entity;\n \n @Entity\n public class Movie {\n \n private String director;\n private String title;\n private int year;\n \n public Movie() {\n }\n \n public Movie(String director, String title, int year) {\n this.director = director;\n this.title = title;\n this.year = year;\n }\n \n public String getDirector() {\n return director;\n }\n \n public void setDirector(String director) {\n this.director = director;\n }\n \n public String getTitle() {\n return title;\n }\n \n public void setTitle(String title) {\n this.title = title;\n }\n \n public int getYear() {\n return year;\n }\n \n public void setYear(int year) {\n this.year = year;\n }\n \n }\n\n## Movies\n\n package org.superbiz.injection.tx;\n \n import javax.ejb.Stateful;\n import javax.ejb.TransactionAttribute;\n import javax.persistence.EntityManager;\n import javax.persistence.PersistenceContext;\n import javax.persistence.PersistenceContextType;\n import javax.persistence.Query;\n import java.util.List;\n \n import static javax.ejb.TransactionAttributeType.MANDATORY;\n \n //START SNIPPET: code\n @Stateful(name = \"Movies\")\n @TransactionAttribute(MANDATORY)\n public class Movies {\n \n @PersistenceContext(unitName = \"movie-unit\", type = PersistenceContextType.TRANSACTION)\n private EntityManager entityManager;\n \n public void addMovie(Movie movie) throws Exception {\n entityManager.persist(movie);\n }\n \n public void deleteMovie(Movie movie) throws Exception {\n entityManager.remove(movie);\n }\n \n public List<Movie> getMovies() throws Exception {\n Query query = entityManager.createQuery(\"SELECT m from Movie as m\");\n return query.getResultList();\n }\n }\n\n## persistence.xml\n\n <persistence xmlns=\"http://java.sun.com/xml/ns/persistence\" version=\"1.0\">\n \n <persistence-unit name=\"movie-unit\">\n <jta-data-source>movieDatabase</jta-data-source>\n <non-jta-data-source>movieDatabaseUnmanaged</non-jta-data-source>\n <class>org.superbiz.injection.tx.Movie</class>\n \n <properties>\n <property name=\"openjpa.jdbc.SynchronizeMappings\" value=\"buildSchema(ForeignKeys=true)\"/>\n </properties>\n </persistence-unit>\n </persistence>\n\n## MoviesTest\n\n package org.superbiz.injection.tx;\n \n import junit.framework.TestCase;\n \n import javax.ejb.EJB;\n import javax.ejb.Stateless;\n import javax.ejb.TransactionAttribute;\n import javax.ejb.embeddable.EJBContainer;\n import java.util.List;\n import java.util.Properties;\n import java.util.concurrent.Callable;\n \n import static javax.ejb.TransactionAttributeType.REQUIRES_NEW;\n \n /**\n * See the transaction-rollback example as it does the same thing\n * via UserTransaction and shows more techniques for rollback \n */\n //START SNIPPET: code\n public class MoviesTest extends TestCase {\n \n @EJB\n private Movies movies;\n \n @EJB\n private Caller transactionalCaller;\n \n protected void setUp() throws Exception {\n final Properties p = new Properties();\n p.put(\"movieDatabase\", \"new://Resource?type=DataSource\");\n p.put(\"movieDatabase.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"movieDatabase.JdbcUrl\", \"jdbc:hsqldb:mem:moviedb\");\n \n EJBContainer.createEJBContainer(p).getContext().bind(\"inject\", this);\n }\n \n private void doWork() throws Exception {\n \n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n movies.addMovie(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n movies.addMovie(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n \n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n \n for (Movie movie : list) {\n movies.deleteMovie(movie);\n }\n \n assertEquals(\"Movies.getMovies()\", 0, movies.getMovies().size());\n }\n \n public void testWithTransaction() throws Exception {\n transactionalCaller.call(new Callable() {\n public Object call() throws Exception {\n doWork();\n return null;\n }\n });\n }\n \n public void testWithoutTransaction() throws Exception {\n try {\n doWork();\n fail(\"The Movies bean should be using TransactionAttributeType.MANDATORY\");\n } catch (javax.ejb.EJBTransactionRequiredException e) {\n // good, our Movies bean is using TransactionAttributeType.MANDATORY as we want\n }\n }\n \n \n public static interface Caller {\n public <V> V call(Callable<V> callable) throws Exception;\n }\n \n /**\n * This little bit of magic allows our test code to execute in\n * the scope of a container controlled transaction.\n */\n @Stateless\n @TransactionAttribute(REQUIRES_NEW)\n public static class TransactionBean implements Caller {\n \n public <V> V call(Callable<V> callable) throws Exception {\n return callable.call();\n }\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.injection.tx.MoviesTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/testing-transactions\n INFO - openejb.base = /Users/dblevins/examples/testing-transactions\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/testing-transactions/target/classes\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/testing-transactions/target/test-classes\n INFO - Beginning load: /Users/dblevins/examples/testing-transactions/target/classes\n INFO - Beginning load: /Users/dblevins/examples/testing-transactions/target/test-classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/testing-transactions\n INFO - Configuring Service(id=Default Stateful Container, type=Container, provider-id=Default Stateful Container)\n INFO - Auto-creating a container for bean Movies: Container(type=STATEFUL, id=Default Stateful Container)\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean TransactionBean: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.injection.tx.MoviesTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Configuring PersistenceUnit(name=movie-unit)\n INFO - Auto-creating a Resource with id 'movieDatabaseNonJta' of type 'DataSource for 'movie-unit'.\n INFO - Configuring Service(id=movieDatabaseNonJta, type=Resource, provider-id=movieDatabase)\n INFO - Adjusting PersistenceUnit movie-unit <non-jta-data-source> to Resource ID 'movieDatabaseNonJta' from 'movieDatabaseUnmanaged'\n INFO - Enterprise application \"/Users/dblevins/examples/testing-transactions\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/testing-transactions\n INFO - PersistenceUnit(name=movie-unit, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 406ms\n INFO - Jndi(name=\"java:global/testing-transactions/Movies!org.superbiz.injection.tx.Movies\")\n INFO - Jndi(name=\"java:global/testing-transactions/Movies\")\n INFO - Jndi(name=\"java:global/testing-transactions/TransactionBean!org.superbiz.injection.tx.MoviesTest$Caller\")\n INFO - Jndi(name=\"java:global/testing-transactions/TransactionBean\")\n INFO - Jndi(name=\"java:global/EjbModule2036741132/org.superbiz.injection.tx.MoviesTest!org.superbiz.injection.tx.MoviesTest\")\n INFO - Jndi(name=\"java:global/EjbModule2036741132/org.superbiz.injection.tx.MoviesTest\")\n INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Created Ejb(deployment-id=TransactionBean, ejb-name=TransactionBean, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=org.superbiz.injection.tx.MoviesTest, ejb-name=org.superbiz.injection.tx.MoviesTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Started Ejb(deployment-id=TransactionBean, ejb-name=TransactionBean, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=org.superbiz.injection.tx.MoviesTest, ejb-name=org.superbiz.injection.tx.MoviesTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/testing-transactions)\n INFO - EJBContainer already initialized. Call ejbContainer.close() to allow reinitialization\n Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.403 sec\n \n Results :\n \n Tests run: 2, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/testing-transactions"
},
{
"name":"testing-transactions-bmt",
"readme":"Title: Testing Transactions BMT\n\nShows how to begin, commit and rollback transactions using a UserTransaction via a Stateful Bean.\n\n## Movie\n\n package org.superbiz.injection.tx;\n\n import javax.persistence.Entity;\n import javax.persistence.GeneratedValue;\n import javax.persistence.Id;\n\n @Entity\n public class Movie {\n\n @Id\n @GeneratedValue\n private Long id;\n private String director;\n private String title;\n private int year;\n\n public Movie(String director, String title, int year) {\n this.director = director;\n this.title = title;\n this.year = year;\n }\n\n public Movie() {\n\n }\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getDirector() {\n return director;\n }\n\n public void setDirector(String director) {\n this.director = director;\n }\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public int getYear() {\n return year;\n }\n\n public void setYear(int year) {\n this.year = year;\n }\n }\n\n## Movies\n\n package org.superbiz.injection.tx;\n\n import javax.annotation.Resource;\n import javax.ejb.Stateful;\n import javax.ejb.TransactionManagement;\n import javax.ejb.TransactionManagementType;\n import javax.persistence.EntityManager;\n import javax.persistence.PersistenceContext;\n import javax.persistence.PersistenceContextType;\n import javax.persistence.Query;\n import javax.transaction.UserTransaction;\n\n @Stateful(name = \"Movies\")\n @TransactionManagement(TransactionManagementType.BEAN)\n public class Movies {\n\n @PersistenceContext(unitName = \"movie-unit\", type = PersistenceContextType.TRANSACTION)\n private EntityManager entityManager;\n\n @Resource\n private UserTransaction userTransaction;\n\n public void addMovie(Movie movie) throws Exception {\n try {\n userTransaction.begin();\n entityManager.persist(movie);\n\n //For some dummy reason, this db can have only 5 titles. :O)\n if (countMovies() > 5) {\n userTransaction.rollback();\n } else {\n userTransaction.commit();\n }\n\n\n } catch (Exception e) {\n e.printStackTrace();\n userTransaction.rollback();\n }\n }\n\n public Long countMovies() throws Exception {\n Query query = entityManager.createQuery(\"SELECT COUNT(m) FROM Movie m\");\n return Long.class.cast(query.getSingleResult());\n }\n }\n\n\n## persistence.xml\n\n <persistence xmlns=\"http://java.sun.com/xml/ns/persistence\" version=\"1.0\">\n\n <persistence-unit name=\"movie-unit\">\n <jta-data-source>movieDatabase</jta-data-source>\n <non-jta-data-source>movieDatabaseUnmanaged</non-jta-data-source>\n <class>org.superbiz.injection.tx.Movie</class>\n\n <properties>\n <property name=\"openjpa.jdbc.SynchronizeMappings\" value=\"buildSchema(ForeignKeys=true)\"/>\n </properties>\n </persistence-unit>\n </persistence>\n\n## MoviesTest\n\n package org.superbiz.injection.tx;\n\n import org.junit.Assert;\n import org.junit.Test;\n\n import javax.ejb.EJB;\n import javax.ejb.embeddable.EJBContainer;\n import java.util.Properties;\n\n public class MoviesTest {\n\n @EJB\n private Movies movies;\n\n @Test\n public void testMe() throws Exception {\n final Properties p = new Properties();\n p.put(\"movieDatabase\", \"new://Resource?type=DataSource\");\n p.put(\"movieDatabase.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"movieDatabase.JdbcUrl\", \"jdbc:hsqldb:mem:moviedb\");\n\n EJBContainer.createEJBContainer(p).getContext().bind(\"inject\", this);\n\n movies.addMovie(new Movie(\"Asif Kapadia\", \"Senna\", 2010));\n movies.addMovie(new Movie(\"José Padilha\", \"Tropa de Elite\", 2007));\n movies.addMovie(new Movie(\"Andy Wachowski/Lana Wachowski\", \"The Matrix\", 1999));\n movies.addMovie(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n movies.addMovie(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n movies.addMovie(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n\n Assert.assertEquals(5L, movies.countMovies().longValue());\n }\n\n }\n\n\n# Running\n\n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.injection.tx.MoviesTest\n INFO - ********************************************************************************\n INFO - OpenEJB http://tomee.apache.org/\n INFO - Startup: Sat Jul 21 16:39:28 EDT 2012\n INFO - Copyright 1999-2012 (C) Apache OpenEJB Project, All Rights Reserved.\n INFO - Version: 4.1.0\n INFO - Build date: 20120721\n INFO - Build time: 12:06\n INFO - ********************************************************************************\n INFO - openejb.home = /home/boto/dev/ws/openejb_trunk/openejb/examples/testing-transactions-bmt\n INFO - openejb.base = /home/boto/dev/ws/openejb_trunk/openejb/examples/testing-transactions-bmt\n INFO - Created new singletonService org.apache.openejb.cdi.ThreadSingletonServiceImpl@3f3f210f\n INFO - Succeeded in installing singleton service\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Cannot find the configuration file [conf/openejb.xml]. Will attempt to create one for the beans deployed.\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Creating TransactionManager(id=Default Transaction Manager)\n INFO - Creating SecurityService(id=Default Security Service)\n INFO - Creating Resource(id=movieDatabase)\n INFO - Beginning load: /home/boto/dev/ws/openejb_trunk/openejb/examples/testing-transactions-bmt/target/classes\n INFO - Configuring enterprise application: /home/boto/dev/ws/openejb_trunk/openejb/examples/testing-transactions-bmt\n WARNING - Method 'lookup' is not available for 'javax.annotation.Resource'. Probably using an older Runtime.\n INFO - Auto-deploying ejb Movies: EjbDeployment(deployment-id=Movies)\n INFO - Configuring Service(id=Default Stateful Container, type=Container, provider-id=Default Stateful Container)\n INFO - Auto-creating a container for bean Movies: Container(type=STATEFUL, id=Default Stateful Container)\n INFO - Creating Container(id=Default Stateful Container)\n INFO - Using directory /tmp for stateful session passivation\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.injection.tx.MoviesTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Creating Container(id=Default Managed Container)\n INFO - Using directory /tmp for stateful session passivation\n INFO - Configuring PersistenceUnit(name=movie-unit)\n INFO - Auto-creating a Resource with id 'movieDatabaseNonJta' of type 'DataSource for 'movie-unit'.\n INFO - Configuring Service(id=movieDatabaseNonJta, type=Resource, provider-id=movieDatabase)\n INFO - Creating Resource(id=movieDatabaseNonJta)\n INFO - Adjusting PersistenceUnit movie-unit <non-jta-data-source> to Resource ID 'movieDatabaseNonJta' from 'movieDatabaseUnmanaged'\n INFO - Enterprise application \"/home/boto/dev/ws/openejb_trunk/openejb/examples/testing-transactions-bmt\" loaded.\n INFO - Assembling app: /home/boto/dev/ws/openejb_trunk/openejb/examples/testing-transactions-bmt\n SEVERE - JAVA AGENT NOT INSTALLED. The JPA Persistence Provider requested installation of a ClassFileTransformer which requires a JavaAgent. See http://tomee.apache.org/3.0/javaagent.html\n INFO - PersistenceUnit(name=movie-unit, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 399ms\n INFO - Jndi(name=\"java:global/testing-transactions-bmt/Movies!org.superbiz.injection.tx.Movies\")\n INFO - Jndi(name=\"java:global/testing-transactions-bmt/Movies\")\n INFO - Existing thread singleton service in SystemInstance() org.apache.openejb.cdi.ThreadSingletonServiceImpl@3f3f210f\n INFO - OpenWebBeans Container is starting...\n INFO - Adding OpenWebBeansPlugin : [CdiPlugin]\n INFO - All injection points are validated successfully.\n INFO - OpenWebBeans Container has started, it took 157 ms.\n INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateful Container)\n INFO - Deployed Application(path=/home/boto/dev/ws/openejb_trunk/openejb/examples/testing-transactions-bmt)\n INFO - Started user transaction org.apache.geronimo.transaction.manager.TransactionImpl@709a1411\n 21-Jul-2012 4:39:32 PM null openjpa.Runtime\n INFO: Starting OpenJPA 2.2.0\n 21-Jul-2012 4:39:32 PM null openjpa.jdbc.JDBC\n INFO: Using dictionary class \"org.apache.openjpa.jdbc.sql.HSQLDictionary\" (HSQL Database Engine 2.2.8 ,HSQL Database Engine Driver 2.2.8).\n 21-Jul-2012 4:39:33 PM null openjpa.Enhance\n INFO: Creating subclass and redefining methods for \"[class org.superbiz.injection.tx.Movie]\". This means that your application will be less efficient than it would if you ran the OpenJPA enhancer.\n INFO - Committing user transaction org.apache.geronimo.transaction.manager.TransactionImpl@709a1411\n INFO - Started user transaction org.apache.geronimo.transaction.manager.TransactionImpl@2bb64b70\n INFO - Committing user transaction org.apache.geronimo.transaction.manager.TransactionImpl@2bb64b70\n INFO - Started user transaction org.apache.geronimo.transaction.manager.TransactionImpl@627b5c\n INFO - Committing user transaction org.apache.geronimo.transaction.manager.TransactionImpl@627b5c\n INFO - Started user transaction org.apache.geronimo.transaction.manager.TransactionImpl@2f031310\n INFO - Committing user transaction org.apache.geronimo.transaction.manager.TransactionImpl@2f031310\n INFO - Started user transaction org.apache.geronimo.transaction.manager.TransactionImpl@4df2a9da\n INFO - Committing user transaction org.apache.geronimo.transaction.manager.TransactionImpl@4df2a9da\n INFO - Started user transaction org.apache.geronimo.transaction.manager.TransactionImpl@3fa9b4a4\n INFO - Rolling back user transaction org.apache.geronimo.transaction.manager.TransactionImpl@3fa9b4a4\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 7.471 sec\n\n Results :\n\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n",
"url":"https://github.com/apache/tomee/tree/master/examples/testing-transactions-bmt"
}
],
"troubleshooting":[
{
"name":"troubleshooting",
"readme":"Title: Troubleshooting\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## Movie\n\n package org.superbiz.troubleshooting;\n \n import javax.persistence.Entity;\n import javax.persistence.GeneratedValue;\n import javax.persistence.GenerationType;\n import javax.persistence.Id;\n \n @Entity(name = \"Movie\")\n public class Movie {\n \n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private long id;\n \n private String director;\n private String title;\n private int year;\n \n public Movie() {\n }\n \n public Movie(String director, String title, int year) {\n this.director = director;\n this.title = title;\n this.year = year;\n }\n \n public String getDirector() {\n return director;\n }\n \n public void setDirector(String director) {\n this.director = director;\n }\n \n public String getTitle() {\n return title;\n }\n \n public void setTitle(String title) {\n this.title = title;\n }\n \n public int getYear() {\n return year;\n }\n \n public void setYear(int year) {\n this.year = year;\n }\n \n }\n\n## Movies\n\n package org.superbiz.troubleshooting;\n \n import javax.ejb.Stateless;\n import javax.persistence.EntityManager;\n import javax.persistence.PersistenceContext;\n import javax.persistence.PersistenceContextType;\n import javax.persistence.Query;\n import java.util.List;\n \n //START SNIPPET: code\n @Stateless\n public class Movies {\n \n @PersistenceContext(unitName = \"movie-unit\", type = PersistenceContextType.TRANSACTION)\n private EntityManager entityManager;\n \n public void addMovie(Movie movie) throws Exception {\n entityManager.persist(movie);\n }\n \n public void deleteMovie(Movie movie) throws Exception {\n entityManager.remove(movie);\n }\n \n public List<Movie> getMovies() throws Exception {\n Query query = entityManager.createQuery(\"SELECT m from Movie as m\");\n return query.getResultList();\n }\n }\n\n## persistence.xml\n\n <persistence xmlns=\"http://java.sun.com/xml/ns/persistence\" version=\"1.0\">\n \n <persistence-unit name=\"movie-unit\">\n <jta-data-source>movieDatabase</jta-data-source>\n <non-jta-data-source>movieDatabaseUnmanaged</non-jta-data-source>\n <class>org.superbiz.testinjection.MoviesTest.Movie</class>\n \n <properties>\n <property name=\"openjpa.jdbc.SynchronizeMappings\" value=\"buildSchema(ForeignKeys=true)\"/>\n </properties>\n </persistence-unit>\n </persistence>\n\n## MoviesTest\n\n package org.superbiz.troubleshooting;\n \n import junit.framework.TestCase;\n \n import javax.annotation.Resource;\n import javax.ejb.EJB;\n import javax.ejb.embeddable.EJBContainer;\n import javax.persistence.EntityManager;\n import javax.persistence.PersistenceContext;\n import javax.transaction.UserTransaction;\n import java.util.List;\n import java.util.Properties;\n \n //START SNIPPET: code\n public class MoviesTest extends TestCase {\n \n @EJB\n private Movies movies;\n \n @Resource\n private UserTransaction userTransaction;\n \n @PersistenceContext\n private EntityManager entityManager;\n \n public void setUp() throws Exception {\n Properties p = new Properties();\n p.put(\"movieDatabase\", \"new://Resource?type=DataSource\");\n p.put(\"movieDatabase.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n \n // These two debug levels will get you the basic log information\n // on the deployment of applications. Good first step in troubleshooting.\n p.put(\"log4j.category.OpenEJB.startup\", \"debug\");\n p.put(\"log4j.category.OpenEJB.startup.config\", \"debug\");\n \n // This log category is a good way to see what \"openejb.foo\" options\n // and flags are available and what their default values are\n p.put(\"log4j.category.OpenEJB.options\", \"debug\");\n \n // This will output the full configuration of all containers\n // resources and other openejb.xml configurable items. A good\n // way to see what the final configuration looks like after all\n // overriding has been applied.\n p.put(\"log4j.category.OpenEJB.startup.service\", \"debug\");\n \n // Will output a generated ejb-jar.xml file that represents\n // 100% of the annotations used in the code. This is a great\n // way to figure out how to do something in xml for overriding\n // or just to \"see\" all your application meta-data in one place.\n // Look for log lines like this \"Dumping Generated ejb-jar.xml to\"\n p.put(\"openejb.descriptors.output\", \"true\");\n \n // Setting the validation output level to verbose results in\n // validation messages that attempt to provide explanations\n // and information on what steps can be taken to remedy failures.\n // A great tool for those learning EJB.\n p.put(\"openejb.validation.output.level\", \"verbose\");\n \n EJBContainer.createEJBContainer(p).getContext().bind(\"inject\", this);\n }\n \n public void test() throws Exception {\n \n userTransaction.begin();\n \n try {\n entityManager.persist(new Movie(\"Quentin Tarantino\", \"Reservoir Dogs\", 1992));\n entityManager.persist(new Movie(\"Joel Coen\", \"Fargo\", 1996));\n entityManager.persist(new Movie(\"Joel Coen\", \"The Big Lebowski\", 1998));\n \n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n } finally {\n userTransaction.commit();\n }\n \n // Transaction was committed\n List<Movie> list = movies.getMovies();\n assertEquals(\"List.size()\", 3, list.size());\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.troubleshooting.MoviesTest\n 2011-10-29 11:50:19,482 - DEBUG - Using default 'openejb.nobanner=true'\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n 2011-10-29 11:50:19,482 - INFO - openejb.home = /Users/dblevins/examples/troubleshooting\n 2011-10-29 11:50:19,482 - INFO - openejb.base = /Users/dblevins/examples/troubleshooting\n 2011-10-29 11:50:19,483 - DEBUG - Using default 'openejb.assembler=org.apache.openejb.assembler.classic.Assembler'\n 2011-10-29 11:50:19,483 - DEBUG - Instantiating assembler class org.apache.openejb.assembler.classic.Assembler\n 2011-10-29 11:50:19,517 - DEBUG - Using default 'openejb.jndiname.failoncollision=true'\n 2011-10-29 11:50:19,517 - INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n 2011-10-29 11:50:19,520 - DEBUG - Using default 'openejb.configurator=org.apache.openejb.config.ConfigurationFactory'\n 2011-10-29 11:50:19,588 - DEBUG - Using default 'openejb.validation.skip=false'\n 2011-10-29 11:50:19,589 - DEBUG - Using default 'openejb.deploymentId.format={ejbName}'\n 2011-10-29 11:50:19,589 - DEBUG - Using default 'openejb.debuggable-vm-hackery=false'\n 2011-10-29 11:50:19,589 - DEBUG - Using default 'openejb.webservices.enabled=true'\n 2011-10-29 11:50:19,594 - DEBUG - Using default 'openejb.vendor.config=ALL' Possible values are: geronimo, glassfish, jboss, weblogic or NONE or ALL\n 2011-10-29 11:50:19,612 - DEBUG - Using default 'openejb.provider.default=org.apache.openejb.embedded'\n 2011-10-29 11:50:19,658 - INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n 2011-10-29 11:50:19,662 - INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n 2011-10-29 11:50:19,665 - INFO - Configuring Service(id=movieDatabase, type=Resource, provider-id=Default JDBC Database)\n 2011-10-29 11:50:19,665 - DEBUG - Override [JdbcDriver=org.hsqldb.jdbcDriver]\n 2011-10-29 11:50:19,666 - DEBUG - Using default 'openejb.deployments.classpath=false'\n 2011-10-29 11:50:19,666 - INFO - Creating TransactionManager(id=Default Transaction Manager)\n 2011-10-29 11:50:19,676 - DEBUG - defaultTransactionTimeoutSeconds=600\n 2011-10-29 11:50:19,676 - DEBUG - TxRecovery=false\n 2011-10-29 11:50:19,676 - DEBUG - bufferSizeKb=32\n 2011-10-29 11:50:19,676 - DEBUG - checksumEnabled=true\n 2011-10-29 11:50:19,676 - DEBUG - adler32Checksum=true\n 2011-10-29 11:50:19,676 - DEBUG - flushSleepTimeMilliseconds=50\n 2011-10-29 11:50:19,676 - DEBUG - logFileDir=txlog\n 2011-10-29 11:50:19,676 - DEBUG - logFileExt=log\n 2011-10-29 11:50:19,676 - DEBUG - logFileName=howl\n 2011-10-29 11:50:19,676 - DEBUG - maxBlocksPerFile=-1\n 2011-10-29 11:50:19,677 - DEBUG - maxBuffers=0\n 2011-10-29 11:50:19,677 - DEBUG - maxLogFiles=2\n 2011-10-29 11:50:19,677 - DEBUG - minBuffers=4\n 2011-10-29 11:50:19,677 - DEBUG - threadsWaitingForceThreshold=-1\n 2011-10-29 11:50:19,724 - DEBUG - createService.success\n 2011-10-29 11:50:19,724 - INFO - Creating SecurityService(id=Default Security Service)\n 2011-10-29 11:50:19,724 - DEBUG - DefaultUser=guest\n 2011-10-29 11:50:19,750 - DEBUG - createService.success\n 2011-10-29 11:50:19,750 - INFO - Creating Resource(id=movieDatabase)\n 2011-10-29 11:50:19,750 - DEBUG - Definition=\n 2011-10-29 11:50:19,750 - DEBUG - JtaManaged=true\n 2011-10-29 11:50:19,750 - DEBUG - JdbcDriver=org.hsqldb.jdbcDriver\n 2011-10-29 11:50:19,750 - DEBUG - JdbcUrl=jdbc:hsqldb:mem:hsqldb\n 2011-10-29 11:50:19,750 - DEBUG - UserName=sa\n 2011-10-29 11:50:19,750 - DEBUG - Password=\n 2011-10-29 11:50:19,750 - DEBUG - PasswordCipher=PlainText\n 2011-10-29 11:50:19,750 - DEBUG - ConnectionProperties=\n 2011-10-29 11:50:19,750 - DEBUG - DefaultAutoCommit=true\n 2011-10-29 11:50:19,750 - DEBUG - InitialSize=0\n 2011-10-29 11:50:19,750 - DEBUG - MaxActive=20\n 2011-10-29 11:50:19,750 - DEBUG - MaxIdle=20\n 2011-10-29 11:50:19,751 - DEBUG - MinIdle=0\n 2011-10-29 11:50:19,751 - DEBUG - MaxWait=-1\n 2011-10-29 11:50:19,751 - DEBUG - TestOnBorrow=true\n 2011-10-29 11:50:19,751 - DEBUG - TestOnReturn=false\n 2011-10-29 11:50:19,751 - DEBUG - TestWhileIdle=false\n 2011-10-29 11:50:19,751 - DEBUG - TimeBetweenEvictionRunsMillis=-1\n 2011-10-29 11:50:19,751 - DEBUG - NumTestsPerEvictionRun=3\n 2011-10-29 11:50:19,751 - DEBUG - MinEvictableIdleTimeMillis=1800000\n 2011-10-29 11:50:19,751 - DEBUG - PoolPreparedStatements=false\n 2011-10-29 11:50:19,751 - DEBUG - MaxOpenPreparedStatements=0\n 2011-10-29 11:50:19,751 - DEBUG - AccessToUnderlyingConnectionAllowed=false\n 2011-10-29 11:50:19,781 - DEBUG - createService.success\n 2011-10-29 11:50:19,783 - DEBUG - Containers : 0\n 2011-10-29 11:50:19,785 - DEBUG - Deployments : 0\n 2011-10-29 11:50:19,785 - DEBUG - SecurityService : org.apache.openejb.core.security.SecurityServiceImpl\n 2011-10-29 11:50:19,786 - DEBUG - TransactionManager: org.apache.geronimo.transaction.manager.GeronimoTransactionManager\n 2011-10-29 11:50:19,786 - DEBUG - OpenEJB Container System ready.\n 2011-10-29 11:50:19,786 - DEBUG - Using default 'openejb.validation.skip=false'\n 2011-10-29 11:50:19,786 - DEBUG - Using default 'openejb.deploymentId.format={ejbName}'\n 2011-10-29 11:50:19,786 - DEBUG - Using default 'openejb.debuggable-vm-hackery=false'\n 2011-10-29 11:50:19,786 - DEBUG - Using default 'openejb.webservices.enabled=true'\n 2011-10-29 11:50:19,786 - DEBUG - Using default 'openejb.vendor.config=ALL' Possible values are: geronimo, glassfish, jboss, weblogic or NONE or ALL\n 2011-10-29 11:50:19,789 - DEBUG - Using default 'openejb.deployments.classpath.include=.*'\n 2011-10-29 11:50:19,789 - DEBUG - Using default 'openejb.deployments.classpath.exclude='\n 2011-10-29 11:50:19,789 - DEBUG - Using default 'openejb.deployments.classpath.require.descriptor=client' Possible values are: ejb, client or NONE or ALL\n 2011-10-29 11:50:19,789 - DEBUG - Using default 'openejb.deployments.classpath.filter.descriptors=false'\n 2011-10-29 11:50:19,789 - DEBUG - Using default 'openejb.deployments.classpath.filter.systemapps=true'\n 2011-10-29 11:50:19,828 - DEBUG - Inspecting classpath for applications: 5 urls.\n 2011-10-29 11:50:19,846 - INFO - Found EjbModule in classpath: /Users/dblevins/examples/troubleshooting/target/classes\n 2011-10-29 11:50:20,011 - DEBUG - URLs after filtering: 55\n 2011-10-29 11:50:20,011 - DEBUG - Annotations path: file:/Users/dblevins/examples/troubleshooting/target/classes/\n 2011-10-29 11:50:20,011 - DEBUG - Annotations path: jar:file:/Users/dblevins/.m2/repository/org/apache/maven/surefire/surefire-api/2.7.2/surefire-api-2.7.2.jar!/\n 2011-10-29 11:50:20,011 - DEBUG - Annotations path: jar:file:/Users/dblevins/.m2/repository/org/apache/openejb/mbean-annotation-api/4.0.0-beta-1/mbean-annotation-api-4.0.0-beta-1.jar!/\n 2011-10-29 11:50:20,011 - DEBUG - Annotations path: jar:file:/Users/dblevins/.m2/repository/org/apache/maven/surefire/surefire-booter/2.7.2/surefire-booter-2.7.2.jar!/\n 2011-10-29 11:50:20,011 - DEBUG - Annotations path: file:/Users/dblevins/examples/troubleshooting/target/test-classes/\n 2011-10-29 11:50:20,011 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/org/apache/geronimo/specs/geronimo-jms_1.1_spec/1.1.1/geronimo-jms_1.1_spec-1.1.1.jar!/\n 2011-10-29 11:50:20,011 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/org/apache/bval/bval-core/0.3-incubating/bval-core-0.3-incubating.jar!/\n 2011-10-29 11:50:20,011 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/org/apache/geronimo/specs/geronimo-j2ee-management_1.1_spec/1.0.1/geronimo-j2ee-management_1.1_spec-1.0.1.jar!/\n 2011-10-29 11:50:20,011 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/org/apache/activemq/activemq-core/5.4.2/activemq-core-5.4.2.jar!/\n 2011-10-29 11:50:20,012 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/org/apache/xbean/xbean-bundleutils/3.8/xbean-bundleutils-3.8.jar!/\n 2011-10-29 11:50:20,012 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/junit/junit/4.8.1/junit-4.8.1.jar!/\n 2011-10-29 11:50:20,012 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/net/sf/scannotation/scannotation/1.0.2/scannotation-1.0.2.jar!/\n 2011-10-29 11:50:20,012 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/org/apache/openejb/javaee-api/6.0-2/javaee-api-6.0-2.jar!/\n 2011-10-29 11:50:20,012 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/commons-beanutils/commons-beanutils-core/1.8.3/commons-beanutils-core-1.8.3.jar!/\n 2011-10-29 11:50:20,012 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/avalon-framework/avalon-framework/4.1.3/avalon-framework-4.1.3.jar!/\n 2011-10-29 11:50:20,012 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/org/apache/openwebbeans/openwebbeans-web/1.1.1/openwebbeans-web-1.1.1.jar!/\n 2011-10-29 11:50:20,012 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/wsdl4j/wsdl4j/1.6.2/wsdl4j-1.6.2.jar!/\n 2011-10-29 11:50:20,012 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/logkit/logkit/1.0.1/logkit-1.0.1.jar!/\n 2011-10-29 11:50:20,012 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/com/ibm/icu/icu4j/4.0.1/icu4j-4.0.1.jar!/\n 2011-10-29 11:50:20,012 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/org/apache/xbean/xbean-asm-shaded/3.8/xbean-asm-shaded-3.8.jar!/\n 2011-10-29 11:50:20,012 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/org/apache/openwebbeans/openwebbeans-ee-common/1.1.1/openwebbeans-ee-common-1.1.1.jar!/\n 2011-10-29 11:50:20,012 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/commons-pool/commons-pool/1.5.6/commons-pool-1.5.6.jar!/\n 2011-10-29 11:50:20,012 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/commons-collections/commons-collections/3.2.1/commons-collections-3.2.1.jar!/\n 2011-10-29 11:50:20,013 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/commons-logging/commons-logging-api/1.1/commons-logging-api-1.1.jar!/\n 2011-10-29 11:50:20,013 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/org/apache/openwebbeans/openwebbeans-impl/1.1.1/openwebbeans-impl-1.1.1.jar!/\n 2011-10-29 11:50:20,013 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/org/apache/xbean/xbean-finder-shaded/3.8/xbean-finder-shaded-3.8.jar!/\n 2011-10-29 11:50:20,013 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/org/apache/geronimo/specs/geronimo-j2ee-connector_1.6_spec/1.0/geronimo-j2ee-connector_1.6_spec-1.0.jar!/\n 2011-10-29 11:50:20,013 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/commons-cli/commons-cli/1.2/commons-cli-1.2.jar!/\n 2011-10-29 11:50:20,013 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/org/apache/activemq/kahadb/5.4.2/kahadb-5.4.2.jar!/\n 2011-10-29 11:50:20,013 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/hsqldb/hsqldb/1.8.0.10/hsqldb-1.8.0.10.jar!/\n 2011-10-29 11:50:20,013 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/log4j/log4j/1.2.16/log4j-1.2.16.jar!/\n 2011-10-29 11:50:20,013 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/org/apache/geronimo/components/geronimo-connector/3.1.1/geronimo-connector-3.1.1.jar!/\n 2011-10-29 11:50:20,013 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/org/apache/activemq/activemq-ra/5.4.2/activemq-ra-5.4.2.jar!/\n 2011-10-29 11:50:20,013 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/net/sourceforge/serp/serp/1.13.1/serp-1.13.1.jar!/\n 2011-10-29 11:50:20,013 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/org/slf4j/slf4j-log4j12/1.6.1/slf4j-log4j12-1.6.1.jar!/\n 2011-10-29 11:50:20,013 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/javax/servlet/servlet-api/2.3/servlet-api-2.3.jar!/\n 2011-10-29 11:50:20,013 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/org/apache/activemq/activeio-core/3.1.2/activeio-core-3.1.2.jar!/\n 2011-10-29 11:50:20,014 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/org/quartz-scheduler/quartz/1.8.5/quartz-1.8.5.jar!/\n 2011-10-29 11:50:20,014 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/org/apache/openwebbeans/openwebbeans-ee/1.1.1/openwebbeans-ee-1.1.1.jar!/\n 2011-10-29 11:50:20,014 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/org/slf4j/slf4j-api/1.6.1/slf4j-api-1.6.1.jar!/\n 2011-10-29 11:50:20,014 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/org/apache/openwebbeans/openwebbeans-spi/1.1.1/openwebbeans-spi-1.1.1.jar!/\n 2011-10-29 11:50:20,016 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/org/codehaus/swizzle/swizzle-stream/1.0.2/swizzle-stream-1.0.2.jar!/\n 2011-10-29 11:50:20,016 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/org/apache/openjpa/openjpa/2.1.1/openjpa-2.1.1.jar!/\n 2011-10-29 11:50:20,016 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/org/apache/xbean/xbean-naming/3.8/xbean-naming-3.8.jar!/\n 2011-10-29 11:50:20,016 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/org/apache/geronimo/components/geronimo-transaction/3.1.1/geronimo-transaction-3.1.1.jar!/\n 2011-10-29 11:50:20,016 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/commons-lang/commons-lang/2.6/commons-lang-2.6.jar!/\n 2011-10-29 11:50:20,016 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/javassist/javassist/3.12.0.GA/javassist-3.12.0.GA.jar!/\n 2011-10-29 11:50:20,016 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/org/objectweb/howl/howl/1.0.1-1/howl-1.0.1-1.jar!/\n 2011-10-29 11:50:20,016 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/org/apache/xbean/xbean-reflect/3.8/xbean-reflect-3.8.jar!/\n 2011-10-29 11:50:20,016 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/org/apache/openwebbeans/openwebbeans-ejb/1.1.1/openwebbeans-ejb-1.1.1.jar!/\n 2011-10-29 11:50:20,016 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/commons-logging/commons-logging/1.1/commons-logging-1.1.jar!/\n 2011-10-29 11:50:20,016 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/commons-net/commons-net/2.0/commons-net-2.0.jar!/\n 2011-10-29 11:50:20,017 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/org/apache/activemq/protobuf/activemq-protobuf/1.1/activemq-protobuf-1.1.jar!/\n 2011-10-29 11:50:20,017 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/commons-dbcp/commons-dbcp/1.4/commons-dbcp-1.4.jar!/\n 2011-10-29 11:50:20,017 - DEBUG - Descriptors path: jar:file:/Users/dblevins/.m2/repository/org/apache/geronimo/javamail/geronimo-javamail_1.4_mail/1.8.2/geronimo-javamail_1.4_mail-1.8.2.jar!/\n 2011-10-29 11:50:20,017 - DEBUG - Searched 5 classpath urls in 80 milliseconds. Average 16 milliseconds per url.\n 2011-10-29 11:50:20,023 - INFO - Beginning load: /Users/dblevins/examples/troubleshooting/target/classes\n 2011-10-29 11:50:20,028 - DEBUG - Using default 'openejb.tempclassloader.skip=none' Possible values are: none, annotations, enums or NONE or ALL\n 2011-10-29 11:50:20,030 - DEBUG - Using default 'openejb.tempclassloader.skip=none' Possible values are: none, annotations, enums or NONE or ALL\n 2011-10-29 11:50:20,099 - INFO - Configuring enterprise application: /Users/dblevins/examples/troubleshooting\n 2011-10-29 11:50:20,099 - DEBUG - No ejb-jar.xml found assuming annotated beans present: /Users/dblevins/examples/troubleshooting, module: troubleshooting\n 2011-10-29 11:50:20,213 - DEBUG - Searching for annotated application exceptions (see OPENEJB-980)\n 2011-10-29 11:50:20,214 - DEBUG - Searching for annotated application exceptions (see OPENEJB-980)\n 2011-10-29 11:50:20,248 - WARN - Method 'lookup' is not available for 'javax.annotation.Resource'. Probably using an older Runtime.\n 2011-10-29 11:50:20,249 - DEBUG - looking for annotated MBeans in \n 2011-10-29 11:50:20,249 - DEBUG - registered 0 annotated MBeans in \n 2011-10-29 11:50:20,278 - INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n 2011-10-29 11:50:20,278 - INFO - Auto-creating a container for bean Movies: Container(type=STATELESS, id=Default Stateless Container)\n 2011-10-29 11:50:20,278 - INFO - Creating Container(id=Default Stateless Container)\n 2011-10-29 11:50:20,279 - DEBUG - AccessTimeout=30 seconds\n 2011-10-29 11:50:20,279 - DEBUG - MaxSize=10\n 2011-10-29 11:50:20,279 - DEBUG - MinSize=0\n 2011-10-29 11:50:20,279 - DEBUG - StrictPooling=true\n 2011-10-29 11:50:20,279 - DEBUG - MaxAge=0 hours\n 2011-10-29 11:50:20,279 - DEBUG - ReplaceAged=true\n 2011-10-29 11:50:20,279 - DEBUG - ReplaceFlushed=false\n 2011-10-29 11:50:20,279 - DEBUG - MaxAgeOffset=-1\n 2011-10-29 11:50:20,279 - DEBUG - IdleTimeout=0 minutes\n 2011-10-29 11:50:20,279 - DEBUG - GarbageCollection=false\n 2011-10-29 11:50:20,279 - DEBUG - SweepInterval=5 minutes\n 2011-10-29 11:50:20,279 - DEBUG - CallbackThreads=5\n 2011-10-29 11:50:20,279 - DEBUG - CloseTimeout=5 minutes\n 2011-10-29 11:50:20,295 - DEBUG - createService.success\n 2011-10-29 11:50:20,296 - INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n 2011-10-29 11:50:20,296 - INFO - Auto-creating a container for bean org.superbiz.troubleshooting.MoviesTest: Container(type=MANAGED, id=Default Managed Container)\n 2011-10-29 11:50:20,296 - INFO - Creating Container(id=Default Managed Container)\n 2011-10-29 11:50:20,310 - DEBUG - createService.success\n 2011-10-29 11:50:20,310 - INFO - Configuring PersistenceUnit(name=movie-unit)\n 2011-10-29 11:50:20,310 - DEBUG - raw <jta-data-source>movieDatabase</jta-datasource>\n 2011-10-29 11:50:20,310 - DEBUG - raw <non-jta-data-source>movieDatabaseUnmanaged</non-jta-datasource>\n 2011-10-29 11:50:20,310 - DEBUG - normalized <jta-data-source>movieDatabase</jta-datasource>\n 2011-10-29 11:50:20,310 - DEBUG - normalized <non-jta-data-source>movieDatabaseUnmanaged</non-jta-datasource>\n 2011-10-29 11:50:20,310 - DEBUG - Available DataSources\n 2011-10-29 11:50:20,310 - DEBUG - DataSource(name=movieDatabase, JtaManaged=true)\n 2011-10-29 11:50:20,311 - INFO - Auto-creating a Resource with id 'movieDatabaseNonJta' of type 'DataSource for 'movie-unit'.\n 2011-10-29 11:50:20,311 - INFO - Configuring Service(id=movieDatabaseNonJta, type=Resource, provider-id=movieDatabase)\n 2011-10-29 11:50:20,311 - INFO - Creating Resource(id=movieDatabaseNonJta)\n 2011-10-29 11:50:20,311 - DEBUG - Definition=\n 2011-10-29 11:50:20,312 - DEBUG - JtaManaged=false\n 2011-10-29 11:50:20,312 - DEBUG - JdbcDriver=org.hsqldb.jdbcDriver\n 2011-10-29 11:50:20,312 - DEBUG - JdbcUrl=jdbc:hsqldb:mem:hsqldb\n 2011-10-29 11:50:20,312 - DEBUG - UserName=sa\n 2011-10-29 11:50:20,312 - DEBUG - Password=\n 2011-10-29 11:50:20,312 - DEBUG - PasswordCipher=PlainText\n 2011-10-29 11:50:20,312 - DEBUG - ConnectionProperties=\n 2011-10-29 11:50:20,312 - DEBUG - DefaultAutoCommit=true\n 2011-10-29 11:50:20,312 - DEBUG - InitialSize=0\n 2011-10-29 11:50:20,312 - DEBUG - MaxActive=20\n 2011-10-29 11:50:20,312 - DEBUG - MaxIdle=20\n 2011-10-29 11:50:20,312 - DEBUG - MinIdle=0\n 2011-10-29 11:50:20,312 - DEBUG - MaxWait=-1\n 2011-10-29 11:50:20,312 - DEBUG - TestOnBorrow=true\n 2011-10-29 11:50:20,312 - DEBUG - TestOnReturn=false\n 2011-10-29 11:50:20,312 - DEBUG - TestWhileIdle=false\n 2011-10-29 11:50:20,312 - DEBUG - TimeBetweenEvictionRunsMillis=-1\n 2011-10-29 11:50:20,312 - DEBUG - NumTestsPerEvictionRun=3\n 2011-10-29 11:50:20,312 - DEBUG - MinEvictableIdleTimeMillis=1800000\n 2011-10-29 11:50:20,312 - DEBUG - PoolPreparedStatements=false\n 2011-10-29 11:50:20,312 - DEBUG - MaxOpenPreparedStatements=0\n 2011-10-29 11:50:20,312 - DEBUG - AccessToUnderlyingConnectionAllowed=false\n 2011-10-29 11:50:20,316 - DEBUG - createService.success\n 2011-10-29 11:50:20,316 - INFO - Adjusting PersistenceUnit movie-unit <non-jta-data-source> to Resource ID 'movieDatabaseNonJta' from 'movieDatabaseUnmanaged'\n 2011-10-29 11:50:20,317 - INFO - Using 'openejb.descriptors.output=true'\n 2011-10-29 11:50:20,317 - INFO - Using 'openejb.descriptors.output=true'\n 2011-10-29 11:50:20,642 - INFO - Dumping Generated ejb-jar.xml to: /var/folders/bd/f9ntqy1m8xj_fs006s6crtjh0000gn/T/ejb-jar-4107959830671443055troubleshooting.xml\n 2011-10-29 11:50:20,657 - INFO - Dumping Generated openejb-jar.xml to: /var/folders/bd/f9ntqy1m8xj_fs006s6crtjh0000gn/T/openejb-jar-5369342778223971127troubleshooting.xml\n 2011-10-29 11:50:20,657 - INFO - Using 'openejb.descriptors.output=true'\n 2011-10-29 11:50:20,658 - INFO - Dumping Generated ejb-jar.xml to: /var/folders/bd/f9ntqy1m8xj_fs006s6crtjh0000gn/T/ejb-jar-5569422837673302173EjbModule837053032.xml\n 2011-10-29 11:50:20,659 - INFO - Dumping Generated openejb-jar.xml to: /var/folders/bd/f9ntqy1m8xj_fs006s6crtjh0000gn/T/openejb-jar-560959152015048895EjbModule837053032.xml\n 2011-10-29 11:50:20,665 - DEBUG - Adding persistence-unit movie-unit property openjpa.Log=log4j\n 2011-10-29 11:50:20,665 - DEBUG - Adjusting PersistenceUnit(name=movie-unit) property to openjpa.RuntimeUnenhancedClasses=supported\n 2011-10-29 11:50:20,674 - INFO - Using 'openejb.validation.output.level=VERBOSE'\n 2011-10-29 11:50:20,674 - INFO - Enterprise application \"/Users/dblevins/examples/troubleshooting\" loaded.\n 2011-10-29 11:50:20,674 - INFO - Assembling app: /Users/dblevins/examples/troubleshooting\n 2011-10-29 11:50:20,678 - DEBUG - Using default 'openejb.tempclassloader.skip=none' Possible values are: none, annotations, enums or NONE or ALL\n 2011-10-29 11:50:20,757 - DEBUG - Using default 'openejb.tempclassloader.skip=none' Possible values are: none, annotations, enums or NONE or ALL\n 2011-10-29 11:50:21,137 - INFO - PersistenceUnit(name=movie-unit, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 407ms\n 2011-10-29 11:50:21,138 - DEBUG - openjpa.jdbc.SynchronizeMappings=buildSchema(ForeignKeys=true)\n 2011-10-29 11:50:21,138 - DEBUG - openjpa.Log=log4j\n 2011-10-29 11:50:21,138 - DEBUG - openjpa.RuntimeUnenhancedClasses=supported\n 2011-10-29 11:50:21,262 - DEBUG - Using default 'openejb.jndiname.strategy.class=org.apache.openejb.assembler.classic.JndiBuilder$TemplatedStrategy'\n 2011-10-29 11:50:21,262 - DEBUG - Using default 'openejb.jndiname.format={deploymentId}{interfaceType.annotationName}'\n 2011-10-29 11:50:21,267 - DEBUG - Using default 'openejb.localcopy=true'\n 2011-10-29 11:50:21,270 - DEBUG - bound ejb at name: openejb/Deployment/Movies/org.superbiz.troubleshooting.Movies!LocalBean, ref: org.apache.openejb.core.ivm.naming.BusinessLocalBeanReference@2569a1c5\n 2011-10-29 11:50:21,270 - DEBUG - bound ejb at name: openejb/Deployment/Movies/org.superbiz.troubleshooting.Movies!LocalBeanHome, ref: org.apache.openejb.core.ivm.naming.BusinessLocalBeanReference@2569a1c5\n 2011-10-29 11:50:21,272 - INFO - Jndi(name=\"java:global/troubleshooting/Movies!org.superbiz.troubleshooting.Movies\")\n 2011-10-29 11:50:21,272 - INFO - Jndi(name=\"java:global/troubleshooting/Movies\")\n 2011-10-29 11:50:21,277 - DEBUG - Using default 'openejb.jndiname.strategy.class=org.apache.openejb.assembler.classic.JndiBuilder$TemplatedStrategy'\n 2011-10-29 11:50:21,277 - DEBUG - Using default 'openejb.jndiname.format={deploymentId}{interfaceType.annotationName}'\n 2011-10-29 11:50:21,277 - DEBUG - bound ejb at name: openejb/Deployment/org.superbiz.troubleshooting.MoviesTest/org.superbiz.troubleshooting.MoviesTest!LocalBean, ref: org.apache.openejb.core.ivm.naming.BusinessLocalBeanReference@3f78e13f\n 2011-10-29 11:50:21,277 - DEBUG - bound ejb at name: openejb/Deployment/org.superbiz.troubleshooting.MoviesTest/org.superbiz.troubleshooting.MoviesTest!LocalBeanHome, ref: org.apache.openejb.core.ivm.naming.BusinessLocalBeanReference@3f78e13f\n 2011-10-29 11:50:21,277 - INFO - Jndi(name=\"java:global/EjbModule837053032/org.superbiz.troubleshooting.MoviesTest!org.superbiz.troubleshooting.MoviesTest\")\n 2011-10-29 11:50:21,277 - INFO - Jndi(name=\"java:global/EjbModule837053032/org.superbiz.troubleshooting.MoviesTest\")\n 2011-10-29 11:50:21,291 - DEBUG - CDI Service not installed: org.apache.webbeans.spi.ConversationService\n 2011-10-29 11:50:21,399 - INFO - Created Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateless Container)\n 2011-10-29 11:50:21,428 - INFO - Created Ejb(deployment-id=org.superbiz.troubleshooting.MoviesTest, ejb-name=org.superbiz.troubleshooting.MoviesTest, container=Default Managed Container)\n 2011-10-29 11:50:21,463 - INFO - Started Ejb(deployment-id=Movies, ejb-name=Movies, container=Default Stateless Container)\n 2011-10-29 11:50:21,463 - INFO - Started Ejb(deployment-id=org.superbiz.troubleshooting.MoviesTest, ejb-name=org.superbiz.troubleshooting.MoviesTest, container=Default Managed Container)\n 2011-10-29 11:50:21,463 - INFO - Deployed Application(path=/Users/dblevins/examples/troubleshooting)\n 2011-10-29 11:50:21,728 - WARN - The class \"org.superbiz.testinjection.MoviesTest.Movie\" listed in the openjpa.MetaDataFactory configuration property could not be loaded by sun.misc.Launcher$AppClassLoader@27a8c4e7; ignoring.\n 2011-10-29 11:50:21,834 - WARN - The class \"org.superbiz.testinjection.MoviesTest.Movie\" listed in the openjpa.MetaDataFactory configuration property could not be loaded by sun.misc.Launcher$AppClassLoader@27a8c4e7; ignoring.\n 2011-10-29 11:50:21,846 - WARN - The class \"org.superbiz.testinjection.MoviesTest.Movie\" listed in the openjpa.MetaDataFactory configuration property could not be loaded by sun.misc.Launcher$AppClassLoader@27a8c4e7; ignoring.\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.642 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/troubleshooting"
}
],
"unit":[
{
"name":"reload-persistence-unit-properties",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/reload-persistence-unit-properties"
}
],
"url":[
{
"name":"change-jaxws-url",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/change-jaxws-url"
}
],
"validation":[
{
"name":"bean-validation-design-by-contract",
"readme":"# Bean Validation - Design By Contract\n\nBean Validation (aka JSR 303) contains an optional appendix dealing with method validation.\n\nSome implementions of this JSR implement this appendix (Apache bval, Hibernate validator for example).\n\nOpenEJB provides an interceptor which allows you to use this feature to do design by contract.\n\n# Design by contract\n\nThe goal is to be able to configure with a finer grain your contract. In the example you specify\nthe minimum centimeters a sport man should jump at pole vaulting:\n\n @Local\n public interface PoleVaultingManager {\n int points(@Min(120) int centimeters);\n }\n\n# Usage\n\nTomEE and OpenEJB do not provide anymore `BeanValidationAppendixInterceptor` since\nBean Validation 1.1 does it (with a slighly different usage but the exact same feature).\n\nSo basically you don't need to configure anything to use it.\n# Errors\n\nIf a parameter is not validated an exception is thrown, it is an EJBException wrapping a ConstraintViolationException:\n\n try {\n gamesManager.addSportMan(\"I lose\", \"EN\");\n fail(\"no space should be in names\");\n } catch (EJBException wrappingException) {\n assertTrue(wrappingException.getCause() instanceof ConstraintViolationException);\n ConstraintViolationException exception = ConstraintViolationException.class.cast(wrappingException.getCausedByException());\n assertEquals(1, exception.getConstraintViolations().size());\n }\n\n# Example\n\n## OlympicGamesManager\n\n package org.superbiz.designbycontract;\n\n import javax.ejb.Stateless;\n import javax.validation.constraints.NotNull;\n import javax.validation.constraints.Pattern;\n import javax.validation.constraints.Size;\n\n @Stateless\n public class OlympicGamesManager {\n public String addSportMan(@Pattern(regexp = \"^[A-Za-z]+$\") String name, @Size(min = 2, max = 4) String country) {\n if (country.equals(\"USA\")) {\n return null;\n }\n return new StringBuilder(name).append(\" [\").append(country).append(\"]\").toString();\n }\n }\n\n## PoleVaultingManager\n\n package org.superbiz.designbycontract;\n\n import javax.ejb.Local;\n import javax.validation.constraints.Min;\n\n @Local\n public interface PoleVaultingManager {\n int points(@Min(120) int centimeters);\n }\n\n## PoleVaultingManagerBean\n\n package org.superbiz.designbycontract;\n\n import javax.ejb.Stateless;\n\n @Stateless\n public class PoleVaultingManagerBean implements PoleVaultingManager {\n @Override\n public int points(int centimeters) {\n return centimeters - 120;\n }\n }\n\n## OlympicGamesTest\n\n public class OlympicGamesTest {\n private static Context context;\n\n @EJB\n private OlympicGamesManager gamesManager;\n\n @EJB\n private PoleVaultingManager poleVaultingManager;\n\n @BeforeClass\n public static void start() {\n Properties properties = new Properties();\n properties.setProperty(BeanContext.USER_INTERCEPTOR_KEY, BeanValidationAppendixInterceptor.class.getName());\n context = EJBContainer.createEJBContainer(properties).getContext();\n }\n\n @Before\n public void inject() throws Exception {\n context.bind(\"inject\", this);\n }\n\n @AfterClass\n public static void stop() throws Exception {\n if (context != null) {\n context.close();\n }\n }\n\n @Test\n public void sportMenOk() throws Exception {\n assertEquals(\"IWin [FR]\", gamesManager.addSportMan(\"IWin\", \"FR\"));\n }\n\n @Test\n public void sportMenKoBecauseOfName() throws Exception {\n try {\n gamesManager.addSportMan(\"I lose\", \"EN\");\n fail(\"no space should be in names\");\n } catch (EJBException wrappingException) {\n assertTrue(wrappingException.getCause() instanceof ConstraintViolationException);\n ConstraintViolationException exception = ConstraintViolationException.class.cast(wrappingException.getCausedByException());\n assertEquals(1, exception.getConstraintViolations().size());\n }\n }\n\n @Test\n public void sportMenKoBecauseOfCountry() throws Exception {\n try {\n gamesManager.addSportMan(\"ILoseTwo\", \"TOO-LONG\");\n fail(\"country should be between 2 and 4 characters\");\n } catch (EJBException wrappingException) {\n assertTrue(wrappingException.getCause() instanceof ConstraintViolationException);\n ConstraintViolationException exception = ConstraintViolationException.class.cast(wrappingException.getCausedByException());\n assertEquals(1, exception.getConstraintViolations().size());\n }\n }\n\n @Test\n public void polVaulting() throws Exception {\n assertEquals(100, poleVaultingManager.points(220));\n }\n\n @Test\n public void tooShortPolVaulting() throws Exception {\n try {\n poleVaultingManager.points(119);\n fail(\"the jump is too short\");\n } catch (EJBException wrappingException) {\n assertTrue(wrappingException.getCause() instanceof ConstraintViolationException);\n ConstraintViolationException exception = ConstraintViolationException.class.cast(wrappingException.getCausedByException());\n assertEquals(1, exception.getConstraintViolations().size());\n }\n }\n }\n\n# Running\n\n\n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running OlympicGamesTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/bean-validation-design-by-contract\n INFO - openejb.base = /Users/dblevins/examples/bean-validation-design-by-contract\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/bean-validation-design-by-contract/target/classes\n INFO - Beginning load: /Users/dblevins/examples/bean-validation-design-by-contract/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/bean-validation-design-by-contract\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean PoleVaultingManagerBean: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean OlympicGamesTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Enterprise application \"/Users/dblevins/examples/bean-validation-design-by-contract\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/bean-validation-design-by-contract\n INFO - Jndi(name=\"java:global/bean-validation-design-by-contract/PoleVaultingManagerBean!org.superbiz.designbycontract.PoleVaultingManager\")\n INFO - Jndi(name=\"java:global/bean-validation-design-by-contract/PoleVaultingManagerBean\")\n INFO - Jndi(name=\"java:global/bean-validation-design-by-contract/OlympicGamesManager!org.superbiz.designbycontract.OlympicGamesManager\")\n INFO - Jndi(name=\"java:global/bean-validation-design-by-contract/OlympicGamesManager\")\n INFO - Jndi(name=\"java:global/EjbModule236054577/OlympicGamesTest!OlympicGamesTest\")\n INFO - Jndi(name=\"java:global/EjbModule236054577/OlympicGamesTest\")\n INFO - Created Ejb(deployment-id=OlympicGamesManager, ejb-name=OlympicGamesManager, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=PoleVaultingManagerBean, ejb-name=PoleVaultingManagerBean, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=OlympicGamesTest, ejb-name=OlympicGamesTest, container=Default Managed Container)\n INFO - Started Ejb(deployment-id=OlympicGamesManager, ejb-name=OlympicGamesManager, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=PoleVaultingManagerBean, ejb-name=PoleVaultingManagerBean, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=OlympicGamesTest, ejb-name=OlympicGamesTest, container=Default Managed Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/bean-validation-design-by-contract)\n Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.245 sec\n\n Results :\n\n Tests run: 5, Failures: 0, Errors: 0, Skipped: 0\n",
"url":"https://github.com/apache/tomee/tree/master/examples/bean-validation-design-by-contract"
}
],
"versioning":[
{
"name":"datasource-versioning",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/datasource-versioning"
}
],
"webapp":[
{
"name":"resources-declared-in-webapp",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/resources-declared-in-webapp"
}
],
"weblogic":[
{
"name":"helloworld-weblogic",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/helloworld-weblogic"
}
],
"webservice":[
{
"name":"webservice-attachments",
"readme":"Title: Webservice Attachments\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## AttachmentImpl\n\n package org.superbiz.attachment;\n \n import javax.activation.DataHandler;\n import javax.activation.DataSource;\n import javax.ejb.Stateless;\n import javax.jws.WebService;\n import javax.xml.ws.BindingType;\n import javax.xml.ws.soap.SOAPBinding;\n import java.io.IOException;\n import java.io.InputStream;\n \n /**\n * This is an EJB 3 style pojo stateless session bean\n * Every stateless session bean implementation must be annotated\n * using the annotation @Stateless\n * This EJB has a single interface: {@link AttachmentWs} a webservice interface.\n */\n @Stateless\n @WebService(\n portName = \"AttachmentPort\",\n serviceName = \"AttachmentWsService\",\n targetNamespace = \"http://superbiz.org/wsdl\",\n endpointInterface = \"org.superbiz.attachment.AttachmentWs\")\n @BindingType(value = SOAPBinding.SOAP12HTTP_MTOM_BINDING)\n public class AttachmentImpl implements AttachmentWs {\n \n public String stringFromBytes(byte[] data) {\n return new String(data);\n }\n \n public String stringFromDataSource(DataSource source) {\n \n try {\n InputStream inStr = source.getInputStream();\n int size = inStr.available();\n byte[] data = new byte[size];\n inStr.read(data);\n inStr.close();\n return new String(data);\n } catch (IOException e) {\n e.printStackTrace();\n }\n return \"\";\n }\n \n public String stringFromDataHandler(DataHandler handler) {\n \n try {\n return (String) handler.getContent();\n } catch (IOException e) {\n e.printStackTrace();\n }\n return \"\";\n }\n }\n\n## AttachmentWs\n\n package org.superbiz.attachment;\n \n import javax.activation.DataHandler;\n import javax.jws.WebService;\n \n /**\n * This is an EJB 3 webservice interface to send attachments throughout SAOP.\n */\n @WebService(targetNamespace = \"http://superbiz.org/wsdl\")\n public interface AttachmentWs {\n \n public String stringFromBytes(byte[] data);\n \n // Not working at the moment with SUN saaj provider and CXF\n //public String stringFromDataSource(DataSource source);\n \n public String stringFromDataHandler(DataHandler handler);\n }\n\n## ejb-jar.xml\n\n <ejb-jar/>\n\n## AttachmentTest\n\n package org.superbiz.attachment;\n \n import junit.framework.TestCase;\n \n import javax.activation.DataHandler;\n import javax.activation.DataSource;\n import javax.mail.util.ByteArrayDataSource;\n import javax.naming.Context;\n import javax.naming.InitialContext;\n import javax.xml.namespace.QName;\n import javax.xml.ws.BindingProvider;\n import javax.xml.ws.Service;\n import javax.xml.ws.soap.SOAPBinding;\n import java.net.URL;\n import java.util.Properties;\n \n public class AttachmentTest extends TestCase {\n \n //START SNIPPET: setup\t\n private InitialContext initialContext;\n \n protected void setUp() throws Exception {\n \n Properties properties = new Properties();\n properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, \"org.apache.openejb.core.LocalInitialContextFactory\");\n properties.setProperty(\"openejb.embedded.remotable\", \"true\");\n \n initialContext = new InitialContext(properties);\n }\n //END SNIPPET: setup \n \n /**\n * Create a webservice client using wsdl url\n *\n * @throws Exception\n */\n //START SNIPPET: webservice\n public void testAttachmentViaWsInterface() throws Exception {\n Service service = Service.create(\n new URL(\"http://127.0.0.1:4204/AttachmentImpl?wsdl\"),\n new QName(\"http://superbiz.org/wsdl\", \"AttachmentWsService\"));\n assertNotNull(service);\n \n AttachmentWs ws = service.getPort(AttachmentWs.class);\n \n // retrieve the SOAPBinding\n SOAPBinding binding = (SOAPBinding) ((BindingProvider) ws).getBinding();\n binding.setMTOMEnabled(true);\n \n String request = \"tsztelak@gmail.com\";\n \n // Byte array\n String response = ws.stringFromBytes(request.getBytes());\n assertEquals(request, response);\n \n // Data Source\n DataSource source = new ByteArrayDataSource(request.getBytes(), \"text/plain; charset=UTF-8\");\n \n // not yet supported !\n // response = ws.stringFromDataSource(source);\n // assertEquals(request, response);\n \n // Data Handler\n response = ws.stringFromDataHandler(new DataHandler(source));\n assertEquals(request, response);\n }\n //END SNIPPET: webservice\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.attachment.AttachmentTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/webservice-attachments\n INFO - openejb.base = /Users/dblevins/examples/webservice-attachments\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/webservice-attachments/target/classes\n INFO - Beginning load: /Users/dblevins/examples/webservice-attachments/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/webservice-attachments/classpath.ear\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean AttachmentImpl: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Enterprise application \"/Users/dblevins/examples/webservice-attachments/classpath.ear\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/webservice-attachments/classpath.ear\n INFO - Created Ejb(deployment-id=AttachmentImpl, ejb-name=AttachmentImpl, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=AttachmentImpl, ejb-name=AttachmentImpl, container=Default Stateless Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/webservice-attachments/classpath.ear)\n INFO - Initializing network services\n INFO - Creating ServerService(id=httpejbd)\n INFO - Creating ServerService(id=cxf)\n INFO - Creating ServerService(id=admin)\n INFO - Creating ServerService(id=ejbd)\n INFO - Creating ServerService(id=ejbds)\n INFO - Initializing network services\n ** Starting Services **\n NAME IP PORT \n httpejbd 127.0.0.1 4204 \n admin thread 127.0.0.1 4200 \n ejbd 127.0.0.1 4201 \n ejbd 127.0.0.1 4203 \n -------\n Ready!\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.034 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/webservice-attachments"
},
{
"name":"webservice-holder",
"readme":"Title: @WebService OUT params via javax.xml.ws.Holder\n\nWith SOAP it is possible to return multiple values in a single request. This is impossible in Java as a method can only return one object.\n\nJAX-WS solves this problem with the concept of Holders. A `javax.xml.ws.Holder` is a simple wrapper object that can be passed into the `@WebService` method as a parameter. The application sets the value of the holder during the request and the server will send the value back as an OUT parameter.\n\n## Using @WebParam and javax.xml.ws.Holder\n\nThe `@WebParam` annotation allows us to declare the `sum` and `multiply` Holders as `WebParam.Mode.OUT` parameters. As mentioned, these holders are simply empty buckets the application can fill in with data to have sent to the client. The server will pass them in uninitialized.\n\n @Stateless\n @WebService(\n portName = \"CalculatorPort\",\n serviceName = \"CalculatorService\",\n targetNamespace = \"http://superbiz.org/wsdl\",\n endpointInterface = \"org.superbiz.ws.out.CalculatorWs\")\n public class Calculator implements CalculatorWs {\n\n public void sumAndMultiply(int a, int b,\n @WebParam(name = \"sum\", mode = WebParam.Mode.OUT) Holder<Integer> sum,\n @WebParam(name = \"multiply\", mode = WebParam.Mode.OUT) Holder<Integer> multiply) {\n sum.value = a + b;\n multiply.value = a * b;\n }\n }\n\nIf the Holders were specified as `WebParam.Mode.INOUT` params, then the client could use them to send data and the application as well. The `Holder` instances would then be initialized with the data from the client request. The application could check the data before eventually overriting it with the response values.\n\n## The WSDL\n\nThe above JAX-WS `@WebService` component results in the folliwing WSDL that will be created automatically. Note the `sumAndMultiplyResponse` complext type returns two elements. These match the `@WebParam` declarations and our two `Holder<Integer>` params.\n\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <wsdl:definitions xmlns:wsdl=\"http://schemas.xmlsoap.org/wsdl/\"\n name=\"CalculatorService\"\n targetNamespace=\"http://superbiz.org/wsdl\"\n xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\"\n xmlns:tns=\"http://superbiz.org/wsdl\"\n xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n <wsdl:types>\n <xsd:schema attributeFormDefault=\"unqualified\" elementFormDefault=\"unqualified\"\n targetNamespace=\"http://superbiz.org/wsdl\"\n xmlns:tns=\"http://superbiz.org/wsdl\"\n xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n <xsd:element name=\"sumAndMultiply\" type=\"tns:sumAndMultiply\"/>\n <xsd:complexType name=\"sumAndMultiply\">\n <xsd:sequence>\n <xsd:element name=\"arg0\" type=\"xsd:int\"/>\n <xsd:element name=\"arg1\" type=\"xsd:int\"/>\n </xsd:sequence>\n </xsd:complexType>\n <xsd:element name=\"sumAndMultiplyResponse\" type=\"tns:sumAndMultiplyResponse\"/>\n <xsd:complexType name=\"sumAndMultiplyResponse\">\n <xsd:sequence>\n <xsd:element minOccurs=\"0\" name=\"sum\" type=\"xsd:int\"/>\n <xsd:element minOccurs=\"0\" name=\"multiply\" type=\"xsd:int\"/>\n </xsd:sequence>\n </xsd:complexType>\n </xsd:schema>\n </wsdl:types>\n <wsdl:message name=\"sumAndMultiplyResponse\">\n <wsdl:part element=\"tns:sumAndMultiplyResponse\" name=\"parameters\"/>\n </wsdl:message>\n <wsdl:message name=\"sumAndMultiply\">\n <wsdl:part element=\"tns:sumAndMultiply\" name=\"parameters\"/>\n </wsdl:message>\n <wsdl:portType name=\"CalculatorWs\">\n <wsdl:operation name=\"sumAndMultiply\">\n <wsdl:input message=\"tns:sumAndMultiply\" name=\"sumAndMultiply\"/>\n <wsdl:output message=\"tns:sumAndMultiplyResponse\" name=\"sumAndMultiplyResponse\"/>\n </wsdl:operation>\n </wsdl:portType>\n <wsdl:binding name=\"CalculatorServiceSoapBinding\" type=\"tns:CalculatorWs\">\n <soap:binding style=\"document\" transport=\"http://schemas.xmlsoap.org/soap/http\"/>\n <wsdl:operation name=\"sumAndMultiply\">\n <soap:operation soapAction=\"\" style=\"document\"/>\n <wsdl:input name=\"sumAndMultiply\">\n <soap:body use=\"literal\"/>\n </wsdl:input>\n <wsdl:output name=\"sumAndMultiplyResponse\">\n <soap:body use=\"literal\"/>\n </wsdl:output>\n </wsdl:operation>\n </wsdl:binding>\n <wsdl:service name=\"CalculatorService\">\n <wsdl:port binding=\"tns:CalculatorServiceSoapBinding\" name=\"CalculatorPort\">\n <soap:address location=\"http://127.0.0.1:4204/Calculator?wsdl\"/>\n </wsdl:port>\n </wsdl:service>\n </wsdl:definitions>\n\n## Testing the OUT params\n\nHere we see a JAX-WS client executing the `sumAndMultiply` operation. Two empty `Holder` instances are created and passed in as parameters. The data from the `sumAndMultiplyResponse` is placed in the `Holder` instances and is then available to the client after the operation completes.\n\nThe holders themselves are not actually sent in the request unless they are configured as INOUT params via WebParam.Mode.INOUT on `@WebParam`\n\n import org.junit.BeforeClass;\n import org.junit.Test;\n\n import javax.ejb.embeddable.EJBContainer;\n import javax.xml.namespace.QName;\n import javax.xml.ws.Holder;\n import javax.xml.ws.Service;\n import java.net.URL;\n import java.util.Properties;\n\n import static org.junit.Assert.assertEquals;\n import static org.junit.Assert.assertNotNull;\n\n public class CalculatorTest {\n\n @BeforeClass\n public static void setUp() throws Exception {\n Properties properties = new Properties();\n properties.setProperty(\"openejb.embedded.remotable\", \"true\");\n //properties.setProperty(\"httpejbd.print\", \"true\");\n //properties.setProperty(\"httpejbd.indent.xml\", \"true\");\n EJBContainer.createEJBContainer(properties);\n }\n\n @Test\n public void outParams() throws Exception {\n final Service calculatorService = Service.create(\n new URL(\"http://127.0.0.1:4204/Calculator?wsdl\"),\n new QName(\"http://superbiz.org/wsdl\", \"CalculatorService\"));\n\n assertNotNull(calculatorService);\n\n final CalculatorWs calculator = calculatorService.getPort(CalculatorWs.class);\n\n final Holder<Integer> sum = new Holder<Integer>();\n final Holder<Integer> multiply = new Holder<Integer>();\n\n calculator.sumAndMultiply(4, 6, sum, multiply);\n\n assertEquals(10, (int) sum.value);\n assertEquals(24, (int) multiply.value);\n }\n }\n\n\n## Inspecting the messages\n\nThe above execution results in the following SOAP message.\n\n### SOAP sumAndMultiply <small>client request</small>\n\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <soap:Body>\n <ns1:sumAndMultiply xmlns:ns1=\"http://superbiz.org/wsdl\">\n <arg0>4</arg0>\n <arg1>6</arg1>\n </ns1:sumAndMultiply>\n </soap:Body>\n </soap:Envelope>\n\n### SOAP sumAndMultiplyResponse <small>server response</small>\n\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <soap:Body>\n <ns1:sumAndMultiplyResponse xmlns:ns1=\"http://superbiz.org/wsdl\">\n <sum>10</sum>\n <multiply>24</multiply>\n </ns1:sumAndMultiplyResponse>\n </soap:Body>\n </soap:Envelope>\n",
"url":"https://github.com/apache/tomee/tree/master/examples/webservice-holder"
},
{
"name":"webservice-handlerchain",
"readme":"Title: @WebService handlers with @HandlerChain\n\nIn this example we see a basic JAX-WS `@WebService` component use a handler chain to alter incoming and outgoing SOAP messages. SOAP Handlers are similar to Servlet Filters or EJB/CDI Interceptors.\n\nAt high level, the steps involved are:\n\n 1. Create handler(s) implementing `javax.xml.ws.handler.soap.SOAPHandler`\n 1. Declare and order them in an xml file via `<handler-chain>`\n 1. Associate the xml file with an `@WebService` component via `@HandlerChain`\n\n## The @HandlerChain\n\nFirst we'll start with our plain `@WebService` bean, called `Calculator`, which is annotated with `@HandlerChain`\n\n @Singleton\n @WebService(\n portName = \"CalculatorPort\",\n serviceName = \"CalculatorService\",\n targetNamespace = \"http://superbiz.org/wsdl\",\n endpointInterface = \"org.superbiz.calculator.wsh.CalculatorWs\")\n @HandlerChain(file = \"handlers.xml\")\n public class Calculator implements CalculatorWs {\n\n public int sum(int add1, int add2) {\n return add1 + add2;\n }\n\n public int multiply(int mul1, int mul2) {\n return mul1 * mul2;\n }\n }\n\nHere we see `@HandlerChain` pointing to a file called `handlers.xml`. This file could be called anything, but it must be in the same jar and java package as our `Calculator` component.\n\n## The &lt;handler-chains> file\n\nOur `Calculator` service is in the package `org.superbiz.calculator.wsh`, which means our handler chain xml file must be at `org/superbiz/calculator/wsh/handlers.xml` in our application's classpath or the file will not be found and no handlers will be used.\n\nIn maven we achieve this by putting our handlers.xml in `src/main/resources` like so:\n\n - `src/main/resources/org/superbiz/calculator/wsh/handlers.xml`\n\nWith this file we declare and **order** our handler chain.\n\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <handler-chains xmlns=\"http://java.sun.com/xml/ns/javaee\">\n <handler-chain>\n <handler>\n <handler-name>org.superbiz.calculator.wsh.Inflate</handler-name>\n <handler-class>org.superbiz.calculator.wsh.Inflate</handler-class>\n </handler>\n <handler>\n <handler-name>org.superbiz.calculator.wsh.Increment</handler-name>\n <handler-class>org.superbiz.calculator.wsh.Increment</handler-class>\n </handler>\n </handler-chain>\n </handler-chains>\n\nThe order as you might suspect is:\n\n - `Inflate`\n - `Increment`\n\n## The SOAPHandler implementation\n\nOur `Inflate` handler has the job of monitoring *responses* to the `sum` and `multiply` operations and making them 1000 times better. Manipulation of the message is done by walking the `SOAPBody` and editing the nodes. The `handleMessage` method is invoked for both requests and responses, so it is important to check the `SOAPBody` before attempting to naviage the nodes.\n\n import org.w3c.dom.Node;\n import javax.xml.namespace.QName;\n import javax.xml.soap.SOAPBody;\n import javax.xml.soap.SOAPException;\n import javax.xml.soap.SOAPMessage;\n import javax.xml.ws.handler.MessageContext;\n import javax.xml.ws.handler.soap.SOAPHandler;\n import javax.xml.ws.handler.soap.SOAPMessageContext;\n import java.util.Collections;\n import java.util.Set;\n\n public class Inflate implements SOAPHandler<SOAPMessageContext> {\n\n public boolean handleMessage(SOAPMessageContext mc) {\n try {\n final SOAPMessage message = mc.getMessage();\n final SOAPBody body = message.getSOAPBody();\n final String localName = body.getFirstChild().getLocalName();\n\n if (\"sumResponse\".equals(localName) || \"multiplyResponse\".equals(localName)) {\n final Node responseNode = body.getFirstChild();\n final Node returnNode = responseNode.getFirstChild();\n final Node intNode = returnNode.getFirstChild();\n\n final int value = new Integer(intNode.getNodeValue());\n intNode.setNodeValue(Integer.toString(value * 1000));\n }\n\n return true;\n } catch (SOAPException e) {\n return false;\n }\n }\n\n public Set<QName> getHeaders() {\n return Collections.emptySet();\n }\n\n public void close(MessageContext mc) {\n }\n\n public boolean handleFault(SOAPMessageContext mc) {\n return true;\n }\n }\n\nThe `Increment` handler is identical in code and therefore not shown. Instead of multiplying by 1000, it simply adds 1.\n\n## The TestCase\n\nWe use the JAX-WS API to create a Java client for our `Calculator` web service and use it to invoke both the `sum` and `multiply` operations. Note the clever use of math to assert both the existence and order of our handlers. If `Inflate` and `Increment` were reversed, the responses would be 11000 and 13000 respectively.\n\n public class CalculatorTest {\n\n @BeforeClass\n public static void setUp() throws Exception {\n Properties properties = new Properties();\n properties.setProperty(\"openejb.embedded.remotable\", \"true\");\n EJBContainer.createEJBContainer(properties);\n }\n\n @Test\n public void testCalculatorViaWsInterface() throws Exception {\n final Service calculatorService = Service.create(\n new URL(\"http://127.0.0.1:4204/Calculator?wsdl\"),\n new QName(\"http://superbiz.org/wsdl\", \"CalculatorService\"));\n\n assertNotNull(calculatorService);\n\n final CalculatorWs calculator = calculatorService.getPort(CalculatorWs.class);\n\n // we expect our answers to come back 1000 times better, plus one!\n assertEquals(10001, calculator.sum(4, 6));\n assertEquals(12001, calculator.multiply(3, 4));\n }\n }\n\n## Running the example\n\nSimply run `mvn clean install` and you should see output similar to the following:\n\n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.calculator.wsh.CalculatorTest\n INFO - openejb.home = /Users/dblevins/work/all/trunk/openejb/examples/webservice-handlers\n INFO - openejb.base = /Users/dblevins/work/all/trunk/openejb/examples/webservice-handlers\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Cannot find the configuration file [conf/openejb.xml]. Will attempt to create one for the beans deployed.\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Creating TransactionManager(id=Default Transaction Manager)\n INFO - Creating SecurityService(id=Default Security Service)\n INFO - Beginning load: /Users/dblevins/work/all/trunk/openejb/examples/webservice-handlers/target/test-classes\n INFO - Beginning load: /Users/dblevins/work/all/trunk/openejb/examples/webservice-handlers/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/work/all/trunk/openejb/examples/webservice-handlers\n INFO - Auto-deploying ejb Calculator: EjbDeployment(deployment-id=Calculator)\n INFO - Configuring Service(id=Default Singleton Container, type=Container, provider-id=Default Singleton Container)\n INFO - Auto-creating a container for bean Calculator: Container(type=SINGLETON, id=Default Singleton Container)\n INFO - Creating Container(id=Default Singleton Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.calculator.wsh.CalculatorTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Creating Container(id=Default Managed Container)\n INFO - Enterprise application \"/Users/dblevins/work/all/trunk/openejb/examples/webservice-handlers\" loaded.\n INFO - Assembling app: /Users/dblevins/work/all/trunk/openejb/examples/webservice-handlers\n INFO - Created Ejb(deployment-id=Calculator, ejb-name=Calculator, container=Default Singleton Container)\n INFO - Started Ejb(deployment-id=Calculator, ejb-name=Calculator, container=Default Singleton Container)\n INFO - Deployed Application(path=/Users/dblevins/work/all/trunk/openejb/examples/webservice-handlers)\n INFO - Initializing network services\n INFO - Creating ServerService(id=httpejbd)\n INFO - Creating ServerService(id=cxf)\n INFO - Creating ServerService(id=admin)\n INFO - Creating ServerService(id=ejbd)\n INFO - Creating ServerService(id=ejbds)\n INFO - Initializing network services\n INFO - ** Starting Services **\n INFO - NAME IP PORT\n INFO - httpejbd 127.0.0.1 4204\n INFO - Creating Service {http://superbiz.org/wsdl}CalculatorService from class org.superbiz.calculator.wsh.CalculatorWs\n INFO - Setting the server's publish address to be http://nopath:80\n INFO - Webservice(wsdl=http://127.0.0.1:4204/Calculator, qname={http://superbiz.org/wsdl}CalculatorService) --> Ejb(id=Calculator)\n INFO - admin thread 127.0.0.1 4200\n INFO - ejbd 127.0.0.1 4201\n INFO - ejbd 127.0.0.1 4203\n INFO - -------\n INFO - Ready!\n INFO - Creating Service {http://superbiz.org/wsdl}CalculatorService from WSDL: http://127.0.0.1:4204/Calculator?wsdl\n INFO - Creating Service {http://superbiz.org/wsdl}CalculatorService from WSDL: http://127.0.0.1:4204/Calculator?wsdl\n INFO - Default SAAJ universe not set\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.783 sec\n\n Results :\n\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n\n## Inspecting the messages\n\nThe above would generate the following messages.\n\n### Calculator wsdl\n\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <wsdl:definitions xmlns:wsdl=\"http://schemas.xmlsoap.org/wsdl/\"\n name=\"CalculatorService\" targetNamespace=\"http://superbiz.org/wsdl\"\n xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\"\n xmlns:tns=\"http://superbiz.org/wsdl\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n <wsdl:types>\n <xsd:schema attributeFormDefault=\"unqualified\" elementFormDefault=\"unqualified\"\n targetNamespace=\"http://superbiz.org/wsdl\" xmlns:tns=\"http://superbiz.org/wsdl\"\n xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n <xsd:element name=\"multiply\" type=\"tns:multiply\"/>\n <xsd:complexType name=\"multiply\">\n <xsd:sequence>\n <xsd:element name=\"arg0\" type=\"xsd:int\"/>\n <xsd:element name=\"arg1\" type=\"xsd:int\"/>\n </xsd:sequence>\n </xsd:complexType>\n <xsd:element name=\"multiplyResponse\" type=\"tns:multiplyResponse\"/>\n <xsd:complexType name=\"multiplyResponse\">\n <xsd:sequence>\n <xsd:element name=\"return\" type=\"xsd:int\"/>\n </xsd:sequence>\n </xsd:complexType>\n <xsd:element name=\"sum\" type=\"tns:sum\"/>\n <xsd:complexType name=\"sum\">\n <xsd:sequence>\n <xsd:element name=\"arg0\" type=\"xsd:int\"/>\n <xsd:element name=\"arg1\" type=\"xsd:int\"/>\n </xsd:sequence>\n </xsd:complexType>\n <xsd:element name=\"sumResponse\" type=\"tns:sumResponse\"/>\n <xsd:complexType name=\"sumResponse\">\n <xsd:sequence>\n <xsd:element name=\"return\" type=\"xsd:int\"/>\n </xsd:sequence>\n </xsd:complexType>\n </xsd:schema>\n </wsdl:types>\n <wsdl:message name=\"multiplyResponse\">\n <wsdl:part element=\"tns:multiplyResponse\" name=\"parameters\">\n </wsdl:part>\n </wsdl:message>\n <wsdl:message name=\"sumResponse\">\n <wsdl:part element=\"tns:sumResponse\" name=\"parameters\">\n </wsdl:part>\n </wsdl:message>\n <wsdl:message name=\"sum\">\n <wsdl:part element=\"tns:sum\" name=\"parameters\">\n </wsdl:part>\n </wsdl:message>\n <wsdl:message name=\"multiply\">\n <wsdl:part element=\"tns:multiply\" name=\"parameters\">\n </wsdl:part>\n </wsdl:message>\n <wsdl:portType name=\"CalculatorWs\">\n <wsdl:operation name=\"multiply\">\n <wsdl:input message=\"tns:multiply\" name=\"multiply\">\n </wsdl:input>\n <wsdl:output message=\"tns:multiplyResponse\" name=\"multiplyResponse\">\n </wsdl:output>\n </wsdl:operation>\n <wsdl:operation name=\"sum\">\n <wsdl:input message=\"tns:sum\" name=\"sum\">\n </wsdl:input>\n <wsdl:output message=\"tns:sumResponse\" name=\"sumResponse\">\n </wsdl:output>\n </wsdl:operation>\n </wsdl:portType>\n <wsdl:binding name=\"CalculatorServiceSoapBinding\" type=\"tns:CalculatorWs\">\n <soap:binding style=\"document\" transport=\"http://schemas.xmlsoap.org/soap/http\"/>\n <wsdl:operation name=\"multiply\">\n <soap:operation soapAction=\"\" style=\"document\"/>\n <wsdl:input name=\"multiply\">\n <soap:body use=\"literal\"/>\n </wsdl:input>\n <wsdl:output name=\"multiplyResponse\">\n <soap:body use=\"literal\"/>\n </wsdl:output>\n </wsdl:operation>\n <wsdl:operation name=\"sum\">\n <soap:operation soapAction=\"\" style=\"document\"/>\n <wsdl:input name=\"sum\">\n <soap:body use=\"literal\"/>\n </wsdl:input>\n <wsdl:output name=\"sumResponse\">\n <soap:body use=\"literal\"/>\n </wsdl:output>\n </wsdl:operation>\n </wsdl:binding>\n <wsdl:service name=\"CalculatorService\">\n <wsdl:port binding=\"tns:CalculatorServiceSoapBinding\" name=\"CalculatorPort\">\n <soap:address location=\"http://127.0.0.1:4204/Calculator?wsdl\"/>\n </wsdl:port>\n </wsdl:service>\n </wsdl:definitions>\n\n### SOAP sum and sumResponse\n\nRequest:\n\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <soap:Body>\n <ns1:sum xmlns:ns1=\"http://superbiz.org/wsdl\">\n <arg0>4</arg0>\n <arg1>6</arg1>\n </ns1:sum>\n </soap:Body>\n </soap:Envelope>\n\nResponse:\n\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <soap:Body>\n <ns1:sumResponse xmlns:ns1=\"http://superbiz.org/wsdl\">\n <return>10001</return>\n </ns1:sumResponse>\n </soap:Body>\n </soap:Envelope>\n\n### SOAP multiply and multiplyResponse\n\nRequest:\n\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <soap:Body>\n <ns1:multiply xmlns:ns1=\"http://superbiz.org/wsdl\">\n <arg0>3</arg0>\n <arg1>4</arg1>\n </ns1:multiply>\n </soap:Body>\n </soap:Envelope>\n\nResponse:\n\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <soap:Body>\n <ns1:multiplyResponse xmlns:ns1=\"http://superbiz.org/wsdl\">\n <return>12001</return>\n </ns1:multiplyResponse>\n </soap:Body>\n </soap:Envelope>\n",
"url":"https://github.com/apache/tomee/tree/master/examples/webservice-handlerchain"
},
{
"name":"webservice-inheritance",
"readme":"Title: Webservice Inheritance\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## Item\n\n package org.superbiz.inheritance;\n \n import javax.persistence.Entity;\n import javax.persistence.GeneratedValue;\n import javax.persistence.GenerationType;\n import javax.persistence.Id;\n import javax.persistence.Inheritance;\n import javax.persistence.InheritanceType;\n import java.io.Serializable;\n \n @Entity\n @Inheritance(strategy = InheritanceType.JOINED)\n public class Item implements Serializable {\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private Long id;\n private String brand;\n private String itemName;\n private double price;\n \n public Long getId() {\n return id;\n }\n \n public void setId(Long id) {\n this.id = id;\n }\n \n public String getBrand() {\n return brand;\n }\n \n public void setBrand(String brand) {\n this.brand = brand;\n }\n \n public String getItemName() {\n return itemName;\n }\n \n public void setItemName(String itemName) {\n this.itemName = itemName;\n }\n \n public double getPrice() {\n return price;\n }\n \n public void setPrice(double price) {\n this.price = price;\n }\n }\n\n## Tower\n\n package org.superbiz.inheritance;\n \n import javax.persistence.Entity;\n \n @Entity\n public class Tower extends Item {\n private Fit fit;\n private String tubing;\n \n public static enum Fit {\n Custom, Exact, Universal\n }\n \n public Fit getFit() {\n return fit;\n }\n \n public void setFit(Fit fit) {\n this.fit = fit;\n }\n \n public String getTubing() {\n return tubing;\n }\n \n public void setTubing(String tubing) {\n this.tubing = tubing;\n }\n \n ;\n }\n\n## Wakeboard\n\n package org.superbiz.inheritance;\n \n import javax.persistence.Entity;\n \n @Entity\n public class Wakeboard extends Wearable {\n }\n\n## WakeboardBinding\n\n package org.superbiz.inheritance;\n \n import javax.persistence.Entity;\n \n @Entity\n public class WakeboardBinding extends Wearable {\n }\n\n## WakeRiderImpl\n\n package org.superbiz.inheritance;\n \n import javax.ejb.Stateless;\n import javax.jws.WebService;\n import javax.persistence.EntityManager;\n import javax.persistence.PersistenceContext;\n import javax.persistence.PersistenceContextType;\n import javax.persistence.Query;\n import java.util.List;\n \n /**\n * This is an EJB 3 style pojo stateless session bean Every stateless session\n * bean implementation must be annotated using the annotation @Stateless This\n * EJB has a single interface: {@link WakeRiderWs} a webservice interface.\n */\n @Stateless\n @WebService(\n portName = \"InheritancePort\",\n serviceName = \"InheritanceWsService\",\n targetNamespace = \"http://superbiz.org/wsdl\",\n endpointInterface = \"org.superbiz.inheritance.WakeRiderWs\")\n public class WakeRiderImpl implements WakeRiderWs {\n \n @PersistenceContext(unitName = \"wakeboard-unit\", type = PersistenceContextType.TRANSACTION)\n private EntityManager entityManager;\n \n public void addItem(Item item) throws Exception {\n entityManager.persist(item);\n }\n \n public void deleteMovie(Item item) throws Exception {\n entityManager.remove(item);\n }\n \n public List<Item> getItems() throws Exception {\n Query query = entityManager.createQuery(\"SELECT i FROM Item i\");\n List<Item> items = query.getResultList();\n return items;\n }\n }\n\n## WakeRiderWs\n\n package org.superbiz.inheritance;\n \n import javax.jws.WebService;\n import javax.xml.bind.annotation.XmlSeeAlso;\n import java.util.List;\n \n /**\n * This is an EJB 3 webservice interface that uses inheritance.\n */\n @WebService(targetNamespace = \"http://superbiz.org/wsdl\")\n @XmlSeeAlso({Wakeboard.class, WakeboardBinding.class, Tower.class})\n public interface WakeRiderWs {\n public void addItem(Item item) throws Exception;\n \n public void deleteMovie(Item item) throws Exception;\n \n public List<Item> getItems() throws Exception;\n }\n\n## Wearable\n\n package org.superbiz.inheritance;\n \n import javax.persistence.MappedSuperclass;\n \n @MappedSuperclass\n public abstract class Wearable extends Item {\n protected String size;\n \n public String getSize() {\n return size;\n }\n \n public void setSize(String size) {\n this.size = size;\n }\n }\n\n## ejb-jar.xml\n\n <ejb-jar/>\n \n\n## persistence.xml\n\n <persistence xmlns=\"http://java.sun.com/xml/ns/persistence\" version=\"1.0\">\n \n <persistence-unit name=\"wakeboard-unit\">\n \n <jta-data-source>wakeBoardDatabase</jta-data-source>\n <non-jta-data-source>wakeBoardDatabaseUnmanaged</non-jta-data-source>\n \n <class>org.superbiz.inheritance.Item</class>\n <class>org.superbiz.inheritance.Tower</class>\n <class>org.superbiz.inheritance.Wakeboard</class>\n <class>org.superbiz.inheritance.WakeboardBinding</class>\n <class>org.superbiz.inheritance.Wearable</class>\n \n <properties>\n <property name=\"openjpa.jdbc.SynchronizeMappings\" value=\"buildSchema(ForeignKeys=true)\"/>\n </properties>\n \n </persistence-unit>\n </persistence>\n\n## InheritanceTest\n\n package org.superbiz.inheritance;\n \n import junit.framework.TestCase;\n import org.superbiz.inheritance.Tower.Fit;\n \n import javax.naming.Context;\n import javax.naming.InitialContext;\n import javax.xml.namespace.QName;\n import javax.xml.ws.Service;\n import java.net.URL;\n import java.util.List;\n import java.util.Properties;\n \n public class InheritanceTest extends TestCase {\n \n //START SNIPPET: setup\t\n private InitialContext initialContext;\n \n protected void setUp() throws Exception {\n \n Properties p = new Properties();\n p.put(Context.INITIAL_CONTEXT_FACTORY, \"org.apache.openejb.core.LocalInitialContextFactory\");\n p.put(\"wakeBoardDatabase\", \"new://Resource?type=DataSource\");\n p.put(\"wakeBoardDatabase.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"wakeBoardDatabase.JdbcUrl\", \"jdbc:hsqldb:mem:wakeBoarddb\");\n \n p.put(\"wakeBoardDatabaseUnmanaged\", \"new://Resource?type=DataSource\");\n p.put(\"wakeBoardDatabaseUnmanaged.JdbcDriver\", \"org.hsqldb.jdbcDriver\");\n p.put(\"wakeBoardDatabaseUnmanaged.JdbcUrl\", \"jdbc:hsqldb:mem:wakeBoarddb\");\n p.put(\"wakeBoardDatabaseUnmanaged.JtaManaged\", \"false\");\n \n p.put(\"openejb.embedded.remotable\", \"true\");\n \n initialContext = new InitialContext(p);\n }\n //END SNIPPET: setup \n \n /**\n * Create a webservice client using wsdl url\n *\n * @throws Exception\n */\n //START SNIPPET: webservice\n public void testInheritanceViaWsInterface() throws Exception {\n Service service = Service.create(\n new URL(\"http://127.0.0.1:4204/WakeRiderImpl?wsdl\"),\n new QName(\"http://superbiz.org/wsdl\", \"InheritanceWsService\"));\n assertNotNull(service);\n \n WakeRiderWs ws = service.getPort(WakeRiderWs.class);\n \n Tower tower = createTower();\n Item item = createItem();\n Wakeboard wakeBoard = createWakeBoard();\n WakeboardBinding wakeBoardbinding = createWakeboardBinding();\n \n ws.addItem(tower);\n ws.addItem(item);\n ws.addItem(wakeBoard);\n ws.addItem(wakeBoardbinding);\n \n \n List<Item> returnedItems = ws.getItems();\n \n assertEquals(\"testInheritanceViaWsInterface, nb Items\", 4, returnedItems.size());\n \n //check tower\n assertEquals(\"testInheritanceViaWsInterface, first Item\", returnedItems.get(0).getClass(), Tower.class);\n tower = (Tower) returnedItems.get(0);\n assertEquals(\"testInheritanceViaWsInterface, first Item\", tower.getBrand(), \"Tower brand\");\n assertEquals(\"testInheritanceViaWsInterface, first Item\", tower.getFit().ordinal(), Fit.Custom.ordinal());\n assertEquals(\"testInheritanceViaWsInterface, first Item\", tower.getItemName(), \"Tower item name\");\n assertEquals(\"testInheritanceViaWsInterface, first Item\", tower.getPrice(), 1.0d);\n assertEquals(\"testInheritanceViaWsInterface, first Item\", tower.getTubing(), \"Tower tubing\");\n \n //check item\n assertEquals(\"testInheritanceViaWsInterface, second Item\", returnedItems.get(1).getClass(), Item.class);\n item = (Item) returnedItems.get(1);\n assertEquals(\"testInheritanceViaWsInterface, second Item\", item.getBrand(), \"Item brand\");\n assertEquals(\"testInheritanceViaWsInterface, second Item\", item.getItemName(), \"Item name\");\n assertEquals(\"testInheritanceViaWsInterface, second Item\", item.getPrice(), 2.0d);\n \n //check wakeboard\n assertEquals(\"testInheritanceViaWsInterface, third Item\", returnedItems.get(2).getClass(), Wakeboard.class);\n wakeBoard = (Wakeboard) returnedItems.get(2);\n assertEquals(\"testInheritanceViaWsInterface, third Item\", wakeBoard.getBrand(), \"Wakeboard brand\");\n assertEquals(\"testInheritanceViaWsInterface, third Item\", wakeBoard.getItemName(), \"Wakeboard item name\");\n assertEquals(\"testInheritanceViaWsInterface, third Item\", wakeBoard.getPrice(), 3.0d);\n assertEquals(\"testInheritanceViaWsInterface, third Item\", wakeBoard.getSize(), \"WakeBoard size\");\n \n //check wakeboardbinding\n assertEquals(\"testInheritanceViaWsInterface, fourth Item\", returnedItems.get(3).getClass(), WakeboardBinding.class);\n wakeBoardbinding = (WakeboardBinding) returnedItems.get(3);\n assertEquals(\"testInheritanceViaWsInterface, fourth Item\", wakeBoardbinding.getBrand(), \"Wakeboardbinding brand\");\n assertEquals(\"testInheritanceViaWsInterface, fourth Item\", wakeBoardbinding.getItemName(), \"Wakeboardbinding item name\");\n assertEquals(\"testInheritanceViaWsInterface, fourth Item\", wakeBoardbinding.getPrice(), 4.0d);\n assertEquals(\"testInheritanceViaWsInterface, fourth Item\", wakeBoardbinding.getSize(), \"WakeBoardbinding size\");\n }\n //END SNIPPET: webservice\n \n private Tower createTower() {\n Tower tower = new Tower();\n tower.setBrand(\"Tower brand\");\n tower.setFit(Fit.Custom);\n tower.setItemName(\"Tower item name\");\n tower.setPrice(1.0f);\n tower.setTubing(\"Tower tubing\");\n return tower;\n }\n \n private Item createItem() {\n Item item = new Item();\n item.setBrand(\"Item brand\");\n item.setItemName(\"Item name\");\n item.setPrice(2.0f);\n return item;\n }\n \n private Wakeboard createWakeBoard() {\n Wakeboard wakeBoard = new Wakeboard();\n wakeBoard.setBrand(\"Wakeboard brand\");\n wakeBoard.setItemName(\"Wakeboard item name\");\n wakeBoard.setPrice(3.0f);\n wakeBoard.setSize(\"WakeBoard size\");\n return wakeBoard;\n }\n \n private WakeboardBinding createWakeboardBinding() {\n WakeboardBinding wakeBoardBinding = new WakeboardBinding();\n wakeBoardBinding.setBrand(\"Wakeboardbinding brand\");\n wakeBoardBinding.setItemName(\"Wakeboardbinding item name\");\n wakeBoardBinding.setPrice(4.0f);\n wakeBoardBinding.setSize(\"WakeBoardbinding size\");\n return wakeBoardBinding;\n }\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.inheritance.InheritanceTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/webservice-inheritance\n INFO - openejb.base = /Users/dblevins/examples/webservice-inheritance\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Configuring Service(id=wakeBoardDatabaseUnmanaged, type=Resource, provider-id=Default JDBC Database)\n INFO - Configuring Service(id=wakeBoardDatabase, type=Resource, provider-id=Default JDBC Database)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/webservice-inheritance/target/classes\n INFO - Beginning load: /Users/dblevins/examples/webservice-inheritance/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/webservice-inheritance/classpath.ear\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean WakeRiderImpl: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Configuring PersistenceUnit(name=wakeboard-unit)\n INFO - Enterprise application \"/Users/dblevins/examples/webservice-inheritance/classpath.ear\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/webservice-inheritance/classpath.ear\n INFO - PersistenceUnit(name=wakeboard-unit, provider=org.apache.openjpa.persistence.PersistenceProviderImpl) - provider time 396ms\n INFO - Created Ejb(deployment-id=WakeRiderImpl, ejb-name=WakeRiderImpl, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=WakeRiderImpl, ejb-name=WakeRiderImpl, container=Default Stateless Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/webservice-inheritance/classpath.ear)\n INFO - Initializing network services\n INFO - Creating ServerService(id=httpejbd)\n INFO - Creating ServerService(id=cxf)\n INFO - Creating ServerService(id=admin)\n INFO - Creating ServerService(id=ejbd)\n INFO - Creating ServerService(id=ejbds)\n INFO - Initializing network services\n ** Starting Services **\n NAME IP PORT \n httpejbd 127.0.0.1 4204 \n admin thread 127.0.0.1 4200 \n ejbd 127.0.0.1 4201 \n ejbd 127.0.0.1 4203 \n -------\n Ready!\n WARN - Found no persistent property in \"org.superbiz.inheritance.WakeboardBinding\"\n WARN - Found no persistent property in \"org.superbiz.inheritance.Wakeboard\"\n WARN - Found no persistent property in \"org.superbiz.inheritance.WakeboardBinding\"\n WARN - Found no persistent property in \"org.superbiz.inheritance.Wakeboard\"\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 4.442 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/webservice-inheritance"
},
{
"name":"webservice-security",
"readme":"Title: Webservice Security\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## CalculatorImpl\n\n package org.superbiz.calculator;\n \n import javax.annotation.security.DeclareRoles;\n import javax.annotation.security.RolesAllowed;\n import javax.ejb.Stateless;\n import javax.jws.WebService;\n \n /**\n * This is an EJB 3 style pojo stateless session bean\n * Every stateless session bean implementation must be annotated\n * using the annotation @Stateless\n * This EJB has a single interface: CalculatorWs a webservice interface.\n */\n //START SNIPPET: code\n @DeclareRoles(value = {\"Administrator\"})\n @Stateless\n @WebService(\n portName = \"CalculatorPort\",\n serviceName = \"CalculatorWsService\",\n targetNamespace = \"http://superbiz.org/wsdl\",\n endpointInterface = \"org.superbiz.calculator.CalculatorWs\")\n public class CalculatorImpl implements CalculatorWs, CalculatorRemote {\n \n @RolesAllowed(value = {\"Administrator\"})\n public int sum(int add1, int add2) {\n return add1 + add2;\n }\n \n @RolesAllowed(value = {\"Administrator\"})\n public int multiply(int mul1, int mul2) {\n return mul1 * mul2;\n }\n }\n\n## CalculatorRemote\n\n package org.superbiz.calculator;\n \n import javax.ejb.Remote;\n \n @Remote\n public interface CalculatorRemote {\n \n public int sum(int add1, int add2);\n \n public int multiply(int mul1, int mul2);\n }\n\n## CalculatorWs\n\n package org.superbiz.calculator;\n \n import javax.jws.WebService;\n \n //END SNIPPET: code\n \n /**\n * This is an EJB 3 webservice interface\n * A webservice interface must be annotated with the @Local\n * annotation.\n */\n //START SNIPPET: code\n @WebService(targetNamespace = \"http://superbiz.org/wsdl\")\n public interface CalculatorWs {\n \n public int sum(int add1, int add2);\n \n public int multiply(int mul1, int mul2);\n }\n\n## ejb-jar.xml\n\n <ejb-jar/>\n\n## openejb-jar.xml\n\n <openejb-jar xmlns=\"http://tomee.apache.org/xml/ns/openejb-jar-2.2\">\n <enterprise-beans>\n <session>\n <ejb-name>CalculatorImpl</ejb-name>\n <web-service-security>\n <security-realm-name/>\n <transport-guarantee>NONE</transport-guarantee>\n <auth-method>BASIC</auth-method>\n </web-service-security>\n </session>\n </enterprise-beans>\n </openejb-jar>\n\n## CalculatorTest\n\n package org.superbiz.calculator;\n \n import junit.framework.TestCase;\n \n import javax.naming.Context;\n import javax.naming.InitialContext;\n import javax.xml.namespace.QName;\n import javax.xml.ws.BindingProvider;\n import javax.xml.ws.Service;\n import java.net.URL;\n import java.util.Properties;\n \n public class CalculatorTest extends TestCase {\n \n //START SNIPPET: setup\n private InitialContext initialContext;\n \n protected void setUp() throws Exception {\n Properties properties = new Properties();\n properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, \"org.apache.openejb.core.LocalInitialContextFactory\");\n properties.setProperty(\"openejb.embedded.remotable\", \"true\");\n \n initialContext = new InitialContext(properties);\n }\n //END SNIPPET: setup\n \n /**\n * Create a webservice client using wsdl url\n *\n * @throws Exception\n */\n //START SNIPPET: webservice\n public void testCalculatorViaWsInterface() throws Exception {\n URL url = new URL(\"http://127.0.0.1:4204/CalculatorImpl?wsdl\");\n QName calcServiceQName = new QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService\");\n Service calcService = Service.create(url, calcServiceQName);\n assertNotNull(calcService);\n \n CalculatorWs calc = calcService.getPort(CalculatorWs.class);\n ((BindingProvider) calc).getRequestContext().put(BindingProvider.USERNAME_PROPERTY, \"jane\");\n ((BindingProvider) calc).getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, \"waterfall\");\n assertEquals(10, calc.sum(4, 6));\n assertEquals(12, calc.multiply(3, 4));\n }\n //END SNIPPET: webservice\n }\n\n# Running\n\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.calculator.CalculatorTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/webservice-security\n INFO - openejb.base = /Users/dblevins/examples/webservice-security\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/webservice-security/target/classes\n INFO - Beginning load: /Users/dblevins/examples/webservice-security/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/webservice-security/classpath.ear\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean CalculatorImpl: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Enterprise application \"/Users/dblevins/examples/webservice-security/classpath.ear\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/webservice-security/classpath.ear\n INFO - Jndi(name=CalculatorImplRemote) --> Ejb(deployment-id=CalculatorImpl)\n INFO - Jndi(name=global/classpath.ear/webservice-security/CalculatorImpl!org.superbiz.calculator.CalculatorRemote) --> Ejb(deployment-id=CalculatorImpl)\n INFO - Jndi(name=global/classpath.ear/webservice-security/CalculatorImpl) --> Ejb(deployment-id=CalculatorImpl)\n INFO - Created Ejb(deployment-id=CalculatorImpl, ejb-name=CalculatorImpl, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=CalculatorImpl, ejb-name=CalculatorImpl, container=Default Stateless Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/webservice-security/classpath.ear)\n INFO - Initializing network services\n INFO - Creating ServerService(id=httpejbd)\n INFO - Creating ServerService(id=cxf)\n INFO - Creating ServerService(id=admin)\n INFO - Creating ServerService(id=ejbd)\n INFO - Creating ServerService(id=ejbds)\n INFO - Initializing network services\n ** Starting Services **\n NAME IP PORT \n httpejbd 127.0.0.1 4204 \n admin thread 127.0.0.1 4200 \n ejbd 127.0.0.1 4201 \n ejbd 127.0.0.1 4203 \n -------\n Ready!\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.481 sec\n \n Results :\n \n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/webservice-security"
},
{
"name":"simple-webservice-without-interface",
"readme":"Title: Simple Webservice Without Interface\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## Calculator\n\n package org.superbiz.calculator;\n \n import javax.ejb.Stateless;\n import javax.jws.WebService;\n \n @Stateless\n @WebService(\n portName = \"CalculatorPort\",\n serviceName = \"CalculatorWsService\",\n targetNamespace = \"http://superbiz.org/wsdl\")\n public class Calculator {\n public int sum(int add1, int add2) {\n return add1 + add2;\n }\n \n public int multiply(int mul1, int mul2) {\n return mul1 * mul2;\n }\n }\n\n## ejb-jar.xml\n\n <ejb-jar/>\n\n## CalculatorTest\n\n package org.superbiz.calculator;\n \n import org.apache.commons.io.IOUtils;\n import org.junit.AfterClass;\n import org.junit.Before;\n import org.junit.BeforeClass;\n import org.junit.Test;\n \n import javax.ejb.embeddable.EJBContainer;\n import javax.naming.NamingException;\n import java.net.URL;\n import java.util.Properties;\n \n import static org.junit.Assert.assertTrue;\n \n public class CalculatorTest {\n private static EJBContainer container;\n \n @BeforeClass\n public static void setUp() throws Exception {\n final Properties properties = new Properties();\n properties.setProperty(\"openejb.embedded.remotable\", \"true\");\n \n container = EJBContainer.createEJBContainer(properties);\n }\n \n @Before\n public void inject() throws NamingException {\n if (container != null) {\n container.getContext().bind(\"inject\", this);\n }\n }\n \n @AfterClass\n public static void close() {\n if (container != null) {\n container.close();\n }\n }\n \n @Test\n public void wsdlExists() throws Exception {\n final URL url = new URL(\"http://127.0.0.1:4204/Calculator?wsdl\");\n assertTrue(IOUtils.readLines(url.openStream()).size() > 0);\n assertTrue(IOUtils.readLines(url.openStream()).toString().contains(\"CalculatorWsService\"));\n }\n }\n\n## ejb-jar.xml\n\n <ejb-jar/>\n",
"url":"https://github.com/apache/tomee/tree/master/examples/simple-webservice-without-interface"
},
{
"name":"webservice-ws-security",
"readme":"Title: Webservice Ws Security\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## CalculatorImpl\n\n package org.superbiz.calculator;\n \n import javax.annotation.security.DeclareRoles;\n import javax.annotation.security.RolesAllowed;\n import javax.ejb.Stateless;\n import javax.jws.WebService;\n \n /**\n * This is an EJB 3 style pojo stateless session bean\n * Every stateless session bean implementation must be annotated\n * using the annotation @Stateless\n * This EJB has a single interface: CalculatorWs a webservice interface.\n */\n //START SNIPPET: code\n @DeclareRoles(value = {\"Administrator\"})\n @Stateless\n @WebService(\n portName = \"CalculatorPort\",\n serviceName = \"CalculatorWsService\",\n targetNamespace = \"http://superbiz.org/wsdl\",\n endpointInterface = \"org.superbiz.calculator.CalculatorWs\")\n public class CalculatorImpl implements CalculatorWs, CalculatorRemote {\n \n @RolesAllowed(value = {\"Administrator\"})\n public int sum(int add1, int add2) {\n return add1 + add2;\n }\n \n public int multiply(int mul1, int mul2) {\n return mul1 * mul2;\n }\n }\n\n## CalculatorRemote\n\n package org.superbiz.calculator;\n \n import javax.ejb.Remote;\n \n @Remote\n public interface CalculatorRemote {\n \n public int sum(int add1, int add2);\n \n public int multiply(int mul1, int mul2);\n }\n\n## CalculatorWs\n\n package org.superbiz.calculator;\n \n import javax.jws.WebService;\n \n //END SNIPPET: code\n \n /**\n * This is an EJB 3 webservice interface\n * A webservice interface must be annotated with the @Local\n * annotation.\n */\n //START SNIPPET: code\n @WebService(targetNamespace = \"http://superbiz.org/wsdl\")\n public interface CalculatorWs {\n \n public int sum(int add1, int add2);\n \n public int multiply(int mul1, int mul2);\n }\n\n## ejb-jar.xml\n\n <ejb-jar xmlns=\"http://java.sun.com/xml/ns/javaee\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd\"\n version=\"3.0\" id=\"simple\" metadata-complete=\"false\">\n \n <enterprise-beans>\n \n <session>\n <ejb-name>CalculatorImplTimestamp1way</ejb-name>\n <service-endpoint>org.superbiz.calculator.CalculatorWs</service-endpoint>\n <ejb-class>org.superbiz.calculator.CalculatorImpl</ejb-class>\n <session-type>Stateless</session-type>\n <transaction-type>Container</transaction-type>\n </session>\n \n <session>\n <ejb-name>CalculatorImplTimestamp2ways</ejb-name>\n <service-endpoint>org.superbiz.calculator.CalculatorWs</service-endpoint>\n <ejb-class>org.superbiz.calculator.CalculatorImpl</ejb-class>\n <session-type>Stateless</session-type>\n <transaction-type>Container</transaction-type>\n </session>\n \n <session>\n <ejb-name>CalculatorImplUsernameTokenPlainPassword</ejb-name>\n <service-endpoint>org.superbiz.calculator.CalculatorWs</service-endpoint>\n <ejb-class>org.superbiz.calculator.CalculatorImpl</ejb-class>\n <session-type>Stateless</session-type>\n <transaction-type>Container</transaction-type>\n </session>\n \n <session>\n <ejb-name>CalculatorImplUsernameTokenHashedPassword</ejb-name>\n <service-endpoint>org.superbiz.calculator.CalculatorWs</service-endpoint>\n <ejb-class>org.superbiz.calculator.CalculatorImpl</ejb-class>\n <session-type>Stateless</session-type>\n <transaction-type>Container</transaction-type>\n </session>\n \n <session>\n <ejb-name>CalculatorImplUsernameTokenPlainPasswordEncrypt</ejb-name>\n <service-endpoint>org.superbiz.calculator.CalculatorWs</service-endpoint>\n <ejb-class>org.superbiz.calculator.CalculatorImpl</ejb-class>\n <session-type>Stateless</session-type>\n <transaction-type>Container</transaction-type>\n </session>\n \n <session>\n <ejb-name>CalculatorImplSign</ejb-name>\n <service-endpoint>org.superbiz.calculator.CalculatorWs</service-endpoint>\n <ejb-class>org.superbiz.calculator.CalculatorImpl</ejb-class>\n <session-type>Stateless</session-type>\n <transaction-type>Container</transaction-type>\n </session>\n \n <session>\n <ejb-name>CalculatorImplEncrypt2ways</ejb-name>\n <service-endpoint>org.superbiz.calculator.CalculatorWs</service-endpoint>\n <ejb-class>org.superbiz.calculator.CalculatorImpl</ejb-class>\n <session-type>Stateless</session-type>\n <transaction-type>Container</transaction-type>\n </session>\n \n <session>\n <ejb-name>CalculatorImplSign2ways</ejb-name>\n <service-endpoint>org.superbiz.calculator.CalculatorWs</service-endpoint>\n <ejb-class>org.superbiz.calculator.CalculatorImpl</ejb-class>\n <session-type>Stateless</session-type>\n <transaction-type>Container</transaction-type>\n </session>\n \n <session>\n <ejb-name>CalculatorImplEncryptAndSign2ways</ejb-name>\n <service-endpoint>org.superbiz.calculator.CalculatorWs</service-endpoint>\n <ejb-class>org.superbiz.calculator.CalculatorImpl</ejb-class>\n <session-type>Stateless</session-type>\n <transaction-type>Container</transaction-type>\n </session>\n \n </enterprise-beans>\n \n </ejb-jar>\n \n\n## openejb-jar.xml\n\n <openejb-jar xmlns=\"http://www.openejb.org/openejb-jar/1.1\">\n \n <ejb-deployment ejb-name=\"CalculatorImpl\">\n <properties>\n # webservice.security.realm\n # webservice.security.securityRealm\n # webservice.security.transportGarantee = NONE\n webservice.security.authMethod = WS-SECURITY\n wss4j.in.action = UsernameToken\n wss4j.in.passwordType = PasswordText\n wss4j.in.passwordCallbackClass = org.superbiz.calculator.CustomPasswordHandler\n \n # automatically added\n wss4j.in.validator.{http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd}UsernameToken = org.apache.openejb.server.cxf.OpenEJBLoginValidator\n </properties>\n </ejb-deployment>\n <ejb-deployment ejb-name=\"CalculatorImplTimestamp1way\">\n <properties>\n webservice.security.authMethod = WS-SECURITY\n wss4j.in.action = Timestamp\n </properties>\n </ejb-deployment>\n <ejb-deployment ejb-name=\"CalculatorImplTimestamp2ways\">\n <properties>\n webservice.security.authMethod = WS-SECURITY\n wss4j.in.action = Timestamp\n wss4j.out.action = Timestamp\n </properties>\n </ejb-deployment>\n <ejb-deployment ejb-name=\"CalculatorImplUsernameTokenPlainPassword\">\n <properties>\n webservice.security.authMethod = WS-SECURITY\n wss4j.in.action = UsernameToken\n wss4j.in.passwordType = PasswordText\n wss4j.in.passwordCallbackClass=org.superbiz.calculator.CustomPasswordHandler\n </properties>\n </ejb-deployment>\n <ejb-deployment ejb-name=\"CalculatorImplUsernameTokenHashedPassword\">\n <properties>\n webservice.security.authMethod = WS-SECURITY\n wss4j.in.action = UsernameToken\n wss4j.in.passwordType = PasswordDigest\n wss4j.in.passwordCallbackClass=org.superbiz.calculator.CustomPasswordHandler\n </properties>\n </ejb-deployment>\n <ejb-deployment ejb-name=\"CalculatorImplUsernameTokenPlainPasswordEncrypt\">\n <properties>\n webservice.security.authMethod = WS-SECURITY\n wss4j.in.action = UsernameToken Encrypt\n wss4j.in.passwordType = PasswordText\n wss4j.in.passwordCallbackClass=org.superbiz.calculator.CustomPasswordHandler\n wss4j.in.decryptionPropFile = META-INF/CalculatorImplUsernameTokenPlainPasswordEncrypt-server.properties\n </properties>\n </ejb-deployment>\n <ejb-deployment ejb-name=\"CalculatorImplSign\">\n <properties>\n webservice.security.authMethod = WS-SECURITY\n wss4j.in.action = Signature\n wss4j.in.passwordCallbackClass=org.superbiz.calculator.CustomPasswordHandler\n wss4j.in.signaturePropFile = META-INF/CalculatorImplSign-server.properties\n </properties>\n </ejb-deployment>\n \n </openejb-jar>\n \n\n## webservices.xml\n\n <webservices xmlns=\"http://java.sun.com/xml/ns/j2ee\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/j2ee\n http://www.ibm.com/webservices/xsd/j2ee_web_services_1_1.xsd\"\n xmlns:ger=\"http://ciaows.org/wsdl\" version=\"1.1\">\n \n <webservice-description>\n <webservice-description-name>CalculatorWsService</webservice-description-name>\n <port-component>\n <port-component-name>CalculatorImplTimestamp1way</port-component-name>\n <wsdl-port>CalculatorImplTimestamp1way</wsdl-port>\n <service-endpoint-interface>org.superbiz.calculator.CalculatorWs</service-endpoint-interface>\n <service-impl-bean>\n <ejb-link>CalculatorImplTimestamp1way</ejb-link>\n </service-impl-bean>\n </port-component>\n <port-component>\n <port-component-name>CalculatorImplTimestamp2ways</port-component-name>\n <wsdl-port>CalculatorImplTimestamp2ways</wsdl-port>\n <service-endpoint-interface>org.superbiz.calculator.CalculatorWs</service-endpoint-interface>\n <service-impl-bean>\n <ejb-link>CalculatorImplTimestamp2ways</ejb-link>\n </service-impl-bean>\n </port-component>\n <port-component>\n <port-component-name>CalculatorImplUsernameTokenPlainPassword</port-component-name>\n <wsdl-port>CalculatorImplUsernameTokenPlainPassword</wsdl-port>\n <service-endpoint-interface>org.superbiz.calculator.CalculatorWs</service-endpoint-interface>\n <service-impl-bean>\n <ejb-link>CalculatorImplUsernameTokenPlainPassword</ejb-link>\n </service-impl-bean>\n </port-component>\n <port-component>\n <port-component-name>CalculatorImplUsernameTokenHashedPassword</port-component-name>\n <wsdl-port>CalculatorImplUsernameTokenHashedPassword</wsdl-port>\n <service-endpoint-interface>org.superbiz.calculator.CalculatorWs</service-endpoint-interface>\n <service-impl-bean>\n <ejb-link>CalculatorImplUsernameTokenHashedPassword</ejb-link>\n </service-impl-bean>\n </port-component>\n <port-component>\n <port-component-name>CalculatorImplUsernameTokenPlainPasswordEncrypt</port-component-name>\n <wsdl-port>CalculatorImplUsernameTokenPlainPasswordEncrypt</wsdl-port>\n <service-endpoint-interface>org.superbiz.calculator.CalculatorWs</service-endpoint-interface>\n <service-impl-bean>\n <ejb-link>CalculatorImplUsernameTokenPlainPasswordEncrypt</ejb-link>\n </service-impl-bean>\n </port-component>\n </webservice-description>\n \n </webservices>\n \n\n## CalculatorTest\n\n package org.superbiz.calculator;\n \n import junit.framework.TestCase;\n import org.apache.cxf.binding.soap.saaj.SAAJInInterceptor;\n import org.apache.cxf.binding.soap.saaj.SAAJOutInterceptor;\n import org.apache.cxf.endpoint.Client;\n import org.apache.cxf.endpoint.Endpoint;\n import org.apache.cxf.frontend.ClientProxy;\n import org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor;\n import org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor;\n import org.apache.ws.security.WSConstants;\n import org.apache.ws.security.WSPasswordCallback;\n import org.apache.ws.security.handler.WSHandlerConstants;\n \n import javax.naming.Context;\n import javax.naming.InitialContext;\n import javax.security.auth.callback.Callback;\n import javax.security.auth.callback.CallbackHandler;\n import javax.security.auth.callback.UnsupportedCallbackException;\n import javax.xml.namespace.QName;\n import javax.xml.ws.Service;\n import javax.xml.ws.soap.SOAPBinding;\n import java.io.IOException;\n import java.net.URL;\n import java.util.HashMap;\n import java.util.Map;\n import java.util.Properties;\n \n public class CalculatorTest extends TestCase {\n \n //START SNIPPET: setup\n protected void setUp() throws Exception {\n Properties properties = new Properties();\n properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, \"org.apache.openejb.core.LocalInitialContextFactory\");\n properties.setProperty(\"openejb.embedded.remotable\", \"true\");\n \n new InitialContext(properties);\n }\n //END SNIPPET: setup\n \n //START SNIPPET: webservice\n public void testCalculatorViaWsInterface() throws Exception {\n Service calcService = Service.create(new URL(\"http://127.0.0.1:4204/CalculatorImpl?wsdl\"),\n new QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService\"));\n assertNotNull(calcService);\n \n CalculatorWs calc = calcService.getPort(CalculatorWs.class);\n \n Client client = ClientProxy.getClient(calc);\n Endpoint endpoint = client.getEndpoint();\n endpoint.getOutInterceptors().add(new SAAJOutInterceptor());\n \n Map<String, Object> outProps = new HashMap<String, Object>();\n outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);\n outProps.put(WSHandlerConstants.USER, \"jane\");\n outProps.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT);\n outProps.put(WSHandlerConstants.PW_CALLBACK_REF, new CallbackHandler() {\n \n public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {\n WSPasswordCallback pc = (WSPasswordCallback) callbacks[0];\n pc.setPassword(\"waterfall\");\n }\n });\n \n WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps);\n endpoint.getOutInterceptors().add(wssOut);\n \n assertEquals(10, calc.sum(4, 6));\n }\n \n public void testCalculatorViaWsInterfaceWithTimestamp1way() throws Exception {\n Service calcService = Service.create(new URL(\"http://127.0.0.1:4204/CalculatorImplTimestamp1way?wsdl\"),\n new QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService\"));\n assertNotNull(calcService);\n \n // for debugging (ie. TCPMon)\n calcService.addPort(new QName(\"http://superbiz.org/wsdl\",\n \"CalculatorWsService2\"), SOAPBinding.SOAP12HTTP_BINDING,\n \"http://127.0.0.1:8204/CalculatorImplTimestamp1way\");\n \n // CalculatorWs calc = calcService.getPort(\n // \tnew QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService2\"),\n //\t\tCalculatorWs.class);\n \n CalculatorWs calc = calcService.getPort(CalculatorWs.class);\n \n Client client = ClientProxy.getClient(calc);\n Endpoint endpoint = client.getEndpoint();\n endpoint.getOutInterceptors().add(new SAAJOutInterceptor());\n \n Map<String, Object> outProps = new HashMap<String, Object>();\n outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.TIMESTAMP);\n WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps);\n endpoint.getOutInterceptors().add(wssOut);\n \n assertEquals(12, calc.multiply(3, 4));\n }\n \n public void testCalculatorViaWsInterfaceWithTimestamp2ways() throws Exception {\n Service calcService = Service.create(new URL(\"http://127.0.0.1:4204/CalculatorImplTimestamp2ways?wsdl\"),\n new QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService\"));\n assertNotNull(calcService);\n \n // for debugging (ie. TCPMon)\n calcService.addPort(new QName(\"http://superbiz.org/wsdl\",\n \"CalculatorWsService2\"), SOAPBinding.SOAP12HTTP_BINDING,\n \"http://127.0.0.1:8204/CalculatorImplTimestamp2ways\");\n \n // CalculatorWs calc = calcService.getPort(\n // \tnew QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService2\"),\n //\t\tCalculatorWs.class);\n \n CalculatorWs calc = calcService.getPort(CalculatorWs.class);\n \n Client client = ClientProxy.getClient(calc);\n Endpoint endpoint = client.getEndpoint();\n endpoint.getOutInterceptors().add(new SAAJOutInterceptor());\n endpoint.getInInterceptors().add(new SAAJInInterceptor());\n \n Map<String, Object> outProps = new HashMap<String, Object>();\n outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.TIMESTAMP);\n WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps);\n endpoint.getOutInterceptors().add(wssOut);\n \n Map<String, Object> inProps = new HashMap<String, Object>();\n inProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.TIMESTAMP);\n WSS4JInInterceptor wssIn = new WSS4JInInterceptor(inProps);\n endpoint.getInInterceptors().add(wssIn);\n \n assertEquals(12, calc.multiply(3, 4));\n }\n \n public void testCalculatorViaWsInterfaceWithUsernameTokenPlainPassword() throws Exception {\n Service calcService = Service.create(new URL(\"http://127.0.0.1:4204/CalculatorImplUsernameTokenPlainPassword?wsdl\"),\n new QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService\"));\n assertNotNull(calcService);\n \n // for debugging (ie. TCPMon)\n calcService.addPort(new QName(\"http://superbiz.org/wsdl\",\n \"CalculatorWsService2\"), SOAPBinding.SOAP12HTTP_BINDING,\n \"http://127.0.0.1:8204/CalculatorImplUsernameTokenPlainPassword\");\n \n // CalculatorWs calc = calcService.getPort(\n // \tnew QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService2\"),\n // \tCalculatorWs.class);\n \n CalculatorWs calc = calcService.getPort(CalculatorWs.class);\n \n Client client = ClientProxy.getClient(calc);\n Endpoint endpoint = client.getEndpoint();\n endpoint.getOutInterceptors().add(new SAAJOutInterceptor());\n \n Map<String, Object> outProps = new HashMap<String, Object>();\n outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);\n outProps.put(WSHandlerConstants.USER, \"jane\");\n outProps.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT);\n outProps.put(WSHandlerConstants.PW_CALLBACK_REF, new CallbackHandler() {\n \n @Override\n public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {\n WSPasswordCallback pc = (WSPasswordCallback) callbacks[0];\n pc.setPassword(\"waterfall\");\n }\n });\n \n WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps);\n endpoint.getOutInterceptors().add(wssOut);\n \n assertEquals(10, calc.sum(4, 6));\n }\n \n public void testCalculatorViaWsInterfaceWithUsernameTokenHashedPassword() throws Exception {\n Service calcService = Service.create(new URL(\"http://127.0.0.1:4204/CalculatorImplUsernameTokenHashedPassword?wsdl\"),\n new QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService\"));\n assertNotNull(calcService);\n \n // for debugging (ie. TCPMon)\n calcService.addPort(new QName(\"http://superbiz.org/wsdl\",\n \"CalculatorWsService2\"), SOAPBinding.SOAP12HTTP_BINDING,\n \"http://127.0.0.1:8204/CalculatorImplUsernameTokenHashedPassword\");\n \n // CalculatorWs calc = calcService.getPort(\n // \tnew QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService2\"),\n // \tCalculatorWs.class);\n \n CalculatorWs calc = calcService.getPort(CalculatorWs.class);\n \n Client client = ClientProxy.getClient(calc);\n Endpoint endpoint = client.getEndpoint();\n endpoint.getOutInterceptors().add(new SAAJOutInterceptor());\n \n Map<String, Object> outProps = new HashMap<String, Object>();\n outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);\n outProps.put(WSHandlerConstants.USER, \"jane\");\n outProps.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_DIGEST);\n outProps.put(WSHandlerConstants.PW_CALLBACK_REF, new CallbackHandler() {\n \n @Override\n public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {\n WSPasswordCallback pc = (WSPasswordCallback) callbacks[0];\n pc.setPassword(\"waterfall\");\n }\n });\n \n WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps);\n endpoint.getOutInterceptors().add(wssOut);\n \n assertEquals(10, calc.sum(4, 6));\n }\n \n public void testCalculatorViaWsInterfaceWithUsernameTokenPlainPasswordEncrypt() throws Exception {\n Service calcService = Service.create(new URL(\"http://127.0.0.1:4204/CalculatorImplUsernameTokenPlainPasswordEncrypt?wsdl\"),\n new QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService\"));\n assertNotNull(calcService);\n \n // for debugging (ie. TCPMon)\n calcService.addPort(new QName(\"http://superbiz.org/wsdl\",\n \"CalculatorWsService2\"), SOAPBinding.SOAP12HTTP_BINDING,\n \"http://127.0.0.1:8204/CalculatorImplUsernameTokenPlainPasswordEncrypt\");\n \n // CalculatorWs calc = calcService.getPort(\n // \tnew QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService2\"),\n // \tCalculatorWs.class);\n \n CalculatorWs calc = calcService.getPort(CalculatorWs.class);\n \n Client client = ClientProxy.getClient(calc);\n Endpoint endpoint = client.getEndpoint();\n endpoint.getOutInterceptors().add(new SAAJOutInterceptor());\n \n Map<String, Object> outProps = new HashMap<String, Object>();\n outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN\n + \" \" + WSHandlerConstants.ENCRYPT);\n outProps.put(WSHandlerConstants.USER, \"jane\");\n outProps.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT);\n outProps.put(WSHandlerConstants.PW_CALLBACK_REF, new CallbackHandler() {\n \n @Override\n public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {\n WSPasswordCallback pc = (WSPasswordCallback) callbacks[0];\n pc.setPassword(\"waterfall\");\n }\n });\n outProps.put(WSHandlerConstants.ENC_PROP_FILE, \"META-INF/CalculatorImplUsernameTokenPlainPasswordEncrypt-client.properties\");\n outProps.put(WSHandlerConstants.ENCRYPTION_USER, \"serveralias\");\n \n WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps);\n endpoint.getOutInterceptors().add(wssOut);\n \n assertEquals(10, calc.sum(4, 6));\n }\n \n public void testCalculatorViaWsInterfaceWithSign() throws Exception {\n Service calcService = Service.create(new URL(\"http://127.0.0.1:4204/CalculatorImplSign?wsdl\"),\n new QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService\"));\n assertNotNull(calcService);\n \n // for debugging (ie. TCPMon)\n calcService.addPort(new QName(\"http://superbiz.org/wsdl\",\n \"CalculatorWsService2\"), SOAPBinding.SOAP12HTTP_BINDING,\n \"http://127.0.0.1:8204/CalculatorImplSign\");\n \n // CalculatorWs calc = calcService.getPort(\n //\tnew QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService2\"),\n //\tCalculatorWs.class);\n \n CalculatorWs calc = calcService.getPort(CalculatorWs.class);\n \n Client client = ClientProxy.getClient(calc);\n Endpoint endpoint = client.getEndpoint();\n endpoint.getOutInterceptors().add(new SAAJOutInterceptor());\n \n Map<String, Object> outProps = new HashMap<String, Object>();\n outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.SIGNATURE);\n outProps.put(WSHandlerConstants.USER, \"clientalias\");\n outProps.put(WSHandlerConstants.PW_CALLBACK_REF, new CallbackHandler() {\n \n @Override\n public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {\n WSPasswordCallback pc = (WSPasswordCallback) callbacks[0];\n pc.setPassword(\"clientPassword\");\n }\n });\n outProps.put(WSHandlerConstants.SIG_PROP_FILE, \"META-INF/CalculatorImplSign-client.properties\");\n outProps.put(WSHandlerConstants.SIG_KEY_ID, \"IssuerSerial\");\n \n WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps);\n endpoint.getOutInterceptors().add(wssOut);\n \n assertEquals(24, calc.multiply(4, 6));\n }\n //END SNIPPET: webservice\n }\n\n## CustomPasswordHandler\n\n package org.superbiz.calculator;\n \n import org.apache.ws.security.WSPasswordCallback;\n \n import javax.security.auth.callback.Callback;\n import javax.security.auth.callback.CallbackHandler;\n import javax.security.auth.callback.UnsupportedCallbackException;\n import java.io.IOException;\n \n public class CustomPasswordHandler implements CallbackHandler {\n @Override\n public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {\n WSPasswordCallback pc = (WSPasswordCallback) callbacks[0];\n \n if (pc.getUsage() == WSPasswordCallback.USERNAME_TOKEN) {\n // TODO get the password from the users.properties if possible\n pc.setPassword(\"waterfall\");\n } else if (pc.getUsage() == WSPasswordCallback.DECRYPT) {\n pc.setPassword(\"serverPassword\");\n } else if (pc.getUsage() == WSPasswordCallback.SIGNATURE) {\n pc.setPassword(\"serverPassword\");\n }\n }\n }\n\n# Running\n\n \n generate keys:\n \n do.sun.jdk:\n [echo] *** Running on a Sun JDK ***\n [echo] generate server keys\n [java] Certificate stored in file </Users/dblevins/examples/webservice-ws-security/target/classes/META-INF/serverKey.rsa>\n [echo] generate client keys\n [java] Certificate stored in file </Users/dblevins/examples/webservice-ws-security/target/test-classes/META-INF/clientKey.rsa>\n [echo] import client/server public keys in client/server keystores\n [java] Certificate was added to keystore\n [java] Certificate was added to keystore\n \n do.ibm.jdk:\n \n run:\n [echo] Running JDK specific keystore creation target\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.calculator.CalculatorTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/webservice-ws-security\n INFO - openejb.base = /Users/dblevins/examples/webservice-ws-security\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/webservice-ws-security/target/classes\n INFO - Beginning load: /Users/dblevins/examples/webservice-ws-security/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/webservice-ws-security/classpath.ear\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean CalculatorImplTimestamp1way: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Enterprise application \"/Users/dblevins/examples/webservice-ws-security/classpath.ear\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/webservice-ws-security/classpath.ear\n INFO - Jndi(name=CalculatorImplTimestamp1wayRemote) --> Ejb(deployment-id=CalculatorImplTimestamp1way)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplTimestamp1way!org.superbiz.calculator.CalculatorRemote) --> Ejb(deployment-id=CalculatorImplTimestamp1way)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplTimestamp1way) --> Ejb(deployment-id=CalculatorImplTimestamp1way)\n INFO - Jndi(name=CalculatorImplTimestamp2waysRemote) --> Ejb(deployment-id=CalculatorImplTimestamp2ways)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplTimestamp2ways!org.superbiz.calculator.CalculatorRemote) --> Ejb(deployment-id=CalculatorImplTimestamp2ways)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplTimestamp2ways) --> Ejb(deployment-id=CalculatorImplTimestamp2ways)\n INFO - Jndi(name=CalculatorImplUsernameTokenPlainPasswordRemote) --> Ejb(deployment-id=CalculatorImplUsernameTokenPlainPassword)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplUsernameTokenPlainPassword!org.superbiz.calculator.CalculatorRemote) --> Ejb(deployment-id=CalculatorImplUsernameTokenPlainPassword)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplUsernameTokenPlainPassword) --> Ejb(deployment-id=CalculatorImplUsernameTokenPlainPassword)\n INFO - Jndi(name=CalculatorImplUsernameTokenHashedPasswordRemote) --> Ejb(deployment-id=CalculatorImplUsernameTokenHashedPassword)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplUsernameTokenHashedPassword!org.superbiz.calculator.CalculatorRemote) --> Ejb(deployment-id=CalculatorImplUsernameTokenHashedPassword)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplUsernameTokenHashedPassword) --> Ejb(deployment-id=CalculatorImplUsernameTokenHashedPassword)\n INFO - Jndi(name=CalculatorImplUsernameTokenPlainPasswordEncryptRemote) --> Ejb(deployment-id=CalculatorImplUsernameTokenPlainPasswordEncrypt)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplUsernameTokenPlainPasswordEncrypt!org.superbiz.calculator.CalculatorRemote) --> Ejb(deployment-id=CalculatorImplUsernameTokenPlainPasswordEncrypt)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplUsernameTokenPlainPasswordEncrypt) --> Ejb(deployment-id=CalculatorImplUsernameTokenPlainPasswordEncrypt)\n INFO - Jndi(name=CalculatorImplSignRemote) --> Ejb(deployment-id=CalculatorImplSign)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplSign!org.superbiz.calculator.CalculatorRemote) --> Ejb(deployment-id=CalculatorImplSign)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplSign) --> Ejb(deployment-id=CalculatorImplSign)\n INFO - Jndi(name=CalculatorImplEncrypt2waysRemote) --> Ejb(deployment-id=CalculatorImplEncrypt2ways)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplEncrypt2ways!org.superbiz.calculator.CalculatorRemote) --> Ejb(deployment-id=CalculatorImplEncrypt2ways)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplEncrypt2ways) --> Ejb(deployment-id=CalculatorImplEncrypt2ways)\n INFO - Jndi(name=CalculatorImplSign2waysRemote) --> Ejb(deployment-id=CalculatorImplSign2ways)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplSign2ways!org.superbiz.calculator.CalculatorRemote) --> Ejb(deployment-id=CalculatorImplSign2ways)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplSign2ways) --> Ejb(deployment-id=CalculatorImplSign2ways)\n INFO - Jndi(name=CalculatorImplEncryptAndSign2waysRemote) --> Ejb(deployment-id=CalculatorImplEncryptAndSign2ways)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplEncryptAndSign2ways!org.superbiz.calculator.CalculatorRemote) --> Ejb(deployment-id=CalculatorImplEncryptAndSign2ways)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplEncryptAndSign2ways) --> Ejb(deployment-id=CalculatorImplEncryptAndSign2ways)\n INFO - Jndi(name=CalculatorImplRemote) --> Ejb(deployment-id=CalculatorImpl)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImpl!org.superbiz.calculator.CalculatorRemote) --> Ejb(deployment-id=CalculatorImpl)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImpl) --> Ejb(deployment-id=CalculatorImpl)\n INFO - Created Ejb(deployment-id=CalculatorImplUsernameTokenHashedPassword, ejb-name=CalculatorImplUsernameTokenHashedPassword, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=CalculatorImpl, ejb-name=CalculatorImpl, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=CalculatorImplSign, ejb-name=CalculatorImplSign, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=CalculatorImplEncryptAndSign2ways, ejb-name=CalculatorImplEncryptAndSign2ways, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=CalculatorImplTimestamp1way, ejb-name=CalculatorImplTimestamp1way, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=CalculatorImplSign2ways, ejb-name=CalculatorImplSign2ways, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=CalculatorImplEncrypt2ways, ejb-name=CalculatorImplEncrypt2ways, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=CalculatorImplUsernameTokenPlainPassword, ejb-name=CalculatorImplUsernameTokenPlainPassword, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=CalculatorImplTimestamp2ways, ejb-name=CalculatorImplTimestamp2ways, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=CalculatorImplUsernameTokenPlainPasswordEncrypt, ejb-name=CalculatorImplUsernameTokenPlainPasswordEncrypt, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=CalculatorImplUsernameTokenHashedPassword, ejb-name=CalculatorImplUsernameTokenHashedPassword, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=CalculatorImpl, ejb-name=CalculatorImpl, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=CalculatorImplSign, ejb-name=CalculatorImplSign, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=CalculatorImplEncryptAndSign2ways, ejb-name=CalculatorImplEncryptAndSign2ways, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=CalculatorImplTimestamp1way, ejb-name=CalculatorImplTimestamp1way, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=CalculatorImplSign2ways, ejb-name=CalculatorImplSign2ways, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=CalculatorImplEncrypt2ways, ejb-name=CalculatorImplEncrypt2ways, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=CalculatorImplUsernameTokenPlainPassword, ejb-name=CalculatorImplUsernameTokenPlainPassword, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=CalculatorImplTimestamp2ways, ejb-name=CalculatorImplTimestamp2ways, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=CalculatorImplUsernameTokenPlainPasswordEncrypt, ejb-name=CalculatorImplUsernameTokenPlainPasswordEncrypt, container=Default Stateless Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/webservice-ws-security/classpath.ear)\n INFO - Initializing network services\n INFO - Creating ServerService(id=httpejbd)\n INFO - Creating ServerService(id=cxf)\n INFO - Creating ServerService(id=admin)\n INFO - Creating ServerService(id=ejbd)\n INFO - Creating ServerService(id=ejbds)\n INFO - Initializing network services\n ** Starting Services **\n NAME IP PORT \n httpejbd 127.0.0.1 4204 \n admin thread 127.0.0.1 4200 \n ejbd 127.0.0.1 4201 \n ejbd 127.0.0.1 4203 \n -------\n Ready!\n Tests run: 7, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 4.582 sec\n \n Results :\n \n Tests run: 7, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/webservice-ws-security"
},
{
"name":"simple-webservice",
"readme":"Title: JAX-WS @WebService example\n\nCreating Web Services with JAX-WS is quite easy. Little has to be done aside from annotating a class with `@WebService`. For\nthe purposes of this example we will also annotate our component with `@Stateless` which takes some of the configuration out of\nthe process and gives us some nice options such as transactions and security.\n\n## @WebService\n\nThe following is all that is required. No external xml files are needed. This class placed in a jar or war and deployed into a compliant Java EE server like TomEE is enough to have the Calculator class discovered and deployed and the webservice online.\n\n import javax.ejb.Stateless;\n import javax.jws.WebService;\n\n @Stateless\n @WebService(\n portName = \"CalculatorPort\",\n serviceName = \"CalculatorService\",\n targetNamespace = \"http://superbiz.org/wsdl\",\n endpointInterface = \"org.superbiz.calculator.ws.CalculatorWs\")\n public class Calculator implements CalculatorWs {\n\n public int sum(int add1, int add2) {\n return add1 + add2;\n }\n\n public int multiply(int mul1, int mul2) {\n return mul1 * mul2;\n }\n }\n\n## @WebService Endpoint Interface\n\nHaving an endpoint interface is not required, but it can make testing and using the web service from other Java clients far easier.\n\n import javax.jws.WebService;\n \n @WebService(targetNamespace = \"http://superbiz.org/wsdl\")\n public interface CalculatorWs {\n \n public int sum(int add1, int add2);\n \n public int multiply(int mul1, int mul2);\n }\n\n## Calculator WSDL\n\nThe wsdl for our service is autmatically created for us and available at `http://127.0.0.1:4204/Calculator?wsdl`. In TomEE or Tomcat this would be at `http://127.0.0.1:8080/simple-webservice/Calculator?wsdl`\n\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <wsdl:definitions xmlns:wsdl=\"http://schemas.xmlsoap.org/wsdl/\" name=\"CalculatorService\"\n targetNamespace=\"http://superbiz.org/wsdl\"\n xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\"\n xmlns:tns=\"http://superbiz.org/wsdl\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n <wsdl:types>\n <xsd:schema attributeFormDefault=\"unqualified\" elementFormDefault=\"unqualified\"\n targetNamespace=\"http://superbiz.org/wsdl\" xmlns:tns=\"http://superbiz.org/wsdl\"\n xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n <xsd:element name=\"multiply\" type=\"tns:multiply\"/>\n <xsd:complexType name=\"multiply\">\n <xsd:sequence>\n <xsd:element name=\"arg0\" type=\"xsd:int\"/>\n <xsd:element name=\"arg1\" type=\"xsd:int\"/>\n </xsd:sequence>\n </xsd:complexType>\n <xsd:element name=\"multiplyResponse\" type=\"tns:multiplyResponse\"/>\n <xsd:complexType name=\"multiplyResponse\">\n <xsd:sequence>\n <xsd:element name=\"return\" type=\"xsd:int\"/>\n </xsd:sequence>\n </xsd:complexType>\n <xsd:element name=\"sum\" type=\"tns:sum\"/>\n <xsd:complexType name=\"sum\">\n <xsd:sequence>\n <xsd:element name=\"arg0\" type=\"xsd:int\"/>\n <xsd:element name=\"arg1\" type=\"xsd:int\"/>\n </xsd:sequence>\n </xsd:complexType>\n <xsd:element name=\"sumResponse\" type=\"tns:sumResponse\"/>\n <xsd:complexType name=\"sumResponse\">\n <xsd:sequence>\n <xsd:element name=\"return\" type=\"xsd:int\"/>\n </xsd:sequence>\n </xsd:complexType>\n </xsd:schema>\n </wsdl:types>\n <wsdl:message name=\"multiplyResponse\">\n <wsdl:part element=\"tns:multiplyResponse\" name=\"parameters\"/>\n </wsdl:message>\n <wsdl:message name=\"sumResponse\">\n <wsdl:part element=\"tns:sumResponse\" name=\"parameters\"/>\n </wsdl:message>\n <wsdl:message name=\"sum\">\n <wsdl:part element=\"tns:sum\" name=\"parameters\"/>\n </wsdl:message>\n <wsdl:message name=\"multiply\">\n <wsdl:part element=\"tns:multiply\" name=\"parameters\"/>\n </wsdl:message>\n <wsdl:portType name=\"CalculatorWs\">\n <wsdl:operation name=\"multiply\">\n <wsdl:input message=\"tns:multiply\" name=\"multiply\"/>\n <wsdl:output message=\"tns:multiplyResponse\" name=\"multiplyResponse\"/>\n </wsdl:operation>\n <wsdl:operation name=\"sum\">\n <wsdl:input message=\"tns:sum\" name=\"sum\"/>\n <wsdl:output message=\"tns:sumResponse\" name=\"sumResponse\"/>\n </wsdl:operation>\n </wsdl:portType>\n <wsdl:binding name=\"CalculatorServiceSoapBinding\" type=\"tns:CalculatorWs\">\n <soap:binding style=\"document\" transport=\"http://schemas.xmlsoap.org/soap/http\"/>\n <wsdl:operation name=\"multiply\">\n <soap:operation soapAction=\"\" style=\"document\"/>\n <wsdl:input name=\"multiply\">\n <soap:body use=\"literal\"/>\n </wsdl:input>\n <wsdl:output name=\"multiplyResponse\">\n <soap:body use=\"literal\"/>\n </wsdl:output>\n </wsdl:operation>\n <wsdl:operation name=\"sum\">\n <soap:operation soapAction=\"\" style=\"document\"/>\n <wsdl:input name=\"sum\">\n <soap:body use=\"literal\"/>\n </wsdl:input>\n <wsdl:output name=\"sumResponse\">\n <soap:body use=\"literal\"/>\n </wsdl:output>\n </wsdl:operation>\n </wsdl:binding>\n <wsdl:service name=\"CalculatorService\">\n <wsdl:port binding=\"tns:CalculatorServiceSoapBinding\" name=\"CalculatorPort\">\n <soap:address location=\"http://127.0.0.1:4204/Calculator?wsdl\"/>\n </wsdl:port>\n </wsdl:service>\n </wsdl:definitions>\n\n## Accessing the @WebService with javax.xml.ws.Service\n\nIn our testcase we see how to create a client for our `Calculator` service via the `javax.xml.ws.Service` class and leveraging our `CalculatorWs` endpoint interface.\n\nWith this we can get an implementation of the interfacce generated dynamically for us that can be used to send compliant SOAP messages to our service.\n\n import org.junit.BeforeClass;\n import org.junit.Test;\n \n import javax.ejb.embeddable.EJBContainer;\n import javax.xml.namespace.QName;\n import javax.xml.ws.Service;\n import java.net.URL;\n import java.util.Properties;\n \n import static org.junit.Assert.assertEquals;\n import static org.junit.Assert.assertNotNull;\n \n public class CalculatorTest {\n \n @BeforeClass\n public static void setUp() throws Exception {\n Properties properties = new Properties();\n properties.setProperty(\"openejb.embedded.remotable\", \"true\");\n //properties.setProperty(\"httpejbd.print\", \"true\");\n //properties.setProperty(\"httpejbd.indent.xml\", \"true\");\n EJBContainer.createEJBContainer(properties);\n }\n \n @Test\n public void test() throws Exception {\n Service calculatorService = Service.create(\n new URL(\"http://127.0.0.1:4204/Calculator?wsdl\"),\n new QName(\"http://superbiz.org/wsdl\", \"CalculatorService\"));\n \n assertNotNull(calculatorService);\n \n CalculatorWs calculator = calculatorService.getPort(CalculatorWs.class);\n assertEquals(10, calculator.sum(4, 6));\n assertEquals(12, calculator.multiply(3, 4));\n }\n }\n\nFor easy testing we'll use the Embeddable EJBContainer API part of EJB 3.1 to boot CXF in our testcase. This will deploy our application in the embedded container and bring the web service online so we can invoke it.\n\n# Running\n\nRunning the example can be done from maven with a simple 'mvn clean install' command run from the 'simple-webservice' directory.\n\nWhen run you should see output similar to the following.\n\n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.calculator.ws.CalculatorTest\n INFO - ********************************************************************************\n INFO - OpenEJB http://tomee.apache.org/\n INFO - Startup: Sat Feb 18 19:11:50 PST 2012\n INFO - Copyright 1999-2012 (C) Apache OpenEJB Project, All Rights Reserved.\n INFO - Version: 4.0.0-beta-3\n INFO - Build date: 20120218\n INFO - Build time: 03:32\n INFO - ********************************************************************************\n INFO - openejb.home = /Users/dblevins/work/all/trunk/openejb/examples/simple-webservice\n INFO - openejb.base = /Users/dblevins/work/all/trunk/openejb/examples/simple-webservice\n INFO - Created new singletonService org.apache.openejb.cdi.ThreadSingletonServiceImpl@16bdb503\n INFO - succeeded in installing singleton service\n INFO - Using 'javax.ejb.embeddable.EJBContainer=true'\n INFO - Cannot find the configuration file [conf/openejb.xml]. Will attempt to create one for the beans deployed.\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Creating TransactionManager(id=Default Transaction Manager)\n INFO - Creating SecurityService(id=Default Security Service)\n INFO - Beginning load: /Users/dblevins/work/all/trunk/openejb/examples/simple-webservice/target/classes\n INFO - Using 'openejb.embedded=true'\n INFO - Configuring enterprise application: /Users/dblevins/work/all/trunk/openejb/examples/simple-webservice\n INFO - Auto-deploying ejb Calculator: EjbDeployment(deployment-id=Calculator)\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean Calculator: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Creating Container(id=Default Stateless Container)\n INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)\n INFO - Auto-creating a container for bean org.superbiz.calculator.ws.CalculatorTest: Container(type=MANAGED, id=Default Managed Container)\n INFO - Creating Container(id=Default Managed Container)\n INFO - Using directory /var/folders/bd/f9ntqy1m8xj_fs006s6crtjh0000gn/T for stateful session passivation\n INFO - Enterprise application \"/Users/dblevins/work/all/trunk/openejb/examples/simple-webservice\" loaded.\n INFO - Assembling app: /Users/dblevins/work/all/trunk/openejb/examples/simple-webservice\n INFO - ignoreXmlConfiguration == true\n INFO - ignoreXmlConfiguration == true\n INFO - existing thread singleton service in SystemInstance() org.apache.openejb.cdi.ThreadSingletonServiceImpl@16bdb503\n INFO - OpenWebBeans Container is starting...\n INFO - Adding OpenWebBeansPlugin : [CdiPlugin]\n INFO - All injection points were validated successfully.\n INFO - OpenWebBeans Container has started, it took [62] ms.\n INFO - Created Ejb(deployment-id=Calculator, ejb-name=Calculator, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=Calculator, ejb-name=Calculator, container=Default Stateless Container)\n INFO - Deployed Application(path=/Users/dblevins/work/all/trunk/openejb/examples/simple-webservice)\n INFO - Initializing network services\n INFO - can't find log4j MDC class\n INFO - Creating ServerService(id=httpejbd)\n INFO - Creating ServerService(id=cxf)\n INFO - Creating ServerService(id=admin)\n INFO - Creating ServerService(id=ejbd)\n INFO - Creating ServerService(id=ejbds)\n INFO - Initializing network services\n INFO - ** Starting Services **\n INFO - NAME IP PORT\n INFO - httpejbd 127.0.0.1 4204\n INFO - Creating Service {http://superbiz.org/wsdl}CalculatorService from class org.superbiz.calculator.ws.CalculatorWs\n INFO - Setting the server's publish address to be http://nopath:80\n INFO - Webservice(wsdl=http://127.0.0.1:4204/Calculator, qname={http://superbiz.org/wsdl}CalculatorService) --> Ejb(id=Calculator)\n INFO - admin thread 127.0.0.1 4200\n INFO - ejbd 127.0.0.1 4201\n INFO - ejbd 127.0.0.1 4203\n INFO - -------\n INFO - Ready!\n INFO - Creating Service {http://superbiz.org/wsdl}CalculatorService from WSDL: http://127.0.0.1:4204/Calculator?wsdl\n INFO - Creating Service {http://superbiz.org/wsdl}CalculatorService from WSDL: http://127.0.0.1:4204/Calculator?wsdl\n INFO - Default SAAJ universe not set\n INFO - TX NotSupported: Suspended transaction null\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.584 sec\n\n Results :\n\n Tests run: 1, Failures: 0, Errors: 0, Skipped: 0\n\n## Inspecting the messages\n\nThe above test case will result in the following SOAP messages being sent between the clien and server.\n\n### sum(int, int)\n\nRequest SOAP message:\n\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <soap:Body>\n <ns1:sum xmlns:ns1=\"http://superbiz.org/wsdl\">\n <arg0>4</arg0>\n <arg1>6</arg1>\n </ns1:sum>\n </soap:Body>\n </soap:Envelope>\n\nResponse SOAP message:\n\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <soap:Body>\n <ns1:sumResponse xmlns:ns1=\"http://superbiz.org/wsdl\">\n <return>10</return>\n </ns1:sumResponse>\n </soap:Body>\n </soap:Envelope>\n\n### multiply(int, int)\n\nRequest SOAP message:\n\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <soap:Body>\n <ns1:multiply xmlns:ns1=\"http://superbiz.org/wsdl\">\n <arg0>3</arg0>\n <arg1>4</arg1>\n </ns1:multiply>\n </soap:Body>\n </soap:Envelope>\n\nResponse SOAP message:\n\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <soap:Body>\n <ns1:multiplyResponse xmlns:ns1=\"http://superbiz.org/wsdl\">\n <return>12</return>\n </ns1:multiplyResponse>\n </soap:Body>\n </soap:Envelope>\n\n## Inside the jar\n\nWith so much going on it can make things look more complex than they are. It can be hard to believe that so much can happen with such little code. That's the benefit of having an app server.\n\nIf we look at the jar built by maven, we'll see the application itself is quite small:\n\n $ jar tvf target/simple-webservice-1.1.0-SNAPSHOT.jar\n 0 Sat Feb 18 19:17:06 PST 2012 META-INF/\n 127 Sat Feb 18 19:17:04 PST 2012 META-INF/MANIFEST.MF\n 0 Sat Feb 18 19:17:02 PST 2012 org/\n 0 Sat Feb 18 19:17:02 PST 2012 org/superbiz/\n 0 Sat Feb 18 19:17:02 PST 2012 org/superbiz/calculator/\n 0 Sat Feb 18 19:17:02 PST 2012 org/superbiz/calculator/ws/\n 855 Sat Feb 18 19:17:02 PST 2012 org/superbiz/calculator/ws/Calculator.class\n 288 Sat Feb 18 19:17:02 PST 2012 org/superbiz/calculator/ws/CalculatorWs.class\n\nThis single jar could be deployed any any compliant Java EE implementation. In TomEE you'd simply place it in the `tomee.home/webapps/` directory. No war file necessary. If you did want to create a war, you'd simply place the jar in the `WEB-INF/lib/` directory of the war.\n\nThe server already contains the right libraries to run the code, such as Apache CXF, so no need to include anything extra beyond your own application code.\n\n",
"url":"https://github.com/apache/tomee/tree/master/examples/simple-webservice"
},
{
"name":"ejb-webservice",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/ejb-webservice"
},
{
"name":"webservice-ws-with-resources-config",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/webservice-ws-with-resources-config"
},
{
"name":"pojo-webservice",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/pojo-webservice"
}
],
"without":[
{
"name":"simple-webservice-without-interface",
"readme":"Title: Simple Webservice Without Interface\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## Calculator\n\n package org.superbiz.calculator;\n \n import javax.ejb.Stateless;\n import javax.jws.WebService;\n \n @Stateless\n @WebService(\n portName = \"CalculatorPort\",\n serviceName = \"CalculatorWsService\",\n targetNamespace = \"http://superbiz.org/wsdl\")\n public class Calculator {\n public int sum(int add1, int add2) {\n return add1 + add2;\n }\n \n public int multiply(int mul1, int mul2) {\n return mul1 * mul2;\n }\n }\n\n## ejb-jar.xml\n\n <ejb-jar/>\n\n## CalculatorTest\n\n package org.superbiz.calculator;\n \n import org.apache.commons.io.IOUtils;\n import org.junit.AfterClass;\n import org.junit.Before;\n import org.junit.BeforeClass;\n import org.junit.Test;\n \n import javax.ejb.embeddable.EJBContainer;\n import javax.naming.NamingException;\n import java.net.URL;\n import java.util.Properties;\n \n import static org.junit.Assert.assertTrue;\n \n public class CalculatorTest {\n private static EJBContainer container;\n \n @BeforeClass\n public static void setUp() throws Exception {\n final Properties properties = new Properties();\n properties.setProperty(\"openejb.embedded.remotable\", \"true\");\n \n container = EJBContainer.createEJBContainer(properties);\n }\n \n @Before\n public void inject() throws NamingException {\n if (container != null) {\n container.getContext().bind(\"inject\", this);\n }\n }\n \n @AfterClass\n public static void close() {\n if (container != null) {\n container.close();\n }\n }\n \n @Test\n public void wsdlExists() throws Exception {\n final URL url = new URL(\"http://127.0.0.1:4204/Calculator?wsdl\");\n assertTrue(IOUtils.readLines(url.openStream()).size() > 0);\n assertTrue(IOUtils.readLines(url.openStream()).toString().contains(\"CalculatorWsService\"));\n }\n }\n\n## ejb-jar.xml\n\n <ejb-jar/>\n",
"url":"https://github.com/apache/tomee/tree/master/examples/simple-webservice-without-interface"
}
],
"ws":[
{
"name":"webservice-ws-security",
"readme":"Title: Webservice Ws Security\n\n*Help us document this example! Click the blue pencil icon in the upper right to edit this page.*\n\n## CalculatorImpl\n\n package org.superbiz.calculator;\n \n import javax.annotation.security.DeclareRoles;\n import javax.annotation.security.RolesAllowed;\n import javax.ejb.Stateless;\n import javax.jws.WebService;\n \n /**\n * This is an EJB 3 style pojo stateless session bean\n * Every stateless session bean implementation must be annotated\n * using the annotation @Stateless\n * This EJB has a single interface: CalculatorWs a webservice interface.\n */\n //START SNIPPET: code\n @DeclareRoles(value = {\"Administrator\"})\n @Stateless\n @WebService(\n portName = \"CalculatorPort\",\n serviceName = \"CalculatorWsService\",\n targetNamespace = \"http://superbiz.org/wsdl\",\n endpointInterface = \"org.superbiz.calculator.CalculatorWs\")\n public class CalculatorImpl implements CalculatorWs, CalculatorRemote {\n \n @RolesAllowed(value = {\"Administrator\"})\n public int sum(int add1, int add2) {\n return add1 + add2;\n }\n \n public int multiply(int mul1, int mul2) {\n return mul1 * mul2;\n }\n }\n\n## CalculatorRemote\n\n package org.superbiz.calculator;\n \n import javax.ejb.Remote;\n \n @Remote\n public interface CalculatorRemote {\n \n public int sum(int add1, int add2);\n \n public int multiply(int mul1, int mul2);\n }\n\n## CalculatorWs\n\n package org.superbiz.calculator;\n \n import javax.jws.WebService;\n \n //END SNIPPET: code\n \n /**\n * This is an EJB 3 webservice interface\n * A webservice interface must be annotated with the @Local\n * annotation.\n */\n //START SNIPPET: code\n @WebService(targetNamespace = \"http://superbiz.org/wsdl\")\n public interface CalculatorWs {\n \n public int sum(int add1, int add2);\n \n public int multiply(int mul1, int mul2);\n }\n\n## ejb-jar.xml\n\n <ejb-jar xmlns=\"http://java.sun.com/xml/ns/javaee\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd\"\n version=\"3.0\" id=\"simple\" metadata-complete=\"false\">\n \n <enterprise-beans>\n \n <session>\n <ejb-name>CalculatorImplTimestamp1way</ejb-name>\n <service-endpoint>org.superbiz.calculator.CalculatorWs</service-endpoint>\n <ejb-class>org.superbiz.calculator.CalculatorImpl</ejb-class>\n <session-type>Stateless</session-type>\n <transaction-type>Container</transaction-type>\n </session>\n \n <session>\n <ejb-name>CalculatorImplTimestamp2ways</ejb-name>\n <service-endpoint>org.superbiz.calculator.CalculatorWs</service-endpoint>\n <ejb-class>org.superbiz.calculator.CalculatorImpl</ejb-class>\n <session-type>Stateless</session-type>\n <transaction-type>Container</transaction-type>\n </session>\n \n <session>\n <ejb-name>CalculatorImplUsernameTokenPlainPassword</ejb-name>\n <service-endpoint>org.superbiz.calculator.CalculatorWs</service-endpoint>\n <ejb-class>org.superbiz.calculator.CalculatorImpl</ejb-class>\n <session-type>Stateless</session-type>\n <transaction-type>Container</transaction-type>\n </session>\n \n <session>\n <ejb-name>CalculatorImplUsernameTokenHashedPassword</ejb-name>\n <service-endpoint>org.superbiz.calculator.CalculatorWs</service-endpoint>\n <ejb-class>org.superbiz.calculator.CalculatorImpl</ejb-class>\n <session-type>Stateless</session-type>\n <transaction-type>Container</transaction-type>\n </session>\n \n <session>\n <ejb-name>CalculatorImplUsernameTokenPlainPasswordEncrypt</ejb-name>\n <service-endpoint>org.superbiz.calculator.CalculatorWs</service-endpoint>\n <ejb-class>org.superbiz.calculator.CalculatorImpl</ejb-class>\n <session-type>Stateless</session-type>\n <transaction-type>Container</transaction-type>\n </session>\n \n <session>\n <ejb-name>CalculatorImplSign</ejb-name>\n <service-endpoint>org.superbiz.calculator.CalculatorWs</service-endpoint>\n <ejb-class>org.superbiz.calculator.CalculatorImpl</ejb-class>\n <session-type>Stateless</session-type>\n <transaction-type>Container</transaction-type>\n </session>\n \n <session>\n <ejb-name>CalculatorImplEncrypt2ways</ejb-name>\n <service-endpoint>org.superbiz.calculator.CalculatorWs</service-endpoint>\n <ejb-class>org.superbiz.calculator.CalculatorImpl</ejb-class>\n <session-type>Stateless</session-type>\n <transaction-type>Container</transaction-type>\n </session>\n \n <session>\n <ejb-name>CalculatorImplSign2ways</ejb-name>\n <service-endpoint>org.superbiz.calculator.CalculatorWs</service-endpoint>\n <ejb-class>org.superbiz.calculator.CalculatorImpl</ejb-class>\n <session-type>Stateless</session-type>\n <transaction-type>Container</transaction-type>\n </session>\n \n <session>\n <ejb-name>CalculatorImplEncryptAndSign2ways</ejb-name>\n <service-endpoint>org.superbiz.calculator.CalculatorWs</service-endpoint>\n <ejb-class>org.superbiz.calculator.CalculatorImpl</ejb-class>\n <session-type>Stateless</session-type>\n <transaction-type>Container</transaction-type>\n </session>\n \n </enterprise-beans>\n \n </ejb-jar>\n \n\n## openejb-jar.xml\n\n <openejb-jar xmlns=\"http://www.openejb.org/openejb-jar/1.1\">\n \n <ejb-deployment ejb-name=\"CalculatorImpl\">\n <properties>\n # webservice.security.realm\n # webservice.security.securityRealm\n # webservice.security.transportGarantee = NONE\n webservice.security.authMethod = WS-SECURITY\n wss4j.in.action = UsernameToken\n wss4j.in.passwordType = PasswordText\n wss4j.in.passwordCallbackClass = org.superbiz.calculator.CustomPasswordHandler\n \n # automatically added\n wss4j.in.validator.{http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd}UsernameToken = org.apache.openejb.server.cxf.OpenEJBLoginValidator\n </properties>\n </ejb-deployment>\n <ejb-deployment ejb-name=\"CalculatorImplTimestamp1way\">\n <properties>\n webservice.security.authMethod = WS-SECURITY\n wss4j.in.action = Timestamp\n </properties>\n </ejb-deployment>\n <ejb-deployment ejb-name=\"CalculatorImplTimestamp2ways\">\n <properties>\n webservice.security.authMethod = WS-SECURITY\n wss4j.in.action = Timestamp\n wss4j.out.action = Timestamp\n </properties>\n </ejb-deployment>\n <ejb-deployment ejb-name=\"CalculatorImplUsernameTokenPlainPassword\">\n <properties>\n webservice.security.authMethod = WS-SECURITY\n wss4j.in.action = UsernameToken\n wss4j.in.passwordType = PasswordText\n wss4j.in.passwordCallbackClass=org.superbiz.calculator.CustomPasswordHandler\n </properties>\n </ejb-deployment>\n <ejb-deployment ejb-name=\"CalculatorImplUsernameTokenHashedPassword\">\n <properties>\n webservice.security.authMethod = WS-SECURITY\n wss4j.in.action = UsernameToken\n wss4j.in.passwordType = PasswordDigest\n wss4j.in.passwordCallbackClass=org.superbiz.calculator.CustomPasswordHandler\n </properties>\n </ejb-deployment>\n <ejb-deployment ejb-name=\"CalculatorImplUsernameTokenPlainPasswordEncrypt\">\n <properties>\n webservice.security.authMethod = WS-SECURITY\n wss4j.in.action = UsernameToken Encrypt\n wss4j.in.passwordType = PasswordText\n wss4j.in.passwordCallbackClass=org.superbiz.calculator.CustomPasswordHandler\n wss4j.in.decryptionPropFile = META-INF/CalculatorImplUsernameTokenPlainPasswordEncrypt-server.properties\n </properties>\n </ejb-deployment>\n <ejb-deployment ejb-name=\"CalculatorImplSign\">\n <properties>\n webservice.security.authMethod = WS-SECURITY\n wss4j.in.action = Signature\n wss4j.in.passwordCallbackClass=org.superbiz.calculator.CustomPasswordHandler\n wss4j.in.signaturePropFile = META-INF/CalculatorImplSign-server.properties\n </properties>\n </ejb-deployment>\n \n </openejb-jar>\n \n\n## webservices.xml\n\n <webservices xmlns=\"http://java.sun.com/xml/ns/j2ee\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/j2ee\n http://www.ibm.com/webservices/xsd/j2ee_web_services_1_1.xsd\"\n xmlns:ger=\"http://ciaows.org/wsdl\" version=\"1.1\">\n \n <webservice-description>\n <webservice-description-name>CalculatorWsService</webservice-description-name>\n <port-component>\n <port-component-name>CalculatorImplTimestamp1way</port-component-name>\n <wsdl-port>CalculatorImplTimestamp1way</wsdl-port>\n <service-endpoint-interface>org.superbiz.calculator.CalculatorWs</service-endpoint-interface>\n <service-impl-bean>\n <ejb-link>CalculatorImplTimestamp1way</ejb-link>\n </service-impl-bean>\n </port-component>\n <port-component>\n <port-component-name>CalculatorImplTimestamp2ways</port-component-name>\n <wsdl-port>CalculatorImplTimestamp2ways</wsdl-port>\n <service-endpoint-interface>org.superbiz.calculator.CalculatorWs</service-endpoint-interface>\n <service-impl-bean>\n <ejb-link>CalculatorImplTimestamp2ways</ejb-link>\n </service-impl-bean>\n </port-component>\n <port-component>\n <port-component-name>CalculatorImplUsernameTokenPlainPassword</port-component-name>\n <wsdl-port>CalculatorImplUsernameTokenPlainPassword</wsdl-port>\n <service-endpoint-interface>org.superbiz.calculator.CalculatorWs</service-endpoint-interface>\n <service-impl-bean>\n <ejb-link>CalculatorImplUsernameTokenPlainPassword</ejb-link>\n </service-impl-bean>\n </port-component>\n <port-component>\n <port-component-name>CalculatorImplUsernameTokenHashedPassword</port-component-name>\n <wsdl-port>CalculatorImplUsernameTokenHashedPassword</wsdl-port>\n <service-endpoint-interface>org.superbiz.calculator.CalculatorWs</service-endpoint-interface>\n <service-impl-bean>\n <ejb-link>CalculatorImplUsernameTokenHashedPassword</ejb-link>\n </service-impl-bean>\n </port-component>\n <port-component>\n <port-component-name>CalculatorImplUsernameTokenPlainPasswordEncrypt</port-component-name>\n <wsdl-port>CalculatorImplUsernameTokenPlainPasswordEncrypt</wsdl-port>\n <service-endpoint-interface>org.superbiz.calculator.CalculatorWs</service-endpoint-interface>\n <service-impl-bean>\n <ejb-link>CalculatorImplUsernameTokenPlainPasswordEncrypt</ejb-link>\n </service-impl-bean>\n </port-component>\n </webservice-description>\n \n </webservices>\n \n\n## CalculatorTest\n\n package org.superbiz.calculator;\n \n import junit.framework.TestCase;\n import org.apache.cxf.binding.soap.saaj.SAAJInInterceptor;\n import org.apache.cxf.binding.soap.saaj.SAAJOutInterceptor;\n import org.apache.cxf.endpoint.Client;\n import org.apache.cxf.endpoint.Endpoint;\n import org.apache.cxf.frontend.ClientProxy;\n import org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor;\n import org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor;\n import org.apache.ws.security.WSConstants;\n import org.apache.ws.security.WSPasswordCallback;\n import org.apache.ws.security.handler.WSHandlerConstants;\n \n import javax.naming.Context;\n import javax.naming.InitialContext;\n import javax.security.auth.callback.Callback;\n import javax.security.auth.callback.CallbackHandler;\n import javax.security.auth.callback.UnsupportedCallbackException;\n import javax.xml.namespace.QName;\n import javax.xml.ws.Service;\n import javax.xml.ws.soap.SOAPBinding;\n import java.io.IOException;\n import java.net.URL;\n import java.util.HashMap;\n import java.util.Map;\n import java.util.Properties;\n \n public class CalculatorTest extends TestCase {\n \n //START SNIPPET: setup\n protected void setUp() throws Exception {\n Properties properties = new Properties();\n properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, \"org.apache.openejb.core.LocalInitialContextFactory\");\n properties.setProperty(\"openejb.embedded.remotable\", \"true\");\n \n new InitialContext(properties);\n }\n //END SNIPPET: setup\n \n //START SNIPPET: webservice\n public void testCalculatorViaWsInterface() throws Exception {\n Service calcService = Service.create(new URL(\"http://127.0.0.1:4204/CalculatorImpl?wsdl\"),\n new QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService\"));\n assertNotNull(calcService);\n \n CalculatorWs calc = calcService.getPort(CalculatorWs.class);\n \n Client client = ClientProxy.getClient(calc);\n Endpoint endpoint = client.getEndpoint();\n endpoint.getOutInterceptors().add(new SAAJOutInterceptor());\n \n Map<String, Object> outProps = new HashMap<String, Object>();\n outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);\n outProps.put(WSHandlerConstants.USER, \"jane\");\n outProps.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT);\n outProps.put(WSHandlerConstants.PW_CALLBACK_REF, new CallbackHandler() {\n \n public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {\n WSPasswordCallback pc = (WSPasswordCallback) callbacks[0];\n pc.setPassword(\"waterfall\");\n }\n });\n \n WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps);\n endpoint.getOutInterceptors().add(wssOut);\n \n assertEquals(10, calc.sum(4, 6));\n }\n \n public void testCalculatorViaWsInterfaceWithTimestamp1way() throws Exception {\n Service calcService = Service.create(new URL(\"http://127.0.0.1:4204/CalculatorImplTimestamp1way?wsdl\"),\n new QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService\"));\n assertNotNull(calcService);\n \n // for debugging (ie. TCPMon)\n calcService.addPort(new QName(\"http://superbiz.org/wsdl\",\n \"CalculatorWsService2\"), SOAPBinding.SOAP12HTTP_BINDING,\n \"http://127.0.0.1:8204/CalculatorImplTimestamp1way\");\n \n // CalculatorWs calc = calcService.getPort(\n // \tnew QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService2\"),\n //\t\tCalculatorWs.class);\n \n CalculatorWs calc = calcService.getPort(CalculatorWs.class);\n \n Client client = ClientProxy.getClient(calc);\n Endpoint endpoint = client.getEndpoint();\n endpoint.getOutInterceptors().add(new SAAJOutInterceptor());\n \n Map<String, Object> outProps = new HashMap<String, Object>();\n outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.TIMESTAMP);\n WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps);\n endpoint.getOutInterceptors().add(wssOut);\n \n assertEquals(12, calc.multiply(3, 4));\n }\n \n public void testCalculatorViaWsInterfaceWithTimestamp2ways() throws Exception {\n Service calcService = Service.create(new URL(\"http://127.0.0.1:4204/CalculatorImplTimestamp2ways?wsdl\"),\n new QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService\"));\n assertNotNull(calcService);\n \n // for debugging (ie. TCPMon)\n calcService.addPort(new QName(\"http://superbiz.org/wsdl\",\n \"CalculatorWsService2\"), SOAPBinding.SOAP12HTTP_BINDING,\n \"http://127.0.0.1:8204/CalculatorImplTimestamp2ways\");\n \n // CalculatorWs calc = calcService.getPort(\n // \tnew QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService2\"),\n //\t\tCalculatorWs.class);\n \n CalculatorWs calc = calcService.getPort(CalculatorWs.class);\n \n Client client = ClientProxy.getClient(calc);\n Endpoint endpoint = client.getEndpoint();\n endpoint.getOutInterceptors().add(new SAAJOutInterceptor());\n endpoint.getInInterceptors().add(new SAAJInInterceptor());\n \n Map<String, Object> outProps = new HashMap<String, Object>();\n outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.TIMESTAMP);\n WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps);\n endpoint.getOutInterceptors().add(wssOut);\n \n Map<String, Object> inProps = new HashMap<String, Object>();\n inProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.TIMESTAMP);\n WSS4JInInterceptor wssIn = new WSS4JInInterceptor(inProps);\n endpoint.getInInterceptors().add(wssIn);\n \n assertEquals(12, calc.multiply(3, 4));\n }\n \n public void testCalculatorViaWsInterfaceWithUsernameTokenPlainPassword() throws Exception {\n Service calcService = Service.create(new URL(\"http://127.0.0.1:4204/CalculatorImplUsernameTokenPlainPassword?wsdl\"),\n new QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService\"));\n assertNotNull(calcService);\n \n // for debugging (ie. TCPMon)\n calcService.addPort(new QName(\"http://superbiz.org/wsdl\",\n \"CalculatorWsService2\"), SOAPBinding.SOAP12HTTP_BINDING,\n \"http://127.0.0.1:8204/CalculatorImplUsernameTokenPlainPassword\");\n \n // CalculatorWs calc = calcService.getPort(\n // \tnew QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService2\"),\n // \tCalculatorWs.class);\n \n CalculatorWs calc = calcService.getPort(CalculatorWs.class);\n \n Client client = ClientProxy.getClient(calc);\n Endpoint endpoint = client.getEndpoint();\n endpoint.getOutInterceptors().add(new SAAJOutInterceptor());\n \n Map<String, Object> outProps = new HashMap<String, Object>();\n outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);\n outProps.put(WSHandlerConstants.USER, \"jane\");\n outProps.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT);\n outProps.put(WSHandlerConstants.PW_CALLBACK_REF, new CallbackHandler() {\n \n @Override\n public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {\n WSPasswordCallback pc = (WSPasswordCallback) callbacks[0];\n pc.setPassword(\"waterfall\");\n }\n });\n \n WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps);\n endpoint.getOutInterceptors().add(wssOut);\n \n assertEquals(10, calc.sum(4, 6));\n }\n \n public void testCalculatorViaWsInterfaceWithUsernameTokenHashedPassword() throws Exception {\n Service calcService = Service.create(new URL(\"http://127.0.0.1:4204/CalculatorImplUsernameTokenHashedPassword?wsdl\"),\n new QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService\"));\n assertNotNull(calcService);\n \n // for debugging (ie. TCPMon)\n calcService.addPort(new QName(\"http://superbiz.org/wsdl\",\n \"CalculatorWsService2\"), SOAPBinding.SOAP12HTTP_BINDING,\n \"http://127.0.0.1:8204/CalculatorImplUsernameTokenHashedPassword\");\n \n // CalculatorWs calc = calcService.getPort(\n // \tnew QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService2\"),\n // \tCalculatorWs.class);\n \n CalculatorWs calc = calcService.getPort(CalculatorWs.class);\n \n Client client = ClientProxy.getClient(calc);\n Endpoint endpoint = client.getEndpoint();\n endpoint.getOutInterceptors().add(new SAAJOutInterceptor());\n \n Map<String, Object> outProps = new HashMap<String, Object>();\n outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);\n outProps.put(WSHandlerConstants.USER, \"jane\");\n outProps.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_DIGEST);\n outProps.put(WSHandlerConstants.PW_CALLBACK_REF, new CallbackHandler() {\n \n @Override\n public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {\n WSPasswordCallback pc = (WSPasswordCallback) callbacks[0];\n pc.setPassword(\"waterfall\");\n }\n });\n \n WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps);\n endpoint.getOutInterceptors().add(wssOut);\n \n assertEquals(10, calc.sum(4, 6));\n }\n \n public void testCalculatorViaWsInterfaceWithUsernameTokenPlainPasswordEncrypt() throws Exception {\n Service calcService = Service.create(new URL(\"http://127.0.0.1:4204/CalculatorImplUsernameTokenPlainPasswordEncrypt?wsdl\"),\n new QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService\"));\n assertNotNull(calcService);\n \n // for debugging (ie. TCPMon)\n calcService.addPort(new QName(\"http://superbiz.org/wsdl\",\n \"CalculatorWsService2\"), SOAPBinding.SOAP12HTTP_BINDING,\n \"http://127.0.0.1:8204/CalculatorImplUsernameTokenPlainPasswordEncrypt\");\n \n // CalculatorWs calc = calcService.getPort(\n // \tnew QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService2\"),\n // \tCalculatorWs.class);\n \n CalculatorWs calc = calcService.getPort(CalculatorWs.class);\n \n Client client = ClientProxy.getClient(calc);\n Endpoint endpoint = client.getEndpoint();\n endpoint.getOutInterceptors().add(new SAAJOutInterceptor());\n \n Map<String, Object> outProps = new HashMap<String, Object>();\n outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN\n + \" \" + WSHandlerConstants.ENCRYPT);\n outProps.put(WSHandlerConstants.USER, \"jane\");\n outProps.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT);\n outProps.put(WSHandlerConstants.PW_CALLBACK_REF, new CallbackHandler() {\n \n @Override\n public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {\n WSPasswordCallback pc = (WSPasswordCallback) callbacks[0];\n pc.setPassword(\"waterfall\");\n }\n });\n outProps.put(WSHandlerConstants.ENC_PROP_FILE, \"META-INF/CalculatorImplUsernameTokenPlainPasswordEncrypt-client.properties\");\n outProps.put(WSHandlerConstants.ENCRYPTION_USER, \"serveralias\");\n \n WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps);\n endpoint.getOutInterceptors().add(wssOut);\n \n assertEquals(10, calc.sum(4, 6));\n }\n \n public void testCalculatorViaWsInterfaceWithSign() throws Exception {\n Service calcService = Service.create(new URL(\"http://127.0.0.1:4204/CalculatorImplSign?wsdl\"),\n new QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService\"));\n assertNotNull(calcService);\n \n // for debugging (ie. TCPMon)\n calcService.addPort(new QName(\"http://superbiz.org/wsdl\",\n \"CalculatorWsService2\"), SOAPBinding.SOAP12HTTP_BINDING,\n \"http://127.0.0.1:8204/CalculatorImplSign\");\n \n // CalculatorWs calc = calcService.getPort(\n //\tnew QName(\"http://superbiz.org/wsdl\", \"CalculatorWsService2\"),\n //\tCalculatorWs.class);\n \n CalculatorWs calc = calcService.getPort(CalculatorWs.class);\n \n Client client = ClientProxy.getClient(calc);\n Endpoint endpoint = client.getEndpoint();\n endpoint.getOutInterceptors().add(new SAAJOutInterceptor());\n \n Map<String, Object> outProps = new HashMap<String, Object>();\n outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.SIGNATURE);\n outProps.put(WSHandlerConstants.USER, \"clientalias\");\n outProps.put(WSHandlerConstants.PW_CALLBACK_REF, new CallbackHandler() {\n \n @Override\n public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {\n WSPasswordCallback pc = (WSPasswordCallback) callbacks[0];\n pc.setPassword(\"clientPassword\");\n }\n });\n outProps.put(WSHandlerConstants.SIG_PROP_FILE, \"META-INF/CalculatorImplSign-client.properties\");\n outProps.put(WSHandlerConstants.SIG_KEY_ID, \"IssuerSerial\");\n \n WSS4JOutInterceptor wssOut = new WSS4JOutInterceptor(outProps);\n endpoint.getOutInterceptors().add(wssOut);\n \n assertEquals(24, calc.multiply(4, 6));\n }\n //END SNIPPET: webservice\n }\n\n## CustomPasswordHandler\n\n package org.superbiz.calculator;\n \n import org.apache.ws.security.WSPasswordCallback;\n \n import javax.security.auth.callback.Callback;\n import javax.security.auth.callback.CallbackHandler;\n import javax.security.auth.callback.UnsupportedCallbackException;\n import java.io.IOException;\n \n public class CustomPasswordHandler implements CallbackHandler {\n @Override\n public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {\n WSPasswordCallback pc = (WSPasswordCallback) callbacks[0];\n \n if (pc.getUsage() == WSPasswordCallback.USERNAME_TOKEN) {\n // TODO get the password from the users.properties if possible\n pc.setPassword(\"waterfall\");\n } else if (pc.getUsage() == WSPasswordCallback.DECRYPT) {\n pc.setPassword(\"serverPassword\");\n } else if (pc.getUsage() == WSPasswordCallback.SIGNATURE) {\n pc.setPassword(\"serverPassword\");\n }\n }\n }\n\n# Running\n\n \n generate keys:\n \n do.sun.jdk:\n [echo] *** Running on a Sun JDK ***\n [echo] generate server keys\n [java] Certificate stored in file </Users/dblevins/examples/webservice-ws-security/target/classes/META-INF/serverKey.rsa>\n [echo] generate client keys\n [java] Certificate stored in file </Users/dblevins/examples/webservice-ws-security/target/test-classes/META-INF/clientKey.rsa>\n [echo] import client/server public keys in client/server keystores\n [java] Certificate was added to keystore\n [java] Certificate was added to keystore\n \n do.ibm.jdk:\n \n run:\n [echo] Running JDK specific keystore creation target\n \n -------------------------------------------------------\n T E S T S\n -------------------------------------------------------\n Running org.superbiz.calculator.CalculatorTest\n Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06\n http://tomee.apache.org/\n INFO - openejb.home = /Users/dblevins/examples/webservice-ws-security\n INFO - openejb.base = /Users/dblevins/examples/webservice-ws-security\n INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)\n INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)\n INFO - Found EjbModule in classpath: /Users/dblevins/examples/webservice-ws-security/target/classes\n INFO - Beginning load: /Users/dblevins/examples/webservice-ws-security/target/classes\n INFO - Configuring enterprise application: /Users/dblevins/examples/webservice-ws-security/classpath.ear\n INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)\n INFO - Auto-creating a container for bean CalculatorImplTimestamp1way: Container(type=STATELESS, id=Default Stateless Container)\n INFO - Enterprise application \"/Users/dblevins/examples/webservice-ws-security/classpath.ear\" loaded.\n INFO - Assembling app: /Users/dblevins/examples/webservice-ws-security/classpath.ear\n INFO - Jndi(name=CalculatorImplTimestamp1wayRemote) --> Ejb(deployment-id=CalculatorImplTimestamp1way)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplTimestamp1way!org.superbiz.calculator.CalculatorRemote) --> Ejb(deployment-id=CalculatorImplTimestamp1way)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplTimestamp1way) --> Ejb(deployment-id=CalculatorImplTimestamp1way)\n INFO - Jndi(name=CalculatorImplTimestamp2waysRemote) --> Ejb(deployment-id=CalculatorImplTimestamp2ways)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplTimestamp2ways!org.superbiz.calculator.CalculatorRemote) --> Ejb(deployment-id=CalculatorImplTimestamp2ways)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplTimestamp2ways) --> Ejb(deployment-id=CalculatorImplTimestamp2ways)\n INFO - Jndi(name=CalculatorImplUsernameTokenPlainPasswordRemote) --> Ejb(deployment-id=CalculatorImplUsernameTokenPlainPassword)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplUsernameTokenPlainPassword!org.superbiz.calculator.CalculatorRemote) --> Ejb(deployment-id=CalculatorImplUsernameTokenPlainPassword)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplUsernameTokenPlainPassword) --> Ejb(deployment-id=CalculatorImplUsernameTokenPlainPassword)\n INFO - Jndi(name=CalculatorImplUsernameTokenHashedPasswordRemote) --> Ejb(deployment-id=CalculatorImplUsernameTokenHashedPassword)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplUsernameTokenHashedPassword!org.superbiz.calculator.CalculatorRemote) --> Ejb(deployment-id=CalculatorImplUsernameTokenHashedPassword)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplUsernameTokenHashedPassword) --> Ejb(deployment-id=CalculatorImplUsernameTokenHashedPassword)\n INFO - Jndi(name=CalculatorImplUsernameTokenPlainPasswordEncryptRemote) --> Ejb(deployment-id=CalculatorImplUsernameTokenPlainPasswordEncrypt)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplUsernameTokenPlainPasswordEncrypt!org.superbiz.calculator.CalculatorRemote) --> Ejb(deployment-id=CalculatorImplUsernameTokenPlainPasswordEncrypt)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplUsernameTokenPlainPasswordEncrypt) --> Ejb(deployment-id=CalculatorImplUsernameTokenPlainPasswordEncrypt)\n INFO - Jndi(name=CalculatorImplSignRemote) --> Ejb(deployment-id=CalculatorImplSign)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplSign!org.superbiz.calculator.CalculatorRemote) --> Ejb(deployment-id=CalculatorImplSign)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplSign) --> Ejb(deployment-id=CalculatorImplSign)\n INFO - Jndi(name=CalculatorImplEncrypt2waysRemote) --> Ejb(deployment-id=CalculatorImplEncrypt2ways)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplEncrypt2ways!org.superbiz.calculator.CalculatorRemote) --> Ejb(deployment-id=CalculatorImplEncrypt2ways)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplEncrypt2ways) --> Ejb(deployment-id=CalculatorImplEncrypt2ways)\n INFO - Jndi(name=CalculatorImplSign2waysRemote) --> Ejb(deployment-id=CalculatorImplSign2ways)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplSign2ways!org.superbiz.calculator.CalculatorRemote) --> Ejb(deployment-id=CalculatorImplSign2ways)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplSign2ways) --> Ejb(deployment-id=CalculatorImplSign2ways)\n INFO - Jndi(name=CalculatorImplEncryptAndSign2waysRemote) --> Ejb(deployment-id=CalculatorImplEncryptAndSign2ways)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplEncryptAndSign2ways!org.superbiz.calculator.CalculatorRemote) --> Ejb(deployment-id=CalculatorImplEncryptAndSign2ways)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImplEncryptAndSign2ways) --> Ejb(deployment-id=CalculatorImplEncryptAndSign2ways)\n INFO - Jndi(name=CalculatorImplRemote) --> Ejb(deployment-id=CalculatorImpl)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImpl!org.superbiz.calculator.CalculatorRemote) --> Ejb(deployment-id=CalculatorImpl)\n INFO - Jndi(name=global/classpath.ear/simple/CalculatorImpl) --> Ejb(deployment-id=CalculatorImpl)\n INFO - Created Ejb(deployment-id=CalculatorImplUsernameTokenHashedPassword, ejb-name=CalculatorImplUsernameTokenHashedPassword, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=CalculatorImpl, ejb-name=CalculatorImpl, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=CalculatorImplSign, ejb-name=CalculatorImplSign, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=CalculatorImplEncryptAndSign2ways, ejb-name=CalculatorImplEncryptAndSign2ways, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=CalculatorImplTimestamp1way, ejb-name=CalculatorImplTimestamp1way, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=CalculatorImplSign2ways, ejb-name=CalculatorImplSign2ways, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=CalculatorImplEncrypt2ways, ejb-name=CalculatorImplEncrypt2ways, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=CalculatorImplUsernameTokenPlainPassword, ejb-name=CalculatorImplUsernameTokenPlainPassword, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=CalculatorImplTimestamp2ways, ejb-name=CalculatorImplTimestamp2ways, container=Default Stateless Container)\n INFO - Created Ejb(deployment-id=CalculatorImplUsernameTokenPlainPasswordEncrypt, ejb-name=CalculatorImplUsernameTokenPlainPasswordEncrypt, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=CalculatorImplUsernameTokenHashedPassword, ejb-name=CalculatorImplUsernameTokenHashedPassword, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=CalculatorImpl, ejb-name=CalculatorImpl, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=CalculatorImplSign, ejb-name=CalculatorImplSign, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=CalculatorImplEncryptAndSign2ways, ejb-name=CalculatorImplEncryptAndSign2ways, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=CalculatorImplTimestamp1way, ejb-name=CalculatorImplTimestamp1way, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=CalculatorImplSign2ways, ejb-name=CalculatorImplSign2ways, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=CalculatorImplEncrypt2ways, ejb-name=CalculatorImplEncrypt2ways, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=CalculatorImplUsernameTokenPlainPassword, ejb-name=CalculatorImplUsernameTokenPlainPassword, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=CalculatorImplTimestamp2ways, ejb-name=CalculatorImplTimestamp2ways, container=Default Stateless Container)\n INFO - Started Ejb(deployment-id=CalculatorImplUsernameTokenPlainPasswordEncrypt, ejb-name=CalculatorImplUsernameTokenPlainPasswordEncrypt, container=Default Stateless Container)\n INFO - Deployed Application(path=/Users/dblevins/examples/webservice-ws-security/classpath.ear)\n INFO - Initializing network services\n INFO - Creating ServerService(id=httpejbd)\n INFO - Creating ServerService(id=cxf)\n INFO - Creating ServerService(id=admin)\n INFO - Creating ServerService(id=ejbd)\n INFO - Creating ServerService(id=ejbds)\n INFO - Initializing network services\n ** Starting Services **\n NAME IP PORT \n httpejbd 127.0.0.1 4204 \n admin thread 127.0.0.1 4200 \n ejbd 127.0.0.1 4201 \n ejbd 127.0.0.1 4203 \n -------\n Ready!\n Tests run: 7, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 4.582 sec\n \n Results :\n \n Tests run: 7, Failures: 0, Errors: 0, Skipped: 0\n \n",
"url":"https://github.com/apache/tomee/tree/master/examples/webservice-ws-security"
},
{
"name":"webservice-ws-with-resources-config",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/webservice-ws-with-resources-config"
}
],
"xml":[
{
"name":"rest-xml-json",
"readme":"No README.md yet, be the first to contribute one!",
"url":"https://github.com/apache/tomee/tree/master/examples/rest-xml-json"
}
]
},
"total":276
}