EJB et WS (Montreal JUG - 12 mai 2011)
Upcoming SlideShare
Loading in...5
×

Like this? Share it with your network

Share

EJB et WS (Montreal JUG - 12 mai 2011)

  • 3,272 views
Uploaded on

http://www.montreal-jug.org/content/pr%C3%A9sentation-sur-ejb-web-service-par-romain-roc%C3%A8s-le-jeudi-12-mai-2011-%C3%A0-17h45

http://www.montreal-jug.org/content/pr%C3%A9sentation-sur-ejb-web-service-par-romain-roc%C3%A8s-le-jeudi-12-mai-2011-%C3%A0-17h45

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
3,272
On Slideshare
1,972
From Embeds
1,300
Number of Embeds
6

Actions

Shares
Downloads
56
Comments
0
Likes
0

Embeds 1,300

http://www.montreal-jug.org 1,283
http://www.montrealjug.org 12
http://www.montreal-jug.org.web04.ovea.com 2
http://www.slideshare.net 1
url_unknown 1
http://translate.googleusercontent.com 1

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. EJB and SOAP WS Par Romain Rocès pour le Montréal JUG
  • 2. About meRomain Rocès Teacher at Supinfo Montreal Blue belt on BlackBelt Factory romain.roces@gmail.com Romain Rocès
  • 3. Concept
  • 4. ConceptEJB regroups several conceptsProvides different services (Session Bean),communicates with another application (Message Bean),saves information (Entity Bean). Just like a brain, EJB is the center of the application. It proposes many functions.
  • 5. Version 3 The previous version (2.1) was too complex The version 3.0 tends to simplification : Less steps, less classes, less configuration Improvements from Java EE 5 Annotations Generics Java Persistance API Concepts remain the same, but Sun integrated many ideas from popular open-source projects like Spring or Hibernate.
  • 6. Application servers WebLogic, by BEA Oracle Application Server, by Oracle JBoss, by RedHat GlassFish, by Sun MicroSystems
  • 7. EJB sessionSingleton, Stateless, Stateful
  • 8. Facade pattern The Session Bean acts as a “facade”. Its the clients interlocutor
  • 9. Client accessDifferent clients can call the Session Bean methods if theypossess its interface Desktop application Interface Implementation Session Bean deployed on a server Web application
  • 10. Session Bean Local Set @Local on the interface (not mandatory) Used when the client is deployed in the same virtual machine Example : A Web application deployed in the same server as the Session Bean Advantage : Resource-friendly More secure Disadvantage : Local scope
  • 11. Session Bean LocalLocal interfaces are not mandatory@Statelesspublic class HelloServiceBean { public String sayHello(){ return "Hello World"; }}
  • 12. Session Bean Remote Set @Remote on the interface Used when the client is located in a different virtual machine Example : A web application deployed in a different server than the Session Bean A rich-client Advantage : Open on the network Disadvantage : Consumes more resources (uses RMI) Security
  • 13. Session Bean RemoteInterface@Remotepublic interface HelloService {public String sayHello();}Implementation@Statelesspublic class HelloServiceBean implements HelloService{ public String sayHello(){ return "Hello World"; }}
  • 14. Stateless modeA Stateless Bean is not bound to any clientExemples : Retrieve a list of products HelloService getPlaces() getPlaces()Advantage : getTrips() Resource-friendly
  • 15. Stateless mode @Stateless public class HelloWorld { public String sayHelloTo(String name){ return "Hello " + name; } }
  • 16. Stateful modeA Statefull Bean is bound to a clientExemples : Cart OrderService getPlaces() getPlaces()Advantage : getTrips() Impact on server performance
  • 17. Stateful mode @Stateful public class OrderService { public void setName(String name){…}; public void setAddress(String address){…}; public void buyDog(){…}; … }
  • 18. Singleton modeOne Singleton Bean per JVMExemples : Counter CacheAdvantage : Resource-friendly One instanceDisadvantage : One instance
  • 19. Singleton mode @Singleton public class Counter { private int i = 0; public int getCount(){ return ++i; } }
  • 20. Asynchronous calls How to have asynchronous call in EJBs ? Threads dont integrate well @Asynchronous Method returns void or java.util.concurrent.Future<T>
  • 21. Asynchronous calls@Statelesspublic class HelloWorld { @EJB MailManager mailManager; public String sayHelloTo(String name){ mailManager.sendMail(); return "Hello " + name; }}@Statelesspublic class MailManager { @Asynchronous public void sendMail(){ ... }}
  • 22. Timer Service Programmatic and Calendar based scheduling « Last day of the month » « Every five minutes on Monday and Friday » Cron-like syntax second [0..59], minute[0..59], hour[0..23], year DayOfMonth[1..31] dayOfWeek[0..7] or [sun, mon, tue..] Month[0..12] or [jan,feb..]
  • 23. Timer Service@Statelesspublic class WakeUpBean { @Schedule(dayOfWeek=“Mon-Fri”, hour=“9”) void wakeUp() { ... }}
  • 24. Unit Test
  • 25. JUnit Not in EJB context@Test public void myTest(){ StatelessBean statelessBean = new StatelessBean(); statelessBean.getCounter(); }
  • 26. JUnit With EJB context : embedded glassfish@Testpublic void myTest() throws NamingException{ EJBContainer createEJBContainer = EJBContainer.createEJBContainer(); StatelessBean statelessBean = (StatelessBean)container.getContext() .lookup("java:global/classes/StatelessBean"); statelessBean.getCounter(); container.close();}
  • 27. Unit Test Cactus is a simple test framework for unit testing server-side java code (Servlets, EJBs, Tag Libs, Filters, ...). The Ejb3Unit project automates Entity and Session bean testing outside the container for the EJB 3.0 specification.
  • 28. Client connection lookup & @EJB
  • 29. EJB connection with lookup The client needs the JNDI context to connect to the server. The client also needs the Session Bean interface Retrieve the Session Bean with a lookup() Then its possible to call methods from the Bean Context context = new InitialContext(); HelloService hello = (HelloService) context.lookup(HelloService.class.getName()); System.out.println(hello.sayHello()); The Session Bean will send you a message !
  • 30. EJB connection with lookupjndi.properties file exampleGlassFish parametersjava.naming.factory.initial=com.sun.enterprise.naming.SerialInitContextFactoryjava.naming.factory.url.pkgs=com.sun.enterprise.namingjava.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImplJBoss Parametersjava.naming.factory.initial=org.jnp.interfaces.NamingContextFactoryjava.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfacesjava.naming.provider.url = 127.0.0.1:1099
  • 31. EJB injection In the same JVM, its not necessary to do a lookup() Obtain a Session Bean with resource injection Used in other EJBs, web applicationspublic class ClientServiceBean implements ClientService { @EJB private OrderService orderService; ...}
  • 32. Soap WS in EJB module Add @WebService and @Stateless annotation on a class It run !@WebService@Statelesspublic class MyBeanPublic { @WebMethod public String helloWorld() { return null; }}Default WSDL address : http://localhost:8080/MyBeanPublicService/MyBeanPublic?wsdl
  • 33. Soap WS in EJB moduleNow, we use our EJB @stateless in our SOAP WS.@WebService@Statelesspublic class MyBeanPublic { @EJB private MyBeanLocal ejbRef; @WebMethod public String helloWorld() { return ejbRef.helloWorld(); }}
  • 34. Soap WS in EJB moduleExemple with NetBeans 7
  • 35. EJB entity
  • 36. Persistence UnitThe persistence unit makes the link between your applicationand a DataSource
  • 37. Persistence UnitDifferent providers Hibernate (use by default in JBoss) TopLink (use by default in Glassfish v2) EclipseLink (use by default in Glassfish v3)
  • 38. Persistence Unitpersistence.xml<?xml version="1.0" encoding="UTF-8"?><persistence version="2.0" ...> <persistence-unit name="montrealjugPU" transaction-type="JTA"> <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> <jta-data-source>jdbc/firone</jta-data-source> <exclude-unlisted-classes>false</exclude-unlisted-classes> <properties> <property name="eclipselink.ddl-generation" value="create-tables"/> </properties> </persistence-unit></persistence>
  • 39. Persistence Unitglassfish-resources.xml<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE resources PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1Resource Definitions//EN" "http://glassfish.org/dtds/glassfish-resources_1_5.dtd"><resources> <jdbc-connection-pool ...> <property name="serverName" value="localhost"/> <property name="portNumber" value="1527"/> <property name="databaseName" value="firone"/> <property name="User" value="firone"/> <property name="Password" value="firone"/> <property name="URL" value="jdbc:derby://localhost:1527/firone"/> <property name="driverClass" value="org.apache.derby.jdbc.ClientDriver"/> </jdbc-connection-pool> <jdbc-resource enabled="true" jndi-name="jdbc/firone" object-type="user" pool-name="derby_net_firone_fironePool"/></resources>
  • 40. EntityManager in EJB Obtain an EntityManager with injection@Statelesspublic class DAO { @PersistenceContext(unitName="montrealjugPU") protected EntityManager em; public void createCat(Cat cat){ em.persist(cat); }}
  • 41. EJB messageJava Message Service
  • 42. JMS presentation The same since 2002 Used when some information should be exchanged between Two applications : point-to-point model Several applications : publish and subscribe model Asynchronous system : messages are received when the client request them Similar to a mail system
  • 43. Queue mode
  • 44. Topic mode
  • 45. Messages There are three different types of messages TextMessage to send simple text ObjectMessage for a serialized object MapMessage contains a map with strings as keys and objects as values
  • 46. Send a message In order to send a message, we have to: Reclaim required objects via JNDI A ConnectionFactory (service provider) A Destination (Queue or Topic) Create a Connection using the factory Open a Session using the connection Create a MessageProducer Send the message
  • 47. Send a messageContext ctx = new InitialContext();ConnectionFactory connectionFactory = (ConnectionFactory) ctx .lookup("ConnectionFactory");Destination destination = (Destination) ctx.lookup("queue/StockValue");Connection cnx = connectionFactory.createConnection();Session session = cnx.createSession(false, Session.AUTO_ACKNOWLEDGE);MessageProducer producer = session.createProducer(destination);TextMessage message = session.createTextMessage();message.setText("Yourmicrosoft stock has been sold !");producer.send(message);cnx.close();
  • 48. Receive a message Two ways to receive a message Blocking, waiting for a message Non-blocking, using a message listener A message listener is similar to an event listener : it "subscribes" to a particular destination and receives messages each time theres a new one
  • 49. Receive a messageBlocking modeMessageConsumer consumer = session.createConsumer(destination);// Retrieve a single messageMessage receivedMessage = consumer.receive();Non-blocking mode, using a listenerMessageConsumer consumer = session.createConsumer(destination);// Set the listenerconsumer.setMessageListener(new MessageListener() { public void onMessage(Message message) { // Will be called each time a message is received}});
  • 50. Receive a message : Message Driven Bean A Message Driven Bean is a specific component for receiving messages Annotation used is @MessageDriven Destination name and type are declared in the annotation Implements javax.jms.MessageListener Method public void onMessage(Message m) Called at the moment of receipt
  • 51. Receive a message : Message Driven Bean@MessageDriven( mappedName="queue/StockValue", activationConfig = {@ActivationConfigProperty( propertyName = "destinationType", propertyValue = "javax.jms.Queue")})class MyDrivenBean implements MessageListener {public void onMessage(Message message) {TextMessage textMessage = (TextMessage) message;System.out.println(textMessage.getText());}}
  • 52. Merci de votre attention
  • 53. SourcesSupinfo : www.supinfo.comParisJUG : www.parisjug.org
  • 54. Licensehttp://creativecommons.org/licenses/by-nc-sa/2.0/fr/