Topics. Advanced Java Programming. Legacy Systems and Java. Legacy Systems. Topics. Approaches

Similar documents
Asynchrone Kommunikation mit Message Driven Beans

java message service marek konieczny

Introduction to Messaging using JMS

Using Message Driven Beans.

Distributed Systems. Messaging and JMS Distributed Systems 1. Master of Information System Management

Introduction Abstract. 1.2 Overview. This specification describes the objectives and functionality of the Java TM Message Service (JMS).

Example Purchase request JMS & MDB. Example Purchase request. Agenda. Purpose. Solution. Enterprise Application Development using J2EE

The Java EE 6 Tutorial

Describe the concepts and some practical applications of messaging. Describe the concepts and basic structure of JMS.

Web Design and Applications

Communication Technologies MoM JMS.NET. Part VI. Message-Oriented Middleware

DS 2009: middleware. David Evans

ESIR SR. Unit 10a: JGroups. François Taïani

MTAT Enterprise System Integration. Lecture 2: Middleware & Web Services

Today: Distributed Objects. Distributed Objects

Asynchronous Messaging. Benoît Garbinato

Developing a Basic JMS Application

Introduction. Enterprise Java Instructor: Please introduce yourself Name Experience in Java Enterprise Edition Goals you hope to achieve

Module 10 Developing Java EE Applications using Messaging

Deccansoft Software Services. J2EE Syllabus

Java Message System. Petr Adámek. April 11 th 2016

Integrating Legacy Assets Using J2EE Web Services

User Guide. The mom4j development team

Java TM. Message-Driven Beans. Jaroslav Porubän 2007

Java Enterprise Edition

Middleware and Distributed Systems. Message-Oriented Middleware. Martin v. Löwis

Chapter 6 Enterprise Java Beans

Java Message Service. The JMS API is an API for accessing enterprise messaging systems from Java programs. Version 2.0 (Public Review Draft)

Distributed Systems/Middleware JMS

Notes. Submit homework on Blackboard The first homework deadline is the end of Sunday, Feb 11 th. Final slides have 'Spring 2018' in chapter title

<Insert Picture Here> WebLogic JMS Messaging Infrastructure WebLogic Server 11gR1 Labs

Angelo Corsaro, Ph.D. Chief Technology Officer! OMG DDS Sig Co-Chair PrismTech

Borland Application Server Certification. Study Guide. Version 1.0 Copyright 2001 Borland Software Corporation. All Rights Reserved.

Developing Message-Driven Beans for Oracle WebLogic Server c (12.1.3)

Enterprise JavaBeans, Version 3 (EJB3) Programming

Oracle Fusion Middleware

Oracle9iAS Tech nicaloverview

EJB ENTERPRISE JAVA BEANS INTRODUCTION TO ENTERPRISE JAVA BEANS, JAVA'S SERVER SIDE COMPONENT TECHNOLOGY. EJB Enterprise Java

Application Servers in E-Commerce Applications

(9A05803) WEB SERVICES (ELECTIVE - III)

Distributed Middleware. Distributed Objects

Introduction to JMS & Apache ActiveMQ

Essential Software Architecture

MOM MESSAGE ORIENTED MIDDLEWARE OVERVIEW OF MESSAGE ORIENTED MIDDLEWARE TECHNOLOGIES AND CONCEPTS. MOM Message Oriented Middleware

Enterprise JavaBeans (I) K.P. Chow University of Hong Kong

Distributed Object-Based Systems The WWW Architecture Web Services Handout 11 Part(a) EECS 591 Farnam Jahanian University of Michigan.

Copyright UTS Faculty of Information Technology 2002 EJB2 EJB-3. Use Design Patterns 1 to re-use well known programming techniques.

WebSphere 4.0 General Introduction

Developing JMS Applications for Oracle WebLogic Server c (12.1.3)

Figure 1: OpenJMS Integration using GenericJMS RA

133 July 23, :01 pm

UNIT-III EJB APPLICATIONS

Introduction to Web Services & SOA

J2EE. Enterprise Architecture Styles: Two-Tier Architectures:

Connecting Enterprise Systems to WebSphere Application Server

Distributed Objects and Remote Invocation. Programming Models for Distributed Applications

Appendix A - Glossary(of OO software term s)

Module 11 Developing Message-Driven Beans

Introduction to Web Services & SOA

ITdumpsFree. Get free valid exam dumps and pass your exam test with confidence

~ Ian Hunneybell: CBSD Revision Notes (07/06/2006) ~

Application Connectivity Strategies

Problems in Scaling an Application Client

EMBEDDED MESSAGING USING ACTIVEMQ

Enterprise Java Security Fundamentals

KINGS COLLEGE OF ENGINEERING DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING ACADEMIC YEAR (ODD SEMESTER) QUESTION BANK

Exam Actual. Higher Quality. Better Service! QUESTION & ANSWER

jar command Java Archive inherits from tar : Tape Archive commands: jar cvf filename jar tvf filename jar xvf filename java jar filename.

Vision of J2EE. Why J2EE? Need for. J2EE Suite. J2EE Based Distributed Application Architecture Overview. Umair Javed 1

NetBeans IDE Field Guide

Oracle 10g: Build J2EE Applications

Distributed Objects. Object-Oriented Application Development

Enterprise JavaBeans TM

CORBA (Common Object Request Broker Architecture)

Electronic Payment Systems (1) E-cash

Artix for J2EE. Version 4.2, March 2007

Enterprise Java (EAI) WebSphere z/os & JCA

Enterprise JavaBeans. Layer 05: Deployment

An Event Service Implemented with J2EE for Integration of Enterprise Systems

CHAPTER 1 FUNDAMENTALS

1.264 Lecture 16. Legacy Middleware

Agent and Object Technology Lab Dipartimento di Ingegneria dell Informazione Università degli Studi di Parma. Distributed and Agent Systems

Application Development Considerations

BEAWebLogic Server and WebLogic Express. Programming WebLogic JNDI

CSci Introduction to Distributed Systems. Communication: RPC

Enterprise JavaBeans. Layer:08. Persistence

PASS4TEST. IT Certification Guaranteed, The Easy Way! We offer free update service for one year

Advanced Topics in Operating Systems

Chapter 10 DISTRIBUTED OBJECT-BASED SYSTEMS

DISTRIBUTED SYSTEMS [COMP9243] Lecture 7: Middleware MIDDLEWARE. Distributed Object based: Slide 1. Slide 3. Message-oriented: Slide 4

Applications MW Technologies Fundamentals. Evolution. Applications MW Technologies Fundamentals. Evolution. Building Blocks. Summary.

Overview p. 1 Server-side Component Architectures p. 3 The Need for a Server-Side Component Architecture p. 4 Server-Side Component Architecture

WebSphere Application Server - Overview

Distributed Applications (RMI/JDBC) Copyright UTS Faculty of Information Technology 2002 EJB EJB-3

Interprocess Communication Tanenbaum, van Steen: Ch2 (Ch3) CoDoKi: Ch2, Ch3, Ch5

A Comparison and Mapping of Data Distribution Service (DDS) and Java Message Service (JMS)

UNIT 4 CORBA 4/2/2013 Middleware 59

Today: Distributed Middleware. Middleware

RPC flow. 4.3 Remote procedure calls IDL. RPC components. Procedure. Program. sum (j,k) int j,k; {return j+k;} i = sum (3,7); Local procedure call

Artix Artix for J2EE (JAX-WS)

Transcription:

Advanced Java Programming Legacy Systems Topics Legacy systems Integration & Java Approaches Java Native Interface (JNI) Network protocols (TCP/IP, HTTP) Middleware (RMI, CORBA) Java Message Service (JMS) J2EE Connector Architecture Chris Wong chw@it.uts.edu.au Based on notes by Wayne Brooks and the Sun tutorials Copyright UTS 2008 Legacy Legacy-1 Copyright UTS 2008 Legacy Legacy-2 Legacy Systems Most enterprises have existing, legacy systems. "Enterprise Information Systems" (EIS) mainframe applications proprietary applications These run the back office of most medium-large enterprises. Current trends: web enablement intranet, extranet, internet application integration internal integration Need to access legacy systems in enterprise applications Legacy Systems and Java In the J2EE world, anything not written in Java is legacy by definition! Works both ways: J2EE app accessed by non-java, non-web client e.g. Native Windows app accessing EJBs and displaying data J2EE application accessing non-java servers e.g. EJB connects to mainframe app to retrieve some data = main focus of this lesson Copyright UTS 2008 Legacy Legacy-3 Copyright UTS 2008 Legacy Legacy-4 Approaches Java Native Interface make an EJB "half-java, half-native" Network Protocols (TCP/IP, HTTP) make an EJB establish a network connection RPC Middleware (RMI, CORBA, DCOM) make an EJB call methods on Java/non-Java objects Messaging make an EJB exchange messages with other applications J2EE Connector architecture Topics Legacy systems Integration & Java Approaches Java Native Interface (JNI) Network protocols (TCP/IP, HTTP) Middleware (RMI, CORBA) Java Message Service (JMS) J2EE Connector Architecture Copyright UTS 2008 Legacy Legacy-5 Copyright UTS 2008 Legacy Legacy-6

Java Native Interface (JNI) Define a Java object containing methods that are implemented with native OS code the Java code acts as "wrapper" for the native code, making the native code facilities available in the Java environment public synchronized native String getwindowsregistrykey(string keyname) JNI advantages Allows access to non-java code libraries some vendors may only provide C/C++ libraries to access their proprietary products You can wrap Application Programming Interfaces (API) such as SAP however, better to use J2EE Connector Architecture the implementation of this method would be written in C/C++ code for the Windows environment it would be contained in a Dynamic Link Library (DLL) file that would be loaded at runtime (.so file on Unix) Copyright UTS 2008 Legacy Legacy-7 Copyright UTS 2008 Legacy Legacy-8 JNI disadvantages A Java object with native methods obviously loses its "write once run anywhere" ability it becomes platform-specific Non-distributed solution Java object must run on server with native libraries Memory allocation, thread management, transaction management, security management are not shared between Java and native "parts" bad idea to have EJBs with native code delays/crashes in the native code could adversely affect app server Topics Legacy systems Integration & Java Approaches Java Native Interface (JNI) Network protocols (TCP/IP, HTTP) Middleware (RMI, CORBA) Java Message Service (JMS) J2EE Connector Architecture Copyright UTS 2008 Legacy Legacy-9 Copyright UTS 2008 Legacy Legacy-10 Network Protocols An EJB can create connections to other servers using any TCP/IP protocol therefore can connect to arbitrary TCP/IP servers using the java.net.* libraries often use socket programming Advantage: almost unlimited potential for connecting to other servers Disadvantage: very low level approach requires understanding of the client/server protocol used Protocols HTTP URL Accessing HTTP URLs is a special case of TCP/IP but EJB container has special support In ejb-jar.xml: <resource-ref> <res-ref-name>url/myhttpeaiserver</res-ref-name> <res-type>java.net.url</res-type> <res-auth>container</res-auth> </resource-ref> In MySessionBean.java: InitialContext ctx = new InitialContext(); URL myurl = (URL) ctx.lookup("java:comp/env/url/myhttpeaiserver"); Copyright UTS 2008 Legacy Legacy-11 Copyright UTS 2008 Legacy Legacy-12

Protocols HTTP URL Your application treats this connection as a standard stream. Read/Write application specific data. Uniform Resource Locator (URL) Uniform Resource Locator (URL) allows the identification of resources on the Internet See RFC 2396: Uniform Resource Identifiers (URI) A URL is made up of: Protocol/Scheme Userinfo (optional) Host port (optional) Path (optional) Query (optional) http://cw@learn.it.uts.edu.au:80/dsp/index.htm?pri nt=1 Copyright UTS 2008 Legacy Legacy-13 Copyright UTS 2008 Legacy Legacy-14 URL & URLConnection classes URL example URL class has 2 main methods openconnection() returns a URLConnector object openstream() method returns InputStream URLConnection class has many interesting methods eg: getinputstream() returns InputStream getheaderfield(header) returns headers See class documentation for more. URL u = new URL("http://"+host+"/"+file); //create a BufferedReader to read the //data from the URL in = new BufferedReader( new InputStreamReader( u.openstream openstream())); // & read it in. while ((line = in.readline readline())!= null) { System.out.println(line); in.close(); Copyright UTS 2008 Legacy Legacy-15 Copyright UTS 2008 Legacy Legacy-16 Topics Legacy systems Integration & Java Approaches Java Native Interface (JNI) Network protocols (TCP/IP, HTTP) Middleware (RMI, CORBA) Java Message Service (JMS) J2EE Connector Architecture Middleware RMI Accessing RMI servers from EJBs is easy just like accessing RMI server from a standalone client Advantage: remote access to Java objects w/o app server overheads can combine with JNI to provide remote access to native services Disadvantages: only Java clients can access the RMI server no app server = no transactions, security infrastructure Copyright UTS 2008 Legacy Legacy-17 Copyright UTS 2008 Legacy Legacy-18

Middleware CORBA = Common Object Request Broker Architecture CORBA is a specification developed by the Object Management Group (http://www.omg.org) CORBA is most popular vendor-independent, language-independent, platform-independent middleware environment can have a Windows or Unix native client app accessing EJB in a "standard" way using CORBA calls can have an EJB accessing a CORBA server implemented in almost any language on almost any platform Copyright UTS 2008 Legacy Legacy-19 Middleware CORBA Advantages: allows programmer to link programs written in different languages/platforms into one client. Object-Oriented Re-use existing objects Disadvantages: Complex to program Requires a broker to be installed Some integration issues between vendors/languages Copyright UTS 2008 Legacy Legacy-20 Middleware CORBA An Object Request Broker (ORB) is a software layer which provides interoperability between objects implemented on different platforms IIOP is the on-the-wire protocol used when CORBA clients make method calls on remote CORBA servers Copyright UTS 2008 Legacy Legacy-21 Middleware CORBA A server consists of instances of CORBA objects A client locates these instances by an Interoperable Object Reference (IOR) this can be represented by a string/hex which encodes the servers address/port/access mechanism Example: IOR:010000001300000049444c3a43616c63756c61746f723a312e30000004000000 CORBA 2 also adds a name service Copyright UTS 2008 Legacy Legacy-22 Middleware CORBA RMI and CORBA have many similarities definition of remote interfaces, generation of stubs and skeletons RMI over IIOP is now standard Some differences: CORBA objects may be implemented in many programming languages eg: C, C++, Perl, Java CORBA has its own Naming Service, Transaction Service, etc. Middleware CORBA CORBA is a popular choice for legacy integration, when Remote Procedure Call (RPC) style interaction is required Create a CORBA "wrapper" around legacy system, with defined methods, and allow remote clients (J2EE or other) to call methods Copyright UTS 2008 Legacy Legacy-23 Copyright UTS 2008 Legacy Legacy-24

CORBA development What do you need to know to create/consume CORBA objects? Development process: 1. Create/Use IDL 2. Create remote object class (ie: implement the interface) 3. Create server code 4. Create client code CORBA development - IDL CORBA has a Interface Definition Language (IDL) this defines the operations but not the implementation Many bindings for various languages Need to use language/platform/os specific IDL compiler to generate stubs from the IDL file. IDL supports modularisation, inheritance, operations+attributes of objects, exceptions, datatypes This is based on C++, with some changes for portability between languages & systems Copyright UTS 2008 Legacy Legacy-25 Copyright UTS 2008 Legacy Legacy-26 CORBA development Example of an IDL file module StockApp { struct Quote { string symbol; double price; ; exception Unknown{; interface Stock { Quote get_quote() raises(unknown); void set_quote(in Quote symbol); readonly attribute string desc ; interface StockFactory { Stock create_stock( in string symbol, in string desc); ; ; Equivalent to: java package java class (data) java exception java interface input param class variable. Generates setter/ getter method java method Copyright UTS 2008 Legacy Legacy-27 CORBA development Standard data type mappings IDL Type Java Type boolean boolean char/wchar char octet byte short/unsigned short short long/unsigned long long float float double double string/wstring String Copyright UTS 2008 Legacy Legacy-28 CORBA development Use the IDL compiler to generate stubs/skeleton code For java 1.4 use: idlj [opts] stock.idl This generates: stock.java represents the IDL as an interface stockoperations.java defines the interface stockhelper.java data type operations for interface stockholder.java manages parameters _stockappstub.java local stub to remote object Use f all option to also generate server code. Use -oldimplbase option to generate an implementation skeleton. Copyright UTS 2008 Legacy Legacy-29 CORBA development Next step: You write server code 1. Develop the implementation extend the use the classes in the _*ImplBase.java file generated by idlj program 2. Define a main method 3. Initialize the ORB 4. Create at least one object 5. Connect each object to the orb (you also need to record the IOR often stored as a string in a text file eg: stock.ref) 6. Wait for requests See the following for details: http://java.sun.com/developer/onlinetraining/corba/corba.html Copyright UTS 2008 Legacy Legacy-30

CORBA development Next step: You write client code: 1. Initialise the ORB code, use: org.omg.corba.orb orb = org.omg.corba.orb.init(argv, null); 2. Create the CORBA object. Note that you need to have the IOR. Often this is stored as a text file. Eg: BufferedReader in = new BufferedReader(new FileReader( stock.ref )); ref = in.readline(); org.omg.corba.object obj = orb.string_to_object(ref); contents of stock.ref could look like: IOR:010000000d00000049444c3a4563.. Copyright UTS 2008 Legacy Legacy-31 CORBA development 3. You now use the helper class to convert the CORBA.Object to your class Stock s = StockHelper.narrow(obj); 4. You can now call the remote method.. try { Quote s.get_quote(); // do whatever catch (Unknown e){ // handle the Unknown exception Copyright UTS 2008 Legacy Legacy-32 CORBA development To run application, you need to 1. Start Orb 2. Start Server 3. Run client We only lightly cover CORBA here. See more detailed tutorials and information at: OMG website http://www.omg.org Sun Java website Today s tutorial Topics Legacy systems Integration & Java Approaches Java Native Interface (JNI) Network protocols (TCP/IP, HTTP) Middleware (RMI, CORBA) Java Message Service (JMS) J2EE Connector Architecture Copyright UTS 2008 Legacy Legacy-33 Copyright UTS 2008 Legacy Legacy-34 Messaging Messaging is simply communication between components! NOT e-mail, instant messaging, SMS etc Some applications are more suited for asynchronous programming paradigm De-couples applications sender/receiver are independent! Many legacy applications use Message Oriented Middleware (MOM). one application sends a message to another application destination application will process it when it is ready. destination application may not be connected all the time message may contain arbitrary data (e.g. an XML document representing a purchase order) Copyright UTS 2008 Legacy Legacy-35 Messaging Examples B2B interaction when stocks are low, my company's application sends an automated "purchase order" message to a supplier's messaging system Load sharing hundreds of service requests arrive each second they are placed in a queue and a set of worker EJBs each takes the next item off the queue and processes it Legacy Integration a mainframe app holds the number of remaining seats for a sporting event. This data is duplicated in an Entity EJB for a web app. But if someone books a seat through the mainframe, any EJB must be notified immediately that one less seat is available Copyright UTS 2008 Legacy Legacy-36

Messaging Patterns Point-to-point messaging Publish-subscribe messaging Messaging Patterns Point-to-Point messaging (Queue) based on a "Queue" Producers send messages to the queue Consumers remove messages from the queue Each message will be delivered to exactly one consumer Consumer can filter messages based on header Request/Reply messaging pattern Sender Sender Queue Receiver Copyright UTS 2008 Legacy Legacy-37 Copyright UTS 2008 Legacy Legacy-38 Messaging Patterns Publish-Subscribe (Topic) called Pub/Sub Based on a topic this is a special case of a Queue One-to-Many conversation from a publisher to 1 or more subscriber(s) Publishers can publish messages under a topic Consumers can read messages in a given topic Consumers can filter messages based on header Messaging patterns Request/Reply pattern Producer establishes Queue for replies Producer issues request to Queue or Topic Consumer receives request from Queue to Topic Consumer issues reply to Reply Queue Original Producer receives reply from Reply Queue Publisher Publisher Topic Subscriber Subscriber Producer Request Reply Queue/ Topic Temporary Reply Queue Request Reply Consumer Copyright UTS 2008 Legacy Legacy-39 Copyright UTS 2008 Legacy Legacy-40 Messaging push vs. pull 2 main paradigms on how a consumer gets a message 1. Push model message is "pushed" to consumer whenever a new message is available, a method on the consumer object is called to process the message 1. Pull model consumer has to ask for message a consumer can periodically poll the message queue to check if any new messages have arrived since it last checked Messaging reliability A message queue/topic may be persistent, meaning that if the server crashes the messages are not lost implemented using backend file system or DBMS Messages may be acknowledged different models, including: no acknowledgement expected automatic acknowledgements sent when message received application sends acknowledgement manually Copyright UTS 2008 Legacy Legacy-41 Copyright UTS 2008 Legacy Legacy-42

Messaging and Java Main vendors of non-java MOM products: IBM MQSeries Microsoft MSMQ Java Message Server (JMS) = standard Java API for accessing these MOM s. NOT the same as JavaMail API! Provides a standard interface to vendor specific implementation of the MOM Some vendors provide built in pure Java MOMs e.g. WebLogic SonicMQ Messaging and Java JMS supports all these combinations of messaging Application servers typically support an implementation of JMS i.e. you can set up message queues and topics within the app server, and applications can send and receive messages to these queues/topics Application servers typically support integration with external messaging systems messages to your EJB may come from an external, legacy application your EJB may generate messages destined for some external messaging service Copyright UTS 2008 Legacy Legacy-43 Copyright UTS 2008 Legacy Legacy-44 Messaging and Java What is missing in the spec? Security Load Balancing/Fault Tolerance Error Notifications Administration Message Repository Wire Protocol This means you cannot mix JMS implementations eg: WebLogic and MQSeries Connection provided by application server eg: WebLogic message bridge Interoperability with non-java clients although if you use XML/text messages, should be ok Copyright UTS 2008 Legacy Legacy-45 JMS and J2EE J2EE 1.2 only required the API to be present J2EE 1.3 makes implementation a CORE requirement. Other J2EE components interact with JMS JDBC May use JDBC in same transaction as JMS operation JNDI Location for configured JMS objects JTA/JTS Messages and other operations can be combined in one transaction EJB Asynchronous bean operations with JMS messages Copyright UTS 2008 Legacy Legacy-46 JMS Classes ConnectionFactory Provided by Application server. Creates Connections Connection Active connection to JMS provider Destination Identity of a message destination Session single-threaded context for sending/receiving messages MessageProducer object that sends messages to a destination. Created by a session MessageConsumer object that receives messages from a destination. Created by a session JMS class relationships Application Server JNDI created by JMS provider MessageProducer ConnectionFactory Connection Session Destination MessageConsumer Message MessageListener created by developer Copyright UTS 2008 Legacy Legacy-47 Copyright UTS 2008 Legacy Legacy-48

PTP and Pub/Sub Interfaces JMS Parent Point-to-Point Pub-Sub ConnectionFactory QueueConnectionFactory TopicConnectionFactory Connection QueueConnection TopicConnection Destination Queue Topic Session QueueSession TopicSession MessageProducer QueueSender TopicPublisher MessageConsumer QueueReceiver TopicSubscriber JMS setup The J2EE application server must be configured for JMS It must provide a JNDI registry of The ConnectionFactory (specific to implementation) The Destination (Queue/Topic) This is usually specific to your application server e.g. WebLogic Console Some application servers provide bridges to alternative JMS engines e.g. WebLogic Foreign message bridge Copyright UTS 2008 Legacy Legacy-49 Copyright UTS 2008 Legacy Legacy-50 JMS setup The J2EE application server must be configured for JMS It must provide a JNDI registry of The ConnectionFactory (specific to implementation) The Destination (Queue/Topic) This is usually specific to your application server e.g. WebLogic Console Some application servers provide bridges to alternative JMS engines e.g. WebLogic Foreign message bridge Sender Example-1 First step is to get the ConnectionFactory import javax.jms.*; // import JMS classes import javax.naming.*; // ditto for JNDI InitialContext ctx = new InitialContext(); QueueConnectionFactory qconfactory = (QueueConnectionFactory)ctx.lookup( "weblogic.jms.connectionfactory"); Here we use the weblogic specific JMS provider. You can define your own e.g. myconnectionfactory Copyright UTS 2008 Legacy Legacy-51 Copyright UTS 2008 Legacy Legacy-52 Sender Example-2 Next, get the Connection, Session, Destination queue & MessageProducer sender QueueConnection qcon = qconfactory.createqueueconnection(); QueueSession qsession = qcon.createqueuesession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = (Queue) ctx.lookup("jms.mymessagequeue"); QueueSender qsender = qsession.createsender(queue); Sender Example-3 NOTE: regarding acknowledgements When we create a session, we have 2 parameters CreateQueueSession(transaction?, ack_flag) Transaction? indicates if this is transaction oriented (we chose false) Ack_flag indicates type of acknowledgement of messages Session.AUTO_ACKNOWLEDGE system automatically acknowleges message receipt. Session.CLIENT_ACKNOWLEDGE client manually acknowledges Session.DUPS_OK_ACKNOWLEDGE session acknowledges later, and duplicate messages are ok Copyright UTS 2008 Legacy Legacy-53 Copyright UTS 2008 Legacy Legacy-54

Sender Example-4 Next, create the message. This can be various types ie: StreamMessage - self-describing sequence of Java objects/primitives MapMessage - key-value pairs TextMessage - single string or message body ObjectMessage - single serialized object as message body BytesMessage - stream of bytes Then, start the connection, and send the message TextMessage msg = qsession.createtextmessage(); qcon.start(); msg.settext ("Hello world"); qsender.send (msg); Note: use specific methods for each message types Message formats Messages have 3 main sections Header Used by clients and providers to identify and route messages JMS standard headers e.g. JMSDestination, JMSMessageID, JMSReplyTo, JMSRedelivered, JMSType, JMSTimeStamp, JMSCorrelationId, JMSDeliveryMode (PERSISTENT/NON_PERSISTENT), JMSExpiration, JMSPriority Or user defined. Properties Application-specific, Standard, and Provider-specific Body Message contents eg: TextMessage Copyright UTS 2008 Legacy Legacy-55 Copyright UTS 2008 Legacy Legacy-56 Message Properties Messages can have user defined properties Set property via Message.setTypeProperty() Where Type is one of boolean, byte, short, int, long, float, double, String Eg: msg.setbooleanproperty("isstaff",true) Retrieve the property via Message.getTypeProperty() Eg: msg.getbooleanproperty("isstaff"); Message Selectors You can filter messages by headers or properties This syntax is similar to SQL99. Use as 2 nd parameter on QueueSession.createReceiver() or TopicSession.createSubscriber() Examples: "isstaff = TRUE" "mycount > 5" "JMSPriority > 3" Element Identifiers Operators Literals Values User properties OR JMS headers AND, OR, LIKE, BETWEEN, =, <>, <,>, <=, >=, IS NULL, IS NOT NULL true, false, numbers, strings Copyright UTS 2008 Legacy Legacy-57 Copyright UTS 2008 Legacy Legacy-58 Receiver example - 1 Because application is asynchronous, we have to write thread safe, event driven code Our receiver has to implement MessageListener and have a method called onmessage(message) JMS provider will call this method when it receives a message destined for this program. Note that messages NOT matching filter will be ignored. Receiver example - 2 We use JNDI to find the connection factory and destination Queue qcf = (QueueConnectionFactory)ctx.lookup("weblogic.jms.ConnectionFactory ); qcon = qcf.createqueueconnection(); qsess = qcon.createqueuesession(false,session.auto_a CKNOWLEDGE); queue = (Queue) ctx.lookup( jms.mymessagequeue ); Copyright UTS 2008 Legacy Legacy-59 Copyright UTS 2008 Legacy Legacy-60

Receiver example - 3 We now start a Queue receiver QueueReceiver qreceiver = qsession.createreceiver(queue); And set this class to be activated when we receive a message qreceiver.setmessagelistener(this); And now start the thread which listens for incoming messages qcon.start(); Receiver example - 4 Our application should now just wait for incoming connections. You might use the wait() method for this. You need to have a onmessage(message) method, which is invoked when a message arrives public void onmessage(message msg) { String msgtext = ((TextMessage)msg).getText(); Note that you can have different message types. Your method needs to cope with any of them. Copyright UTS 2008 Legacy Legacy-61 Copyright UTS 2008 Legacy Legacy-62 Message-Driven Beans Under EJB 1.1 spec, EJB s could only produce messages, not receive them. you needed to write wrapper classes and RMI proxies to receive messages EJB 2.0 spec introduced a better method Message Driven Beans (MDB) not to be confused with Management Beans (Mbeans) Message Driven Beans MDBs integrate EJBs with JMS act as a standard JMS message consumer. is a stateless component invoked by the EJB container as a result of receiving messages from a JMS Queue or Topic The MDB then performs business logic based on the message contents Copyright UTS 2008 Legacy Legacy-63 Copyright UTS 2008 Legacy Legacy-64 Message-Driven Beans Message-Driven Beans have no methods that can be invoked by users directly unlike Session and Entity Beans Instead, Message-Driven Beans are message receivers, and implement the onmessage() method a Message-Driven Bean is attached to a message Queue whenever a new message arrives on the queue, the Bean will execute it's onmessage() method the only way to interact with Message-Driven Beans Message Driven Beans Unlike session or entity beans, MDBs have no home or remote interface, and therefore cannot be directly accessed by internal or external clients Clients interact with MDBs only indirectly, by sending a JMS message to a JMS Queue or Topic The EJB container automatically creates and removes MDB instances as needed to process incoming messages The goal of the MDB model is to ensure that developing an EJB that is asynchronously invoked to handle the processing of incoming JMS messages is as easy as developing the same functionality in any other JMS MessageListener Copyright UTS 2008 Legacy Legacy-65 Copyright UTS 2008 Legacy Legacy-66

Message Driven Beans Queue or Topic is defined in the deployment descriptor message selector is also defined in DD - restrictive MDB Life Cycle Does not exist MDB must implement javax.jms.messagelistener and javax.ejb.messagedrivenbean onmessage() must not throw JMS or application exceptions; instead they must be caught or handled. At least, they could be re-thrown as EJBException newinstance() setmessagecontext(mdc) ejbcreate() ejbremove() MessageDrivenBean specifies two methods: ejbremove() is invoked just before the bean is removed setmessagedrivencontext(messagedrivenbean ctx) sets the context for the bean ejbcreate() needs to be defined as well onmessage() Ready pool Copyright UTS 2008 Legacy Legacy-67 Copyright UTS 2008 Legacy Legacy-68 Example Message-driven EJB2 import javax.ejb.*; import javax.jms.*; public class MessageTraderBean implements MessageDrivenBean, MessageListener { public void ejbcreate () throws CreateException { public void ejbremove() { public void setmessagedrivencontext(messagedrivencontext ctx) { public void onmessage(message msg) { try { // process message catch (EJBException ex) { Copyright UTS 2008 Legacy Legacy-69 Example Message-driven EJB3 import javax.ejb.*; @MessageDriven public class MessageTraderBean implements MessageListener { public void onmessage(message msg) { try { // process message catch (Exception ex) { Copyright UTS 2008 Legacy Legacy-70 Example Message-driven bean ejb-jar.xml <ejb-jar> <enterprise-beans> <message-driven> <ejb-name>examplemessagedriven</ejb-name> <ejb-class>examples.ejb20.message.messagetraderbean</ejb-class> <transaction-type>container</transaction-type> <message-driven-destination> <jms-destination-type>javax.jms.topic javax.jms.topic</jms-destination-type> </message-driven-destination> <security-identity> <run-as-specified-identity> <role-name>foo</role-name> </run-as-specified-identity> </security-identity> </message-driven> </enterprise-beans> </ejb-jar> Copyright UTS 2008 Legacy Legacy-71 Messaging summary Messaging is becoming an important topic in enterprise application development The messaging model is scalable, and well-suited to many forms of interactions between looselycoupled enterprise systems More available than was presented in this lesson e.g. publish/subscribe to Topics with many receivers messaging and transactions See http://edocs.bea.com/wls/docs100/jms/ Copyright UTS 2008 Legacy Legacy-72

Topics Legacy systems Integration & Java Approaches Java Native Interface (JNI) Network protocols (TCP/IP, HTTP) Middleware (RMI, CORBA) Java Message Service (JMS) J2EE Connector Architecture J2EE Connector Architecture Intended as a standard way for third-party vendors to allow J2EE applications to access their proprietary systems Vendor provides a "Resource Adapter" for their system, which plugs into a J2EE container JCA compliant EJBs can then access the vendor system via the resource adapter, using a standard, generic API - CCI Very similar to access relational databases via JDBC blackbox resource adapters provide a mock environment for testing purposes Copyright UTS 2008 Legacy Legacy-73 Copyright UTS 2008 Legacy Legacy-74 J2EE Connector Architecture J2EE compliant server must support for JCA JCA defines following services System level contracts for J2EE server and resource adpater to co-ordinate with each other (security, transactions, etc.) Common Client Inteface (CCI) defines client API that J2EE components (EJBs, JSPs etc.) can use to connect and interact with EIS Allows various EIS resource adapters to plug into J2EE applications J2EE Connector Architecture From Programming weblogic J2EE Connectors bea.com Copyright UTS 2008 Legacy Legacy-75 Copyright UTS 2008 Legacy Legacy-76 J2EE Connector process An application using a J2EE Connector would: Locate a ConnectionFactory using JNDI lookup Create a Connection (using ConnectionFactory) Create an Interaction (using Connection) Call Interaction.execute(...) method to access remote system J2EE Connector Architecture Status: support required by J2EE 1.4 app servers Holds future promise for a uniform method for accessing legacy systems from Java if/when vendors provide Resource Adapters for their particular legacy systems Copyright UTS 2008 Legacy Legacy-77 Copyright UTS 2008 Legacy Legacy-78

Summary Many approaches to accessing legacy systems RMI/IIOP allows you to do RPC to existing Java RMI applications Network protocols allow you to connect to network based applications eg. By using Sockets or HTTP URLs. CORBA is good for connecting to existing CORBA based legacy systems. JMS is good for message-oriented interactions which seem well suited to many legacy integration tasks J2EE Connector Architecture provides a neutral mechanism to connect to vendor specific API s Copyright UTS 2008 Legacy Legacy-79