1 / 59

Advanced Java Session 8

Advanced Java Session 8. New York University School of Continuing and Professional Studies. Objectives. Java Message Service Overview of JMS JMS Message Types Sending Messages Receiving Messages Pub/Sub P2P EJB What is an EJB Entity/Session Beans Services Message Driven Beans

Download Presentation

Advanced Java Session 8

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Advanced JavaSession 8 New York University School of Continuing and Professional Studies

  2. Objectives • Java Message Service • Overview of JMS • JMS Message Types • Sending Messages • Receiving Messages • Pub/Sub • P2P • EJB • What is an EJB • Entity/Session Beans • Services • Message Driven Beans • JMS Transactions • JMS Performance Considerations

  3. Java Message Service • JMS is a specification not a product • Part of the suite of J2EE specs • A standard API to interface with various messaging systems – although IBM MQ was the main driver and influence • JMS does not define any standard or portable format for messages themselves

  4. The Java Message • TextMessage – simple text message • getText(), setText(text) • BytesMessage – contains “raw” bytes without any “type” information – you can write a Long on one side and read it as Double on the other side. • writeBoolean(), writeByte(), writeDouble()… and readBoolean(), readByte(), readDouble()… • ObjectMessage – contains Serializable java objects • getObjectt(), setObject(Serializable obj)

  5. The Java Message • MapMessage – contains name/value pairs like the java HashMap • getBoolean(String), getByte(String), getDouble(String) ... • setBoolean(String), setByte(String), setDouble(String) … • setObject(String name, Object value) – will throw an Exception for any Object other than the basic data types such as Integer, Double, etc. • StreamMessage – contains a stream of java data types without any keys, data values are accompanied by their type information (in BytesMessage they are not); is more efficient than MapMessage • getBoolean(String), getByte(String), getDouble(String) ... • setBoolean(String), setByte(String), setDouble(String) …

  6. JMS Destinations • Represent “end points” for JMS participants • Well known destinations may be pre-configured • temporary destinations may be created programmatically • Base interface is javax.jms.Destination • Publish/Subscribe domain • Javax.jms.Topic • Point 2 Point domain • Javax.jms.Queue

  7. Java Message Properties • JMSDestination – address of JMS message • Destination getJMSDestination() • setJMSDestination(Destination d) – clients cannot use this method to directly set the destination – clients provide a destination when creating a session (or optionally when sending a message) • JMSDeliveryMode – reliable and nonreliable • int getDeliveryMode() • setDeliveryMode(int m) • Javax.jms.DeliveryMode.PERSISTENT • Javax.jms.DeliveryMode.NONPERSISTENT • JMSExpiration • Time after which a message expires – zero means “infinity” – timestamp indicating GMT based time • Not always honored by all providers • JMSPriority • An integer from 0 to 9 where 0-4 indicates “normal” and 5-9 indicates expedited delivery • Not required to be supported by providers

  8. Java Message Properties • JMSMessageID • Is generated and set by the provider immediately when a message is submitted for delivery • JMSTimestamp • GMT-based timestamp represents the time a client application submitted a message to the provider for delivery • JMSCorrelationID • Can be set by an application before submitting for delivery to indicate that a message is related to a previously received message. • JMSReplyTo • Applications can set this property to let the receiver know where to send the reply to • setJMSReplyTo(Destination d)

  9. Java Message Properties • JMSType • Can be set by the application to indicate the type of contents of the message • JMSRedelivered • Set by the provider to indicate that this message is being redelivered • Custom Properties • Applications can set any additional properties using methods of the form • Set<TYPE>Property (e.g. setIntProperty, setFloatProperty etc.) • Standard properties defined by JMS • JMSXUserID, JMSXAppID, JMSXDeliveryCount, JMSXGroupID, JMSXGroupID, JMSXProducerTXID, JMSXConsumerTXID, JMSXRcvTimestamp, JMSXState

  10. Sending Java MessagesCreate Connection Factory • Create an initial context from properties Hashtable hash = new Hashtable() hash.put(Context.INITIAL_CONTEXT_FACTORY, “weblogic.jndi.WLInitialContextFactory”); hash.put(Context.PROVIDER_URL, “t3://localhost:7001”); Context ctx = new InitialContext(hash); • Create a ConnectionFactory using JNDI TopicConnectionFactory tfactory = (TopicConnectionFactory) ctx.lookup(“XXXX”); QueueConnectionFactory qfactory = (TopicConnectionFactory) ctx.lookup(“XXXX”); • Create a ConnectionFactory using new ConnectionFactory factory = new ActiveMQConnectionFactory(user, password, url);

  11. Create Connection and Session • Topic TopicConnection tconn = tfactory.createTopicConnection(); TopicSession tsess = tconn.createTopicSession(false,AUTO_ACK..); • Queue QueueConnection qconn = qfactory.createQueueConnection(); QueueSession qsess = qconn.createQueueSession(false,AUTO_ACK..); • Common (ActiveMQ) Connection conn = factory.createConnection(); Session sess = conn.createSession(false, AUTO_ACK);

  12. Construct A Message • TextMessage TextMessage msg = session.createTextMessage(); msg.setText(“hello world”); • MapMessage MapMessage msg = session.createMapMessage(); msg.setLong(“OrderNumber”, 12345); msg.setInt(“Quantity”, 5000); • BytesMessage BytesMessage msg = session.createBytesMessage(); msg.writeBytes(“Hello World”.getBytes()); • StreamMessage StreamMessage msg = session.createStreamMessage(); msg.writeLong(12345); msg.writeInt(5000); • ObjectMessage Order order = new Order(12345, 5000, “IBM”, …) ; ObjectMessage msg = session.createObjectMessage(); msg.setObject(order);

  13. Create a Message Producer • Topic Publisher – temporary/dynamic Topic Topic topic = tsess.createTopic(“testtopic”); TopicPublisher publisher = tsess.createPublisher(topic); • Queue Sender – temporary/dynamic Queue Queue queue = qsess.createQueue(“testqueue”); QueueSender sender = qsess.createQueueSender(“queue”); • Topic Publisher – preconfigured Topic Topic topic = ctx.lookup(“testtopic”); TopicPublisher publisher = tsess.createPublisher(topic); • Queue Sender – preconfigured Queue Queue queue = ctx.lookup(“testqueue”); QueueSender sender = qsess.createQueueSender(“queue”);

  14. Configuring delivery options andsending a message • Setting Options MessageProducer producer = (MessageProducer)queueSender; producer.setDeliveryMode(javax.jms.DeliveryMode.PERSISTENT); producer.setTimeToLive(30000) // 30 seconds producer.setPriority(9) // highest producer.setDisableMessageID(true); // do not use message IDs producer.setDisableMessageTimestamp(true); // do not use timestamp • Sending the message publisher.publish(msg); sender.send(msg);

  15. Receiving Messages • Creating Message Consumer for Topics Topic topic = tsess.createTopic(“testtopic”); //or Topic topic = ctx.lookup(“testtopic”); TopicSubscriber subscriber = tsess.createTopicSubscriber(topic); • Creating Message Consumer for Queues Queue queue = qsess.createQueue(“testqueue”); // or Queue queue = ctx.lookup(“testqueue”); QueueReceiver receiver = qsess.createQueueReceiver(queue);

  16. Receiving Messages • Creating Message Consumer for Topics Topic topic = tsess.createTopic(“testtopic”); //or Topic topic = ctx.lookup(“testtopic”); TopicSubscriber subscriber = tsess.createTopicSubscriber(topic); • Creating Message Consumer for Queues Queue queue = qsess.createQueue(“testqueue”); // or Queue queue = ctx.lookup(“testqueue”); QueueReceiver receiver = qsess.createQueueReceiver(queue); • Starting the session to begin msg delivery tconn.start(); qconn.start();

  17. Processing Messages • Synchronously Message msg = consumer.receive(); if( msg instanceof TextMessage ) System.out.println(msg.getText(); • Asynchronously while( true ) { Message msg = consumer.receiveNoWait(); if( msg == null ) doSomethingElse(); else if( msg instanceof TextMessage ) System.out.println(msg.getText()); }

  18. Message Handlers • Registering a call back when message arrives: public class MyMessageHandler implements MessageListener { public void onMessage(Message msg) { if( msg instanceof TextMessage ) System.out.println(msg.getText(); } } // then after creating subscriber or receiver - tsubscriber.setMessageListener(new MyMessageHandler()); qreceiver.setMessageListener(new MyMessageHandler());

  19. Threading Concerns • All calls to onMessage() for the same session are automatically synchronized. However if you register the same listener from multiple sessions, your listener may get called from multiple threads. • Similarly calls to consumer.receive() must not be made from two different threads – if multi-threading is needed, create a separate consumer for each thread.

  20. Acknowledging Messages • Consumers (or listeners) acknowledge messages to indicate that the message was successfully received (and processed) • AUTO_ACKNOWLEDGE • Messages received in this type of session do not require any explicit acknowledgement • CLIENT_ACKNOWLEDGE • This mode requires specific call to msg.acknowledge() • not acknowledging will not result in “redelivery” unless there is a system failure. • Acknowledging any message effectively acknowledges all preceding unacknowledged messages as well

  21. Acknowledging Messages • Consumers (or listeners) acknowledge messages to indicate that the message was successfully received (and processed) • DUPS_OK_ACKNOWLEDGE • Messages received in this type of session do not require any explicit acknowledgement • Messages are automatically acknowledged by the system in a “lazy” manner • Method to acknowledge a message msg.acknowledge();

  22. Filtering With Message Selectors • Client may express an interest in messages based on almost any property attached to the message • SQL like syntax is used to specify a condition for the filter • Filters may only reference message properties – not any content (fields of a MapMessage are part of content)

  23. Message Selector “TradeSize >= 100000” will refer to the TradeSize in “red”

  24. TopicRequestor • can be used instead of multiple steps of creating a temporary topic, creating a subscriber, and sending the request with JMSReplyTo and finally cleaning up. Topic rt = tsess.createTopic(“temp”); TextMessage msg = tsess.createTextMessage(); msg.setText(“request”); TopicRequestor requestor = new TopicRequestor(tsess, rt); Message reply = requestor.receive(msg); requestor.close();

  25. Durable Subscribers • Topic clients that do not wish to “miss” messages even when they are “down” must create Durable Subscriber TopicSubscriber dsub = tsess.createDurableSubscriber(topic, “UNIQUENAME”); // to unsubscribe Tsess.unsubscribe(“UNIQUENAME”);

  26. Durable Subscribers • Messages sent to a topic before a durable subscription is create are not available to the durable subscriber • Only one session at a time can have a durable subscription active for any particular named subscription – (for any given client ID/topic name combination) • Reusing the client ID to create a second durable subscription with a different topic cancels the previous subscription.

  27. Multiple Queue Readers • JMS Spec does not specify exactly how this should work • Most vendors implementations will deliver messages in a round-robin fashion

  28. QueueRequestor • Point to point version of the TopicRequestor Queue rq = qsess.createQueue(“temp”); TextMessage msg = qsess.createTextMessage(); msg.setText(“Hello”); QueueRequestor qr = new QueueRequestor(qsess,rq); Message reply = qr.receive(msg);

  29. QueueBrowser • Class allows clients to “browse” the contents of the queue QueueBrowser qb = qsess.createBrowser(queue, [selector]); qconn.start(); Enumeration en = qb.getEnumeration(); while( en.hasMoreElements() ) { msg = (Message)en.nextElement(); } • Providers implement this differently • Exact behavior is undefined when other QueueReceivers are present

  30. Message Driven Beans • Components that “live” in a J2EE Application Server • Must implement javax.ejb.MessageDrivenBean “and” javax.jms.MessageListener • Deployment Descriptor ties classes to specific destinations • Container automatically creates a new instance and delivers the message to onMessage method

  31. JMS Transactions • Transactions are managed on a “per-session” basis which means that all activity related to a particular session object can be either committed or rolled back as a unit. • Transaction boundaries in JMS separate individual clients. Which means that client A’s interaction with the provider will be in a transaction and Client B’s interaction with the provider will be in a separate transaction.

  32. Using transactions • Receiving messages in a Transaction • Create a transacted session by passing “true” to createSession call • Use session.commit() instead of msg.acknowledge() • Sending messages in a Transaction • Use session.commit() after each batch of messages is sent

  33. Middle Tier Back-End Tier Web tier internet Web browser Synchronous calls Web server App server Database Web browser Web browser Web browser 1000 orders per minute 500 orders per minute

  34. Middle Tier Back-End Tier Web tier internet Web browser Web server App server Database Web browser Web browser JMS queue Web browser 1000 orders per minute 500 orders per minute

  35. Middle Tier Back-End Tier Web tier internet Web browser Web server App server Database Web browser Web browser JMS queue App server Web browser 1000 orders per minute 500 orders per minute

  36. Enterprise Java Beans • Server-side component architecture • Enables and simplifies the process of building enterprise-class distributed object applications that are scalable, reliable, and secure • Analogous to the hardware components model

  37. N-Tier Architecture Presentation logic Presentation layer Pricing component billing component driver Business logic layer database Data Layer

  38. EJB Servers and Containers Client (servlet, applet, app) EJB Server EJB Container EJB Container EJB EJB EJB EJB

  39. Enterprise Beans • Session Beans • Typically represent business processes (like authorize credit card) • Last only through the duration of the client • Stateless Session Beans • Stateful Session Beans • Entity Beans • Typically models permanent data objects – such as credit card, account, customer • Are long lasting, or persistent objects • Bean managed persistence • Container managed persistence

  40. Enterprise Bean Model Client code Get ref to Home Object EJB Server/container create Home Object Method call Home interface EJB Object delegate EJB Remote interface

  41. Services Provided by Container Client (servlet, applet, app) EJB Server/Container invokes • Resource management • Lifecycle management • State management • Transactions • Security • Persistence delegates EJB

  42. Resource Management EJB Container is responsible for coordinating the entire effort of resource management for resources such as • Threads • Socket Connections • Database Connections

  43. Lifecycle Management Controls the lifecycle of the Bean Creates or destroys beans in response to client requests Provides “instance pooling”

  44. State Management • Stateful beans or Entity Beans need to maintain a “state” for each clients • The container provides services to maintain the state • The same state may be passed on to another bean if necessary before invoking a method that a client requested

  45. Transactions • EJBs may participate in transactions • EJB Container handles the underlying transaction operations, coordinating efforts behind the scenes. • Java Transaction API is used to implement transactions for beans • Transactions may be configured to be managed entirely by Container or be managed by the Bean classes

  46. Security • EJB containers add transparent Security to the Beans • Enterprise Beans can automatically run as a certain security identity, or can programmatically ensure that clients are authorized to perform desired operations

  47. Persistence • Containers can provide transparent persistence for Entity Beans • EJBs can manage their own persistence if they prefer

  48. Remote AccessibilityLocation Transparency • Converts a network-naïve component to a networked component • Containers use Java RMI to specify remote accessibility • Gives sysadmins the ability to upgrade a certain machine while clients are routed to another (better fault tolerance, availability)

  49. Specialized Container Features • Integration to mainframe systems • COM+ integration • Transparent fail-over • Stateful recovery • Server clustering • Dynamic redeployment • Monitoring support • Visual development environment integration

  50. Bean classes and interfaces • The EnterpriseBean class contains implementation details of your component. It extends Serializable. • SessionBean – extends EnterpriseBean • EntityBean – extends EnterpriseBean • EJBObject class represents the “surrogate” object that is created instead of your Bean object • Remote Interfaces for your bean must extend EJBObject • EJBHome class represents the factory object • Home Interfaces for your bean must extend EJBHome

More Related