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