407
THE EXPERT’S VOICE ® IN SOA Jeff Davies, BEA Senior SOA Architect with Ashish Krishna and David Schorow Foreword by Jayaram Kasi Director of Technical Program Management, BEA Systems The Definitive Guide to SOA BEA AquaLogic ® Service Bus A hands-on guide to SOA with BEA AquaLogic ® Service Bus

Davies j. the definitive guide to soa. bea aqua logic service bus(2007)(408)

Embed Size (px)

DESCRIPTION

Definitive Guide to SOA. BEA AquaLogic

Citation preview

Page 1: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

this print for content only—size & color not accurate 7" x 9-1/4" / CASEBOUND / MALLOY(0.8125 INCH BULK -- 408 pages -- 50# Thor)

The eXPeRT’s VOIce® In sOA

Jeff Davies, BEA Senior SOA Architect

with Ashish Krishna and David SchorowForeword by Jayaram Kasi Director of Technical Program Management, BEA Systems

The Definitive Guide to

SOABEA AquaLogic® Service Bus

A hands-on guide to SOA with BEA AquaLogic® Service Bus

eMPOWeRInG PRODUcTIVITY FOR The seRVIce DeVeLOPeR

The Definitive Guide to SOA: BEA AquaLogic® Service BusDear Reader,

In the past few years, Service Oriented Architecture (SOA) in general and Enterprise Service Buses (ESBs) specifically have gained a lot of momentum in the software industry. Although a number of excellent books are available on these topics, the book I really wanted to read was one that married the theory to real-world practice. Like many software developers and architects, I learn best from code. I began learning the BEA AquaLogic® Service Bus (ALSB) while it was still in beta form. I found myself struggling with some of the product’s core concepts and supporting technologies.

It occurred to me that there are many people like myself in the software industry today: software professionals who know what they need to do, but who find themselves at a loss when moving to new products, technologies, and paradigms. I wanted a book that would allow me to understand the service bus quickly and show me, with living code, how these SOA and ESB theories are best put into practice.

Sadly, no such book existed. The opportunity was clear. I began to work on this book knowing that my greatest strength was my ignorance. I would ask the experts at BEA every question I had, and then document their answers. I believe that many of your questions will be the same as mine. Of course, some topics require true expertise before you can write about them authoritatively, specifically security and the Transport SDK. To address these topics, I asked my coauthors Ashish Krishna and David Schorow to contribute their invaluable expertise. As a result, this book is suitable for people who are completely new to ESBs and SOA theory. It is also an invaluable tool for experts in ALSB.

Jeff Davies, BEA Senior SOA Architect

THE APRESS JAVA™ ROADMAP

Beginning J2EE™ 1.4

Beginning Java™ EE 5

The Definitive Guide to SOA:BEA AquaLogic® Service Bus

Davies,Krishna,

Schorow

cYAn MAGenTA

YeLLOW BLAcK PAnTOne 123 c

ISBN-13: 978-1-59059-797-2ISBN-10: 1-59059-797-4

9 781590 597972

90000Shelve in Java Programming/ Web Services (with other SOA books)

User level: Intermediate–Advanced

www.apress.comSOURCE CODE ONLINE

Companion eBook

See last page for details

on $10 eBook version

Companion eBook Available

SOA

The Definitive Guide to

BEA AquaLogic® Service Bus

Page 2: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Jeff Davies with Ashish Krishna and David Schorow

The Definitive Guide toSOA: BEA AquaLogic®

Service Bus

797-4FM 4/4/07 5:00 PM Page i

Page 3: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

The Definitive Guide to SOA: BEA AquaLogic® Service Bus

Copyright © 2007 by BEA Systems, Inc.

All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means,electronic or mechanical, including photocopying, recording, or by any information storage or retrievalsystem, without the prior written permission of the copyright owner and the publisher.

ISBN-13: 978-1-59059-797-2

ISBN-10: 1-59059-797-4

Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1

Trademarked names may appear in this book. Rather than use a trademark symbol with every occurrenceof a trademarked name, we use the names only in an editorial fashion and to the benefit of the trademarkowner, with no intention of infringement of the trademark.

AquaLogic® and all other AquaLogic-based marks are trademarks or registered trademarks of BEA Systems, Inc. in the US and in other countries. Apress, Inc. is not affiliated with BEA Systems, Inc.

Lead Editor: Steve AnglinTechnical Reviewer: Jayaram KasiEditorial Board: Steve Anglin, Ewan Buckingham, Gary Cornell, Jason Gilmore, Jonathan Gennick,

Jonathan Hassell, James Huddleston, Chris Mills, Matthew Moodie, Jeff Pepper, Paul Sarknas, Dominic Shakeshaft, Jim Sumser, Matt Wade

Project Manager: Elizabeth SeymourCopy Edit Manager: Nicole FloresCopy Editors: Susannah Davidson Pfalzer and Heather LangAssistant Production Director: Kari Brooks-CoponyProduction Editor: Katie StenceCompositor: Dina Quan and Gina RexrodeProofreader: Liz WelchIndexer: Broccoli Information ManagementCover Designer: Kurt KramesManufacturing Director: Tom Debolski

Distributed to the book trade worldwide by Springer-Verlag New York, Inc., 233 Spring Street, 6th Floor,New York, NY 10013. Phone 1-800-SPRINGER, fax 201-348-4505, e-mail [email protected], orvisit http://www.springeronline.com.

For information on translations, please contact Apress directly at 2560 Ninth Street, Suite 219, Berkeley,CA 94710. Phone 510-549-5930, fax 510-549-5939, e-mail [email protected], or visit http://www.apress.com.

The information in this book is distributed on an “as is” basis, without warranty. Although every precau-tion has been taken in the preparation of this work, neither the author(s) nor Apress shall have anyliability to any person or entity with respect to any loss or damage caused or alleged to be caused directlyor indirectly by the information contained in this work.

797-4FM 4/4/07 5:00 PM Page ii

Page 4: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Contents at a Glance

Foreword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii

About the Authors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv

About the Technical Reviewer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii

Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xix

Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxi

nCHAPTER 1 Why Use a Service Bus? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

nCHAPTER 2 Installing and Configuring the Software . . . . . . . . . . . . . . . . . . . . . . . . 11

nCHAPTER 3 Hello World Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

nCHAPTER 4 Message Flow Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

nCHAPTER 5 A Crash Course in WSDL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67

nCHAPTER 6 Message Flows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95

nCHAPTER 7 Advanced Messaging Topics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117

nCHAPTER 8 Reporting and Monitoring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173

nCHAPTER 9 Security Models and Service Bus. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195

nCHAPTER 10 Planning Your Service Landscape . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205

nCHAPTER 11 Versioning Services. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233

nCHAPTER 12 Administration, Operations, and Management . . . . . . . . . . . . . . . . . 253

nCHAPTER 13 Custom Transports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281

nCHAPTER 14 How Do I . . . ? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335

nAPPENDIX AquaLogic Service Bus Actions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355

nINDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369

iii

797-4FM 4/4/07 5:00 PM Page iii

Page 5: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

797-4FM 4/4/07 5:00 PM Page iv

Page 6: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Contents

Foreword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii

About the Authors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv

About the Technical Reviewer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii

Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xix

Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxi

nCHAPTER 1 Why Use a Service Bus? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

The Problems We Face Today. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Point-to-Point Integrations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Tight Coupling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3More Code Than Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

Early ESBs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Modern Solutions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

Loose Coupling. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Location Transparency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6Mediation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6Schema Transformation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6Service Aggregation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6Load Balancing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6Enforcing Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7Monitoring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7Configuration vs. Coding. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

Enter AquaLogic Service Bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7Loose Coupling. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7Location Transparency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8Mediation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8Schema Transformation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8Service Aggregation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8Load Balancing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8Enforcing Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9Monitoring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9Configuration vs. Coding. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

Won’t This Lock Me into BEA Technologies? . . . . . . . . . . . . . . . . . . . . . . . . . 9Why Buy an Enterprise Service Bus? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

v

797-4FM 4/4/07 5:00 PM Page v

Page 7: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

nCHAPTER 2 Installing and Configuring the Software . . . . . . . . . . . . . . . . . . 11

Installing the Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

Configuring WebLogic Workshop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

A Quick Tour of Workshop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

Creating the Service Bus Domain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

Configuring Ant in Eclipse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

Configuring Workshop for the AquaLogic Server . . . . . . . . . . . . . . . . . . . . . 16

Importing the Sample Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

nCHAPTER 3 Hello World Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

Creating and Deploying a Web Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

@WebService . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

@SoapBinding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

@WLHttpTransport . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

@WebMethod. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

Creating a POJO Test Client. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

Creating the HelloWorld Project in ALSB . . . . . . . . . . . . . . . . . . . . . . . 35

Creating the WSDL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

Business Services and Proxy Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

Creating the Business Service. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

Creating the Proxy Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

A Quick Note on the Configuration Changes Screen . . . . . . . . . . . . . 45

Testing the Proxy Service. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50

nCHAPTER 4 Message Flow Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

Message Flow Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

Pipeline Pairs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

Branch Nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54

Route Nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

Goodbye World! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

What the Heck Just Happened Here?. . . . . . . . . . . . . . . . . . . . . . . . . . 60

A Hidden Design Flaw . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65

nCONTENTSvi

797-4FM 4/4/07 5:01 PM Page vi

Page 8: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

nCHAPTER 5 A Crash Course in WSDL. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67

Namespaces. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70

The Default Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

Target Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

<types> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74

Native Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74

Custom Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74

minOccurs and maxOccurs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75

Importing XML Schemas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76

<message> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76

<portType> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76

<binding>. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77

<service> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77

<port>. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78

WSDL Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78

Elements vs. Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78

The Dependency Trap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80

Document-Centric vs. RPC. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83

Troubleshooting WSDLs and Schemas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85

Visualizing Documents from Schemas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88

The ElementFormDefault Attribute . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88

The attributeFormDefault Attribute . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92

Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94

nCHAPTER 6 Message Flows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95

Scenario 1: User Requests a Product Catalog . . . . . . . . . . . . . . . . . . . . . . . 95

Scenario 2: User Orders a Product . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110

Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116

nCHAPTER 7 Advanced Messaging Topics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117

Synchronous Invocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117

Asynchronous Invocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119

Setting up WebLogic Server. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120

Asynchronous Business Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120

nCONTENTS vii

797-4FM 4/4/07 5:01 PM Page vii

Page 9: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Service Types and Transport Protocols . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124

SOAP with WSDL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125

SOAP Without WSDL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126

XML with WSDL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127

XML Without WSDL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131

Messaging Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131

Transport Typed Service: EJB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157

POJO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164

SOAP with Attachments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167

Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172

nCHAPTER 8 Reporting and Monitoring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173

Monitoring. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173

The Temperamental Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174

Reporting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188

Viewing Report Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189

Purging Report Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191

Reporting Providers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192

Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194

nCHAPTER 9 Security Models and Service Bus . . . . . . . . . . . . . . . . . . . . . . . . . 195

Security Paradigms with SOA Challenges. . . . . . . . . . . . . . . . . . . . . . . . . . 195

Transport-Level Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196

Message-Level Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197

Ad-Hoc, Custom, Token-Based Security . . . . . . . . . . . . . . . . . . . . . . 197

ALSB Security Model. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198

Inbound Security in ALSB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198

Identity Propagation in ALSB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200

SSL Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200

Digital Signatures and Encryption. . . . . . . . . . . . . . . . . . . . . . . . . . . . 201

Using ALSB Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201

Recommendations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204

nCONTENTSviii

797-4FM 4/4/07 5:01 PM Page viii

Page 10: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

nCHAPTER 10 Planning Your Service Landscape . . . . . . . . . . . . . . . . . . . . . . . . 205

The SOA Coordinate System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205

The Software Abstraction Scale . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205

The Service Domain Scale . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210

The Coordinate System. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211

Mapping Your SOA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213

The Top-Down Approach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213

The Bottom-Up Approach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215

SOA Mapping Test 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216

SOA Mapping Test 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217

Service Maps at Scale. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218

Service Tooling. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219

Architectural Transformation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219

Communication Principles and Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . 224

Communication Principle I . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225

Communication Principle II . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225

Communication Principle III . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225

Communication Pattern I: Flow of Gravity . . . . . . . . . . . . . . . . . . . . . 225

Communication Pattern II: Direct Use of Enterprise Services . . . . 227

Communication Pattern III: Indirect Use of Enterprise Services. . . 228

Communication Pattern IV: Inter-Application Communications Within a Domain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229

Geared for Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229

Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231

nCHAPTER 11 Versioning Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233

What Is a Service?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233

Service Orientation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237

What Is Versioning?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238

Do We Version Services or Operations? . . . . . . . . . . . . . . . . . . . . . . . . . . . 239

Versioning Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240

Versioning Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243

Constrained by Reality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245

If Not Versions, Then What?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245

The Future of IT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251

nCONTENTS ix

797-4FM 4/4/07 5:01 PM Page ix

Page 11: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

nCHAPTER 12 Administration, Operations, and Management. . . . . . . . . . . 253

Support for Team Development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253

The Change Center . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253

Conflict Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253

Undo and Redo. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254

How to Resolve Conflicts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254

System Administration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256

Operations Settings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256

Access Control Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257

Deployment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258

Deployment Automation Basics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260

Advanced Automation Technique . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267

ALSB Clusters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267

Creating a Cluster . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270

Introducing the Node Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271

Controlling Managed Servers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273

Deploying to a Cluster. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274

Location Transparency and ALSB . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274

Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279

nCHAPTER 13 Custom Transports. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281

Introduction to Custom Transports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281

Why Build a Custom Transport? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282

How Does a Custom Transport Fit into ALSB? . . . . . . . . . . . . . . . . . 283

Components of a Custom Transport. . . . . . . . . . . . . . . . . . . . . . . . . . 285

The Sample Socket Transport . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285

Capabilities of the Socket Transport. . . . . . . . . . . . . . . . . . . . . . . . . . 286

Building and Installing the Sample Transport . . . . . . . . . . . . . . . . . . 286

Using the Sample Socket Transport . . . . . . . . . . . . . . . . . . . . . . . . . . 290

Building a Custom Transport . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294

Overview of the Transport SDK Interfaces. . . . . . . . . . . . . . . . . . . . . 294

Overview of Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296

Transport Provider Configuration XML File . . . . . . . . . . . . . . . . . . . . 297

Transport Provider Schemas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298

Implementing Transport Provider User Interface Classes. . . . . . . . 301

Deploying Service Endpoints Using the Custom Transport. . . . . . . 310

Implementing Transport Provider Runtime Classes. . . . . . . . . . . . . 313

Registering the Transport Provider . . . . . . . . . . . . . . . . . . . . . . . . . . . 332

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333

nCONTENTSx

797-4FM 4/4/07 5:01 PM Page x

Page 12: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

nCHAPTER 14 How Do I . . . ? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335

Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335

Administration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337

Messaging and Protocols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343

XML, XQuery, and XSLT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350

Miscellaneous . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351

Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353

nAPPENDIX AquaLogic Service Bus Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . 355

Communication Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355

Dynamic Publish . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356

Publish . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357

Publish Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357

Routing Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358

Service Callout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359

Transport Headers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359

Flow Control Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359

For Each . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360

If . . . Then . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361

Raise Error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361

Reply . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362

Resume . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362

Skip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363

Message Processing Actions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363

Assign . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363

Delete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364

Insert . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364

Java Callout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364

MFL Transform. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365

Rename . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365

Replace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366

Validate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366

Reporting Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366

Alert . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367

Log . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367

Report . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368

nINDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369

nCONTENTS xi

797-4FM 4/4/07 5:01 PM Page xi

Page 13: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

797-4FM 4/4/07 5:01 PM Page xii

Page 14: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

xiii

Enterprise Service Bus (ESB) is a hot topic today. Many vendors are either building newproducts in this category or dressing up their existing products to pitch them as an ESB. How-ever, there is no clearly accepted definition of what an ESB is, or what its architecture orprogramming paradigm should be. Definitions range from saying that ESB is wholly unneededto saying it has all the capabilities of a full integration suite with built-in BPM, data aggrega-tion, and WSM capabilities. Architectures range from being embedded in the clients andendpoints to being a central intermediary. Programming paradigms for the ESB range fromwriting Java to being completely configuration driven and pliable with graphical interfaces.

BEA did not dress up one of their existing products and pitch it as an ESB but built an ESBfrom scratch. First introduced in summer 2005, BEA’s ESB has a razor sharp focus on where itis positioned as a component in an end-to-end SOA architecture. It complements a BPM service or a data aggregation service but serves a different and distinct role. Much of SOA isabout componentization, interconnectivity, and reuse, and the ESB component serves as anintermediary with the clear and distinct role of providing loose coupling between clients andservices, a routing fabric, connectivity, and a central point of security enforcement that con-tribute to the manageability of your SOA network. It can be a central intermediary or adecentralized network of intermediaries. Also, it is completely configuration based withbrowser-based graphical interfaces.

In this book, Jeff Davies introduces you to ESBs in general and BEA’s AquaLogic ServiceBus in particular. He includes many examples and clear, understandable explanations of theproduct and how it can be leveraged to implement a number of ESB use cases. He takes thevery practical and useful approach of picking one of the leading products in the ESB categoryand doing a “show and tell” instead of delving into a lot of philosophical discussions and argu-ments about various contrasting architectures or definitions for an ESB. The book is veryreadable and instructive. As one of the architects of the first release of the product, I feel thisbook is a fine introduction to AquaLogic Service Bus.

Jayaram KasiDirector of Technical Program Management

AquaLogic Service BusBEA Systems

Foreword

797-4FM 4/4/07 5:01 PM Page xiii

Page 15: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

797-4FM 4/4/07 5:01 PM Page xiv

Page 16: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

About the Authors

nJEFF DAVIES, SOA architect and technical evangelist at BEA, has over 20years of experience in the software field. Jeff has extensive experience developing retail applications, such as Act! for the Windows and Macintoshplatforms, and a number of other commercially available applications, principally in the telecommunications field. His background also includesthe development, design, and architecture of enterprise applications. Priorto joining BEA, Jeff was the chief architect at a telecommunications company

and responsible for their SOA. Now at BEA, Jeff is focused on the practical application of BEAproducts to create SOA solutions.

nASHISH KRISHNA is part of the product management team for integrationand SOA products at BEA Systems; he’s responsible for BEA’s integrationproduct. Prior to this, Ashish worked as an SOA architect and was responsiblefor enabling SOA and EDA solutions at key customers for BEA. Ashish was alsopart of core engineering team at BEA responsible for architecture and designof various components for BEA’s ESB. Before BEA, Ashish was a foundingengineering staff member of ECtone, a Silicon Valley start-up that was later

acquired by BEA. Ashish has a diverse background in enterprise integration and softwaredevelopment, including legacy systems, EDI, and ERP integration technologies. He was a consultant for SAP R/3 and EDI, responsible for numerous implementations at Fortune 500companies in telecommunications, automotive, and manufacturing industries. Ashish holds amaster’s degree in aerospace engineering and a bachelor of engineering degree in mechanicalengineering. He is also a PhD candidate in mechanical engineering at Texas A&M University.

nDAVID SCHOROW has over 20 years of experience working on enterprise soft-ware. David is the chief architect for BEA AquaLogic Service Bus and hasguided its development and evolution. Prior to joining BEA, David was thechief Java architect at the NonStop division of HP, overseeing the develop-ment of a wide variety of Java projects, including the NonStop Java JVM,NonStop SQL JDBC drivers, the port of WebLogic Server to the NonStop platform, and other enterprise Java products. David has extensive experience

in high-performance transaction processing systems, the environments used by the mostdemanding, mission-critical applications, such as airline reservations, health care, and banking. David has a bachelor of science degree from MIT and a PhD from the University of California, Berkeley.

xv

797-4FM 4/4/07 5:01 PM Page xv

Page 17: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

797-4FM 4/4/07 5:01 PM Page xvi

Page 18: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

About the Technical Reviewer

nJAY KASI has been an infrastructure architect since 1988, working for Hewlett Packard, Commerce One, and BEA Systems. He has architected the kernel of a relational database management system, system-level high-availability capabilities, a messaging and routing fabric for B2B electronic commerce, and ESBs at both Commerceone and BEA. He has alsoworked as a distributed OLTP architecture consultant. He was one of the key architects ofALSB and has been with the project since inception. He is now the director of program management for ALSB and is working on a variety of integrations with other products.

xvii

797-4FM 4/4/07 5:01 PM Page xvii

Page 19: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

797-4FM 4/4/07 5:01 PM Page xviii

Page 20: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Acknowledgments

There are many people who have helped me to make this book a reality. I want to thank mywife for her love and understanding as I spent hours on my computer mumbling incoherentlyabout “namespaces” and the like. There is no finer wife in the world. Similarly, I’d like to thankmy children, Eric and Madeline, for putting up with my highly distracted nature while writingthis book. Of course, I’d like to thank my parents and my aunt and uncle for enabling me to getto this point in my life with their constant love and support.

I’d like to thank Jay Kasi at BEA for his help and tutelage while writing this book. I havenever met a person with such a deep understanding of any software product in my life. Manytimes when I was stuck on a problem, Jay would quickly look at the code and deliver an exactanalysis of the problem within moments.

I’d also like to thank the many folks who helped review the book and provided me withtechnical answers to the more unusual scenarios. Specifically, I want to recognize (in alpha-betical order) Deb Ayers, Stephen Bennett, Naren Chawla, George Gould, David Groves, DainHansen, Gregory Haardt, Karl Hoffman, Ashish Krishna, Usha Kuntamukkala, Saify Lanewala,Michael Reiche, Kelly Schwarzhoff, Jeremy Westerman, Mike Wooten, and Bradley Wright.

Finally, I’d like to thank the great mentors in my life, Mark Russell and Gerry Millar. Theytaught me everything from how to tie a neck-tie to how to “listen to what they are feeling.”They both taught me that it’s the people who are important; the software is incidental. That’s ahard but invaluable lesson for a natural-born geek. Thank you.

Jeff Davies

The BEA AquaLogic Service Bus team is full of innovative people. Their contributions anddrive to be the best are reflected in the product. I would like to thank the team for all the hardwork. It would not have been possible to write this book without their efforts in producing aworld-class product, and I know firsthand, as I was part of the engineering team for the firstcustomer ship (FCS) back in 2005.

I would like to thank my wife Sumina, and my daughter, Isheeta, for their support andpatience especially in letting me work on this book at late hours, on holidays, and especiallyduring our month-long vacation to India—our first in four years!

Ashish Krishna

Chapter 13 explains the Transport SDK; this useful extensibility mechanism was designed andimplemented by Greg Fichtenholtz, a senior engineer on the ALSB team. It is his design thatenables ALSB to be used in new and different environments not addressed in the originalimplementation. The usefulness of the Transport SDK is because of his good design work.

Greg is only one member of a very talented team that created the ALSB product; however,their names are too numerous to mention (and I’d be afraid of leaving someone out). Thisgroup, with its engineering prowess and creative energy, works under the management ofAshok Aletty, who fosters a productive, cooperative, and enjoyable atmosphere; these people

xix

797-4FM 4/4/07 5:01 PM Page xix

Page 21: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

are responsible for making AquaLogic Service Bus such a fantastic product. I consider myselffortunate to have the opportunity to work with such a great team on this exciting product.

I’d also like to thank my sister, Stephanie Schorow, for her thorough review of an earlydraft of the chapter. She is the real writer of the family—Chapter 13 is much more readablebecause of her efforts.

Lastly, I’d like to thank my wife, Mona, and my son, Marcus, for their understanding andsupport when working on this book required my nights and weekends (and cancelling a skitrip).

David Schorow

nACKNOWLEDGMENTSxx

797-4FM 4/4/07 5:01 PM Page xx

ccee59bc36148c9d24781934e7ce1b10

Page 22: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Introduction

Service-Oriented Architecture (SOA) is rapidly becoming the new standard for today’s enter-prises. A number of books have appeared in bookstores that discuss various aspects of SOA.Most (if not all) are high-level discussions that provide some strategies for you to consider butvery little tactical information. As a software engineer, I am able to grasp these abstract con-cepts fairly quickly, as I’m sure you are. However, the devil is always in the details. I know thatonce I begin to implement a new technology, I will discover a whole new dimension of bugs,design issues, and other problems that are never discussed in those strategic books.

SOA is not a technology—it is architecture and a strategy. In order for you to implementyour own SOA, you need to learn not a single new technology but a whole series of differingtechnologies. I thought I knew XML pretty well before I began walking the path to SOA. It didn’t take long for me to figure out that there was a lot more to XML than I had previouslythought. I had to learn the details of XML, XML Schema, WSDL, XQuery, and XPath before Icould begin to make informed design judgments.

While I enjoy reading about new strategies, I enjoy realizing them in code just as much.Code keeps you honest. A lot of things work very well on paper, but once you start flippingbits, the truth will emerge in all of its intolerant glory. What I really wanted to read was adetailed book on SOA development. Since I could not find one, I wrote one. I wrote this bookunder the assumption that there were thousands of other software developers like myself—people who enjoyed writing code and loved to put theory into practice.

This book is a mix of theory and working code samples. One reason there are so few bookson writing real code for an SOA is because few SOA platforms exist that the average developercan download and use. Most SOA (specifically ESB) vendors keep their software locked away,demanding that you purchase it before you can use it. This is like purchasing a car you havenever seen or driven based solely on the description provided to you by the salesperson.

Fortunately, BEA Systems provides an enterprise class ESB that anyone can download forfree. This book will walk you through many detailed examples of connecting the ALSB tolegacy systems, show common design patterns for web services, and generally increase bothyour development and architectural expertise in ESB and SOA.

What Is AquaLogic?AquaLogic Service Bus is a single product in the AquaLogic product family. The AquaLogicfamily includes many products with diverse functionalities; see the BEA web site for a com-plete listing (www.bea.com).

xxi

797-4FM 4/4/07 5:01 PM Page xxi

Page 23: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

How This Book Is OrganizedThis book comprises 15 chapters in total. We’ve written most of the chapters so that they maybe read individually. However, we do recommend reading Chapters 2 and 3 so that you can set up your development environment and understand the basic principles of an enterpriseservice bus.

Chapter 1, “Why Use a Service Bus?,” describes the functions and benefits of an enterpriseservice bus.

Chapter 2, “Installing and Configuring the Software,” guides you through installing andconfiguring the AquaLogic Service Bus and a development environment. By installing thesoftware as described in this chapter, you will be able to run all of the sample code con-tained in this book.

In Chapter 3, “Hello World Service,” following the grand tradition of programming books,we write a web service, test it, and integrate it with the AquaLogic Service Bus. Along theway, we provide a quick tour of AquaLogic Service Bus Administration console.

In Chapter 4, “Message Flow Basics,” you’ll learn what message flows are, how to createthem, and how they are used in AquaLogic Service Bus.

Chapter 5, “A Crash Course in WSDL,” introduces you to Web Services Description Lan-guage (WSDL), the language of modern web services. Creating (or just reading) WSDLrequires a fair bit of skill beyond simple XML. This chapter teaches you the core of whatyou need to know about WSDLs and leaves out the fluff!

In Chapter 6, “Message Flows,” we really put AquaLogic Service Bus through its paces,with sample code for almost every feature available.

Chapter 7, “Advanced Messaging Topics,” covers just about every weird integration issueand use of ALSB that you will ever see.

Chapter 8, “Reporting and Monitoring,” shows you that there is more to ALSB than justmessaging. It can keep you informed about the health of your enterprise and provideautomated alerts and sophisticated status reports of services and the servers that hostthem.

Chapter 9, “Security Models and Service Bus,” presents a topic that is often discussed butseldom understood. This chapter will provide you with a solid understanding of how toimplement security within your service bus.

Chapter 10, “Planning Your Service Landscape,” discusses the considerable planningrequired to move to SOA. In this chapter, we introduce a methodology that will simplifythis planning process and provide you with a taxonomy by which you can quickly classifyyour services.

Chapter 11, “Versioning Services,” is possibly the most controversial chapter in the book!Forget everything you’ve heard about versioning web services and brace yourself for someheresy!

nINTRODUCTIONxxii

797-4FM 4/4/07 5:01 PM Page xxii

Page 24: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Chapter 12, “Administration, Operations, and Management,” will teach you some bestpractices for how to keep your service bus running, because there is more to a service busthan development.

Chapter 13, “Custom Transports,” explores the Transport SDK. While AquaLogic ServiceBus provides many useful transport protocols out of the box, it also contains an API thatallows you to create your own customer transports, so it can integrate with any legacy system.

Chapter 14, “How Do I . . . ?,” answers some common questions about using AquaLogicService Bus in the real world.

The Appendix, “AquaLogic Service Bus Actions,” is a quick reference for the actions sup-ported by AquaLogic Service Bus.

—Jeff Davies

nINTRODUCTION xxiii

797-4FM 4/4/07 5:01 PM Page xxiii

Page 25: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

797-4FM 4/4/07 5:01 PM Page xxiv

Page 26: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Why Use a Service Bus?

Enterprise Service Buses (ESBs) are all the rage in modern software development. You can’tpick up a trade magazine these days without some article on ESBs and how they make yourlife wonderful. If you’re a software development veteran, you’ll recognize the hype immedi-ately. ESBs aren’t going to be the magic answer for our industry any more than were XML, webservices, application servers, or even ASCII. Each of the aforementioned technologies startedlife with a lot of fanfare and unrealistic expectations (the result of the inevitable ignorance weall have with any emerging technology), and each technology ended up becoming a reliabletool to solve a specific set of problems.

The same is true for the ESB. Putting the hype aside, let’s focus on a bit of software historyso we can better understand the problems that the ESB is designed to address.

The Problems We Face TodaySoftware development is a tough business. We expect modern software systems to have expo-nentially more functionality than we expected from them only a few years ago. We oftendevelop these systems with ever-dwindling budgets and sharply reduced timeframes, all in aneffort to improve efficiency and productivity. However, we cannot lament these issues. Thesevery issues drive us to deliver software that’s better, faster, and cheaper.

As we’ve raced to develop each generation of software system, we’ve added significantly tothe complexity of our IT systems. Thirty years ago, an IT shop might have maintained a singlesignificant software system. Today most IT shops are responsible for dozens, and sometimeshundreds, of software systems. The interactions between these systems are increasingly com-plex. By placing a premium on delivering on time, we often sacrifice architecture and design,promising ourselves that we’ll refactor the system some time in the future. We’ve developedtechnologies that can generate large quantities of code from software models or templatecode. Some of the side effects of this race into the future are a prevalence of point-to-pointintegrations between software applications, tight coupling at those integration points, lotsof code, and little configuration.

1

C H A P T E R 1

7974CH01.qxd 2/20/07 1:10 PM Page 1

Page 27: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Point-to-Point IntegrationsSoftware development today is tactical and project oriented. Developers and architects fre-quently think in terms of individual software applications, and therefore their designs andimplementations directly reflect this thinking. As a result, individual applications are directlyintegrated with one another in a point-to-point manner.

A point-to-point integration is where one application depends on another specific appli-cation. For example, in Figure 1-1, the CustomerContactManager (CCM) application uses theBilling application interface. You can say that the CCM application “knows” about the billingapplication. You also hear this kind of relationship referred to as a “dependency,” becauseone application depends on another application to function correctly.

Figure 1-1. Early point-to-point integrations

Figure 1-1 illustrates a trivial IT environment, one that has only two applications and twopoint-to-point integrations. Just to be clear, the first integration allows the CCM system tocall the Billing system. The second integration point allows the Billing system to call the CCMsystem. When your IT department is this small, point-to-point integration is fairly easy tomanage.

Figure 1-2 expands on the problem a bit. The IT shop is now home to 8 software systemsand a total of 11 integration points. This illustrates a common pattern in integration: the num-ber of integration points grows faster than the number of systems you’re integrating!

Even Figure 1-2 is, by modern standards, a trivial IT system. A midsized service providerwhere Jeff once worked had 67 business systems and another 51 network systems. One hun-dred eighteen software systems integrated in a point-to-point manner is unmanageable. Weknow of telcos that have 12 or more billing systems. Having duplicates of certain software sys-tems (such as billing) or having a large number of software systems in general is quitecommon; large companies can acquire smaller companies (and therefore acquire the softwaresystems of the smaller companies) faster than most IT shops can integrate the newly acquiredsystems.

CHAPTER 1 n WHY USE A SERVICE BUS?2

7974CH01.qxd 2/20/07 1:10 PM Page 2

Page 28: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Tight CouplingTight coupling is often a byproduct of point-to-point integrations, but it’s certainly possible todevelop tightly coupled applications no matter what your integration environment looks like.There are two types of coupling, tight and loose. Loose coupling is desirable for good softwareengineering, but tight coupling can be necessary for maximum performance. Coupling isincreased when the data exchanged between components becomes larger or more complex.In reality, coupling between systems can rarely be categorized as “tight” or “loose.” There’s acontinuum between the two extremes.

Most systems use one another’s APIs directly to integrate. For Enterprise JavaBeans (EJB)applications, you commonly create a client JAR file for each EJB application. The client JAR filecontains the client stubs necessary for the client applications to call the EJB application. If youmake a change to any of the APIs of the EJB application, you need to recompile and deploy theEJB application, recompile the client JAR, and then recompile and redeploy each of the clientapplications. Figure 1-3 illustrates this set of interdependencies between the software compo-nents and the file artifacts that realize them.

CHAPTER 1 n WHY USE A SERVICE BUS? 3

Figure 1-2. Increasing point-to-point integration

7974CH01.qxd 2/20/07 1:10 PM Page 3

Page 29: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 1-3. EJB coupling model

Tight coupling results in cascading changes. If you change the interface upon which othercomponents depend, you must then recompile the client applications, often modifying theclient code significantly.

It’s a common (and false) belief that you can use interfaces to reduce the couplingbetween systems. Interfaces are intended to abstract out the behavior of the classes thatimplement the interfaces. They do provide some loosening of the coupling between the clientand the implementation, but their effect is almost negligible in today’s systems. This is not tosay that interfaces aren’t useful; they most certainly are. But it’s important to understand thereasons why they’re useful. You still end up tightly coupled to a specific interface. For example:

package com.alsb.foo;public interface SampleIF {

public int getResult(String arg1);}

A client that depends on this interface is tightly coupled. If you change the getResult()method to take another argument, all clients of the interface must be recompiled. It’s preciselythis level of intolerance to change that tightly couples the code. The problem isn’t so much inthe design of the interface, but with the technology that implements the interface.

More Code Than ConfigurationEvery medium-to-large sized enterprise runs a lot of code these days. We have so much codeas an industry that we needed to invent tools to manage it all. We have source code control(SCC) systems that provide document management of our code. In the last few years we’veseen the rise of source code knowledge bases.

CHAPTER 1 n WHY USE A SERVICE BUS?4

7974CH01.qxd 2/20/07 1:10 PM Page 4

Page 30: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Early ESBsEarly ESBs were primarily concerned with making web services available to service con-sumers. Their implementation was clunky (as new technologies usually are) and didn’tembrace many open standards, simply because those standards didn’t exist at the time. Fur-thermore, the developers of early ESBs could only try to predict how web services would affectenterprise computing and IT organizations.

The early ESBs were “ESBs” in name only. As the industry has matured, so has our under-standing of the role of an ESB in modern architecture. Today’s ESBs must go far beyond simply“service enabling” functionality. An ESB must also provide robust solutions for today’s ITchallenges.

Modern SolutionsThe IT industry is constantly evolving. Our understanding of the issues that surround themanagement of large IT systems matures on a daily basis. Modern ESBs are simply the latesttools to help us manage our IT problems. They benefit from real-world examples of howService-Oriented Architecture (SOA) is changing the face of today’s advanced corporations.Although early ESBs could only address a handful of the following issues, modern ESBs needto address them all.

Loose CouplingYou might have heard that web services provide you with loose coupling between systems.This is only partially true. Web services, by the very nature of Web Services Description Lan-guage (WSDL) and XML Schema Document (XSD), can provide some loose coupling becausethey formalize a contract between the service consumer and the service provider. This is a“design by contract” model, and it does provide tangible benefits. If you’re careful, you cancreate a schema that’s platform neutral and highly reusable.

However, if you take a look at any WSDL you’ll see that the service endpoints are writteninto the WSDL, as you can see in Listing 1-1.

Listing 1-1. HelloWorld Service Defintion

<service name="HelloWorldService"><port binding="s1:HelloWorldServiceSoapBinding"

name="HelloWorldPortSoapPort"><s2:address location="http://www.bea.com:7001/esb/Hello_World" />

</port></service>

By specifying a specific machine and port (or a set of machines and ports), you’re tightlycoupling this service to its physical expression on a specific computer. You can use a DomainName Server (DNS) to substitute portions of the URL, and therefore direct clients into multi-ple machines in a server farm. However, DNS servers are woefully inadequate for this, due totheir inability to understand and manage the status of the services running on these servers.

CHAPTER 1 n WHY USE A SERVICE BUS? 5

7974CH01.qxd 2/20/07 1:10 PM Page 5

Page 31: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

So, loose coupling isn’t achieved by WSDL or web services alone. A more robust solution isto provide some mediation layer between service clients and service producers. Such a media-tion layer should also be capable of bridging transport and security technologies. For example,a service might be invoked through a traditional HTTP transport mechanism, but it can theninvoke lower-level services through Java Message Service (JMS), e-mail, File Transfer Protocol(FTP), and so on. This approach is often effectively used to “wrap” older services and theirtransports from the newer service clients.

Location TransparencyLocation transparency is a strategy to hide the physical locations of service endpoints from theservice clients. Ideally a service client should have to know about a single, logical machine andport name for each service. The client shouldn’t know the actual service endpoints. This allowsfor greater flexibility when managing your services. You can add and remove service endpointsas needed without fear of having to recompile your service clients.

MediationAn enterprise service bus is an intermediary layer, residing between the service client and theservice providers. This layer provides a great place for adding value to the architecture. An ESBis a service provider to the service clients. When clients use a service on the service bus, theservice bus has the ability to perform multiple operations: it can transform the data or theschema of the messages it sends and receives, and it can intelligently route messages to vari-ous service endpoints, depending on the content of those messages.

Schema TransformationThe web service published by the service bus might use a different schema from the schemaof the business service it represents. This is a vital capability, especially when used in conjunc-tion with a canonical taxonomy or when aggregating or orchestrating other web services. It’squite common that a service client will need to receive its data using a schema that’s signifi-cantly different from that of the service provider. The ability to transform data from oneschema to another is critical for the success of any ESB.

Service AggregationThe service bus can act as a façade and make a series of web service calls appear as a singleservice. Service aggregation follows this pattern, making multiple web service calls on behalfof the proxy service and returning a single result. Service orchestration is similar to serviceaggregation, but includes some conditional logic that defines which of the lower-level webservices are called, and the order in which they’re invoked.

Load BalancingDue to their position in any architecture, ESBs are well suited to perform load balancing ofservice requests across multiple service endpoints. When you register a business web servicewith AquaLogic Service Bus (ALSB), you can specify the list service endpoints where thatbusiness service is running. You can change this list, adding or removing service endpointswithout having to restart the ALSB server.

CHAPTER 1 n WHY USE A SERVICE BUS?6

7974CH01.qxd 2/20/07 1:10 PM Page 6

Page 32: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Enforcing SecurityYou should enforce security in a centralized manner whenever possible. This allows for agreater level of standardization and control of security issues. Furthermore, security is bestenforced through a policy-driven framework. Using security policies means that the creationand application of security standards happens outside the creation of the individual webservices.

MonitoringAn ESB plays a vital role in an SOA. As such, you must have a robust way to monitor the statusof your ESB, in both proactive and reactive manners. The ability to proactively view the per-formance of the service bus allows you to help performance-tune the service bus for betterperformance. Tracking the performance over time can help you plan for increasing the capac-ity of your ESB.

Reactive monitoring allows you to define alerts for specific conditions. For example, if aspecific service doesn’t complete within a given timeframe, the ESB should be able to send analert so that a technician can investigate the problem.

Configuration vs. CodingA modern service bus should be configuration based, not code based. For many engineersthe importance of that statement isn’t immediately obvious. It took us some time before weappreciated the configuration-oriented capability of ALSB. Most software systems in use todayare code based. J2EE applications are a great example of this. In a J2EE application you writesource code, compile it into an EAR or WAR file, copy that EAR or WAR file onto one or moreJ2EE application servers, then deploy those applications. Sometimes it’s necessary to restartthe J2EE server, depending on the nature of your deployment.

Configuration-based systems work differently. There’s nothing to compile or deploy. Yousimply change the configuration and activate those changes. We would argue that your tele-phone is configuration based; you configure the telephone number you want to call, and yourcall is placed. There’s no need to restart your phone. Similarly, network routers and switchesare configuration based. As you make changes to their configuration, those changes takeeffect. There’s no need for a longer software development life cycle to take place.

Configuration and coding are two different strategies. Neither is superior to the other inall situations. There are times when the J2EE approach is the right approach, and times whenthe configuration-based approach is best.

Enter AquaLogic Service BusBEA released AquaLogic Service Bus in June 2005. ALSB runs on Windows, Linux, and Solarisplatforms. ALSB is a fully modern ESB and provides functionality for each of the capabilitiesexpected from today’s enterprises, described in the following sections.

Loose CouplingAside from the loose coupling benefits from WSDL and XSD, ALSB adds the ability to storeWSDL, XSD, eXtensible Stylesheet Language Transformation (XSLT), and other information

CHAPTER 1 n WHY USE A SERVICE BUS? 7

7974CH01.qxd 2/20/07 1:10 PM Page 7

Page 33: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

types within the ALSB server as “resources.” These resources are then made available through-out the ALSB cluster of servers, allowing you to reuse these resources as needed.

The benefit of this might not be immediately clear, so we’ll give an example. Many com-panies define and manage enterprise-wide data types using an XML schema. Because ALSBcan store an XML schema as a resource in the service bus, that schema can easily be reused byany number of WSDLs or other XSDs. This enables you to create and enforce enterprise-widestandards for your data types and message formats.

Location TransparencyOne of the capabilities of ALSB is to register and manage the locations of various web serviceswithin the enterprise. This provides a layer of abstraction between the service client and theservice provider, and improves the operational aspect of adding or removing service providerswithout impact to the service clients.

MediationOne of the roles for which ALSB is specifically designed is that of a service mediator. ALSB usesthe paradigm of “proxy services” and “business services,” where the proxy service is the serv-ice that ALSB publishes to its service clients, and the business services are external to ALSB. Inbetween the proxy service and the business service is the layer where service mediation takesplace. Schemas can be transformed, as can the data carried by those schemas. Intelligent orcontent-based routing also takes place in this mediation layer.

Schema TransformationSchema transformation is a central capability of ALSB. ALSB provides a number of ways totransform schemas, depending on your specific needs. You can use XSLT to transform XMLdata from one schema to another. Similarly, you can use XQuery and XPath to perform XMLschema transformations. Additionally, ALSB supports the use of Machine Format Language(MFL) to format schemas to and from non-XML formats.

Service AggregationALSB doesn’t match a single proxy service to a single business service. Instead, ALSB allowsyou to define a many-to-many relationship between proxy services and business services.This approach allows for service aggregation, orchestration, and information enrichment.

Load BalancingBecause ALSB registers the service endpoints of all business services, it’s ideally situated foroperating as a load balancer. This is especially true because ALSB is configuration based, notcode based. As a result, you can add or remove service endpoints from a business service andactivate those changes without having to restart your service bus.

CHAPTER 1 n WHY USE A SERVICE BUS?8

7974CH01.qxd 2/20/07 1:10 PM Page 8

Page 34: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Enforcing SecurityALSB, as a service mediator, is ideally situated to enforce the security of the web servicesbecause it operates on the perimeters of the enterprise. ALSB is designed to enforce securitythrough the use of explicit security policies. Using ALSB, you can propagate identities, medi-ate, and transform between different security technologies, such as Basic Authentication,Secure Sockets Layer (SSL), and Security Assertion Markup Language (SAML).

MonitoringALSB provides a robust set of features around monitoring. The service bus console allows youto look proactively at the state of your entire ESB.

For reactive monitoring, ALSB allows you to define alerts for conditions that you define.You can send these alerts via Simple Network Management Protocol (SNMP) traps to third-party monitoring programs, such as Hewlett Packard’s OpenView or AmberPoint’s SOAManagement System. Also, alerts can be delivered via e-mail to specified recipients. We’lldiscuss monitoring more fully in Chapter 8.

Configuration vs. CodingALSB is a configuration-based service bus. You don’t write Java code for ALSB, although ALSBcan recognize and make use of Java code in some circumstances. Instead, you configureALSB through its web-based console.

One handy feature of the ALSB console is the Change Center. Your configuration changesdon’t take effect when you make each change. Instead, your configuration changes aregrouped together, similarly to a database transaction, and only take effect when you tell ALSBto activate your changes. This is a critical capability, because many times you’ll make multiplechanges that are interdependent.

Of course, creating these changes by hand can be an error-prone process. As a result,ALSB allows you to make changes in one environment (a development or a test environment)and then export those changes as a JAR file. You can then import that JAR file into your pro-duction environment as a set of configuration changes, and activate them as if you hadentered those changes directly into the Change Center by hand.

Won’t This Lock Me into BEA Technologies?ALSB is entirely standards based. You configure ALSB through the use of XQuery, XPath, XSLT,and WSDLs. The only aspect of ALSB that might be deemed “proprietary” is the implementa-tion of the message flows (see Chapter 4). However, these message flows are simply graphicalconstructs for common programming logic, and they’re easy to reproduce in just about anyprogramming language. The real heavy lifting in ALSB is done using the open standards forfunctionality, and WebLogic Server for reliability and scalability.

Because ALSB is standards based, it’s designed to integrate with and operate in a hetero-geneous architecture. Using ALSB as a service bus doesn’t preclude you from using othertechnologies in any way. ALSB is used to integrate with .NET applications, TIBCO, SAP, Oracle,JBoss, WebSphere, Siebel, and many more. BEA didn’t achieve this level of heterogeneity byaccident; it’s all part of its “blended” strategy: using open standards and open source toachieve the maximum amount of interoperability.

CHAPTER 1 n WHY USE A SERVICE BUS? 9

7974CH01.qxd 2/20/07 1:10 PM Page 9

Page 35: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Why Buy an Enterprise Service Bus?We come across this question frequently. The truth is that an ESB contains no magic in it at all.It’s possible to build your own ESB from scratch. In fact, one of the authors has done it twicebefore joining BEA. There’s nothing that the engineers at BEA can write that you cannot write,given enough time, money, and training. This principle holds true for all software. You don’thave to use Microsoft Word to write your documents; you could create your own word proces-sor. The same holds true for your web browser. HTML standards are publicly available, andyou could use your engineering time to develop your own browser.

Naturally, few of us would ever consider writing our own word processor or web browser.It’s a far better use of our time and money either to buy the software or to use an open sourceversion. This is especially true if your company isn’t a software company. If you work in an ITshop for a company whose primary line of business isn’t software, you’ll recognize the factthat building software from scratch is a difficult sell to your executive staff. There simply is noreturn on investment for such development efforts. Your time and skills are better spent solv-ing problems specific to your company.

There are a number of benefits to purchasing ALSB. First is the fact that it comes from adyed-in-the-wool software company. BEA has been in business for more than a decade andhas a long history of delivering innovative, successful products. Furthermore, BEA supportsthose products for many years. BEA’s first product was Tuxedo, a product that BEA still sellsand supports to this day, though it’s gone through many versions to keep it current withtoday’s technologies.

A number of open source ESBs are available today. Most are in the early stages of develop-ment and functionality. Although we love open source and advocate its use in many areas, wewould be hesitant to use an open source ESB. An ESB will become the central nervous systemof your enterprise. You should exercise caution and diligence when selecting an ESB. You wantone with a proven record of success, from an organization that works hard to keep itself aheadof current market demands.

ALSB is built on BEA’s WebLogic Server technology. This gives you enterprise-qualityreliability and scalability. On top of this, AquaLogic is built on open standards for maximuminteroperability in a heterogeneous environment. It’s an ESB that will carry your company intothe future.

SummaryIn this chapter we reviewed the features and functions that a modern ESB should have, andwe’ve described each feature’s importance to the organization. ALSB implements all these fea-tures, and possesses many more advanced features that we’ll cover in this book. But we’vetalked enough about ALSB. It’s time to start to demonstrate, in working code, exactly how touse these features to their fullest.

CHAPTER 1 n WHY USE A SERVICE BUS?10

7974CH01.qxd 2/20/07 1:10 PM Page 10

Page 36: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Installing and Configuringthe Software

This chapter will walk you through the installation process for ALSB and the process of con-figuring your development environment. By the end of this chapter, you’ll be able to compileand run the sample code that comes with this book.

To begin with, you need a computer that runs Java. Specifically, it needs to run Java Devel-opment Kit (JDK ) version 1.5 or later. All the examples are written using JDK 1.5, and ALSBrequires that you have JDK 1.5 installed. Fortunately, ALSB ships with two different JDKsthat meet this requirement. One is the JRockit JDK, which is intended for use on productionsystems that run on Intel (or compatible) CPUs. The second is the Sun JDK, which is recom-mended for use with development versions of ALSB, or production versions that aren’trunning on Intel-compatible CPUs.

Naturally, you need to install the ALSB software. You can download ALSB from http://dev2dev.bea.com/alservicebus/. It’s also a good idea to download the most recent documen-tation so you can stay informed about recent changes.

Of course, you’ll need an editor to edit your sample source code. ALSB ships withWebLogic Workshop, an IDE that’s based on Eclipse (http://www.eclipse.org), and comeswith a suite of Eclipse plug-ins that are preconfigured to make your development with ALSBmust faster.

You’ll often use Ant to build your software, especially the Java web service that will act asyour “business service” (more about business services later). You’ll need Ant version 1.6 orlater. Like most of the software used by ALSB, Ant is included with the ALSB installer and ispreconfigured into the WebLogic Workshop environment. The Ant home page is at http://ant.apache.org.

Finally, you’ll need two software packages for some of your more advanced work with theservice bus. The first is an FTP server that you’ll use to demonstrate integrating the service buswith legacy systems via FTP. You can use any FTP server that you like. We selected the FileZillaFTP server, which resides at http://filezilla.sourceforge.net/. Also, you’ll need access toan e-mail server when testing the e-mail integration. Because your company might not appre-ciate you sending test e-mails over its e-mail server, we recommend installing your own e-mailserver. We selected Java Mail Server, which is available at http://www.ericdaugherty.com/java/mailserver. Because both FTP and SMTP are based on well-defined standards, feel freeto substitute your own FTP and e-mail servers. However, we do provide a detailed configura-tion walkthrough of both these programs, so if you aren’t accustomed to setting up these typesof servers, you’re better off using the same ones we’ve used.

11

C H A P T E R 2

7974CH02.qxd 2/20/07 1:14 PM Page 11

Page 37: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

You’ll find all the software you need for this book in the Source Code/Download area ofthe Apress web site at http://www.apress.com.

Installing the SoftwareALSB comes with most of the software you’ll need to compile and deploy the applications youcreate in this book: Ant, WebLogic Workshop, WebLogic 9.x, and the JDK 1.5. Installing ALSB isa breeze. For the most part, you can safely accept the default values provided by the installa-tion program. However, we do recommend creating a new BEA home directory if you have aprevious version of WebLogic 9 installed. On our system we have WebLogic 8.1 installed in thetraditional BEA home directory of C\bea. We installed ALSB into C:\bea92ALSB to keep theinstallations separate.

Once you have the software installed, you need to do a little configuration to complete thesetup.

Configuring WebLogic WorkshopALSB ships with a customized version of Eclipse known as the WebLogic Workshop. Thiscustomization is achieved by using Eclipse’s plug-in capability to extend Eclipse. Workshopcomes entirely preconfigured and ready to run. When you start Workshop for the first time, itwill ask you to select a workspace (see Figure 2-1). A workspace is a directory where your Work-shop projects will be created. Workshop allows you to create as many workspaces as you like.For your purposes, we recommend that you name your new workspace alsb_book, and usethat workspace as the home for all the projects you’ll create in this book.

Figure 2-1. Create a workspace in Eclipse.

Once you’re happy with the name of your workspace, click the OK button, and theWebLogic Workshop IDE loads. If you’re familiar with the Eclipse IDE, learning Workshop willbe a breeze for you. If you’re moving to WebLogic Workshop 9 from WebLogic Workshop 8, orare otherwise unfamiliar with Workshop 9, we’ll review the major capabilities of the latest ver-sion of Workshop in the following section. Also, you’ll find that the first project in Chapter 3will walk you through the IDE in detail, making it much easier to learn the Workshop IDE asyou go.

CHAPTER 2 ■ INSTALLING AND CONFIGURING THE SOFTWARE12

7974CH02.qxd 2/20/07 1:14 PM Page 12

Page 38: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

A Quick Tour of WorkshopWorkshop is a modern IDE for developing modern applications. Much of the functionality ofWorkshop is directly inherited from Eclipse. Developers using Workshop enjoy the featuresthey’ve come to expect from a modern IDE: code completion, code refactoring, project aware-ness, built-in Ant and JUnit, and much more. Workshop is even aware of a wide variety ofapplication servers, and you can easily configure it to start and stop application servers fromwithin the IDE. A robust debugger is included.

When you run Workshop for the first time, it will resemble Figure 2-2. The left side of theIDE is dedicated to project information. The right side shows properties and annotations ofthe current file. The bottom portion of the IDE provides information on code problems, holds“watched” variables during debugging sessions, and tracks task markers in your code. Thecenter of the IDE is dedicated to editing source code and other file types.

Figure 2-2. Workshop’s first run

You might have noticed that Workshop makes liberal use of tabs. Every window in the IDEhas a tab, allowing you to switch quickly between different views of information. This helps tomake the most of your screen real estate. The real star of the show is the icon with each win-dow. Those of you moving to Workshop 9 from Workshop 8 will also love this little icon.Clicking this icon causes the associated window to expand to fill the entire IDE applicationwindow. The claustrophobic days of Workshop 8 are now a distant memory!

CHAPTER 2 ■ INSTALLING AND CONFIGURING THE SOFTWARE 13

7974CH02.qxd 2/20/07 1:14 PM Page 13

Page 39: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

You also want to configure Workshop to be aware of the specific libraries you’ll need touse, especially for some of your client code that doesn’t execute within a WebLogic container.To this end, you need to create several libraries in Workshop. A library is just a named collec-tion of JAR files that you can add to your projects.

Begin by selecting Windows ➤ Preferences from the main menu bar of Workshop. Whenthe Preferences dialog appears, select the Java ➤ Build Path ➤ User Libraries path in the tree.Click the Add button and specify the name of the library (see Figure 2-3). Your first library willbe designed for web service test clients, so name the library WebLogic WebService Client.

Figure 2-3. Naming the new library

Next, click the Add JARs button. You need to navigate into your %WEBLOGIC_HOME%\server\lib directory to find the JAR files you need. Select the following JAR files:

%WEBLOGIC_HOME%\server\lib\weblogic.jar%WEBLOGIC_HOME%\server\lib\webserviceclient.jar%WEBLOGIC_HOME%\common\lib\apache_xbean.jar

That’s it for our short tour of Workshop. You’ll learn more as you begin to use it in Chapter 3.

Creating the Service Bus DomainFor the purposes of this book, you’ll create a new WebLogic 9 domain for ALSB. You’ll use theConfiguration Wizard. On a Windows box, from the Start menu select BEA Products ➤ Tools ➤Configuration Wizard. Once the wizard is running, perform the following steps:

1. Ensure the “Create a new WebLogic domain” radio button is selected and click the Nextbutton.

2. Ensure the “Generate a domain configured automatically to support the followingBEA Products” radio button is selected. Also ensure the ALSB and the Workshop forWebLogic Platform checkboxes are checked. Click the Next button.

3. Set the password to something simple, such as weblogic. Be sure your Caps Lock isn’tset on your keyboard. Click the Next button.

4. Select Development Mode and the BEA-supplied JDK radio buttons. Select the SunSDK from the associated listbox. The JDK must be version 1.5.0 or later. Click the Nextbutton.

CHAPTER 2 ■ INSTALLING AND CONFIGURING THE SOFTWARE14

7974CH02.qxd 2/20/07 1:14 PM Page 14

Page 40: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

5. In the Customize Environment and Service Settings page, ensure the No radio buttonis selected and click the Next button.

6. Set the Domain name to alsb_book and click the Create button.

7. In the Creating Domain page, check the Start Admin Server checkbox, then click theDone button.

You have now created and started the alsb_book domain that you’ll use for the rest ofthis book.

Configuring Ant in EclipseThe Ant plug-in in Workshop needs a slight configuration to enable it to recognize theWebLogic-specific Ant tasks you’ll use in this book. Furthermore, some WebLogic Ant taskssimply won’t work unless you tell Ant about the weblogic.jar file. From the main menu inWorkshop, select Window ➤ Preferences. This displays the preferences as shown in Figure 2-4.In the Preferences dialog, navigate to the Ant/Runtime category, then click the Classpath tab.You need to add the weblogic.jar file to the Ant classpath. Click the Ant Home Entries and thenclick the Add External JARs button. Navigate to your <BEA_HOME>\weblogic92\server\libdirectory and select the weblogic.jar file.

Figure 2-4. Configuring the Ant plug-in in Workshop

This enables Ant to recognize the WebLogic-specific Ant tasks listed in Table 2-1.

CHAPTER 2 ■ INSTALLING AND CONFIGURING THE SOFTWARE 15

7974CH02.qxd 2/20/07 1:14 PM Page 15

Page 41: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Table 2-1. WebLogic-Specific Ant Tasks

Task Description

ClientGenTask Web service client generator Ant task

JwscTask Java web service compiler Ant task

WLDeploy WebLogic deployment Ant task

WsdlcTask WSDL compiler Ant task

You’ll use these tasks in each of your project Ant files.

Configuring Workshop for the AquaLogic ServerNext you want to configure Workshop for WebLogic so you can manage your ALSB server fromthe Workshop interface. Using the Workshop menu, select File ➤ New ➤ Server. The NewServer dialog appears, and the Server’s host name field should be set to localhost, as shownin Figure 2-5. Click the Next button.

Figure 2-5. The first step in creating a new server is to specify the host name and runtime.

Your next step is to select the domain that you created earlier in this chapter. Once you’veselected the alsb_book domain, as shown in Figure 2-6, click the Next button.

The last step of configuring a server is to define the projects that are deployed on theserver. Because you don’t have any projects defined yet, just click the Finish button, as shownin Figure 2-7.

CHAPTER 2 ■ INSTALLING AND CONFIGURING THE SOFTWARE16

7974CH02.qxd 2/20/07 1:14 PM Page 16

Page 42: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 2-6. Selecting the domain home of the server

Figure 2-7. Adding and removing projects from the ALSB server

CHAPTER 2 ■ INSTALLING AND CONFIGURING THE SOFTWARE 17

7974CH02.qxd 2/20/07 1:14 PM Page 17

Page 43: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

At this point, your new server should appear in the Servers window of the Workshop IDE,as shown in Figure 2-8.

Figure 2-8. The Servers tab in the Workshop IDE

If you haven’t already started the alsb_book server, you can do so now by right-clickingthe server name and selecting Start from the pop-up menu, or by selecting the server from thelist (as shown in Figure 2-8), and clicking the start button ( ). If you’ve previously started theserver, Workshop automatically detects that the server is running.

Importing the Sample CodeThis book comes with a significant amount of sample code. Your first step is to copy the proj-ects you downloaded from the Source Code/Download area at http://www.apress.com into theworkspace that you created when you first started Workshop for WebLogic (see Figure 2-1).Next you need to import those projects into the Workshop IDE. You do this by right-clicking inthe Package Explorer window and selecting Import from the pop-up menu. This brings up theImport dialog, shown in Figure 2-9.

Select Existing Projects into Workspace from the dialog and click the Next button. Thenext step in the Import Projects wizard is to select the workspace that contains the projects.Do this by selecting the root directory and browsing to the workspace directory you createdearlier in this chapter, as shown in Figure 2-10.

Your project list might not match the one shown in Figure 2-10 exactly, but that’s okay.Click the Finish button to import all these projects into Workshop.

CHAPTER 2 ■ INSTALLING AND CONFIGURING THE SOFTWARE18

7974CH02.qxd 2/20/07 1:14 PM Page 18

Page 44: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

CHAPTER 2 ■ INSTALLING AND CONFIGURING THE SOFTWARE 19

Figure 2-9. Import the existing projects into Workshop.

Figure 2-10. The final step in importing the sample projects into Workshop

7974CH02.qxd 2/20/07 1:14 PM Page 19

Page 45: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

SummaryWhen these steps are complete, your Workshop for WebLogic IDE will be fully configured touse with the following chapters of this book. The ease with which you can interact with theAquaLogic server will improve your coding experience and productivity. You’re now readyfor the fun part. In the next chapter, you’ll get right down to business by creating a Java webservice, then using ALSB to exercise the web service.

CHAPTER 2 ■ INSTALLING AND CONFIGURING THE SOFTWARE20

7974CH02.qxd 2/20/07 1:14 PM Page 20

Page 46: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Hello World Service

In the tradition of computer learning books of the past several decades, in this chapter you’llwrite a quick Hello World service to help you get an understanding of the basics of ALSB.During this process, you’ll gain a fundamental understanding of the ALSB interface, how tocreate a project using the ALSB console, and more. You’ll also see from end to end how to cre-ate and deploy business and proxy services on ALSB, along with how to create test clients toensure that your services are working as desired. You’ll follow these steps:

1. Use Workshop to create and deploy a web service that implements the business logic.

■Note ALSB supports interoperability between heterogeneous systems. It can connect to .NET, ApacheAxis, WebSphere, and other web service platforms. However, for ease of development, you’ll develop yourweb services using WebLogic Server (WLS).

2. Use Workshop to create a client for the web service created in step 1.

3. Create a HelloWorld project in ALSB.

4. Define the WSDL for the web service in ALSB, based on the web service you created instep 1.

5. Create a business service definition in ALSB, based on the WSDL.

6. Create a proxy service in ALSB based on the business service.

7. Create a test client for the proxy service to confirm that everything runs properly, endto end.

Before you proceed, be sure that the alsb_book domain is running.

Creating and Deploying a Web ServiceYour first step is to create a web service that implements the business logic. Your requirementsfor this service are simple.

21

C H A P T E R 3

7974CH03.qxd 3/2/07 10:04 AM Page 21

Page 47: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

The service will contain one operation named getGreeting. This operation must take astring argument that’s a name of a person. The service returns a string greeting that includesthe name argument.

getGreeting(String name) : String

You’ll implement this web service using the JDK 1.5 with annotations, using Workshop tocreate the source files and Ant to build your project. You need to have completed the installa-tion process defined in Chapter 2. You’ll find the complete source code for this exercise in theSource Code/Download area at http://www.apress.com.

Begin by starting the Workshop IDE by selecting BEA Products ➤ Workshop for WebLogicPlatform from the Start menu. If it prompts you to select a workspace, select the workspacethat you created in Chapter 2. After Workshop loads, right-click in the Package Explorer tab(on the left side of the IDE) and select New ➤ Project from the pop-up menu. This brings upthe New Project dialog, shown in Figure 3-1.

Figure 3-1. Workshop’s New Project wizard

Select the Web Service Project in the Web Services folder and click the Next button. Namethe project “Hello World.” The Target Runtime should default to BEA WebLogic 9.2 if you’reusing ALSB version 2.5 or later. Click the Next button.

On the Select Project Facets page of the New Project wizard, you need to select the“facets” of your project, as shown in Figure 3-2. For your purposes, the defaults are fine.Click the Next button.

CHAPTER 3 ■ HELLO WORLD SERVICE22

7974CH03.qxd 3/2/07 10:04 AM Page 22

Page 48: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 3-2. Hello World project facets

The next window allows you to configure the web module (see Figure 3-3). Here you’llmake some changes. Change the Context Root field from “Hello World” to “business/hello.”Context roots must be unique across projects within a server. The “business” prefix of the rootallows you to group all your “business” services together, making it easier to navigate the webservices later on.

Figure 3-3. Specify the Hello World context root.

CHAPTER 3 ■ HELLO WORLD SERVICE 23

7974CH03.qxd 3/2/07 10:04 AM Page 23

Page 49: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Click the Next button. This is the last page of the New Project wizard. Ensure that the UseShared J2EE Libraries radio button is selected and click the Finish button. The Hello Worldproject appears in the Project Explorer window, and should look identical to the structureshown in Figure 3-4.

Figure 3-4. The Hello World project

Writing a web service for WLS 9.x is a snap. You’ll write your web service as a POJO (that is,Plain Old Java Object) because that’s the simplest way to create a web service. First, you needto create a Java package for your web service. Right-click the src folder in the Project Explorerand select New ➤ Package from the pop-up menu. Name the package com.proalsb.business.Now, right-click the newly created package and select New ➤ WebLogic Web Service from thepop-up menu. Enter HelloWorld for the file name and click the Finish button. Workshop cre-ates a HelloWorld.java file for you and displays it in the source code section of the WorkshopIDE. It already bears some annotations, specifically @WebService and @WebMethod. This is just askeleton web service; you need to put some meat on the bones before it becomes useful.

Workshop for WebLogic allows you to work either directly with the source code, or via“property sheets.” One of the great things about property sheets is that they give you a menuof options, making it simple to see what’s available to you. Each of these properties translatesdirectly into an annotation in the source file, so there’s no hidden code. The source files arestill the source of “truth,” reflecting all the property and annotation settings.

For example, with the HelloWorld.java file selected in Workshop, look at the Annotationswindow (see Figure 3-5). At the top of this window is a group of properties under the title ofWebService (if this group isn’t open, click the plus sign next to the group name to show thechild properties). Take a look at the name attribute of the WebService annotation. By default it’sset to [HelloWorld]. The square brackets are an idiom specific to Workshop, and they indicatedefault values that will be used.

Maybe it’s just our nature, but we’ve never trusted default values, so we prefer to set themexplicitly. Remove the square brackets around the name property so that the name is now set toHelloWorld. Notice how the @WebService annotation in your source code has been modified toinclude the name attribute. Now set the serviceName field to HelloWorldService and set thetargetNamespace field to http://www.proalsb.com.

CHAPTER 3 ■ HELLO WORLD SERVICE24

7974CH03.qxd 3/2/07 10:04 AM Page 24

Page 50: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 3-5. Workshop property sheet for Hello World

Next, move to the WLHttpTransport property. This property is worthy of some description.Setting this property defines the transport protocol used by your web service. Every webservice needs to have a protocol specified to function. You’ll set the portName field toHelloWorldSoapPort to indicate that you’re using a SOAP binding for the web service port.Next, you need to set the serviceURI field to HelloWorldService. The service URI is appendedto the context path for the web service, which brings up an interesting point. When you cre-ated this web service project, the wizard prompted you for a contextRoot, which you set tobusiness/hello. If you set a value in the contextPath attribute of the WLHttpTransport property,it will override the value that you set when you first created the project. Because you don’tneed to override that value, leave the contextPath attribute blank.

Next you need to modify the WSDL property, at the bottom of the property list window. Setits exposed attribute to true. You want to be able to see the WSDL in a web browser. You alsoneed to set the SOAPBinding property. Set the parameterStyle to WRAPPED, the style to DOCUMENT,and the use to LITERAL.

Last, you need to write some code for this web service. Your HelloWorld service needs tohave one operation: getGreeting(). This operation takes a string argument that contains aname, and returns a string that contains a customized greeting. See Listing 3-1 for the imple-mentation details of this method.

Listing 3-1. The HelloWorld Web Service

package com.proalsb.business;import javax.jws.*;import weblogic.jws.WLHttpTransport;import weblogic.jws.WSDL;import javax.jws.soap.SOAPBinding;

@WebService(name="HelloWorld", serviceName = "HelloWorldService",targetNamespace = "http://www.proalsb.com")

@WLHttpTransport(serviceUri = "HelloWorldService", portName = "HelloWorldSoapPort")@WSDL(exposed=true)@SOAPBinding(parameterStyle=SOAPBinding.ParameterStyle.WRAPPED)public class HelloWorld {

CHAPTER 3 ■ HELLO WORLD SERVICE 25

7974CH03.qxd 3/2/07 10:04 AM Page 25

Page 51: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

@WebMethodpublic String getGreeting(String name) {

return("Hello " + name + " from the business service!");}

}

In this web service, you use only the fundamental annotations to achieve your goal, so it’sworth your time to better understand these annotations.

@WebServiceThis annotation denotes the Java class as defining a web service. This annotation takes at mostfive arguments, shown in Table 3-1.

Table 3-1. @WebService Annotation Attributes

Attribute Description Required

name The name of the port type of the WSDL that will be Nogenerated for this service.

targetNamespace This is the XML namespace that will be used in the Nogenerated WSDL. The default value is specified by the JAX-RPC specification (at http://java.sun.com/xml/jaxrpc/index.jsp).

serviceName The name of the service. This maps to the <wsdl:service> Noelement of the WSDL file. The default value is the unqualified name of the Java class with the string Service appended.

wsdlLocation The relative or absolute URL of a predefined WSDL file Nothat this web service will implement. If you leave this undefined, a WSDL will be generated for you by the jwscAnt task. If you do enter a value here, the jwsc Ant task will return errors if the Java class is inconsistent with the port types and bindings specified in the WSDL file.

endpointInterface The fully qualified name of an existing service endpoint Nointerface file. If you specify this value, the jwsc Ant task won’t generate the interface for you, and you’re required to have the interface file in your CLASSPATH. If this value is undefined, the jwsc Ant task will generate the interface for you.

In general, we recommend always specifying at least the name and the targetNamespaceattributes. To use this annotation you need to import javax.jws.WebMethod in your Javasource code.

@SoapBindingThe @SoapBinding annotation allows you to specify the information that’s contained in the<wsdlsoap:binding> section of a WSDL file (see Table 3-2).

CHAPTER 3 ■ HELLO WORLD SERVICE26

7974CH03.qxd 3/2/07 10:04 AM Page 26

Page 52: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Table 3-2. @SoapBinding Annotation Attributes

Attribute Description Required

style Specifies the encoding style of the SOAP messages. NoValid values are:SOAPBinding.Style.DocumentSOAPBinding.Style.RPCThe default is SOAPBinding.Style.Document

use Specifies the formatting style of the SOAP messages. NoValid values are:SOAPBinding.Use.LiteralSOAPBinding.Use.EncodedThe default value is SOAPBinding.Use.Literal

parameterStyle Defines if method parameters represent the entire body of Noa message or if they are elements wrapped inside a top-level element named after the operation. Valid values are:SOAPBinding.ParameterStyle.BareSOAPBinding.ParameterStyle.WrappedThe default value is SOAPBinding.ParameterStyle.Wrapped

■Note You should generally avoid using the Encoded SOAP binding. It isn’t WS-I compliant and thereforereduces your ability to reuse encoded web services.

In general, we recommend specifying all these attributes explicitly to communicate yourintention clearly for how the code will operate. To use this annotation you need to importjavax.jws.SOAPBinding in your Java source code.

@WLHttpTransportThe @WLHttpTransport annotation specifies the URI information for the resulting web service(see Table 3-3).

Table 3-3. @WLHttpTransport Annotation Attributes

Attribute Description Required

contextPath The context root of the web service. Yes

serviceURI The web service URI portion of the URL used by the client. YesWebLogic Workshop IDE will provide a default serviceURI for you if you don’t use this annotation.

portName The name of the <wsdl:port> value. If you don’t specify this Novalue, the jwsc Ant task and the WebLogic Workshop IDE will generate a default port name based on the name of the class that implements the service.

CHAPTER 3 ■ HELLO WORLD SERVICE 27

7974CH03.qxd 3/2/07 10:04 AM Page 27

Page 53: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Just to clarify this a bit more, if you refer to the code in Listing 3-1 you’ll see that the@WLHttpTransport attribute is defined with a contextPath of business and the serviceURI ofHelloWorldService. When you run this service on your local ALSB server running on port 7001,the full URL for the web service will be http://localhost:7001/business/HelloWorldService.

@WebMethodYou use the @WebMethod annotation to identify a Java method as a web service operation (seeTable 3-4).

Table 3-4. @WebMethod Annotation Attributes

Attribute Description Required

operationName The name of the operation. This maps to a <wsdl:operation> Notag in the WSDL file. The default value is the name of the Java method.

action The action for this operation. For SOAP bindings, the value Noof this attribute determines the value of the SOAPActionheader in the SOAP messages. This attribute appears in the WSDL file that’s generated for the web service.

At this point you need to test the web service. However, web services need to run on aserver, so your next task is to define a WebLogic Server within Workshop. At the bottom of theWorkshop IDE you’ll see a tab named Servers. Click that tab, right-click in the Servers window,and select New ➤ Server from the pop-up menu. Set the server name to localhost and set theruntime to BEA WebLogic v9.2. Click the Next button to continue.

Browse for the alsb_book domain directory you created in Chapter 2. Click the Nextbutton. Now you can select the HelloWorld project for deployment onto the server by clickingthe Add All button. Click the Finish button to complete the creation of this server in Workshop.Now, in the Servers window, you should see the alsb_book server listed (see Figure 3-6). Youcan also see the status of the server. To make life even more convenient, you can start and stopthat server from within the Workshop IDE itself.

Figure 3-6. The configured alsb_book server

Notice that the state of your server is listed as Republish. This is because the HelloWorldproject needs to be published (that is, deployed) to the server. This occurs for two reasons:

• You’ve never published the project to that server before.

• You’ve made changes to the project and now it’s out of sync with the server.

CHAPTER 3 ■ HELLO WORLD SERVICE28

7974CH03.qxd 3/2/07 10:04 AM Page 28

Page 54: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Publishing a project to the server is a simple process. Just right-click the server name (seeFigure 3-7) and select Publish from the pop-up menu. If the state of the server changes toSynchronized, then you know the server is running the latest compiled versions of all yourprojects.

You can confirm the deployment of the web service by pointing your web browser to theURL http://localhost:7001/business/hello/HelloWorldService?WSDL. The WSDL that wasgenerated for your HelloWorld POJO is displayed. It should look identical to Listing 3-2.

Listing 3-2. WSDL for the HelloWorld Web Service

<?xml version='1.0' encoding='UTF-8'?><definitions name="HelloWorldServiceDefinitions"

targetNamespace="http://www.proalsb.com"xmlns="http://schemas.xmlsoap.org/wsdl/"xmlns:s0="http://www.proalsb.com"xmlns:s1="http://schemas.xmlsoap.org/wsdl/soap/">

<types><xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified"targetNamespace="http://www.proalsb.com" xmlns:s0="http://www.proalsb.com"xmlns:s1="http://schemas.xmlsoap.org/wsdl/soap/"xmlns:xs="http://www.w3.org/2001/XMLSchema"><xs:element name="getGreeting"><xs:complexType><xs:sequence><xs:element name="name" type="xs:string"/>

</xs:sequence></xs:complexType>

</xs:element><xs:element name="getGreetingResponse"><xs:complexType><xs:sequence><xs:element name="return" type="xs:string"/>

</xs:sequence></xs:complexType>

</xs:element></xs:schema>

</types><message name="getGreeting"><part element="s0:getGreeting" name="parameters"/>

</message><message name="getGreetingResponse"><part element="s0:getGreetingResponse" name="parameters"/>

</message><portType name="HelloWorld"><operation name="getGreeting" parameterOrder="parameters">

CHAPTER 3 ■ HELLO WORLD SERVICE 29

7974CH03.qxd 3/2/07 10:04 AM Page 29

Page 55: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

<input message="s0:getGreeting"/><output message="s0:getGreetingResponse"/>

</operation></portType><binding name="HelloWorldServiceSoapBinding" type="s0:HelloWorld"><s1:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/><operation name="getGreeting"><s1:operation soapAction="" style="document"/><input><s1:body parts="parameters" use="literal"/>

</input><output><s1:body parts="parameters" use="literal"/>

</output></operation>

</binding><service name="HelloWorldService"><port binding="s0:HelloWorldServiceSoapBinding" name="HelloWorldSoapPort"><s1:address location=➥

"http://localhost:7001/business/hello/HelloWorldService"/></port>

</service></definitions>

■Tip If you get a “failed to deploy” message from Workshop, open the server by clicking the plus sign nextto the ALSB server in the Servers window, right-click the HelloWorld project, and select Remove from thepop-up menu. Then you can republish the project.

Figure 3-7. Viewing the deployment state of your projects

Once the project is published to the server, you need to test it. There are two ways totest your web services. The first way is to right-click the web service file name in the ProjectBrowser (HelloWorld.java, in this case). This is the fastest and easiest way to test a web service.The second way to test a web service is to create a test client project. This approach is morelabor intensive. However, it’s a good exercise for you here because it demonstrates how tocreate a Java POJO in Workshop that can interface with web services.

CHAPTER 3 ■ HELLO WORLD SERVICE30

7974CH03.qxd 3/2/07 10:04 AM Page 30

Page 56: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Creating a POJO Test ClientIn general, it’s good practice to write test code whenever possible. Your next step is to write asmall client program to call your web service directly to ensure that it was coded and deployedproperly. Fortunately, using WLS 9 makes this process a snap. The process for writing a webservice client is as follows:

1. Create a Java project for the client.

2. Generate the client code for the web service based on the WSDL.

3. Get the port object from the service.

4. Use the port object to interact with the service.

Listing 3-3 shows how easy it is to create a web service client.

Listing 3-3. The HelloWorld Client Program

package com.alsb.client;public class HelloWorldClient {

/*** @param args*/public static void main(String[] args) {

// TODO Auto-generated method stubString url = "http://localhost:7001/business/hello/HelloWorldService?WSDL";try {

HelloWorldService service = new HelloWorldService_Impl(url);HelloWorld port = service.getHelloWorldSoapPort();String greeting = port.getGreeting("Bob");System.out.println(greeting);

} catch(Exception ex) {ex.printStackTrace();

}}

}

Create a new project in the Workshop IDE. Select the Java project in the Java folder of theSelect Wizard dialog. Name the service HelloWorldClient, as shown in Figure 3-8. Click theFinish button. We prefer to keep our source code separate from the generated code, so we rec-ommend selecting the “Create separate source and output folders” radio button.

CHAPTER 3 ■ HELLO WORLD SERVICE 31

7974CH03.qxd 3/2/07 10:04 AM Page 31

Page 57: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 3-8. Creating the HelloWorldClient project

In the src folder of the HelloWorldClient project, create a new package named com.alsb.client. In this package, create a new Java class called HelloWorldClient. You’ll fill in the codefor this class in a moment. You still have a few more housekeeping tasks to perform first.

A POJO needs a few libraries to call a web service. Right-click the HelloWorldClient proj-ect in the Project Explorer and select Properties. In the Properties dialog (see Figure 3-9),navigate to the Java Build Path entry and then click the Libraries tab. Click the Add Librarybutton, select the User Library entry, and click the Next button. Finally, check the checkboxnext to the WebLogic WebService Client library and click the Finish button. This is the libraryyou created in Chapter 2, and it gives you access to WebLogic-specific Ant tasks and theApache XML Bean libraries.

For your POJO client to access the HelloWorld web service, you need to generate someinterface files. BEA ships an Ant task called clientgen (located in the weblogic.jar file) that cangenerate utility files to make accessing web services a breeze. The clientgen utility will createsome source files for you. Because we’re also picky about keeping our generated source codeseparate from our handwritten source code, we create a second folder for the generatedsource code called gensrc (hey, we’re picky, not creative).

To create a second source code folder, click the Source tab in the Properties dialog. Clickthe Add Folder button and create a folder named gensrc. Now Workshop knows to look intotwo folders when looking for source code.

CHAPTER 3 ■ HELLO WORLD SERVICE32

7974CH03.qxd 3/2/07 10:04 AM Page 32

Page 58: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 3-9. Add the WebLogic WebService Client library.

Click the OK button to close the Properties dialog. You’ll invoke the clientgen utility froman Ant script. Workshop is aware of Ant scripts and provides Ant-specific functionality. In theroot directory of the HelloWorldClient project, create a file named build.xml (the traditionalAnt script name). The script is rather long (74 lines to be exact), so we recommend copying thecontents of the build.xml file from the version available in the Source Code/Download area athttp://www.apress.com. If you prefer, you can enter the code as shown in Listing 3-4.

Listing 3-4. HelloWorld Client build.xml Ant Script

<?xml version="1.0" encoding="ISO-8859-1"?><project name="HelloWorldClient" default="all" basedir=".">

<!-- set global properties for this build --><property name="weblogic.home" value="d:/bea92/weblogic92" /><property name="src.dir" value="src"/><property name="gensrc.dir" value="gensrc"/><property name="classes.dir" value="./bin" /><property name="webservice.name" value="HelloWorldService"/><property name="webservice.wsdl.url" value= ➥

"http://localhost:7001/business/hello/${webservice.name}?WSDL"/><property name="package.name" value="com.alsb.client" /><!-- Create a PATH-like version of the package name --><property name="package.path" value="com/alsb/client" />

<!-- Standard WebLogic Ant tasks --><taskdef name="clientgen"

classname="weblogic.wsee.tools.anttasks.ClientGenTask"/>

CHAPTER 3 ■ HELLO WORLD SERVICE 33

7974CH03.qxd 3/2/07 10:04 AM Page 33

Page 59: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

<!--========================================

Path Section========================================--><path id="javabuild.class.path">

<pathelement path="${classes.dir}"/><fileset dir="${weblogic.home}/server/lib">

<include name="webserviceclient.jar"/></fileset>

</path>

<path id="clientrun.class.path"><pathelement path="${classes.dir}"/>

<fileset dir="${weblogic.home}/server/lib"><include name="weblogic.jar"/><include name="webserviceclient.jar"/>

</fileset></path>

<target name="all" depends="build.wsclient" description="Create the web ➥

service client libraries for the HelloWorldClient."/><target name="build.wsclient" depends="clean"

description="==> Build the Hello World Service Client Files. Be sure ➥

the web service is running before you execute this task."><!-- BEGIN: Generate and compile Web Services client classes --><clientgen wsdl="${webservice.wsdl.url}"

destDir="${gensrc.dir}"packageName="${package.name}" />

<!-- Compile our generated classes --><javac srcdir="${gensrc.dir}"

destdir="${classes.dir}"includes="**/*.java"debug="on"classpathref="javabuild.class.path"/>

<!-- Compile our client class --><javac srcdir="${src.dir}/${package.path}"

destdir="${classes.dir}"includes="**/*.java"debug="on"classpathref="javabuild.class.path"/>

<!-- END: Generate and compile Web Services client classes --></target>

<target name="clean" description="Removes all generated files"><delete dir="${classes.dir}" failonerror="false"/><delete dir="${gensrc.dir}" failonerror="false"/>

CHAPTER 3 ■ HELLO WORLD SERVICE34

7974CH03.qxd 3/2/07 10:04 AM Page 34

Page 60: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

<mkdir dir="${classes.dir}" /><mkdir dir="${gensrc.dir}" />

</target>

<target name="run.wsclient" description="Run the client to test our businessservice">

<java fork="yes" classname="${package.name}.Client" failonerror="true"><classpath refid="clientrun.class.path"/>

</java></target>

</project>

Be sure to modify the script to match your environment. Specifically, look at the value forthe weblogic.home property. If it isn’t set correctly, Ant will give you an error.

Also, be sure that your ALSB server is running before you run the Ant script. Theclientgen utility in the Ant script interrogates the ALSB server to get the WSDL. It’s usuallybetter to get the WSDL from the source (that is, the server that hosts the web service) ratherthan copying the WSDL file to a local directory.

Once you have this Ant script entered, open the script file in Workshop. You’ll see a win-dow named Outline on the right side of the Workshop IDE. At the top of the outline is a nodenamed HelloWorldClient. Expand that node and look for the all target. To run an Ant targetfrom within Workshop, just right-click the target name and select Run As ➤ Ant Build fromthe pop-up menu. Ant runs the script and generates the needed utility files for yourHelloWorldClient.

Now open the HelloWorldClient.java file. Modify the source code so that it matches thecode shown in Listing 3-3. It’s worth noting a few things about the code that clientgen createsfor you. There are three main steps in invoking a web service. First, you need to create a serv-ice stub that can connect to the service. You do this by invoking the <service>_Impl class andpassing in the URL of the service.

The second step is to get the port from the service. The port is the interface to the service.This service interface contains the Java methods you’ll invoke. The third and final step is toinvoke the operation(s) on the port. This is the pattern for all web service invocations from aPOJO.

This test client is intended for a human to execute. You could just as easily have written aunit test using JUnit to perform an automated test on the web service.

Creating the HelloWorld Project in ALSBUntil now, all your work has taken place in WLS. Nothing about it has been specific to ALSB.Now that you’re certain that your HelloWorld web service is working as intended, it’s time tomove into ALSB and learn how to use it.

Open your web browser and point it to the service bus console at http://localhost:7001/sbconsole. When you point your browser to the service bus console, it defaults to the Dash-board view (under the Monitoring section in the left navigation bar). ALSB uses BEA’s portaltechnology to provide a robust, customizable interface. As you can see from Figure 3-10, theleft navigation bar provides you with several different categories of views into the service bus.The Dashboard view gives you a quick status of the service bus servers and services. In later

CHAPTER 3 ■ HELLO WORLD SERVICE 35

7974CH03.qxd 3/2/07 10:04 AM Page 35

Page 61: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

chapters, we’ll explore the other categories in the navigation bar in greater detail as we usethem to complete our exercises.

Let’s get started and create the HelloWorld project. Click the Project Explorer link in thenavigation bar to see the currently deployed projects. At this time, the Project Explorer shouldonly show the default project.

Figure 3-10. ServiceBus console window

All work done in ALSB is done under the context of a change. Think of a change as a trans-action with a transactional database. With a database you create a transaction context, makeyour changes to the database, then commit those changes if you’re satisfied with them. Thechanges you make to a database don’t take effect until you commit those changes. The sameprinciple applies here. Also, just as with a transactional database, if you change your mindabout making the changes, you can roll back the transaction. In ALSB, you can discard yourchanges. When you discard your changes, no change is made to ALSB.

Usually, the ability to create a change in the Change Center is reserved for the Administra-tor role. Each administrator account can only make one change at a time; however, multipleadministrators may make their changes to the system independently of one another. Let’s lookat a quick example to help illustrate this. Imagine that you have two administrators on yourservice bus, users john and jane. Both users (john and jane) log into the system and begin tomake their respective changes. If they create changes that conflict with one another, thoseconflicts will show up in the Change Center and neither user will be able to commit his or herchanges until all conflicts are resolved. ALSB does a great job of ensuring the validity of itsconfiguration at all times.

CHAPTER 3 ■ HELLO WORLD SERVICE36

7974CH03.qxd 3/2/07 10:04 AM Page 36

Page 62: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

One last note on the Change Center: each change is associated with a user session. A usercan log in and start a change. If the user logs out or gets disconnected before he commits hischanges, the work he has done up to that point is preserved (not lost) by the service bus. Thenext time that user logs into the system he can resume making changes right where he left off.This preservation of changes holds true even if the server crashes or is restarted.

Your first step in creating the new project is to click the Create button in the ChangeCenter (located in the top-left corner of the ALSB console). Notice how the Create button haschanged to a green color and now says Activate. Don’t click the Activate button yet; you havesome changes to make first.

To create your project, type the project name into the Enter New Project Name field andclick the Add Project button. The console should now show that you have both the defaultproject and the Hello World project, as shown in Figure 3-11.

Figure 3-11. Hello World created

Next, click the Hello World link in the Project Explorer. On this page you have the optionsto add folders and create resources for the project. Folders are used to help organize the vari-ous resources of the project. Even though your Hello World project is going to be trivial in itscomplexity, it’s still a good idea to start developing professional ALSB habits. You’ll create afolder called WSDL that will contain your WSDL file for this service, and you’ll also createfolders named ProxyServices and BusinessServices. We’ll discuss these folders in the section“Business Services and Proxy Services.” Use the Add Folder link to create these new folders.

Creating the WSDLClick the WSDL folder to open it. In the WSDL folder, use the Create Resource combo box toselect a WSDL entry. Name the WSDL HelloWorld. Enter a brief description for the WSDL file.The description isn’t necessary, but it’s a good practice, especially when you use ALSB in thereal world and have to manage many different resources.

In the WSDL field, you need to paste in the WSDL for the web service you created earlierin this chapter. The easiest way to do this is to open your browser and navigate to http://localhost:7001/business/hello/HelloWorldService?WSDL. Once you see the WSDL in thebrowser, be sure to view the source (View ➤ Page Source in Firefox, View ➤ Source in InternetExplorer) for that page to get the raw XML. Copy the raw XML in its entirety and paste it into

CHAPTER 3 ■ HELLO WORLD SERVICE 37

7974CH03.qxd 3/2/07 10:04 AM Page 37

Page 63: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

the large text area box in the service bus console. It’s important that you copy this from thebrowser’s source page, because if you do it directly from the browser window, you’ll get extra-neous characters that corrupt the WSDL. Alternatively, you can enter the file path to the WSDLfile in the textbox near the top of the page, next to the Browse button (see Figure 3-12).

Figure 3-12. Creating the HelloWorld WSDL resource

You can also load a WSDL resource from a URL. The process for this is described inChapter 14 in the “Administration” section.

Click the Save button. If you mistyped anything in the WSDL, then the ALSB console willreport an error in red text. If everything went perfectly, you’ll see the new HelloWorldWSDLresource listed in the WSDL folder for the project.

WHAT IS A WSDL?

WSDL stands for Web Services Description Language. A WSDL defines a contract between the serviceprovider and the consumers of the service. The WSDL you just added to the project defines a single document-style call that takes a string as an argument and returns an XML document that contains the greeting stringfrom the service.

The current version of the WSDL specification is 1.1. WSDL version 2.0 is expected to have some signif-icant changes to the specification. You can get more information on the WSDL specifications at http://www.w3.org/TR/wsdl.

CHAPTER 3 ■ HELLO WORLD SERVICE38

7974CH03.qxd 3/2/07 10:04 AM Page 38

Page 64: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Business Services and Proxy ServicesALSB divides services into two categories: business services and proxy services. You can thinkof proxy services as the services published by ALSB. Instead of your service clients calling theservices directly, they call ALSB proxy services instead. This might seem odd at first glance, butwe promise it will make sense by the time you finish reading this section.

Business services are defined in ALSB to represent services that are external to ALSB. Forexample, the HelloWorld service you created at the beginning of this chapter is external as faras ALSB is concerned. For ALSB to be able to call the HelloWorld service, you have to create abusiness service in ALSB. We often think of a business service as the client stub that ALSBuses to interact with external services. As for the external services, we refer to them as serviceproviders.

So let’s answer the question that we’re sure you’re asking yourself: “Why shouldn’t myservice clients just call the services they need?” There are five reasons. First is location trans-parency. One of the features of ALSB is the ability to proxy multiple endpoints for the sameservice. If you have the same service running on five different machines, ALSB can round-robin or otherwise load balance the calls among those servers. Location transparency allowsyou to add, remove, and change service endpoints without having to recompile your clientsor perform some DNS trickery.

The second reason to invoke ALSB instead of the end services is service aggregation. Notevery proxy service in ALSB has to represent a single business service. A proxy service caninvoke any number of business services, and can apply conditional logic to select the rightsubset of business services, depending on the needs of the caller. This also abstracts out therouting logic from the client and places it inside the service bus, where it belongs.

The third reason to use ALSB is to provide a layer of abstraction between your serviceclients and your service providers. For example, let’s say you have a customer managementsystem at your company, and you’ve created a number of service providers that provide serv-ices based on a set of XML document schemas that you’ve defined. At some point yourcompany decides to replace your old customer management system with a newer system.This new system has web services built in. The problem is that the new system uses its ownset of XML document schemas that are different from yours. What’s a developer to do? Rewriteall your existing service clients? Madness! With ALSB you can simply create transformationsthat modify the new XML documents into the form expected by your current clients.

The fourth reason to use ALSB is that it provides a centralized area for collecting serviceinvocation metrics. It allows you to create your own Service-Level Agreements (SLAs) that helpyou monitor service performance, display statistics, and provide a reporting platform. ALSBdoes all this without requiring you to modify or otherwise instrument the services themselves.

The fifth reason to use ALSB is that it provides a centralized platform for security policies.Even if the external web service isn’t robust enough to provide security, the fact that ALSB“proxies” those services gives you the ability to apply industry-standard, robust security policies.

ALSB is a powerful tool in your enterprise, granting you flexibility where you need it most.

CHAPTER 3 ■ HELLO WORLD SERVICE 39

7974CH03.qxd 3/2/07 10:04 AM Page 39

Page 65: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Creating the Business ServiceWhen you create a business service in ALSB, you’re making ALSB aware of an existing, externalweb service. In this case, you’re creating a business service that represents the web service youcreated in the first part of this chapter. You begin by navigating to the BusinessServices folderyou created earlier, and selecting Business Service from the Create Resource combo box. Setthe Service Name field to Hello World Business Service. Enter any description you like.

Next, select the WSDL Web Service radio button and click the Browse button. This bringsup the WSDL browser window (see Figure 3-13).

Figure 3-13. WSDL browser window

Click the Hello World name to select it as the WSDL for your business service. In the nextwindow, click the HelloWorldSoapPort and click the Submit button. Back in the main browserwindow, click the Next button.

The next window allows you to specify the transport configuration of the business service(see Figure 3-14). Notice that the correct endpoint for the business service is prepopulated foryou in the Existing URIs section. This is because you copied the WSDL of the business servicedirectly. If the same business service existed on multiple endpoints (that is, on multiplemachines), you could specify the additional endpoints and the load balancing algorithm,allowing ALSB to balance the calls across multiple servers.

Figure 3-14. Business Service - Transport Configuration window

CHAPTER 3 ■ HELLO WORLD SERVICE40

7974CH03.qxd 3/2/07 10:04 AM Page 40

Page 66: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

For your purposes, the defaults are fine. Click the Next button. The next window is theHTTP Transport Configuration window. Once again, just click the Next button to accept thedefaults. The next step in the wizard is the SOAP Binding Configuration page. This page allowsyou to specify whether or not ALSB should enforce WS-I compliance. For this exercise, leavethe checkbox unchecked. This brings you to the final step in the configuration wizard: thesummary page (see Figure 3-15).

Figure 3-15. Business Service - Summary window

Click the Save button to save the business service. At this point, ALSB is aware of the busi-ness service, and it knows how to invoke it. Your next step is to define a proxy service thatrepresents (and provides a layer of abstraction for) this business service.

Creating the Proxy ServiceA proxy service is a web service published by the service bus that represents a “real” service(also known as a service provider) elsewhere. By using a proxy service, you can create a layer ofabstraction between the consumers of a service and the service provider. This allows you tomove and change the service providers without affecting the consumers.

For your HelloWorld service, you need a proxy service to present the service to yourconsumers.

CHAPTER 3 ■ HELLO WORLD SERVICE 41

7974CH03.qxd 3/2/07 10:04 AM Page 41

Page 67: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

You begin by navigating to the ProxyServices folder in the HelloWorld project, using theProject Browser. In the Create Resource combo box, select Proxy Service. Set the Service Nameto HelloWorld and provide a brief description of the service. Under Service Type - Create fromExisting Service, select the Business Service radio button and click the associated Browse but-ton. This brings up the Service Browser window (see Figure 3-16).

Figure 3-16. Service Browser

In the Service Browser window, select the radio button for the Hello World Business Ser-vice and click the Submit button. Back in the Edit a Proxy Service - General Configurationwindow, click the Next button.

In the Edit a Proxy Service - Transport Configuration window, set the Endpoint URI to/esb/Hello_World (see Figure 3-17). It’s critical that your end point begins with the “/” charac-ter or you’ll get errors later. Click the Next button.

The next window is the Edit a Proxy Service - HTTP Transport Configuration window.You’ll use the default configuration, so just click the Next button.

Similarly, in the Edit a Proxy Service - Operation Selection Configuration window, you usethe default values. Click the Next button.

Figure 3-17. Specify the endpoint URI for the proxy service.

CHAPTER 3 ■ HELLO WORLD SERVICE42

7974CH03.qxd 3/2/07 10:04 AM Page 42

Page 68: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

The final window is the summary window. Your window should look identical to the onein Figure 3-18. Click the Save button to save this proxy service.

Figure 3-18. Edit Proxy Service - Summary window

Now let’s make sure that your creation of the proxy service was successful. Click the Acti-vate button to commit your changes to ALSB. ALSB prompts you for a description of thechanges you’re activating. Once again, the description isn’t necessary, but it is a best practice.When you’re operating in a production environment, where your changes may affect manyservers, and you make a mistake while configuring something, the session activation descrip-tions can be a lifesaver. Get into the habit of entering meaningful descriptions and you won’tregret it. The proxy service you just created is now running.

Let’s take a look at the WSDL for your proxy service. Open your browser and navigate tohttp://localhost:7001/esb/HelloWorld?WSDL. If the WSDL displays, you know the service wasalso deployed. The WSDL for the proxy service looks similar to the WSDL for the business serv-ice, with the exception of a different service endpoint. However, a little magic happened here,and you need to be aware of it. Back in the ALSB console, navigate to the proxy service you justcreated. You’re going to make some changes, so you need to click the Create button in theChange Center again. Next, click the Edit Message Flow button of the proxy service, as high-lighted in Figure 3-19.

CHAPTER 3 ■ HELLO WORLD SERVICE 43

7974CH03.qxd 3/2/07 10:04 AM Page 43

Page 69: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 3-19. Proxy Services folder

This brings up the message flow for the Hello World proxy service (see Figure 3-20). Allproxy services have a message flow. Every message flow has a start node; in this case the startnode is called Hello World. It has a pair of green arrows on the icon. These arrows indicatethat the service is two way. That is, the service is invoked and returns in a synchronousmanner.

Figure 3-20. Hello World message flow

The bottom node in the flow is a routing node. As its name suggests, it routes a messageto another service. The name was generated for you by ALSB and succinctly tells you thatit’s routing the message to the Hello World Business Service that you defined earlier in thischapter.

CHAPTER 3 ■ HELLO WORLD SERVICE44

7974CH03.qxd 3/2/07 10:04 AM Page 44

Page 70: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Left-click the bottom node and select Edit ➤ Route Node from the pop-up menu. The EditStage Configuration window shows you more detail on how the route node operates (see Fig-ure 3-21). In the combo box, select the getGreeting operation. You’ve just instructed the nodeto route all requests to the getGreeting operation of the HelloWorld Business Service.

Figure 3-21. Edit Stage Configuration window

Click the Save button, once for each of the two windows, until you get back to the browserpage that shows the proxy service. Now click the Activate button. Your proxy service is nowconfigured to route all requests it receives to the proper business service. Your next step is totest the proxy service to ensure that it’s working as intended.

A Quick Note on the Configuration Changes ScreenAs you can see, after you activate a change in the Change Center, the ALSB console will showyou the View Configuration Changes page (see Figure 3-22).

Figure 3-22. The View Configuration Changes page

This page shows all the changes that have been applied to the domain. Each entry repre-sents a change session where you’ve clicked the Create and Activate buttons, and shows all thechanges you made to the system in between those two button clicks. If you click one of thetask names, another window will show you a more detailed view of the changes that tookplace inside the task (see Figure 3-23).

CHAPTER 3 ■ HELLO WORLD SERVICE 45

7974CH03.qxd 3/2/07 10:04 AM Page 45

Page 71: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 3-23. Individual tasks inside a change

Testing the Proxy ServiceALSB provides a simple-to-use but robust mechanism for testing proxy and business servicesmanually. For automated testing, we recommend that you write test clients that can beinvoked from JUnit or use some other testing framework.

The test console is designed to let you quickly test any service defined in ALSB. The testconsole is only available if no changes are active in the Change Center. Now that you’ve savedyour changes for the HelloWorld proxy service, you can left-click the Test Console button, asshown in Figure 3-24.

Figure 3-24. The Test Console button

The test console provides a general-use user interface to any web service. The test consoleparses the interface of the service and customizes itself to make it easier to enter test informa-tion. For example, if you click the Test Console button for your HelloWorld proxy service, you’llsee the test console as shown in Figure 3-25.

CHAPTER 3 ■ HELLO WORLD SERVICE46

7974CH03.qxd 3/2/07 10:04 AM Page 46

Page 72: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 3-25. The HelloWorld proxy service test console

There are two important parts of the test console. First is the Available Operations combobox at the top. This is an important control once you begin to develop more sophisticatedservices that have more than one operation. The second important area is the Request Docu-ment section of the console. See how the SOAP Body text area has been filled with the appro-priate document for invoking the HelloWorld web service? As you go on to develop morecomplex services and documents, the test console will become a vital tool to help keep youproductive by automating the generation of test documents.

CHAPTER 3 ■ HELLO WORLD SERVICE 47

7974CH03.qxd 3/2/07 10:04 AM Page 47

Page 73: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Let’s use the test console to run a quick test. Replace the string entry between the<alsb:name> tags and click the Execute button. The test console invokes the proxy serviceusing the name you’ve supplied and then shows you a result page. The result page shows therequest document, the response document (see Figure 3-26), the response metadata, andthe invocation trace (see Figure 3-27).

Figure 3-26. The request and response documents in the test console

If you click the plus signs in the Invocation Trace section of the test console results, youcan see the receiving request and routing information. You can drill down into detailed infor-mation: document construction, header information, the creation of user-defined variables,and the list goes on. Figure 3-28 shows the invocation trace for the Hello World proxy service.The Invocation Trace section of the test console is an invaluable tool when it comes to debug-ging both proxy and business services.

CHAPTER 3 ■ HELLO WORLD SERVICE48

7974CH03.qxd 3/2/07 10:04 AM Page 48

Page 74: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 3-27. The response metadata and the invocation trace in the test console

Figure 3-28. Invocation Trace details

CHAPTER 3 ■ HELLO WORLD SERVICE 49

7974CH03.qxd 3/2/07 10:04 AM Page 49

Page 75: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

SummaryYou did quite a lot quickly in this chapter. Let’s review what you’ve accomplished.

• You learned how to create and deploy a web service for WebLogic 9.x. This became yourservice provider.

• You learned the basics of ALSB. ALSB acts as an intermediary between the serviceprovider and the service consumer, providing a layer of abstraction between the two.

• You gained a basic understanding of the ALSB interface.

• You learned how to create several of the most common resources in any ALSB project:business services, proxy services, and WSDLs.

• You learned how to create web service test clients to verify that your code behaves asexpected and the deployments were successful.

• You learned how to use the test console to quickly test the proxy and business servicethat you created.

In the next chapter, you’ll learn more about the message flows and how to use themeffectively.

CHAPTER 3 ■ HELLO WORLD SERVICE50

7974CH03.qxd 3/2/07 10:04 AM Page 50

Page 76: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Message Flow Basics

Messaging is at the heart of ALSB. Messages are handled by message flows: a set of instruc-tions on what to do with each message. In Chapter 3 you created your first message flow.It was trivial in nature, yet it shares the same basic set of components that even the mostadvanced message flows possess. Each message flow is constructed from one or more nodes.There are four basic node types: Start, Pipeline Pair, Route, and Branch. If no nodes are addedto a message flow, then ALSB simply echoes the request message back to the caller.

Message Flow OverviewA proxy service is defined by its message flow. A message flow consists of a set of nodes. Thereare four types of nodes: Start, Pipeline Pair, Branch, and Route. Each type of node is used for aspecific purpose, as noted in Table 4-1.

Table 4-1. Message Flow Node Types

Node Type Description

Start Every message flow begins with a Start node. A Start node cannot be modified.It exists only to mark the entry point of the message flow.

Route This is a leaf node that handles the request/response dispatching of the messageto a business service. No other nodes can follow a Route node.

Branch This node is used to make decisions in the message flow, based on the contentsof the message. You can make two types of decisions in a Branch node:operational branches or conditional branches.

Pipeline Pair A Pipeline Pair node explicitly represents both the request and the responsemessage paths in the node, making it easier to customize transformations andother operations on either the request or response side of the node. This type ofnode can be followed by at most one other node type.

As you can see from Table 4-1, there are rules concerning each node, specifically aboutthe number of nodes that might follow. (That is, the Pipeline Pair node can have at most onenode following it, and so on.) Figure 4-1 is a graphical representation of a sample messageflow that helps to demonstrate some of these node rules. The Pipeline Pair nodes are followedby, at most, one other node. The Branch nodes can make decisions to route the messageamong any number of other nodes. Though the diagram only shows Branch nodes routing to

51

C H A P T E R 4

7974CH04.qxd 3/2/07 10:11 AM Page 51

Page 77: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

at most two nodes, there is, in fact, no limit on the number of nodes that a Branch node canreference. Last, the Route nodes make up the leaves of this message flow tree, because theirjob is to route messages to external services.

Figure 4-1. Sample message flow structure

Pipeline PairsAs its name implies, a Pipeline Pair is a pair of pipelines. Each pipeline is a sequence of stagesrepresenting a nonbranching, one-way processing path. The left pipeline is the requestpipeline. This pipeline is dedicated to request processing only. The right pipeline is theresponse pipeline, dedicated solely to the handling of the response.

Pipeline Pairs are composed of Stages. A Stage is simply a group of Actions (more onActions later). Figure 4-2 shows this relationship graphically. The Pipeline Pair contains arequest pipeline and a response pipeline. Each pipeline contains a chain of Stage nodes. Youcan create error handlers at the stage level. Additionally, you have the option of adding anerror handler to each of the two pipelines. This error handler will catch any errors generatedin the pipeline that aren’t already handled by a stage error handler.

CHAPTER 4 ■ MESSAGE FLOW BASICS52

7974CH04.qxd 3/2/07 10:11 AM Page 52

Page 78: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 4-2. Pipeline Pair details

Using Figure 4-2 as a guide, you can see that the request pipeline has a pipeline errorhandler attached. By the way, both the Request Pipeline start ( ) and Response Pipeline start( ) icons are unmodifiable. The only thing you can do with these nodes is to add or removestages or add a pipeline error handler.

Let’s focus on the request pipeline side for a bit. You can see that the request pipeline hasan pipeline error handler associated with it. The warning symbol ( ) indicates that there’s anassociated error handler. This means that if any of the stages within the pipeline generate anerror, the request pipeline will handle the error. However, you also see that the “transformrequest format” stage has a stage error handler associated with it, so any errors that are gener-ated in that stage will be handled by the stage error handler, not the overall request pipelineerror handler. One interesting thing to note: if the stage error handler raises an error, then thepipeline error handler will then handle that error. This nesting of error handlers is reminiscentof Java’s exception handling approach.

On the other side of the pipeline, the response pipeline has no error handlers at all. Anyerrors that arise in this pipeline will be handled by the default system error handler, which forSOAP messages will generate a SOAP fault to the caller.

CHAPTER 4 ■ MESSAGE FLOW BASICS 53

7974CH04.qxd 3/2/07 10:11 AM Page 53

Page 79: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Branch NodesBranch nodes provide decision-making capability to the message flow. Branches are definedby creating a lookup table of string values. Each Branch node is capable of enforcing a singledecision only. If your decision logic requires multiple decisions, you’ll need to use multipleBranch nodes.

There are two subtypes of Branch nodes: conditional and operational. A conditionalbranch node makes decisions based on string matching conditions. For example, Figure 4-3shows the lookup table for a conditional branch. There are three possible paths the Branchnode can take, depending on the contents of the variable name. If the name is Foo, the Foobranch will be taken; if the name is Bar, the Bar branch will be taken. If the name variabledoesn’t match either of those string values, the default path will be taken.

Figure 4-3. Defining a conditional branch node

An operational branch node works similarly, but it uses operations defined in a WSDL,not string values. This is handy if your WSDL defines multiple operations and you need toperform some additional logic based on the operation that’s being invoked, as shown inFigure 4-4.

Figure 4-4. Defining an operational branch node

CHAPTER 4 ■ MESSAGE FLOW BASICS54

7974CH04.qxd 3/2/07 10:11 AM Page 54

Page 80: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Route NodesRoute nodes are the nodes that handle the request and response communication between themessage flow and another service. The other service might be a business service, or it mightbe another proxy service in the ESB itself. It represents the boundary between the request andresponse processing for the proxy. Like a Pipeline Pair node, the Route node has an intrinsicunderstanding of both the request and response values of its messages. Also, like with thePipeline Pair, you can perform specific request and response functions on the messages. How-ever, unlike the Pipeline Pair, the Route node isn’t divided into stages. From an error handlingpoint of view it’s an all-or-nothing construct. You can add an error handler to the entire Routenode, but that’s the limit. No error handling is possible within a Route node. Finally, becausethe Route node communicates with other services directly, there can be no other nodes in themessage flow that follow a Route node. Unlike Pipeline Pairs and Branch nodes, a Route nodeis comprised of a series of actions that are performed on the request and/or response portionsof the message.

ActionsEach Route node in the message flow or stage in a Pipeline Pair or an error handler pipelinecan contain any number of actions. An action is an instruction, similar in nature to a line ofcode in a traditional programming language. However, unlike traditional programming lan-guages, actions aren’t source code that gets compiled, but configuration information that’sstored in the message bus. Actions aren’t written in Java, C++, or even in a scripting languagesuch as Python or Ruby. Instead, actions are created graphically, with the occasional mix ofXQuery, XPath, and/or XSLT.

Goodbye World!Let’s put this newfound knowledge to use by creating a variant of your Hello World proxyservice. In this exercise, you’ll create a new project and a new proxy service. However, you’llreuse the existing Hello World business service. The purpose of this project is to take thestring response from the Hello World business service and transform its contents to say“Goodbye” instead of “Hello.” Though modest in scope, this simple project will demonstratethe value of data transformation and service reuse.

1. To begin, open up the ALSB console and click the Create button in the Change Center.

2. Create a new project and name it Goodbye World.

3. In the new project, create a folder named Proxy Services. In this folder, create a proxyservice resource named GoodbyeWorld. This proxy service is based on the existingHello World business service.

4. Set the End Point URI for the service to /esb/GoodbyeWorld. Just accept the rest of thedefault values on the following pages until the proxy service is created.

5. Click the Edit Message Flow icon for the Goodbye_World proxy service. Left-click theRouteTo_Hello World Business Service icon and select Edit Route from the pop-upmenu.

CHAPTER 4 ■ MESSAGE FLOW BASICS 55

7974CH04.qxd 3/2/07 10:11 AM Page 55

Page 81: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Now you’ll work some magic. You know that the Hello World business service takes aname argument and returns a greeting result that contains the string Hello <name> from thebusiness service!You need to intercept and transform the response from the business serv-ice and change the “Hello” to a “Goodbye.” Therefore, you need to perform some actions inthe response portion of the Route node. You need to perform a minimum of two steps. Thefirst step is to get the greeting string from the response and store it in a local variable. The sec-ond step is to replace the “Hello” portion with “Goodbye” and then put the new string backinto the response value.

If you followed the preceding steps, you should see the “Edit Stage Configuration: RouteNode” page displayed in the ALSB console. Perform the following steps to complete theresponse processing for this node:

1. Select the getGreeting operation from the combo box.

2. Click the “Add an action” link in the Response Actions table. Select Message Processing➤ Assign action from the pop-up menu.

3. Click the Expression link and type in the following XQuery expression to retrieve thestring data from the response:

replace($body/alsb:getGreetingResponse/alsb:return, 'Hello', 'Goodbye')

Your expression should appear exactly like the one shown in Figure 4-5.

Figure 4-5. Say “Goodbye” to “Hello”!

4. Now click the Validate button to be sure you typed it in correctly. Finally, click the Savebutton.

■Note The XQuery replace() method is case dependent!

CHAPTER 4 ■ MESSAGE FLOW BASICS56

7974CH04.qxd 3/2/07 10:11 AM Page 56

Page 82: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

A bit of explanation is due here. You just created an XQuery script that calls the XQueryreplace() function. It searches through the first string argument, finding all instances of thesecond string argument (“Hello” in this case) and replaces all those instances with the thirdargument, “Goodbye.” It then returns the resulting string.

Next you’ll assign the result of the replace function to a local variable. This is a simpleprocess of typing the variable name into the associated variable field, as shown in Figure 4-6.

Figure 4-6. Assign the string to the goodbyeGreeting variable.

■Note You don’t need to declare variables in advance when using the ALSB console. Simply enter thevariable name and ALSB takes care of the rest.

Now that you have the “Goodbye” string stored in the goodbyeGreeting variable, you needto insert that data back into the message response. To do this you need to create a Replaceaction to follow your existing Assign action. Left-click the icon of the Assign action you justcreated (that is, ) and select Add an Action ➤ Message Processing ➤ Replace from the pop-up menu).

Click the XPath link for the newly created Replace action. You need to tell ALSB what nodeyou’re replacing. In the XPath Expression Editor, enter the following expression:

./alsb:getGreetingResponse/alsb:return

As you can see from the expression, you’re just putting your modified string back whereyou found the original string. Click the Save button to return to the main page for configuringthe Route node.

For the variable name, enter body. Note that you don’t enter $body when using the con-sole because you aren’t writing direct XQuery, so you only enter the name of the variable itself,without the $.

Now click the Expression link for the Replace action and enter the following XQueryexpression:

string($goodbyeGreeting)

CHAPTER 4 ■ MESSAGE FLOW BASICS 57

7974CH04.qxd 3/2/07 10:11 AM Page 57

Page 83: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

■Caution You cannot just enter the variable ($goodbyeGreeting) here. You must cast it to a string datatype or you’ll get an error.

Click the Save button. Back at the Route Node Configuration window, be sure to select the“Replace node contents” radio button, because you just want to replace the node contents. Ifyou were to replace the entire node with this string, you’d corrupt the message format.

This last step is optional. When you call this proxy service it operates as a black box. Youcan’t see what’s going on inside easily. We like to add some logging functions, to make it easierfor us to see that our proxy services are working as expected, especially in the early stages ofdevelopment.

■Tip Using logging actions can make it easier to debug proxy services.

Left-click the Replace action icon ( ) and select Add an Action ➤ Log to create your Logaction. Click the Expression link for the Log action and enter the following XQuery expression:

concat('Goodbye data: ', string($goodbyeGreeting))

Click the Save button. Be sure to set the “at severity level” combo box to Error. This willdisplay the log entry onto the ALSB system console (not the user interface, but the consolewindow that shows the System.out messages for your operating system). You can leave the“with Annotation” field blank.

Your Route node configuration should now look like Figure 4-7.Click the Save button twice, then click the Activate button in the Change Center. Once

you’ve activated that session, it’s time to test your new proxy service. Once you’ve activatedyour new Goodbye World project, navigate to the Proxy Services folder of the project and clickthe little insect icon to the right of the proxy service name ( ). Notice that the XML documentin the test console looks exactly like the one from your Hello World project, as shown inFigure 4-8.

Just enter a name in the “name” field and click the Execute button. In a moment, theresults appear in the test console. What we love about the test console is the incredibly richdetail that it provides. You don’t just get the response string, you get so much more! The testconsole provides you with the following details:

• The request document

• The response document

• The response metadata

• A detailed invocation tree

You’ll quickly come to love and rely on the test console. It lays open to you all the infor-mation to make your life as a service developer or service composer as easy as possible.

CHAPTER 4 ■ MESSAGE FLOW BASICS58

7974CH04.qxd 3/2/07 10:11 AM Page 58

Page 84: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 4-7. The final version of the GoodbyeWorld Route node

Figure 4-8. The Goodbye World test console

CHAPTER 4 ■ MESSAGE FLOW BASICS 59

7974CH04.qxd 3/2/07 10:11 AM Page 59

Page 85: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

What the Heck Just Happened Here?Did you find the Goodbye World exercise a little confusing? Does it seem like you’ve steppedinto an alien world where nothing makes sense? Good; that’s normal, unless you have a strongbackground in XML and XQuery.

We felt the same way when we got started with ALSB. We thought we had a good under-standing of XML, but it turns out that our knowledge only scratched the surface. ALSB does agreat job of making much of the work quick and easy. However, there’s no masking XML orXQuery. These are important technologies that will be with us for a long time to come. The dif-ficulty is that if you come from a traditional programming background, XML and XQuery oftenseem like alien languages; they just don’t map well to procedural or object-oriented program-ming models.

The good news is that with a little practice, and a little bit of explanation, this will becomeclear and simple. We’ll walk you through the XQuery you just entered and do our best toexplain some of the basics so that this becomes a simple process when you’re working onyour own projects. On top of what we’ll cover here, Chapter 5 is all about WSDL; that will alsohelp to give you some clarity.

Let’s begin with the replace statement you used in the Goodbye World project. Thereplace function is an XQuery function. If you look carefully at Figure 4-5 you’ll see a list ofavailable XQuery functions on the left-hand side of the ALSB console. The replace functionitself is easy to understand if you have a background in software engineering. The part ofthe statement you’re probably confused by is the first argument in that function: $body/alsb:getGreetingResponse/alsb:return. How did we know what the first argument shouldbe? More importantly, how will you know which argument to use when you’re using this inthe real world?

To begin, it’s important to understand that ALSB breaks all request and response mes-sages down into several components and makes these components available to you throughthe use of XQuery variables. The $body variable is a prime example of this. The $body variableholds the main payload (also known as the body) of the message. You’ll find that most of yourmessage processing and transformations involve the $body of the message. The other standardXQuery variables of a message are $attachments, $header, $inbound, $operation, and$outbound.

■Note ALSB uses SOAP as the canonical message format. Whenever non-SOAP messages are used, ALSBwill transform the messages into SOAP format. The $body variable contains the <soap:body> element, andthe $header variable contains the <soap:header> element.

The $body is comprised of XML. To know the format of that XML, you have to know thetype of message you’re dealing with. In this case, you know that you’re dealing with a responsemessage from the HelloWorld business service. In ALSB, navigate to the HelloWorldWSDL thatyou created in Chapter 3. Start by looking for the operation declaration. You know you’re deal-ing with the getGreeting operation. For convenience’s sake, we’ve included this declaration inListing 4-1.

CHAPTER 4 ■ MESSAGE FLOW BASICS60

7974CH04.qxd 3/2/07 10:11 AM Page 60

Page 86: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Listing 4-1. The getGreeting Operation Definition

<operation name="getGreeting" parameterOrder="parameters"><input message="s0:getGreeting"/><output message="s0:getGreetingResponse"/>

</operation>

As you can see in Listing 4-1, the operation takes an input message and returns an outputmessage. Because you’re modifying the greeting that’s returned by the business service, youknow that you need to know the structure of the response message. From Listing 4-1 you candetermine that the message you need to modify is named getGreetingResponse (ignore thes0: namespace prefix for now). You next step is to find the getGreetingResponse message dec-laration in the WSDL file (see Listing 4-2).

Listing 4-2. The getGreetingResponse Message Definition

<message name="getGreetingResponse"><part element="s0:getGreetingResponse" name="parameters"/>

</message>

Not a lot to see here. The format of this message is defined by the getGreetingResponseelement. Your next step is to find that element definition, which is conveniently located inListing 4-3.

Listing 4-3. The getGreetingResponse Element Definition

<xs:element name="getGreetingResponse"><xs:complexType>

<xs:sequence><xs:element name="return" type="xs:string"/>

</xs:sequence></xs:complexType>

</xs:element>

Finally, you’ve discovered the structure of the return message. You now know that the$body variable in the return message will contain the structure in Listing 4-4 (namespacesomitted for now).

Listing 4-4. The getGreetingResponse Return

<getGreetingResponse><return>greeting goes here</return>

</getGreetingResponse>

Now that you know the structure of the return document, you can create an XPath expres-sion to represent it:

$body/alsb:getGreetingResponse/alsb:return

CHAPTER 4 ■ MESSAGE FLOW BASICS 61

7974CH04.qxd 3/2/07 10:11 AM Page 61

Page 87: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Here we’ve inserted the namespaces again for completeness. This XPath expressioninstructs ALSB to get the contents of the alsb:return node. Now, if you return to Figure 4-5,the entire XQuery function call should make sense to you. The real benefit here is that you’velearned how to determine the contents of the $body variable for any message you process.

■Caution Namespaces are as fundamental to modern XML communications as package names are inJava. Once you’re comfortable with XQuery and XPath, the most common reason for your XQuery and XPathcode not to work correctly will be due to using the wrong namespace.

One last note about namespaces: like all programming paradigms, they’re brutally intol-erant of errors. In Java, if you omit the package name of a class (and don’t explicitly import theclass), most modern IDEs will detect this and prompt you at design time either to import theclass, import the entire package, or specify a fully qualified class name when you use it. Dueto its interpretative nature, ALSB doesn’t validate namespace usage at this level of detail. Thebest it will do is tell you if you’ve used a namespace prefix that hasn’t been defined. If you omitthe namespace when you should have included it, ALSB won’t detect a problem until runtime.Even at runtime, errors are rarely recognized and reported. Usually your expressions are sim-ply evaluated to null and no value is returned at all. For example, Listing 4-5 shows three(invalid) variations of the proper XPath expression from Listing 4-4.

Listing 4-5. Three Invalid Expressions

$body/alsb:getGreetingResponse/return$body/getGreetingResponse/alsb:return$body/getGreetingResponse/return

As you can see, it would be easy to omit a namespace inadvertently, and difficult to spotthe problem when looking at the code. If your expressions are coming back null or empty,look at the namespace usage first.

A Hidden Design FlawYour Goodbye World project runs like a rocket, but did you notice the subtle design flaw? Theflaw isn’t in the service itself, but in how you assembled it. Remember that reuse is a core con-cept of any ESB and is central to SOA. Your proxy service is certainly reusable, but you missedthe opportunity to reuse something within the proxy service itself: the XQuery function thatchanges “Hello” to “Goodbye.”

ALSB has the ability to store XQuery, WSDL, XML Schema, XSLT, WS-Policy files, and moreas reusable resources. The ability to store these resources (sometimes referred to as “assets or“artifacts”) along with proxy services makes ALSB a lightweight service repository. It’s certainlya best practice to reuse these resources whenever possible.

CHAPTER 4 ■ MESSAGE FLOW BASICS62

7974CH04.qxd 3/2/07 10:11 AM Page 62

Page 88: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Let’s take a moment to see how you can make XQuery a reusable resource in your ESB.For this exercise, you’ll create a new proxy service inside your Goodbye World project. You’llname this new proxy service GoodbyeWorldXF (the XF indicates it uses an XQuery function). Youwon’t overwrite your GoodbyeWorld service because it will be handy to compare the two whenyou’re done.

You should be familiar with the process of creating a proxy service by now, so we’ll skipover the boring details. The process is essentially the same as the one you followed when youcreated the GoodbyeWorld proxy. However, before you create the actions in the Route node foryour new GoodbyeWorldXF, you need to create your XQuery resource.

Creating the XQuery process is similar to creating a proxy service. You first navigate to theproject and folder where you’d like to create the resource. Then select XQuery from the “Createresource” combo box. Name the resource Hello_to_Goodbye and provide a short description:“Change the word ‘Hello’ in a given string to ‘Goodbye’.”

Next you write your XQuery into the large text area box. Listing 4-6 shows the content ofthe XQuery resource you’re creating.

Listing 4-6. Sample XQuery Function Performing a String Replacement

xquery version "1.0";declare namespace xf = "http://tempuri.org/util/";declare function xf:helloToGoodbye($hello as xs:string) as xs:string {

let $goodbye := replace($hello, 'Hello', 'Goodbye')return $goodbye

};declare variable $greeting as xs:string external;xf:helloToGoodbye($greeting)

Let’s look at this XQuery script resource in more detail. It’s a good guide for other XQueryresources that you might create. The first line is a declaration of the type of data contained inthis resource. It’s optional in ALSB to include this line. We like to include it for completeness,and because there are other, external tools that require the line to exist, so including it makesit easier to copy and paste the script between tools.

The second line of text is your namespace declaration. This places your function in a spe-cific namespace, which helps to avoid naming collisions. Immediately after the namespacedeclaration, you declare your XQuery function. Note that you prefix the function name by thenamespace. This function take a single xs:string argument named $hello and returns anxs:string. The body of the function is pretty straightforward. You can see how the call tothe replace function is stored in a local variable named $goodbye, which is returned by thefunction.

The next line of code is interesting. Here you formally declare a variable, which you’venever had to do before. You must explicitly define a variable because you’re using an externalXQuery variable. Later, when you use this script resource, ALSB will prompt you to provide avalue for this external variable. Declaring external variables is the mechanism for passing datafrom ALSB to the XQuery script.

CHAPTER 4 ■ MESSAGE FLOW BASICS 63

7974CH04.qxd 3/2/07 10:11 AM Page 63

Page 89: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

The last line of code in this script calls the function you’ve defined, passing in the externalvariable as the argument. This last line is necessary to “hook up” the caller to the script. With-out this line, the XQuery script would still run, but the method would never be invoked. Thecaller of this script has no knowledge of the xf:helloToGoodbye function. It only knows aboutthe XQuery script resource itself. When ALSB invokes the script, it runs the entire script; itdoesn’t invoke a method. This is similar in nature to how other scripting languages areinvoked.

Okay, back to defining your proxy service. Click the Save button to save your XQueryscript. If you made a typo, the ALSB console will give you a warning and let you correct theproblem before it saves the script. In fact, the console won’t let you save the script resourceunless it’s syntactically valid.

Now it’s time to edit the Route node for your GoodbyeWorldXF proxy service. In theResponse Actions section, create a new Assign action. When editing the Assign expression,be sure to click the XQuery Resources link, as shown in Figure 4-9. You can then use theBrowse button to search for the XQuery expression you want to invoke. In this case, you’llselect Goodbye World/Hello_to_Goodbye. In the Bind Variables section of this page, set thegreeting field to string($body/alsb:getGreetingResponse/alsb:return). This tells ALSB toset the XQuery script’s external variable to the value you need to modify.

Figure 4-9. Invoking an XQuery resource

Click the Save button to save this portion of the Assign action. Set the variable namefor the Assign action to greeting. Next you add a Replace action. Set the XPath to./alsb:getGreetingResponse/alsb:return and set the variable field to body. Finally, set theExpression to string($greeting) and select the “Replace node contents” radio button.

Your Route node should now look like Figure 4-10.

CHAPTER 4 ■ MESSAGE FLOW BASICS64

7974CH04.qxd 3/2/07 10:11 AM Page 64

Page 90: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 4-10. Your final Route node for GoodbyeWorldXF

Save everything and activate your changes. Test the new service to be sure that it performscorrectly. One interesting thing to note: as you can see from Figure 4-11, you can also test yourXQuery script.

Figure 4-11. You can test XQuery resources too!

When you test the Hello_To_Goodbye script, remember to include the word “Hello” on thetest string.

SummaryIn this chapter you were introduced to the basics of message flows. You also reused one ofyour existing services from Chapter 3. Reuse is one of the core concepts of ESBs and SOA, andhere we’ve demonstrated the power of that concept. You also saw an example of data transfor-mation, where you intercepted data in flight and modified it to suit your needs. You learnedhow to create, use, and store XQuery scripts as reusable resources within ALSB, again promot-ing the reusability of your ESB. You also gained familiarity with a powerful tool in ALSB: thetest console. Your skills are rapidly growing and you’re now ready to tackle more advancedtopics.

CHAPTER 4 ■ MESSAGE FLOW BASICS 65

7974CH04.qxd 3/2/07 10:11 AM Page 65

Page 91: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

7974CH04.qxd 3/2/07 10:11 AM Page 66

Page 92: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

A Crash Course in WSDL

In this chapter, you’ll learn the “bare bones” of creating a WSDL by hand. Our goal in thischapter is to provide you with some best practices and quickly get you up to speed with thelanguage. If you’re already comfortable with the WSDL language, you can safely skip this chap-ter. If you’re a WSDL/XML Schema purist, then reading this chapter will only upset you: wewon’t take the time to cover the esoteric capabilities of the language here.

In Chapter 3 you learned how to use the Java annotations to have WLS generate a WSDLfor you. This is a handy feature, especially when learning how to write web services in Java.WLS also provides the ability to generate code in the other direction: to generate Java codefrom a WSDL.

You should be aware of the subtle differences in these approaches. They both have theirstrengths and their weaknesses. We’ve heard it proposed that if you’re a Java-centric shop, youshould just use the WSDL generation feature and not worry about the details of WSDL creationand syntax. This is patent nonsense.

We remember the days when the C language was introduced to the personal computingworld. At the time, BASIC was the dominant language. Some vendors created BASIC-to-C lan-guage converters, making the claim that you didn’t need to waste time learning C; you couldcontinue to write your BASIC programs and then push a button to convert the programs intoC. These programs did work, especially for very small projects, but they weren’t viable in thelong run. By using this code generation approach, you rob yourself of the ability to use morepowerful, language-specific capabilities. As a result, you guarantee that you’ll write mediocresoftware at best. The one saving grace of these BASIC-to-C converters was that they did workas a learning tool to help BASIC programmers understand how to write C programs.

We live in an increasingly web service–oriented world. WSDL is the language of web serv-ices, and it will serve you well to become conversant in WSDL, especially if you’re striving tocreate excellent systems. You can fall into a subtle mental trap when you generate WSDL fromyour Java code: you might find yourself generating Java API–oriented web services. If you lookat the world through Java-colored glasses, the work you produce will be similarly colored,whereas if you look at the world through the prism of web services, your work will naturallybecome more service oriented. It’s vital to adopt the new mindset as soon as possible.

WSDL is a nontrivial language. To express the depth and breadth of the language fully isbeyond the scope of this book. In this chapter, we’ll focus on a WSDL format that’s mostamenable to creating highly interoperable web services: document-centric, unencoded (alsoknown as bare or literal encoding). Don’t worry if these terms are meaningless to you now. Bythe end of this chapter they’ll make perfect sense.

67

C H A P T E R 5

7974CH05.qxd 3/12/07 12:33 PM Page 67

Page 93: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

A WSDL is comprised of six sections contained by the <definitions> root element:

• types: You define the data types used by your WSDL here. Data types in a WSDL areexpressed as XML Schema elements.

• portType: This is the abstract interface definition of your web service. It’s similar to aninterface definition in Java or C#. If you want a quick understanding of the functionalityprovided by a web service, this is the section of the WSDL to read.

• message: This section defines the format of the messages (think documents) that theweb service uses.

• Binding: Describes how the portType is mapped into a concrete expression of dataformats and protocols.

• port: Describes the deployment of the service endpoint. In plain English, it describesthe URL where the service can be found.

• service: A collection of port elements. This allows you to specify the fact that a webservice might live on multiple end points.

Listing 5-1 shows a sample WSDL file for a simple web service that returns customerinformation based on the ID of the customer. Even though it describes a simple service, thesample WSDL includes all the necessary principles that you need to understand. We’ll use thislisting as a reference throughout the rest of our discussion on WSDL basics.

Listing 5-1. A Basic WSDL File

<?xml version="1.0" encoding="UTF-8"?><wsdl:definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"xmlns:tns="http://www.alsb.com/Sample/"xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="Sample"targetNamespace="http://www.alsb.com/Sample/"><wsdl:types>

<xsd:schema targetNamespace="http://www.alsb.com/Sample/"><xsd:complexType name="Customer">

<xsd:sequence><xsd:element name="customerID" type="xsd:int" minOccurs="1"/><xsd:element name="firstName" type="xsd:string" minOccurs="1"/><xsd:element name="lastName" type="xsd:string" minOccurs="1"/>

</xsd:sequence></xsd:complexType>

<xsd:complexType name="CustomerQuery"><xsd:sequence>

<xsd:element name="customerID" type="xsd:int" minOccurs="1"/></xsd:sequence>

</xsd:complexType>

CHAPTER 5 ■ A CRASH COURSE IN WSDL68

7974CH05.qxd 3/12/07 12:33 PM Page 68

Page 94: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

<!-- Map our types into elements --><xsd:element name="getCustomer" type="tns:CustomerQuery"/><xsd:element name="getCustomerResponse" type="tns:Customer"/>

</xsd:schema></wsdl:types>

<wsdl:message name="GetCustomerRequest"><wsdl:part element="tns:GetCustomer" name="customerQuery" />

</wsdl:message>

<wsdl:message name="GetCustomerResponse"><wsdl:part element="tns:getCustomerResponse" name="customer"/>

</wsdl:message>

<wsdl:portType name="Sample"><wsdl:operation name="getCustomer">

<wsdl:input message="tns:GetCustomerRequest" /><wsdl:output message="tns:GetCustomerResponse" />

</wsdl:operation></wsdl:portType>

<wsdl:binding name="SampleSOAP" type="tns:Sample"><soap:binding style="document"

transport="http://schemas.xmlsoap.org/soap/http" /><wsdl:operation name="getCustomer">

<soap:operationsoapAction="http://www.alsb.com/Sample/Customer" /><wsdl:input>

<soap:body parts="GetCustomerRequest" use="literal" /></wsdl:input><wsdl:output>

<soap:body parts="GetCustomerResponse" use="literal" /></wsdl:output>

</wsdl:operation></wsdl:binding>

<wsdl:service name="Sample"><wsdl:port binding="tns:SampleSOAP" name="SampleSOAP"><soap:address location="http://www.alsb.com/" /></wsdl:port>

</wsdl:service></wsdl:definitions>

CHAPTER 5 ■ A CRASH COURSE IN WSDL 69

7974CH05.qxd 3/12/07 12:33 PM Page 69

Page 95: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

NamespacesBefore we get too far into our discussion of WSDL, we’ll take a moment to discuss XML name-spaces. The namespace concept is used extensively both by WSDL and XML Schema.Namespaces can make reading a WSDL file difficult unless you understand what a namespaceis and how it affects the document.

A namespace is a way to categorize or group element, data type, and attribute nameswithin an XML document. This is especially handy when combining multiple XML vocabular-ies into a single document. An XML namespace is analogous to a Java package or a C#namespace keyword. Namespaces help to protect against naming collisions. Let’s examine aconcrete example of a naming collision and learn how XML namespaces help. Examine bothListing 5-2 and Listing 5-3 and notice the difference in how the Address data types are defined.

Listing 5-2. Shipping.xsd Snippet

<xsd:complexType name="Address"><xsd:sequence>

<xsd:element name="street" type="xsd:string" minOccurs="1"/><xsd:element name="city" type="xsd:string" minOccurs="1" maxOccurs="1'"/><xsd:element name="state" type="xsd:string" minOccurs="1" maxOccurs="1"/><xsd:element name="zipCode" type="xsd:string" minOccurs="1" maxOccurs="1"/>

</xsd:sequence></xsd:complexType>

Listing 5-3. Customer.xsd Snippet

<xsd:complexType name="Address"><xsd:sequence>

<xsd:element name="street1" type="xsd:string" minOccurs="1" maxOccurs="1"/><xsd:element name="street2" type="xsd:string" minOccurs="1" maxOccurs="1"/><xsd:element name="street3" type="xsd:string" minOccurs="1" maxOccurs="1"/><xsd:element name="city" type="xsd:string" minOccurs="1" maxOccurs="1'"/><xsd:element name="state" type="xsd:string" minOccurs="1" maxOccurs="1"/><xsd:element name="zipCode" type="xsd:string" minOccurs="1" maxOccurs="1"/>

</xsd:sequence></xsd:complexType>

Both Address types are valid, but their structure varies significantly. If you try to use boththese schemas in an Order web service, there will be a naming conflict because they share thesame name. To correct this problem, you’d declare two namespaces—one for each of theschemas that you want to use. The following XML snippet shows you how to declare a name-space:

xmlns:shp="http://www.alsb.com/shipping"

In this case, the namespace you declare is http://www.alsb.com/shipping. This name-space uses the prefix of shp to represent the namespace. A namespace is defined by a URIstring, not the prefix. You can think of the prefix as a variable that holds the namespace“value.” Alternatively, you can think of a namespace prefix as a pointer that represents a

CHAPTER 5 ■ A CRASH COURSE IN WSDL70

7974CH05.qxd 3/12/07 12:33 PM Page 70

Page 96: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

namespace. For example, Listing 5-4 shows what might appear to be two namespace declara-tions. In reality, it is a single namespace that two different namespace prefixes refer to. Thestring is the namespace, not the prefix.

Listing 5-4. Two Prefixes Can Represent the Same Namespace

xmlns:shp="http://www.alsb.com/shipping"xmlns:foo="http://www.alsb.com/shipping"

Note that the URI doesn’t have to point to anything in particular or even be a URL. It’ssimply a string within the document. The xmlns: that appears before the prefix is simply thenotation that tells the XML parser that an XML namespace is about to be declared.

Listing 5-5 shows how namespaces allow you to use two different data types with thesame name (Address, in this case) in the same WSDL. The <CustomerAddress> element takesthe form of the <Address> type that you defined in Listing 5-3, while the <ShippingAddress>takes the form of the <Address> type you defined in Listing 5-2.

Listing 5-5. The Order.wsdl Snippet

<?xml version="1.0" encoding="UTF-8"?><wsdl:definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"

xmlns:tns="http://www.alsb.com/Sample/"xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="Sample"xmlns:shp="http://www.alsb.com/shipping"xmlns:customer="http://www.alsb.com/customer"targetNamespace="http://www.alsb.com/order/">

<xsd:import namespace="http://www.alsb.com/customer"<wsdl:types>

<xsd:schema targetNamespace="http://www.alsb.com/customer/"><xsd:element name="CustomerAddress" type="customer:Address><xsd:element name="ShippingAddress" type="shp:Address>...

</xsd:schema></wsdl:types>

</wsdl:definitions>

If you’ve been paying close attention, you might be wondering how these namespacesmap to the data types; how does the computer know that a customer:Address has the defini-tion that you provided in Listing 5-3? The answer is that it doesn’t. You have to provide thatmapping in a separate XML import statement when you import the Customer.xsd schema.

You’ll find that namespaces are used frequently in XML Schema and WSDL documents.Knowing how to use them is critical for understanding these documents.

The Default NamespaceEvery element in an XML document or XSD belongs to a namespace. The default namespaceis the namespace applied to all nodes in the document that don’t have an explicit namespaceassociated. Defining a default namespace is similar to defining a namespace with a prefix; you

CHAPTER 5 ■ A CRASH COURSE IN WSDL 71

7974CH05.qxd 3/12/07 12:33 PM Page 71

Page 97: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

just don’t define a prefix. There can only be one default namespace for each element. There’s afair bit of subtle detail to that last sentence, so let’s explore it further.

Listing 5-6 shows how to define a default namespace for an entire WSDL file. Namespacesare inherited by each sub-element in an XML document. Because this is a WSDL document,it’s a common practice to define the WSDL namespace as the default namespace. As a result,the WSDL-specific elements don’t have to have a namespace prefix. You can see this in actionin Listing 5-6. The <types> element has no namespace prefix defined for it, so the XML parseruses the default namespace, whereas the <schema> elements all have the xsd: prefix explicitlydefined, because the <schema> element isn’t part of the WSDL namespace.

Listing 5-6. Defining and Using a Default Namespace

<?xml version="1.0" encoding="UTF-8"?><wsdl:definitions name="Sample"xmlns="http://schemas.xmlsoap.org/wsdl/"xmlns:xsd="http://www.w3.org/2001/XMLSchema"targetNamespace="http://www.alsb.com/order/"><types>

<xsd:schema targetNamespace="http://www.alsb.com/customer/"><xsd:element name="CustomerAddress" type="customer:Address><xsd:element name="ShippingAddress" type="shipping:Address>...

</xsd:schema></types>

You can override default namespaces in sub-elements. This allows you to simplify yourdocuments (at least for human readers) by providing a new default namespace in a section ofthe document where that new namespace is commonly used. You see an example of this inListing 5-7. The elements <definitions> and <types> are both part of the WSDL namespace.Because <definitions> declares the WSDL namespace as its default namespace, it doesn’tneed to specify a namespace prefix. Furthermore, the child <types> element inherits thedefault namespace of its parent <definitions> element.

However, the <schema> and <element> tags are part of the XML Schema namespace, yetthey don’t have a namespace prefix in their tags. This is because the default namespace isoverridden by the <schema> element: it declares its own default namespace, and this newdefault namespace is inherited by its child <element> tags.

Listing 5-7. Overriding the Default Namespace

<definitionsname="DefaultNamespaceSample"xmlns="http://schemas.xmlsoap.org/wsdl/"xmlns:tns="foo"xmlns:xsd="http://www.w3.org/2001/XMLSchema"targetNamespace="foo">

CHAPTER 5 ■ A CRASH COURSE IN WSDL72

7974CH05.qxd 3/12/07 12:33 PM Page 72

Page 98: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

<types><schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="foo">

<element name="Response" type="xsd:string"/><element name="Request" type="xsd:string"/>

</schema></types>

Some people feel this makes the resulting XML easier to read. Other folks argue that itmakes it harder to read, especially if you don’t know which tag belongs in which namespace.You’ll have to decide for yourself how you want to use namespaces in your XML. Just like theold arguments about where to place the curly braces in your C, C++, and Java code, it’s a mat-ter of style and personal preference.

Target NamespaceAside from a default namespace, you can define a target namespace. Initially, we found thisconfusing. Like all things technical, it becomes simple once you understand its usage. In yourWSDL and XML Schema files, you’re often creating new data types. These new types ought tobelong to a namespace. Technically, you can define new elements that don’t belong to a name-space, but remember that you’re concerned with real-world usage here, not every fringeusage. You should always define a target namespace.

Listing 5-7 shows the targetNamespace attribute in action. The <schema> element defines atargetNamespace with the value "foo". Nested inside the <schema> element are two elementdefinitions: Request and Response. These new elements are created as members of the "foo"namespace. For example, the proper way to use the Request element in an XML document isas follows:

<Response xmlns="foo">Some string here</Response>

Alternatively, you could do the following:

<ParentElement xmlns:tns="foo"<tns:Response>Some string here</tns:Response>

</ParentElement >

Just like the default namespace, child elements can also override targetNamespaces.

■Caution Earlier we mentioned that XML namespaces are analogous to Java and C# package names. It’strue that they’re similar in many ways, but it’s important to know where they’re different. When you create apackage name in a Java application, you’re creating a namespace that affects the organization of softwarewithin the scope of that application. When you’re defining an XML namespace, you’re creating a namespacethat will affect the organization of data types and services throughout your entire organization! As a result,it’s important to consider carefully how you’ll organize and manage namespaces as a company.

CHAPTER 5 ■ A CRASH COURSE IN WSDL 73

7974CH05.qxd 3/12/07 12:33 PM Page 73

Page 99: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

<types>WSDLs use XML Schema to define data types. Therefore, learning some basics of XML Schemawill be our first topic. XML Schema is a large topic. To facilitate things, we’ll assume that youhave a basic understanding of object-oriented principles. With that background in mind, we’llfocus on how to map object-oriented concepts into XML Schema data types. Traditionally,XML Schema files use the XSD file extension.

Native Data TypesXML Schema provides for a fair number of native data types (also known as primitives) thatyou can use in your schemas—data types such as strings, integers, dates, times, and so on.You’d expect these things from any modern language. Using a native data type is pretty simple.For example, declaring an object of type string looks like the following:

<element name="MyString" type="string" />

You can find a complete list of these native data types at http://www.w3.org/TR/xmlschema-2/#built-in-datatypes.

Custom Data TypesLet’s move to the next level and create some data types that are much more useful. For thisexample, you’ll create a Customer data type. Your customer has the attributes first name, lastname, and customer ID. Listing 5-8 shows how you would define the customer object.

Listing 5-8. The Customer Type Definition

<complexType name="Customer"><sequence>

<element name="customerID" type="int" minOccurs="1" /><element name="firstName" type="string" minOccurs="1" /><element name="lastName" type="string" minOccurs="1" />

</sequence></complexType>

As you can see, you define the Customer object as a complexType. This is roughly equivalentto defining a customer class in Java or C++/C#. You name the complex type using the nameattribute.

■Best Practice It’s possible to define data types as being anonymous within a named element. This isn’ta good practice within the XSD file itself. This type of design pattern is okay within the WSDL file, though.Name your complex types in your XSD files and then refer to them via <element> tags within your WSDL.

CHAPTER 5 ■ A CRASH COURSE IN WSDL74

7974CH05.qxd 3/12/07 12:33 PM Page 74

Page 100: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Next you add properties to your Customer data type. In XML Schema, add the propertiesusing the <sequence> tag. The <sequence> tag means that a series of elements or types will fol-low, in a specific sequence. In this example, you have three properties in this sequence:customerID, firstName, and lastName.

Although you use the <sequence> tag to define a sequence of object attributes, you canuse two other tags here, depending on your needs. Those are the <choice> and <all> tags. Youuse those tags when defining more complicated data types, and they’re beyond the scope ofthis chapter. For our purposes, a <complexType> will always contain a <sequence> of attributes.

Notice that each of the attributes in your Customer data type is defined as an element. Youuse the <element> tag when referring to an existing data type. In the case of our attributes, theexisting data types are of type string and int. Inside the Customer data type, you can also ref-erence other custom data types. For example, you can create an Address data type and thenuse it within your Customer data type, as shown in Listing 5-9.

Listing 5-9. Nesting Complex Data Types

<complexType name="Customer"><sequence><element name="customerID" type="int" minOccurs="1" />

<element name="firstName" type="string" minOccurs="1" /><element name="lastName" type="string" minOccurs="1" /><element name="homeAddress" type="Address"/>

</sequence></complexType><complexType name="Address">

<sequence><element name="street" type="string" minOccurs="1" /><element name="city" type="string" minOccurs="1" /><element name="state" type="string" minOccurs="1" /><element name="postalCode" type="string" minOccurs="1" />

</sequence></complexType>

minOccurs and maxOccursYou might have noticed in all the listings so far, you use the minOccurs attribute in your ele-ment definitions. This specifies the minimum number of times the element can occur withinthe sequence. By setting the minOccurs value to 1, you’re specifying that the element mustoccur at least once in the sequence. If you set the value to 0, then you’re specifying that theelement is optional.

The complement to minOccurs is the maxOccurs attribute. It specifies the maximum num-ber of times the element can occur in the sequence. The maxOccurs value must be a positiveinteger, or might be the term “unbounded” (to indicate that there’s no limit on the number oftimes it might occur). These attributes are often used in conjunction. For example, the combi-nation of minOccurs="1" and maxOccurs="1" specifies that the element must appear only once.The default values of minOccurs and maxOccurs are both "1".

CHAPTER 5 ■ A CRASH COURSE IN WSDL 75

7974CH05.qxd 3/12/07 12:33 PM Page 75

Page 101: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Importing XML SchemasAs mentioned previously, you can import existing schemas into your XML schema or WSDLdocuments. This is an excellent way to reuse these assets, allowing you to make broad changesto your enterprise definitions in a centralized manner. Importing a schema into your WSDL isdone within the <types> section. The general format of an import statement is as follows:

<import namespace="[the URI to the namespace]" schemaLocation= ➥

"[file path or URI to your .XSD file]" />

For example, in your WSDL, if you wanted to use the customer.xsd and the shipping.xsdschemas, you’d use the following import statements:

<xs:import namespace="http://www.alsb.com/customer" schemaLocation="customer.xsd" /><xs:import namespace="http://www.alsb.com/shipping" schemaLocation="shipping.xsd" />

Notice that the URI for the namespace matches exactly the URIs you used in Listing 5-5when you defined the namespaces. Now, when you declare an element to be of typecustomer:Address or shp:Address, the web service is able to determine exactly which Addressdefinition to use.

<message>A message describes the abstract form of the input, output, or fault messages. Messages arecomposed of one or more <part> elements. The <part> elements describe the composition ofthe <message>.

Because you’re using the document-centric style of WSDL, the <part> elements of the<message> must refer to data structures using the element attribute (see Listing 5-10).

Listing 5-10. Sample Document-Style Message Definition

<wsdl:message name="GetCustomerResponse"><wsdl:part element="tns:getCustomerResponse" name="customer"/>

</wsdl:message>

For document-centric WSDL, it's common practice to use the operation name as thename of the request message and to append the text “Response” to the operation name anduse that as the name of the response message. Listing 5-10 demonstrates this namingapproach with the GetCustomerResponse message.

<portType>The portType section of the WSDL describes the abstract interface of the web service. Listing5-11 provides an example of a simple portType definition. This section of the WSDL is oftencompared to an abstract Java interface because it defines, at a high level, how the operationsof the service work (that is, what arguments are expected and what results are returned).

The <portType> element is made up of <operation> elements. The <operation> elements,in turn, are comprised of <input> and <output> elements that map directly to the <message>

CHAPTER 5 ■ A CRASH COURSE IN WSDL76

7974CH05.qxd 3/12/07 12:33 PM Page 76

Page 102: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

elements. The <operation> elements might also contain <fault> elements to indicate theSOAP faults that the operation might throw. However, for the purposes of our crash course,you’ll ignore the <fault> element.

Listing 5-11. An Example of the <portType>

<wsdl:portType name="CustomerPortType"><wsdl:operation name="findCustomer">

<wsdl:input message="tns:findCustomer" /><wsdl:output message="tns:findCustomerResponse" />

</wsdl:operation></wsdl:portType>

<binding>The <binding> is used to define how the <portType> (that is, the abstract interface of the webservice) is bound to a transport protocol and an encoding scheme. A single portType may bebound to many transports and encoding scheme combinations. The most commonly usedencoding scheme and transport protocol combination these days is SOAP over HTTP. Themost common bindings other than HTTP/SOAP are HTTP/POST and HTTP/GET, especially whendealing with web services that were developed before HTTP/SOAP gained popularity.

As you can see from Listing 5-12, the <binding> is mapped to a <portType>. Each opera-tion of the <portType> is defined in the binding, including the mapping of the operation’sinput and outputs to specific message types.

Listing 5-12. An Example of the HTTP/SOAP Binding

<wsdl:binding name="CustomerServiceSOAP" type="tns:CustomerPortType"><soap:binding style="document"

transport="http://schemas.xmlsoap.org/soap/http" /><wsdl:operation name="findCustomer">

<soap:operation soapAction="" style="document" /><wsdl:input>

<soap:body parts="findCustomer" use="literal" /></wsdl:input><wsdl:output>

<soap:body parts="findCustomerResponse" use="literal" /></wsdl:output>

</wsdl:operation></wsdl:binding>

<service>A service is simply a collection of <port> elements. A WSDL might contain multiple <service>definitions, one for every distinct binding type that’s supported by the web service.

CHAPTER 5 ■ A CRASH COURSE IN WSDL 77

7974CH05.qxd 3/12/07 12:33 PM Page 77

Page 103: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

<port>A <port> describes the physical locations of a binding. Listing 5-13 shows a sample web servicethat exists on two different end points. The term “end point” is commonly used when dis-cussing web services. An end point is simply a URI that points to a physical location where aservice exists.

Listing 5-13. Sample <service> and <port> Tags

<wsdl:service name="CustomerService"><wsdl:port binding="tns:CustomerServiceSOAP" name="CustomerServiceSOAP">

<soap:address location="http://server1:7001/customer/CustomerService" /><soap:address location="http://server2:7001/customer/CustomerService" />

</wsdl:port></wsdl:service>

That’s it for the basics of WSDL. Like many technical topics, it’s conceptually simple. Also,like many technical topics, “the devil is in the details.” Fortunately, this technology has existedlong enough for some best practices to emerge. We’ll go over two of those best practices in thenext section.

WSDL Best PracticesOnce you begin creating your own services, the flexibility of WSDL can cause some confusionand even arguments among service designers. Everyone wants to write services “the rightway,” especially when they’re brand new to services and don’t have any experience to draw on.At BEA, we have the advantage of speaking with numerous members of our Professional Ser-vices Group who help customers design not only individual services, but entire SOAs on adaily basis. This provides us with a great source of real-world experience. In this section, we’llshare the best practices that we use to help simplify designs and ensure success.

Elements vs. TypesIn some of the sample WSDLs you’ve seen so far, you used several different mechanisms tocreate your data types. The first is to use <elements> to wrap anonymous data types. Listing 5-14 shows how this is done.

Listing 5-14. Using an <element> to Wrap a <complexType>

<xs:element name="findProduct"><xs:complexType>

<xs:sequence><xs:element name="id" type="xs:int"/><xs:element name="name" type="xs:string"/><xs:element name="family" type="xs:string"/>

</xs:sequence></xs:complexType>

</xs:element>

CHAPTER 5 ■ A CRASH COURSE IN WSDL78

7974CH05.qxd 3/12/07 12:33 PM Page 78

Page 104: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

This approach provides considerable flexibility, allowing the service designer to defineany data type needed by the service.

A second, but closely related, approach is to define separate, named <complexType> typesand then create <elements> of the required type. Listing 5-15 provides a concise example ofdefining a complexType and then using an element to refer to it.

Listing 5-15. Using Named Types and Elements

<xs:complexType name="ProductRequestType"><xs:sequence>

<xs:element name="id" type="xs:int"/><xs:element name="name" type="xs:string"/><xs:element name="family" type="xs:string"/>

</xs:sequence></xs:complexType><xs:element name="findProduct" type="ProductRequestType"/>

This approach is an improvement over the first approach. It gives the service designer thesame level of flexibility as the first approach, but now the service designer has the ability toreuse the named complexType. In large, real-world services, documents (defined by data struc-tures) become increasingly complex and the ability to reuse data types becomes increasinglyimportant. This reuse also eases maintenance of the service, because if a complexType needs tochange, having a separate definition of that type will make the change simpler to perform.Also, you can be sure that all the elements of that type will automatically inherit the change.

By defining a complexType by name, you gain the ability to reuse it in your document.However, this principle also operates at a higher level: the enterprise. Many data types are theproperty of the enterprise. If you define these data types as externally available resources, yougain the ability not only to reuse them across multiple WSDLs, but also to provide enterprise-wide standards and a control point for your SOA governance group.

Listing 5-16 shows how this is done. You create your complexTypes in one or more externalXML schema files and then import them into your WSDLs for use. This approach sacrificessome flexibility for the sake of reuse, standardization, and control.

Listing 5-16. Define Enterprise Data Types Outside Your WSDLs

<xs:import namespace="http://www.alsb.com/product" schemaLocation="product.xsd" /><xs:element name="findProductRequest" type="ProductRequestType"/>

Ideally, you’d store and publish your XML Schema documents in an enterprise servicerepository. However, because service repositories are relatively new, you can also simply pub-lish the XSDs on a set of web servers to achieve some of the same benefit. The one benefit thata service repository provides over a simple web server is that a repository can cross-check anychanges that you make to your XSDs with any services that import those schemas.

ALSB provides you with some repository behavior out of the box. When you create aWSDL or a service that uses a specific XSD, ALSB keeps track of the resulting dependencies.In fact, ALSB will go so far as to prohibit you from removing a resource that’s used by existingservices and resources.

CHAPTER 5 ■ A CRASH COURSE IN WSDL 79

7974CH05.qxd 3/12/07 12:34 PM Page 79

Page 105: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

■Best Practice Define your types in separate and distinct XML Schema files and reference those typesfrom within your WSDLs.

One thing to note, however: you must exercise moderation when importing variousschemas into each other lest you fall into the dependency trap.

The Dependency TrapWhen you import a schema, you’re creating a fairly tight coupling between the importedschema and the WSDL or XSD that imports it. You can create an enterprise-wide set ofschemas that are all interdependent, allowing you to more easily “inherit” changes made inlower-level schemas. However, this becomes difficult to manage at scale. It’s better to createclusters of related schemas and WSDLs and then use a tool such as ALSB to loosely couplethem via transformation.

If you examine Figure 5-1, you can see how the dependency trap can manifest itself. Inthe lower-right section of the figure is a legacy EJB application called Contract Manager. Thisapplication was developed in house several years ago to handle the contract managementneeds of the company. The IT department has service-enabled the Contract Manager applica-tion by creating the ContractManagerAppService, a web service wrapper. TheContractManagerAppService is invoked via an HTTP over SOAP protocol, and is defined by theContractManagerAppWSDL, which imports the ContractManagerAppTypes XML Schema.

To the left of the legacy Contract Manager application is the Scorecard application. Thisapplication is newer, and therefore comes with a prebuilt web service interface. The Scorecardweb service also follows the best practice of having the WSDL import its XML Schema typesfrom a separate XML Schema file.

So far, everything seems to be fairly standard. There are no problems yet simply becausewe’re only looking at standalone web service implementations. At this point, the IT departmenthas matured its SOA thinking beyond mere service enablement, and it has begun to realize thevalue of service aggregation. It decides to create a CustomerService component that will act as afaçade for all customer-centric information. This service uses the CustomerServicesWSDL asits contract, which in turn imports the CustomerTypes XML Schema file. The CustomerTypesschema also imports a UtilityTypes schema, because the architects and developers havebegun to identify some utility types used across the entire organization, namely thePostalAddress type.

Also, the architects have embraced the concept of reuse, so they design the CustomerServiceWSDL to import the XML Schemas used by the Contract Manager and the Scorecard applica-tions. The CustomerServices web service is then coded and placed into production. Everythingseems fine on the surface, but the dependency trap is now fully set and is about to be sprung!

The trap is unknowingly sprung by the business leaders of the company when they decidethat their home-grown contract management application no longer meets their increasingneeds. The business purchases a Commercial, Off The Shelf (COTS) application and asks theIT department to install this new application while the company decommissions the ContractManager application. The business sees this as a simple operation: unplug the old applicationand plug in the new one—what could be hard about that?

CHAPTER 5 ■ A CRASH COURSE IN WSDL80

7974CH05.qxd 3/12/07 12:34 PM Page 80

Page 106: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Of course, the architects and developers can now see why this change of applicationswon’t be easy. The new COTS contract management application is already web serviceenabled. That means that it comes with its own WSDL and one or more XSDs that definethe types specific to itself. Because the CustomerServiceWSDL imported the olderContractManagerAppTypes directly, it needs to be updated. Furthermore, you can bet that weexposed those types directly to the consumers of the CustomerService web service, and nowthey might all have to be recompiled.

In its simplest form, the dependency trap occurs when you allow low-level implementa-tion details, such as application-specific schemas, to bubble up through your services bydirectly importing them. The way you defeat this trap is through architecture: by defining spe-cific layers of abstraction and then breaking the direct dependencies between each layer. We’lltalk about layers of architecture in Chapter 10, when we introduce the concept of a “servicelandscape.” For now, let’s see how we’d use ALSB to defeat the dependency trap and give us theagility we need.

Figure 5-2 shows the proper usage of ALSB to defeat the dependency trap and provide anopportunity to stop the ripple effect of changing the contract application from affecting theservice clients. ALSB acts as a layer of abstraction between the ContractManagerAppServiceand the CustomerServices. Inside the service bus, you create a project that defines a proxyservice, with its own WSDL and XSD. This helps to decouple the proxy service from the

CHAPTER 5 ■ A CRASH COURSE IN WSDL 81

Figure 5-1. The dependency trap in action

7974CH05.qxd 3/12/07 12:34 PM Page 81

Page 107: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

physical service implementation. There has also been another slight change, due to the intro-duction of ALSB. The business service in the ALSB project is dependent on the WSDL of theContractManagerAppService, and now only indirectly dependent on the schema objects thatthe ContractManagerAppService defines.

So how does this help us achieve the flexible, change-absorbing architecture we desire?Let’s go back to our scenario and see how this affects the architects and developers that aretasked with replacing the legacy ContractManager application. First, they’d need to update thebusiness service definition in ALSB to match that of the new COTS application. Second, theywould change the message flow of the proxy service, mapping the new message and schemaformats into the existing logical formats defined within the proxy service itself. There wouldbe no need to change the CustomerServices component at all.

CHAPTER 5 ■ A CRASH COURSE IN WSDL82

Figure 5-2. Using ALSB to disarm the dependency trap

7974CH05.qxd 3/12/07 12:34 PM Page 82

Page 108: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Of course, in the real world it might be that the changes between the legacy applicationand the new application are so significant that the message flow of the proxy service won’t besufficient to encapsulate the entire change. However, this approach will give your systems theresilience they need to absorb the majority of system changes without affecting the serviceclients. When you couple this simple example with the methodology described in Chapter 10,you’ll see how you can use multiple layers of abstraction to control the effects of changeswithin your SOA.

Figure 5-2 only shows the solution for the contract management system. A similarapproach would be used to insulate the Scorecard application from its service consumers. Infact, even the CustomerServices component should be abstracted from its service consumersusing this same approach. You might wonder why this approach is needed, given the fact thatwe’re only dealing with three systems; imagine the levels of coupling when you consider anentire enterprise with hundreds of software components!

Document-Centric vs. RPCAlthough WSDL allows considerable flexibility when designing web services, there areemerging standards that promote greater interoperability between different web serviceimplementations. The two main approaches are often referred to as document-centric andRemote Procedure Call (RPC). Within each of these major approaches is the use of encodedor unencoded (also known as “literal”) data.

RPC History and IssuesRPC style was the first style in use by web service designers. In the early days of SOAP, therewas a strong desire to use RPC as a vehicle for invoking remote procedures. The commonthinking at that time in the evolution of our industry was to treat a network of computers as ifit were one giant, virtual computer. Because the programming paradigm at the time was tomake procedure calls, this thinking was carried over into the realm of distributed computing.

As a direct result of this thinking, RPC-style web services usually take multiple arguments.For example, a web service that allowed the caller to create a simple customer record andreturned the ID of the new customer record might look like this:

createCustomer(String firstName, String lastName) : int ID

At first glance, this seems simple enough and completely harmless. However, problemsbegan to arise as service developers increased the level of abstraction employed in their webservices. As the abstraction level increased, the associated data payload also increased. Imag-ine a service that accepts an order on behalf of a customer, such as many shopping cartimplementations on modern web sites. A typical order carries a lot of information: customername, billing information, lists of products and their costs, customer address information,and possible tax implications. Using an RPC approach to such a service might look like thefollowing:

submitOrder(Customer customer, Address shipAddr, Address billAddr, Product[] ➥

products) : int

As you can see, as services became more abstract and broader in scope, by necessity theyhad to deal with more information. That additional information added arguments to each

CHAPTER 5 ■ A CRASH COURSE IN WSDL 83

7974CH05.qxd 3/12/07 12:34 PM Page 83

Page 109: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

service. In extreme cases, a dozen or more arguments would appear in the operational signa-ture of a web service. This demanded that the service consumer understand the ordering ofthe arguments and whether or not it was acceptable to use null values for some arguments.Furthermore, if the service provider changed the service’s operational signature to ask for anadditional argument, all existing service consumers were immediately obsolete. RPC wassimply too brittle an approach at the enterprise level.

The advantage that RPC has over the document-centric style is that the RPC WSDLs aregenerally easier to read. This is because there’s less “wrapper” code around the arguments foreach operation.

Document-Centric Style EmergesThe document-centric design approach for web services was created to address some of theproblems evident in the RPC approach. The primary difference between the RPC and document-centric styles is that the document-centric approach always uses a single argument in itsoperational signatures; for example:

submitOrder(OrderDocument orderDoc) : int

This change in design might seem trivial, but it has a number of beneficial side effectsthat we’ll point out. First and foremost, it makes your designs more message oriented.Because you’re passing a single argument that contains all the necessary information for theservice to perform its duties, the service designer will naturally begin to think more in termsof the document (read: message) that he’s passing around, and less about individual serviceoperations. A byproduct of this change in thinking is that more thought is given to the inter-face and less to the functional composition of the service. In turn, services become less“chatty.”

We hasten to point out that creating document-centric services doesn’t immunize youfrom bad design. It’s still possible to create document-oriented services that are chatty, finegrained, and so on. However, this design style encourages good design habits, whereas RPCstyle does not.

Encoded vs. LiteralWhether you use RPC or document-centric services, you have another design decision tomake: whether or not to encode the data of the service calls (that is, the operational argu-ments) or to leave them in their literal form.

■Note Using the Literal or Encoded styles only applies to SOAP services.

Here, the decision is easy. The WS-I organization was created to clarify issues regardingthe various web service specifications in an effort to improve the interoperability of differentweb service implementations (commonly referred to as web service stacks). WS-I complianceclearly states that encoding is never to be used. Therefore, you’re left with using the literal stylein your SOAP messages.

CHAPTER 5 ■ A CRASH COURSE IN WSDL84

7974CH05.qxd 3/12/07 12:34 PM Page 84

Page 110: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

WrappingAt this point, it’s obvious that you’re going to use the document-centric, literal style in yourSOAP bindings. In the past, this design style wasn’t sufficient to ensure maximum interoper-ability. An additional step was taken in the design of WSDLs called wrapping. Wrapping is theprocess of naming operations and their request and return values. As an example, an opera-tion named getCustomer would accept a message, also named getCustomer, and it wouldreturn a response document named getCustomerResponse.

For a while in web services history this was an accepted way of improving web serviceinteroperability, especially in the Java community. However, with the advent of the WS-I man-date that the root element of the document must be unique across all operations defined inthe WSDL, the use of wrapping is fading into history.

■Best Practice Use document, literal web services whenever possible.

Troubleshooting WSDLs and SchemasInevitably, as you create WSDL and XML Schema documents, you’ll make mistakes. Some-times the tools you use, such as Workshop and ALSB, will catch those mistakes and highlightthem for you. However, if you’re new to XML documents, you might not understand the errormessages when you first see them. Here’s a primer to help you troubleshoot these problems.

Open up Workshop and then open the WSDL Samples project. In the WSDL folder, open thesimple.wsdl file. It looks like Listing 5-17. The listing contains a number of errors. However,Workshop only detects two when you open this file, and the first error is really a byproduct ofthe second error: the missing closing quote on the bold-faced line in Listing 5-17. If you addthe closing quote, then save the file, Workshop won’t report any errors.

Listing 5-17. The Simple.wsdl File

<?xml version="1.0" encoding="UTF-8"?><wsdl:definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"

xmlns:tns="http://www.bea.com/simple/"xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="simple"targetNamespace="http://www.bea.com/simple"><wsdl:types>

<xsd:schematargetNamespace="http://www.bea.com/simple/simple"elementFormDefault="qualified"><xsd:element name="FindCustomerResponse">

<xsd:complexType><xsd:sequence>

<xsd:element name="customer" type="xsd:string"minOccurs="0" maxOccurs="unbounded" />

CHAPTER 5 ■ A CRASH COURSE IN WSDL 85

7974CH05.qxd 3/12/07 12:34 PM Page 85

Page 111: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

</xsd:sequence></xsd:complexType>

</xsd:element>

<xsd:element name="FindCustomer" type="string /></xsd:schema>

</wsdl:types>

<!-- Messages --><wsdl:message name="FindCustomerResponse">

<wsdl:part element="FindCustomerResponse"name="FindCustomerResponse" />

</wsdl:message><wsdl:message name="FindCustomer">

<wsdl:part element="tns:FindCustomer" name="FindCustomer" /></wsdl:message>

<!-- PortType --><wsdl:portType name="SimplePort">

<wsdl:operation name="FindCustomer"><wsdl:input message="tns:FindCustomer" /><wsdl:output message="tns:FindCustomerResponse" />

</wsdl:operation></wsdl:portType>

<!-- SOAP Binding --><wsdl:binding name="SimpleSOAP" type="SimplePort">

<soap:binding style="document"transport="http://schemas.xmlsoap.org/soap/http" />

<wsdl:operation name="FindCustomer"><soap:operation

soapAction="http://www.bea.com/FindCustomer" /><wsdl:input>

<soap:body parts="FindCustomer" use="literal" /></wsdl:input><wsdl:output>

<soap:body parts="FindCustomerResponse" use="literal" /></wsdl:output>

</wsdl:operation></wsdl:binding><wsdl:service name="SimpleService">

<wsdl:port binding="tns:SimpleSOAP" name="SimpleSOAPService"><soap:address location="http://www.bea.com/simple" />

</wsdl:port></wsdl:service>

</wsdl:definitions>

CHAPTER 5 ■ A CRASH COURSE IN WSDL86

7974CH05.qxd 3/12/07 12:34 PM Page 86

Page 112: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

However, there are still plenty of errors in the simple.wsdl file. One simple way to validatethe WSDL is to create a WSDL resource in an ALSB project. Copy the contents of thesimple.wsdl file into ALSB and click the Save button. ALSB reports the following error:

An error occurred creating the resource:The WSDL is not semantically valid: error: src-resolve.a: Could not find type'string'. Do you mean to refer to the type named string@http://schemas.xmlsoap.org/soap/encoding/?.

ALSB quickly identified that the definition of the FindCustomer element in the <schema>section of the WSDL is defined with a type of string. Looking at the line, you should quicklyrealize that the type should really be xsd:string. ALSB tries to help by asking you if you reallymeant to use a different type of string. Add the xsd: prefix to the type and click the Save but-ton again.

Now ALSB reports another error: portType not found 'SimplePort'. Whenever you getany sort of not found error, that’s your clue to start to look for missing or improperly definednamespaces. You might be tempted to look at the <portType> definition first, but the real cul-prit is in the <binding> tag, which references the <portType>. Once again, the namespace ismissing from the type attribute. Take a look at the following line:

<wsdl:binding name="SimpleSOAP" type="SimplePort">

You should change it to this:

<wsdl:binding name="SimpleSOAP" type="tns:SimplePort">

Now let’s try to save this file again. Oops! Another error:

portType not found '{http://www.bea.com/simple/}SimplePort'

This error is very subtle, and one that we’ve come across on more than one occasion. Asusual, ALSB is deadly accurate in its error reporting. It’s telling you that there’s no such type asSimplePort in the namespace http://www.bea.com/simple/. If you examine the namespacedefinition for the tns prefix you’ll see that it’s correct. The real problem lies in the fact that thetargetNamespace in the <wsdl:definitions> tag is missing the trailing / character. Add thetrailing slash character and save the WSDL again.

The next error is as follows:

The WSDL is not semantically valid: The element or type specified forpart'FindCustomerResponse' in message '{http://www.bea.com/simple/}FindCustomerResponse' cannot be found in any schemas referenced by this wsdl.

Again, this message is accurate once you understand it. It says that the typeFindCustomerResponse defined in the <part> tag cannot be found.

CHAPTER 5 ■ A CRASH COURSE IN WSDL 87

7974CH05.qxd 3/12/07 12:34 PM Page 87

Page 113: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

<wsdl:message name="FindCustomerResponse"><wsdl:part element="FindCustomerResponse"

name="FindCustomerResponse" /></wsdl:message>

You could (and should) use the tns: prefix with the element name. However, that isn’tthe true problem. The real problem lies in the fact that the <schema> element declares its owntargetNamespace, and this targetNamespace is also missing the trailing slash. We bring this par-ticular issue up because it’s quite common to overlook the fact the targetNamespace might bedefined in multiple sections of a WSDL, and those targetNamespaces might not always agreewith one another.

■Best Practice Minimize the number of targetNamespace attributes in your WSDL and XSD files to theabsolute minimum necessary.

We’ve seen some WSDL generation tools that define a targetNamespace in several sectionswhere you might not be accustomed to seeing them. The best fix for this problem is to removethe targetNamespace attribute from the <schema> tag completely.

Visualizing Documents from SchemasAt this point, you’re ready to put all this information to good use. It’s one thing to know how todefine document structures using WSDL and XML Schema. However, it’s a different skill tothen visualize how instances of these XML documents will appear in the real world. Being ableto look at a document definition and then know, unambiguously, how that definition will berealized as a document instance is a critical skill for your success with web services and ALSB.

In this section, you’ll learn by doing. We’ll show you a number of WSDLs and XMLSchemas and then ask you to choose the right XML document instance from a choice ofseveral sample documents. In our experience, most of the trouble in accurately visualizingdocument instances is centered around XML namespaces. Namespace errors can be subtle (aswe just saw), but they fall into a small number of specific problems. We’ll examine the mostcommon namespace problems here. Also, because we’re concerned with document instances,when we show the WSDLs that define the structures of the documents, we’ll skip over the portand binding information because it isn’t important for this discussion.

The ElementFormDefault AttributeVisualizing a document is complicated by the use of the elementFormDefault attribute in the<schema> tag. This attribute is optional and has two possible values, qualified or unqualified.This attribute specifies whether or not the elements in the document must have their name-spaces explicitly specified or not. The default value for this attribute is unqualified.

At this point in time, we’re not willing to declare a best practice around the use of thisattribute. Certainly, using fully qualified elements leads to more precise WSDLs and XSDs. Onthe other hand, unqualified elements give you a far more forgiving environment. It doesn’t

CHAPTER 5 ■ A CRASH COURSE IN WSDL88

7974CH05.qxd 3/12/07 12:34 PM Page 88

Page 114: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

take a lot of skill to create document instances for unqualified elements. Therefore, we’ll focuson qualified element form documents.

Our first exercise uses the schema defined in Listing 5-18 and the WSDL shown inListing 5-19. The WSDL imports the schema.

Listing 5-18. The common.xsd File

<?xml version="1.0" encoding="UTF-8"?><schema xmlns="http://www.w3.org/2001/XMLSchema"

targetNamespace="http://www.bea.com/RefArch/common/" xmlns:tns="http://www.bea.com/RefArch/common/elementFormDefault="qualified"><complexType name="PostalAddressType">

<sequence><!-- Unique ID for this address --><element name="id" type="int" /><element name="streetAddress" type="string" maxOccurs="unbounded"/><element name="city" type="string" /><element name="state" type="string" /><element name="postalCode" type="string" />

</sequence></complexType>

</schema>

Listing 5-19. The SimpleImport1.wsdl File (snippet)

<wsdl:definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"xmlns:tns="http://www.bea.com/simple/"xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"xmlns:xsd="http://www.w3.org/2001/XMLSchema"xmlns:cmn="http://www.bea.com/simple/common/"name="simple"targetNamespace="http://www.bea.com/simple/"><wsdl:types>

<xsd:schema targetNamespace="http://www.bea.com/simple/"elementFormDefault="qualified"><xsd:import namespace="http://www.bea.com/simple/common/" ➥

schemaLocation="common.xsd" /><xsd:element name="FindAddressResponse">

<xsd:complexType><xsd:sequence>

<xsd:element name="address" type="cmn:PostalAddressType" ➥

minOccurs="0" maxOccurs="unbounded" /></xsd:sequence>

</xsd:complexType></xsd:element><xsd:element name="FindAddress" type="xsd:string" />

CHAPTER 5 ■ A CRASH COURSE IN WSDL 89

7974CH05.qxd 3/12/07 12:34 PM Page 89

Page 115: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

</xsd:schema></wsdl:types><!-- Messages --><wsdl:message name="FindAddressResponse">

<wsdl:part element="tns:FindAddressResponse" name="FindAddressResponse" /></wsdl:message><wsdl:message name="FindAddress">

<wsdl:part element="tns:FindAddress" name="FindAddress" /></wsdl:message>

Each <message> in a WSDL is an XML document. Take a look at the FindAddress messagein the WSDL (see Listing 5-19). Which of the following XML documents conforms to the mes-sage format defined by the WSDL?

<sim:FindAddress xmlns:sim="http://www.bea.com/simple/">Harold</sim:FindAddress>

or

<FindAddress>Lucy</FindAddress>

or

<FindAddress><String>Lucy</String></FindAddress>

The answer is the first example. It defines and uses the same namespace that’s defined inthe WSDL file. The namespace prefix is changed to sim, but that’s just a prefix and is perfectlyacceptable. As you learned earlier in this chapter, the namespace is defined by the literalstring, not by the prefix name.

The second example could be correct, if the following line appeared near the top of thedocument:

xmlns="http://www.bea.com/simple/"

The preceding code line, of course, defines the default namespace to be the same name-space needed by the <FindAddress> element.

Lets try a slightly more ambitious example. Looking at Listings 5-18 and 5-19 again, selectthe correct instance of the FindAddressResponse document.

<sim:FindAddressResponse xmlns:sim="http://www.bea.com/simple/"><cmn:address xmlns:cmn="http://www.bea.com/simple/common/">

<cmn:id>279</cmn:id><cmn:streetAddress>100 Main Street</cmn:streetAddress><cmn:city>San Jose</cmn:city><cmn:state>CA</cmn:state><cmn:postalCode>95131</cmn:postalCode>

</cmn:address></sim:FindAddressResponse>

or

CHAPTER 5 ■ A CRASH COURSE IN WSDL90

7974CH05.qxd 3/12/07 12:34 PM Page 90

Page 116: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

<sim:FindAddressResponse xmlns:sim="http://www.bea.com/simple/"><sim:address xmlns:cmn="http://www.bea.com/simple/common/">

<cmn:id>279</cmn:id><cmn:streetAddress>100 Main Street</cmn:streetAddress><cmn:city>San Jose</cmn:city><cmn:state>CA</cmn:state><cmn:postalCode>95131</cmn:postalCode>

</sim:address></sim:FindAddressResponse>

or

<sim:FindAddressResponse xmlns:sim="http://www.bea.com/simple/"><sim:address xmlns:cmn="http://www.bea.com/simple/common/">

<sim:id>279</ sim:id>< sim:streetAddress>100 Main Street</ sim:streetAddress>< sim:city>San Jose</ sim:city>< sim:state>CA</ sim:state>< sim:postalCode>95131</ sim:postalCode>

</sim:address></sim:FindAddressResponse>

The correct example is the second one. The point of confusion usually centers on the<address> element. The <address> element is defined in the WSDL under the targetNamespacehttp://www.bea.com/simple/. However, it represents the PostalAddressType defined in theXML Schema file under the http://www.bea.com/simple/common/ namespace. The rule isto always use the namespace in which the element is defined, not the type. Therefore, your<address> element must use the http://www.bea.com/simple/ namespace.

■Tip You always use the namespace in which the <element> was defined.

The second common area of confusion has to do with the elements defined in thePostalAddressType. By applying the rule defined in the preceding Tip, you can easily deter-mine that the <id>, <streetAddress>, and other elements in the PostalAddressType weredefined in the http://www.bea.com/simple/common/ namespace. Therefore, you must declarethose elements to be in that same namespace when used in a document instance.

If you examine the WSDL, you’ll see that the <address> type is defined as an element inthe WSDL under the targetNamespace http://www.bea.com/simple/. However, the elementscontained by the PostalAddressType are defined under the http://www.bea.com/simple/common/ namespace in the common.xsd file. As a result, all the elements that appear inside the<address> element must have the cmn: namespace prefix.

CHAPTER 5 ■ A CRASH COURSE IN WSDL 91

7974CH05.qxd 3/12/07 12:34 PM Page 91

Page 117: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Just for completeness, we’ve included a version of the FindAddressResponse document(see Listing 5-20), which uses unqualified elements.

Listing 5-20. Sample Unqualified Document Instance

<sim:FindAddressResponse xmlns:sim="http://www.bea.com/simple/"><address xmlns:cmn="http://www.bea.com/simple/common/">

<id>279</id><streetAddress>100 Main Street</streetAddress><city>San Jose</city><state>CA</state><postalCode>95131</postalCode>

</address></sim:FindAddressResponse>

Notice that only the first element in the document has a namespace declared. Theremaining elements are simply “understood” by the parser. The real choice between the quali-fied and unqualified approaches is, “Do I want strongly typed documents or loosely typed?”That’s a question you’ll have to answer for yourself.

The attributeFormDefault AttributeAttributes, like elements, also exist within namespaces. The attributeFormDefault attribute isdefined in the <schema> tag and can have a value of "qualified" or "unqualified". The defaultvalue for the attributeFormDefault is "unqualified". This attribute value is not overriddenwhen its schema is included into a new schema. Listing 5-21 shows a schema that defines theInnerType complex type using a qualified attribute namespace. The important lines of theXML Schema have been highlighted in bold.

Listing 5-21. XML Schema That Defines an Attribute in a Namespace

<?xml version="1.0" encoding="UTF-8"?><schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.org/inner/" xmlns:tns="http://www.example.org/inner/"attributeFormDefault="qualified">

<complexType name="InnerType" mixed="false"><sequence>

<element name="quantity" type="int" /></sequence><attribute name="foo" type="string" />

</complexType></schema>

CHAPTER 5 ■ A CRASH COURSE IN WSDL92

7974CH05.qxd 3/12/07 12:34 PM Page 92

Page 118: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Listing 5-22 shows a portion of a WSDL that imports the schema object and uses it in anelement. Note that the attributeFormDefault in the <schema> section of the WSDL is set tounqualified.

Listing 5-22. A Snippet of a WSDL That Imports the XML Schema

<wsdl:definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"xmlns:tns="http://www.bea.com/inner/"xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="inner"xmlns:inner="http://www.example.org/inner/"targetNamespace="http://www.bea.com/inner/"><wsdl:types>

<xsd:schema attributeFormDefault="unqualified"targetNamespace="http://www.bea.com/inner/">

<xsd:import namespace="http://www.example.org/inner/" ➥

schemaLocation="inner.xsd" />

<xsd:element name="GetInner" type="inner:InnerType" /><xsd:element name="GetInnerResponse" type="inner:InnerType" />

</xsd:schema></wsdl:types>

In Listing 5-23 you can see a sample XML document that uses the WSDL from Listing 5-22.Even though the WSDL states that the attributeFormDefault is set to unqualified, it doesn’toverride the "qualified" declaration in the XML Schema file. Therefore, any reference to theattribute must be qualified by a namespace.

Listing 5-23. An Example XML Document Showing the Use of a Qualified Attribute

<inn1:GetInner inn:foo="string" xmlns:inn="http://www.example.org/inner/" ➥

xmlns:inn1="http://www.bea.com/inner/"><quantity>3</quantity>

</inn1:GetInner>

The elementFormDefault and attributeFormDefault attributes give you a lot of controlover when and where namespaces are used. Once again, we aren’t prepared to define any bestpractices around the use of the attributeFormDefault attribute. However, declaring all yourattributes to be qualified can certainly complicate your XML documents. This additional com-plexity then increases the complexity of the XML document transformations in your messageflows. As a result, we discourage the use of qualified attribute names unless you see a clearbenefit in your specific project or enterprise.

CHAPTER 5 ■ A CRASH COURSE IN WSDL 93

7974CH05.qxd 3/12/07 12:34 PM Page 93

Page 119: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

SummaryIn this chapter, we haven’t gone into detail with samples of document-centric, literal WSDLs,simply because that’s the only style used in this book. Instead, we focused on why this is thebest approach for creating modern, highly interoperable web services. We also examined thedetails of a WSDL file, and provided you with a number of best practices on how to create yourown WSDLs. The section on “Troubleshooting WSDLs and Schemas” should save you manyhours of frustration. Perhaps most importantly, we’ve also shown you how to take a WSDL andvisualize exactly how the various messages of that WSDL would appear in the form of XMLdocuments.

Now that you’ve completed this chapter, the WSDLs and XML Schemas that you’ll see inthe rest of the book should make perfect sense to you. The way is now cleared for you to gain areal expertise in AquaLogic Service Bus.

CHAPTER 5 ■ A CRASH COURSE IN WSDL94

7974CH05.qxd 3/12/07 12:34 PM Page 94

Page 120: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Message Flows

In this chapter, you’ll do a couple fun and interesting projects to help you get accustomed tocreating more advanced message flows. Before long, you’ll intuitively understand when to useeach type of message flow node and exactly how get the maximum benefit.

To begin, you’ll create two use-case scenarios. The first use case will return a product cat-alog to the caller. The contents of the product catalog will contain only products for which thecustomer is qualified to buy, based on the customer’s credit rating.

The second use case allows the customer to submit an order, filled with products. You’llbuild a submitOrder service that verifies that the products ordered don’t exceed the customer’scredit rating. If the value of the order does exceed the customer’s credit rating, you’ll return afault message. If the order is otherwise valid, you’ll then invoke the processOrder service. TheprocessOrder service is asynchronous in nature, because order processing and fulfillmentoften occur at human speeds instead of computer speeds.

■Best Practice Although you’ve generated your web service (and its WSDL) from Java code in the past,this is not a best practice. When dealing with web services, or even SOA, the contract (that is, the WSDL) isof highest importance. The code that implements the contract defined in the WSDL is incidental.

By defining the WSDL first, you can plan your architecture up front, without having to wait for the codeto be created. It allows your company to focus on what’s most important (the contract), and defer the details(the code) until implementation time.

Scenario 1: User Requests a Product CatalogIn the first scenario, the user wants to contact a service and get a customized product catalog.The service first gets the credit score for the customer, then builds a catalog of products thatare appropriate for the customer’s credit score. For this scenario, you need two new opera-tions. The first is getCreditRating(). This operation takes the customer’s first name and lastname and returns the credit score. Obviously, credit scores aren’t determined this simplisti-cally in the real world, but the implementation isn’t important here, so we’ll keep things assimple as possible.

The second operation you need to create for your business service is getProductCatalog().This operation takes a credit rating as the argument and returns a list of products that the cus-tomer can order. Both these service implementations are shown in Listing 6-1.

95

C H A P T E R 6

7974CH06.qxd 3/21/07 4:28 PM Page 95

Page 121: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

You can find this code in the MessageFlow project, which is included in the Source Code/Download area at http://www.apress.com. Compile this code and deploy it to your WebLogicServer by building the project in Workshop. Be sure to assign the MessageFlow project to theservice bus server that you created.

Alternatively, if you learn like we do, by doing the work, then follow along and we’ll walkyou through the process.

1. Create the MessageFlow project. In Workshop, create a new Web Service project (locatedin the Web Service folder of Workshop’s New Project wizard).

2. In the src folder of the project, create a package called com.alsb.messageflow.

3. Create a folder in the project and name the folder WSDL. In this folder, you can eithercopy in the MessageFlow.wsdl file from the sample MessageFlow project that accompa-nies this book, or you can undergo the painstaking process of creating the WSDL fromscratch. If you do opt to create the WSDL yourself (using Listing 6-1 as your guide), werecommend that you try and do most of the work using the WSDL editor that comeswith Workshop. It allows you to view the WSDL in a graphical format and a text format,depending on your needs.

Listing 6-1. The MessageFlow.wsdl for Your MessageFlow Project

<?xml version='1.0' encoding='UTF-8'?><definitions name="MessageFlowServiceDefinitions"

targetNamespace="http://www.alsb.com"xmlns="http://schemas.xmlsoap.org/wsdl/"xmlns:alsb="http://www.alsb.com"xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"><types>

<xs:schema attributeFormDefault="unqualified"elementFormDefault="qualified" targetNamespace="http://www.alsb.com"xmlns:alsb="http://www.alsb.com"xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"xmlns:xs="http://www.w3.org/2001/XMLSchema"><xs:complexType name="Product">

<xs:sequence><xs:element minOccurs="1" name="CreditNeeded"

nillable="true" type="xs:int" /><xs:element minOccurs="1" name="Name"

nillable="true" type="xs:string" /></xs:sequence>

</xs:complexType><xs:complexType name="LineItem">

<xs:sequence><xs:element minOccurs="1" name="Product"

type="alsb:Product" /><xs:element minOccurs="1" name="Quantity"

type="xs:int" /></xs:sequence>

CHAPTER 6 ■ MESSAGE FLOWS96

7974CH06.qxd 3/21/07 4:28 PM Page 96

Page 122: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

</xs:complexType><xs:complexType name="Order">

<xs:sequence><xs:element minOccurs="1" name="FirstName"

nillable="true" type="xs:string" /><xs:element minOccurs="1" name="LastName"

nillable="true" type="xs:string" /><xs:element maxOccurs="unbounded" minOccurs="0"

name="LineItem" type="alsb:LineItem" /></xs:sequence>

</xs:complexType><xs:complexType name="ProductList">

<xs:sequence><xs:element maxOccurs="unbounded" minOccurs="0"

name="Product" type="alsb:Product" /></xs:sequence>

</xs:complexType><!-- TIP: Start your element names off lower case. This willmore closely match the Java naming conventions when you generatethe code -->

<xs:complexType name="processPreferredOrder"><xs:sequence>

<xs:element name="order" type="alsb:Order" /></xs:sequence>

</xs:complexType><xs:complexType name="getCreditRating">

<xs:sequence><xs:element name="firstName" type="xs:string" /><xs:element name="lastName" type="xs:string" />

</xs:sequence></xs:complexType><xs:complexType name="getCreditRatingResponse">

<xs:sequence><xs:element name="return" type="xs:int" />

</xs:sequence></xs:complexType><xs:complexType name="getProductCatalog">

<xs:sequence><xs:element name="creditRating" type="xs:int" />

</xs:sequence></xs:complexType><xs:complexType name="getProductCatalogResponse">

<xs:sequence><xs:element name="productList"

type="alsb:ProductList" /></xs:sequence>

</xs:complexType>

CHAPTER 6 ■ MESSAGE FLOWS 97

7974CH06.qxd 3/21/07 4:28 PM Page 97

Page 123: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

<xs:complexType name="processOrder"><xs:sequence>

<xs:element name="order" type="alsb:Order" /></xs:sequence>

</xs:complexType></xs:schema>

</types><message name="processPreferredOrder">

<part type="alsb:processPreferredOrder" name="processPreferredOrder" /></message><message name="getCreditRating">

<part type="alsb:getCreditRating" name="getCreditRating" /></message><message name="getCreditRatingResponse">

<part type="alsb:getCreditRatingResponse"name="getCreditRatingResponse" />

</message><message name="getProductCatalog">

<part type="alsb:getProductCatalog" name="getProductCatalog" /></message><message name="getProductCatalogResponse">

<part type="alsb:getProductCatalogResponse"name="parameters" />

</message><message name="processOrder">

<part type="alsb:processOrder" name="processOrder" /></message><portType name="MessageFlowPort">

<operation name="processPreferredOrder"parameterOrder="processPreferredOrder"><input message="alsb:processPreferredOrder" />

</operation><operation name="getCreditRating" parameterOrder="getCreditRating">

<input message="alsb:getCreditRating" /><output message="alsb:getCreditRatingResponse" />

</operation><operation name="getProductCatalog"

parameterOrder="getProductCatalog"><input message="alsb:getProductCatalog" /><output message="alsb:getProductCatalogResponse" />

</operation><operation name="processOrder" parameterOrder="processOrder">

<input message="alsb:processOrder" /></operation>

</portType>

CHAPTER 6 ■ MESSAGE FLOWS98

7974CH06.qxd 3/21/07 4:28 PM Page 98

Page 124: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

<binding name="MessageFlowServiceSoapBinding"type="alsb:MessageFlowPort"><soap:binding style="document"

transport="http://schemas.xmlsoap.org/soap/http" /><operation name="processPreferredOrder">

<soap:operation soapAction="" style="document" /><input>

<soap:body parts="parameters" use="literal" /></input>

</operation><operation name="getCreditRating">

<soap:operation soapAction="" style="document" /><input>

<soap:body parts="parameters" use="literal" /></input><output>

<soap:body parts="parameters" use="literal" /></output>

</operation><operation name="getProductCatalog">

<soap:operation soapAction="" style="document" /><input>

<soap:body parts="parameters" use="literal" /></input><output>

<soap:body parts="parameters" use="literal" /></output>

</operation><operation name="processOrder">

<soap:operation soapAction="" style="document" /><input>

<soap:body parts="parameters" use="literal" /></input>

</operation></binding><service name="MessageFlowService">

<port binding="alsb:MessageFlowServiceSoapBinding"name="MessageFlowSoapPort"><soap:address

location="http://localhost:7001/messageflow/MessageFlowService" /></port>

</service></definitions>

CHAPTER 6 ■ MESSAGE FLOWS 99

7974CH06.qxd 3/21/07 4:28 PM Page 99

Page 125: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

4. Right-click the MessageFlow.wsdl file in the WSDL folder and select WebServices ➤Generate Web Service from the pop-up menu. The “Source folder” field should defaultto MessageFlow/src. For the Package field, enter (or browse) to the value com.alsb.messageflow. At the end of the wizard, a file named MessageFlowPortImpl.java isgenerated in the com.alsb.messageflow package in the src folder.

Because your WSDL is document oriented, your generated source code is also documentoriented. Instead of passing multiple arguments into each method, only a single argumentappears in each method signature. Listing 6-2 illustrates what we mean by “document-oriented source code.”

Listing 6-2. The Complete Version of the MessageFlowPortImpl Class File

package com.alsb.messageflow;

import java.util.Vector;import javax.jws.WebService;import com.alsb.Product;import weblogic.jws.*;

/*** MessageFlowPortImpl class implements web service endpoint interface* MessageFlowPort*/

@WebService(serviceName = "MessageFlowService", targetNamespace = "http://www.alsb.com", endpointInterface = "com.alsb.messageflow.MessageFlowPort")

@WLHttpTransport(contextPath = "messageflow", serviceUri = "MessageFlowService", portName = "MessageFlowSoapPort")

public class MessageFlowPortImpl implements MessageFlowPort {private static Product[] productCatalog = { new Product(), new Product(),

new Product(), new Product() };

public MessageFlowPortImpl() {productCatalog[0].setName("Television");productCatalog[0].setCreditNeeded(610);productCatalog[1].setName("Microwave");productCatalog[1].setCreditNeeded(500);productCatalog[2].setName("Automobile");productCatalog[2].setCreditNeeded(710);productCatalog[3].setName("Paper Hat");productCatalog[3].setCreditNeeded(440);

}

CHAPTER 6 ■ MESSAGE FLOWS100

7974CH06.qxd 3/21/07 4:28 PM Page 100

Page 126: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

public void processPreferredOrder(com.alsb.ProcessPreferredOrder processPreferredOrder) {

com.alsb.Order order = processPreferredOrder.getOrder();System.out.println("Received a PREFERRED order from "

+ order.getFirstName() + " " + order.getLastName()+ " for product "+ order.getLineItem()[0].getProduct().getName()+ " in quantity of " + order.getLineItem()[0].getQuantity());

return;}

public com.alsb.GetCreditRatingResponse getCreditRating(com.alsb.GetCreditRating getCreditRating) {

String lastName = getCreditRating.getLastName();String firstName = getCreditRating.getFirstName();com.alsb.GetCreditRatingResponse response = new ➥

com.alsb.GetCreditRatingResponse();

int rating;if (lastName.compareToIgnoreCase("X") > 0) {

// If the last name starts with an X or later in the alphabet// the person has a bad credit rating.rating = 200;

} else if (lastName.compareToIgnoreCase("S") > 0) {// Names starting with S or later have a poor credit ratingrating = 600;

} else {// Everyone else has a great credit ratingrating = 750;

}System.out.println("Business: The credit rating for " + firstName + " "

+ lastName + " is " + rating);response.setReturn(rating);return response;

}

public com.alsb.GetProductCatalogResponse getProductCatalog(com.alsb.GetProductCatalog getProductCatalog) {

// Iterate over the product catalog and return the products that the// customer can purchasecom.alsb.ProductList productList = new com.alsb.ProductList();Vector<Product> customerCatalog = new Vector<Product>();int creditRating = getProductCatalog.getCreditRating();com.alsb.GetProductCatalogResponse response = new ➥

com.alsb.GetProductCatalogResponse();

CHAPTER 6 ■ MESSAGE FLOWS 101

7974CH06.qxd 3/21/07 4:28 PM Page 101

Page 127: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

for (int x = 0; x < productCatalog.length; x++) {if (productCatalog[x].getCreditNeeded() <= creditRating) {

// Add this product to the list because the customer can buy itcustomerCatalog.add(productCatalog[x]);

}}

Product[] customerProducts = new Product[customerCatalog.size()];customerCatalog.copyInto(customerProducts);productList.setProduct(customerProducts);response.setProductList(productList);return response;

}

public void processOrder(com.alsb.ProcessOrder processOrder) {com.alsb.Order order = processOrder.getOrder();System.out.println("Received a regular order from "

+ order.getFirstName() + " " + order.getLastName()+ " for product "+ order.getLineItem()[0].getProduct().getName()+ " in quantity of " + order.getLineItem()[0].getQuantity());

return;}

}

Of course, the generated source file won’t contain any method implementations. Youneed to add those yourself. Compile and deploy the Message Flow web service to WLS. You’vesuccessfully created your business service.

Now we get to the heart of the matter. You need to create a new proxy service in ALSB thatuses the two business services you just created. Your new service will aggregate the two busi-ness functions, hiding them from the user. This pattern of hiding underlying complexity iscalled the Façade pattern. In SOA, it’s more commonly known as service mediation: using oneservice to hide the complexity and interrelationships of lower-level services.

Let’s get started creating our proxy service. First, create a new project in ALSB. Name thenew project MessageFlow. Next, create a new folder in the project called WSDL.

■Best Practice This exercise demonstrates the best practice for separating the data types used by aWSDL into an XML Schema document. This enhances the ability to reuse fundamental data types. If youwere to define these types (such as the Order type) within the WSDL itself, you’d be forced to redefinethese types if you ever needed to use them in a different WSDL. This is akin to copying and pasting code,and should be shunned whenever possible.

CHAPTER 6 ■ MESSAGE FLOWS102

7974CH06.qxd 3/21/07 4:28 PM Page 102

Page 128: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Now move to the WSDL folder in the ALSB console for your current project. In this folder,you need to create a new WSDL resource for the business service that you’ll use. The easiestway to get the WSDL contents is directly from its URL (assuming the WSDL is publishedonline). In the Create Resource combo box, in the Bulk category, select Resources from URL.Then follow the Resource Creation wizard, supplying the URL for the WSDL and a name forthe WSDL resource you’re creating. The URL for the Message Flow web service is http://localhost:7001/MessageFlow/MessageFlowService?WSDL. Notice that when you import theWSDL, ASLB detects the import of the order.xsd schema. ALSB will generate a new file namefor the order.xsd file when it imports it. You can rename it later, using the service bus consoleif you like.

■Note Be aware that when you import WSDLs and other resources that ALSB makes a local copy of thatfile. It doesn’t maintain a live link to the file you import. As a result, if you change the business service WSDL,you’ll need to re-import the WSDL into ALSB.

However, there might not always be a WSDL published online. In those situations, youneed to copy and paste a WSDL directly into the console. Begin by selecting WSDL from theCreate Resource combo box. Follow the steps of the wizard to paste in your WSDL.

Navigate to the root directory of your MessageFlow project. Create a business service calledMessageFlow Business. Set its type to WSDL Web Service and browse to select the Message FlowWSDL. Click the Next button and examine the End Point URI of the service (see Figure 6-1). Ifyou see that the URI includes a specific IP address, you might wish to change the URI to usethe alias localhost instead of the physical IP address. This is especially important if your com-puter is occasionally connected to a Virtual Private Network (VPN), because that mightchange your physical IP address and make your web service unavailable.

Figure 6-1. It’s best to replace literal IP addresses with DNS names or “localhost” when workingwith the exercises in this book.

CHAPTER 6 ■ MESSAGE FLOWS 103

7974CH06.qxd 3/21/07 4:28 PM Page 103

Page 129: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Now click the Last button to accept the default values for your business service. Click theSave button to save the definition of the business service. Activate your changes by clickingthe Activate button in the Change Center. Now let’s test our business service to ensure that it’sworking as intended.

Click the test console icon, next to the Message Flow Business resource in the service busconsole (the little bug icon, under the Actions heading). The test console should default to thegetCreditRating operation. Change the SOAP body so that the firstName and lastName fieldsare something other than “string.” Only the last name is important for this operation. Settingthe lastName to a value of Smith should return a credit rating of 600. Check the source code forthe web service to see the credit rating logic to confirm that your results are correct as you trydifferent names.

Now we get to the new and fun part of the exercise. You’ll create a proxy service that willtake a customer name and return a list of products that the customer can purchase. Previ-ously, your proxy services simply published the WSDL of the business service it represented(à la Hello World in Chapter 3). However, in this case you have no such luxury. You need a newWSDL that represents your aggregate service.

Now, we find that creating a WSDL by hand is about as much fun as hand-coding EJBdeployment descriptors (that is to say, no fun at all). Fortunately for us, we can quickly puta WSDL together based on the two operations we’re aggregating (getCreditRating andgetProductCatalog). Fortunately for you, you can just use the WSDL that you created byhand in the WSDL/ folder of the MessageFlow project. It’s named Message Flow Proxy WSDL.

Your next step: in the ALSB console, navigate to the WSDL folder in your ALSB project.Create a WSDL resource here named Message Flow Proxy WSDL. Because this WSDL isn’t pub-lished by any web servers yet, you need to copy the text from the WSDL file in the Eclipseproject and paste it into the large WSDL textarea control in the service bus console. Click theSave button.

Next, in the service bus console, navigate to the root directory of your project. In thisfolder, you’ll create a new proxy service resource named getProducts, and you’ll base the serv-ice type on the Message Flow Proxy WSDL resource that you just created. Click the Next buttonand specify the Endpoint URI as /esb/getProducts. Click the Last button and then the Savebutton to save the new proxy service.

So far, so good. You have created a proxy service that uses the WSDL you need for theservice. Your next step is to “hook up” the proxy service so that it calls the supporting businessservices. Click the Edit Message Flow icon ( ).

Your current message flow for your proxy service contains only a Start node. You want touse a Pipeline Pair for this message flow. The reason we chose to use a Pipeline Pair is that itnaturally breaks its work processing down into a series of stages. You’ll use a stage for the callto the getCreditRating() business service and a second stage for the getProductCatalog()business service.

Now you could do all this work in a single Route node, but that would be a poor designdecision, similar in nature to taking multiple methods in you Java code and making them justone big method. You can do it, but it’s not very modular. Modularity of design is important,even within a message flow. Later on, when we take a closer look at fault handling, you’ll seehow your use of stages in a Pipeline Pair helps to make fault handling much simpler and moreprecise.

CHAPTER 6 ■ MESSAGE FLOWS104

7974CH06.qxd 3/21/07 4:28 PM Page 104

Page 130: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

To add a Pipeline Pair to your message flow, left-click the Ordering Proxy Start node andselect Add Pipeline Pair from the pop-up menu. When the Pipeline Pair is added, your mes-sage flow should look like the one in Figure 6-2.

Figure 6-2. An empty Pipeline Pair

Let’s add our first stage to the request pipeline (the icon on the left with the green arrowpointing down). Left-click the request pipeline and select Add Stage. Left-click the newly cre-ated stage and select Edit ➤ Name and Description from the pop-up menu. Set the name ofthe node to assign variables and click the Save button.

■Tip Give your stages meaningful names. It will help when you need to make changes in the future!

Your next step is to edit the stage to the request pipeline to retrieve the firstName andlastName parameters that were passed into your proxy service and store them into local vari-ables. You do this because later on, when you use the service callout actions, those actionscannot use XPath expressions; instead, the service callout action expects to see local vari-ables only.

Left-click the assign variables stage and select Edit ➤ Stage. You need to add two Assignactions to this stage. You’re assigning the values of the first name and last name of the incom-ing message to your local variables firstName and lastName. It’s easy to enter the wrong text ora typo here, so we strongly recommend that you make good use of the Variable Structuresbrowser to ensure that only valid data is entered. When editing your XQuery, click the VariableStructures heading at the bottom of the left navigation pane, as shown in Figure 6-3. Selectbody in the combo box, because the data you’re looking for is carried in the body of the SOAPmessage. Then drill down through the contents of the body variable and click the firstNameelement. You’ll see the XPath for that element in the Property Inspector, near the bottom ofthe page. To use the value that’s displayed in the Property Inspector, just click once inside thetextarea control and then click the Copy Property link (to the right of the Property Inspector).Because you only need the actual text from the firstName node, you append the /text()command to the end of the XPath.

CHAPTER 6 ■ MESSAGE FLOWS 105

7974CH06.qxd 3/21/07 4:28 PM Page 105

Page 131: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 6-3. Using the Variable Structures browser

Using this technique will save you hours of headaches trying to figure out why yourservice isn’t working as expected. Use this technique to assign the firstName and lastNamevariables. Be sure to append the /text() method to the Assign action for the lastName variablealso. Ensure that your assign variables stage matches the information that appears inTable 6-1. Click the Save button.

Table 6-1. The Expressions to Use in the Assign Variables Stage

Expression Local Variable Name

$body/alsb:CustomerName/alsb:firstName/text() firstName

$body/alsb:CustomerName/alsb:lastName/text() lastName

Left-click the assign variables stage and select Add ➤ Stage from the pop-up menu. Setthe name of the node to get credit rating and click the Save button. Now it’s time to hook upthis stage to make the call to the getCreditRating() operation of the business service. Left-click the get credit rating stage and select Edit ➤ Stage from the pop-up menu. This bringsyou to an empty Action page. Left-click the “Add an action” link and select Message Processing➤ Assign. You need to create the SOAP Body structure that you’ll pass into the business serv-ice. Assign the expression from Listing 6-3 to a variable named soapBodyRequest.

CHAPTER 6 ■ MESSAGE FLOWS106

7974CH06.qxd 3/21/07 4:28 PM Page 106

Page 132: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Listing 6-3. Creating the SOAP Body for the getCreditRating Request

<soap:Body xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><alsb:getCreditRating xmlns:alsb="http://www.alsb.com">

<alsb:firstName>{$firstName}</alsb:firstName><alsb:lastName>{$lastName}</alsb:lastName>

</alsb:getCreditRating></soap:Body>

Now you add the service callout action. Left-click the existing Assign action and selectCommunication ➤ Service Callout from the pop-up menu. The service callout action allowsyou to make a call to an existing service. Left-click the Service link, select the Message FlowBusiness service, and click the Submit button.

Next, select the getCreditRating() operation from the combo box. Select the ConfigureSoap Body radio button and enter the value soapRequestBody for the SOAP Request Body field.Similarly, enter the value of soapResponseBody into the SOAP Response Body field. Your Serviceaction should look like Figure 6-4.

Figure 6-4. Calling the getCreditRating service

After the Service Callout action, you need to create an Assign action that retrieves thecustomer’s credit rating. In the Assign action, assign the expression $soapResponseBody/getCreditRatingResponse/alsb:return/text() to the variable creditRating.

Click the Save button to save your changes to the stage.Now, as you discovered in Chapter 4, a Pipeline Pair can have at most one node following

it. What we didn’t point out is that if the Pipeline Pair doesn’t have a node following it, thenALSB will create an “echo” response for you. This response will just echo the SOAP requestback to the caller, which is definitely not what you want here. For this reason, you must adda Route node after the Pipeline Pair. It’s in the Route node that you’ll make your call to thegetProductCatalog business service.

CHAPTER 6 ■ MESSAGE FLOWS 107

7974CH06.qxd 3/21/07 4:28 PM Page 107

Page 133: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

To add a Route node, left-click the Pipeline Pair node (near the top of the node, not downin the area that shows the stages) and select Add ➤ Add Route. Rename the Route node to getproduct catalog. Save the new name and edit the Route node itself. Click the Add Action linkand select Communication ➤ Routing. This will create the Route action. Click the Service linkof the Route action and select the Message Flow Business service. Select getProductCatalogfrom the combo box.

Now things get a little murky here, so we’ll take a moment to shed some light onto what ishappening. By default, all a Route node does is route the request message to a service. In thiscase, the body of the request message is what the node will route to the getProductCatalogservice. However, the body of the original request message to your proxy service isn’t whatthe service is expecting to see, as shown in Figure 6-5.

Figure 6-5. The request $body of the proxy service

You know that the getProductCatalog service couldn’t care less about receiving thefirstName and lastName arguments. It demands that you send it the customer’s creditrating. As a result, you must transform the request to match the format expected by thegetProductCatalog service. To perform this transformation, you’ll use the Replace action. Youneed to replace the contents of the getProductCatalog element (that is, the firstName andlastName nodes) with the credit rating.

You need to transform the contents of the request message from this:

<alsb:getProducts xmlns:alsb="http://www.alsb.com"><alsb:firstName>John</alsb:firstName><alsb:lastName>Doe</alsb:lastName>

</alsb:getProducts>

to this:

<alsb:getProductCatalog xmlns:alsb="http://www.alsb.com"><alsb:creditRating>600</alsb:creditRating>

</alsb:getProductCatalog>

Click the <XPath> link. Enter the XPath expression ./*. This XPath notation means “allchildren relative to the current node.” You need to replace everything in the SOAP Body ele-ment, represented by the $body variable. Click the Expression link to enter the expression thatwill replace the contents of the $body variable. The expression you’ll use is in Listing 6-4. Asyou can see, you manually construct the XML structure that you want to send to the businessservice. Most of this is static XML. The curly braces are escape characters, used to denote thesection in which dynamic XQuery can be found.

CHAPTER 6 ■ MESSAGE FLOWS108

7974CH06.qxd 3/21/07 4:28 PM Page 108

Page 134: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Listing 6-4. The Expression for the Replace Action in the Route Node

<alsb:getProductCatalog xmlns:alsb="http://www.alsb.com"><alsb:creditRating>{$creditRating}</alsb:creditRating>

</alsb:getProductCatalog>

Save your XPath expression and fill out the rest of the Route node so that it matchesFigure 6-6.

Figure 6-6. Defining the stage for retrieving the product list

Because the return message format of the getProductCatalog service matches exactlythe format of your proxy service, you allow the return message from the Route node to flowthrough the Pipeline Pair node without any transformation. Or, to put it more plainly, you’redone with this message flow; no more work is necessary.

Your message flow should now look like Figure 6-7.That completes the creation of the proxy service. Save all your changes and click the

Activate button in the Change Center to activate all your work.Let’s test our handiwork to ensure that everything is running as expected. Using the ALSB

console, navigate to the proxy service in the Message Flow project and click the testing icon( ). Enter the name Bob Aaron and click the Execute button. You should see the name youentered in the request document section, and you should see a list of four products in theresponse document section of the page. Try it again with the name Tom Zanka, and youshould see only one product show up in the response document. The getCreditRating servicereturns the credit rating based on the last name of the customer (our apologies to those of youwith last names in the second half of the alphabet), then the getProductCatalog business serv-ice makes a decision about which products the customer can order.

What if you wanted to make a decision in your proxy service instead of in a business serv-ice? For example, when the customer orders from you, you want to send a confirmation of theorder to the customer. If the customer has a high credit rating, you’d like to send an additional“up-sell” e-mail, encouraging the customer to purchase additional products from your com-pany. You’d also like to place this decision logic in your proxy service so that you might be ableto change it quickly if necessary. This brings us to our second scenario.

CHAPTER 6 ■ MESSAGE FLOWS 109

7974CH06.qxd 3/21/07 4:28 PM Page 109

Page 135: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 6-7. Message flow after stage 2

Scenario 2: User Orders a ProductIn this scenario, the customer submits an order to your submitOrder proxy service. The proxyservice invokes the getCreditRating business service. It then checks the credit rating of thecustomer, and if the customer’s credit rating is high enough, it will route the order to theprocessPreferredOrder business service. Otherwise, the order will be routed to theprocessOrder business service. This routing decision is performed in a Branch node.

The bulk of the infrastructure that you need for this exercise has already been created inScenario 1. Let’s begin by creating the submitOrder proxy service in the proxy directory of yourMessage Flow project. You’ll base this proxy on the WSDL port of the Message Flow ProxyWSDL.

■Tip Place business decisions into proxy services instead of compiled code. Doing so allows you to changebusiness logic without recompiling any code. This increases your IT and business agility.

Edit the message flow of your submitOrder proxy service. You first need to add a PipelinePair to the Start node. Like our previous scenario, you need to have two stages in this PipelinePair. However, we’re going to share a time-saving trick here, so don’t race off and create bothstages yet. Simply create the first stage and name it get customer name. Edit this stage, createtwo Assign actions, and configure them according to Table 6-2. If you use the Variable Struc-tures browser, be sure to browse the body of the submitOrder operation, not the getProductsoperation.

CHAPTER 6 ■ MESSAGE FLOWS110

7974CH06.qxd 3/21/07 4:28 PM Page 110

Page 136: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Table 6-2. Retrieving the Customer’s Name from the Order

Expression Variable Name

$body/alsb:Order/FirstName/text() firstName

$body/alsb:Order/LastName/text() lastName

Now here’s the time-saving trick. You need a service callout to the getCreditRating opera-tion of the business service. If you were to create this stage by hand, it would look exactly likethe same stage you defined earlier in Scenario 1 of this chapter. Fortunately, ALSB allows youto copy and paste stages, and that’s what you’re going to do.

Navigate to the message flow of the getProducts proxy service. Left-click the get creditrating stage, and the pop-up menu gives you the option to copy the stage. Copy the stage andthen navigate back to the message flow of the submitOrder proxy service. Left-click the getcustomer name stage and select Paste from the pop-up menu. Voilà! Just like copy and paste ina document, this process can help to speed up your editing process and reduce typos at thesame time.

Next, you add a conditional branch node after the Pipeline Pair node. Name this newnode decide order processing type. You go through two phases when editing a Branch node.The first phase involves creating the various branches, as shown in Figure 6-8. The secondphase involves adding stages to each branch. Your Branch node is simple: customers with acredit rating greater than 700 are preferred customers, and their orders will be processed byyour preferred order processor. Everyone else is a regular customer who will have their ordersprocessed by the normal order processor.

You need to create a single, additional branch in your Branch node (there’s always adefault branch). Click the Branch node icon and select Edit Branch from the pop-up menu.Edit the Branch Definitions window so that it looks like Figure 6-8.

Figure 6-8. Branch Definitions window

Click the Save button after you’ve added your branch. Take a look at the Map of MessageFlow portion of the console on the left-hand side of the page. It shows you the entire messageflow, including the Branch node and the branches that you just created. You can use thismessage flow map to navigate quickly through your message flow. You’ll use this control tonavigate directly to the preferred customer branch of your Branch node. Click the “preferredcustomer” link in the Map of Message Flow control (shown in Figure 6-9) now.

CHAPTER 6 ■ MESSAGE FLOWS 111

7974CH06.qxd 3/21/07 4:28 PM Page 111

Page 137: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 6-9. Map of Message Flow control

You’re now looking at the page that allows you to define the message flow for the pre-ferred customer branch condition. Notice that the start icon ( ) at the top of the messageflow is different from the other Start node icon you’re used to seeing. This is a visual cue thatyou’re editing a Branch node and not a full message flow.

Click the Start node, and add a Route node, and name it route to preferred orderprocessing. Edit the Route node, selecting Message Flow Business as the service andselecting processPreferredOrder as the operation. Now you need to do some additionalwork here, because the submitOrder proxy service takes one message format while theprocessPreferredOrder and processOrder operations on the business service each require adifferent format. You’ll find this to be a common occurrence when working with XML docu-ments and web services. This can be confusing unless you take your time and understand thestructure of each document. There’s a simple way to know unambiguously which documentformat is used and where: the test console feature of ALSB, which is an invaluable tool. Openthe test console for the submitOrder service and then select the submitOrder operation fromthe combo box. You’ll see a sample payload that should look exactly like that in Listing 6-5.

Listing 6-5. The Document Format of the submitOrder Proxy Service

<alsb:Order xmlns:alsb="http://www.alsb.com"><FirstName>string</FirstName><LastName>string</LastName><!--Zero or more repetitions:--><LineItem>

<Product><CreditNeeded>3</CreditNeeded><Name>string</Name>

</Product><Quantity>3</Quantity>

</LineItem></alsb:Order>

CHAPTER 6 ■ MESSAGE FLOWS112

7974CH06.qxd 3/21/07 4:28 PM Page 112

Page 138: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Listing 6-5 tells you what the $body variable will contain when the submitOrderoperation is invoked. Your next step is to figure out what the exact document format of theprocessPreferredOrder business service operation is. You accomplish this task also by usingthe test console. Listing 6-6 shows the document format for the processPreferredOrderoperation.

Listing 6-6. The Document Structure for the processPreferredOrder Business Service Operation

<processPreferredOrder xmlns="http://www.alsb.com"><alsb:order xmlns:alsb="http://www.alsb.com">

<FirstName>string</FirstName><LastName>string</LastName><!--Zero or more repetitions:--><LineItem>

<Product><CreditNeeded>3</CreditNeeded><Name>string</Name>

</Product><Quantity>3</Quantity>

</LineItem></alsb:order>

</processPreferredOrder>

Within the Request actions of the Route node, you need to change the value of $body fromits original structure defined in Listing 6-5 to the processPreferredOrder structure in Listing 6-6.Now that you know exactly what you have to do, the work itself becomes almost trivial:

1. You need to change the <alsb:Order> tag to become an <alsb:order> tag.

2. You need to wrap the new <alsb:order> tag with a <processPreferredOrder> tag.

Other than that, the structures are identical. Here are the logical steps you’ll take to trans-form the message:

1. Copy the contents of the $body variable into a local variable called order. You do thisby using the Assign action to assign the expression $body/alsb:Order to the variableorder.

2. Use a Rename action to rename the value of the XPath expression /alsb:Order in theorder variable to use the local name of order and the namespace of http://www.alsb.com.

3. You use a Replace action to replace the XPath expression ./* in the variable body withthe expression shown in Listing 6-7. Be sure to select the “Replace entire node” radiobutton.

CHAPTER 6 ■ MESSAGE FLOWS 113

7974CH06.qxd 3/21/07 4:28 PM Page 113

Page 139: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Listing 6-7. The Expression to Wrap the $order Variable

<processPreferredOrder xmlns="http://www.alsb.com">{$order}</processPreferredOrder>

That completes the preferred order branch. The Route node should now look like Figure 6-10. Next, you need to do the same thing in the default branch, but change theXML tag shown in Listing 6-7 to <processOrder xmlns="http://www.alsb.com">.

Figure 6-10. The Route node for the preferred order branch

That’s it for this message flow. Save all your work and activate your changes. It’s time totest the changes. Navigate to the submitOrder proxy service and click the test console button totest this service. Click the submitOrder link at the top of the test console. The test console pageshould look like Figure 6-11.

CHAPTER 6 ■ MESSAGE FLOWS114

7974CH06.qxd 3/21/07 4:28 PM Page 114

Page 140: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 6-11. Test console for the submitOrder proxy service

Notice the field where you can enter your order. You know from your schema that anOrder is a complex object, containing the customer’s first name, last name, and an array of lineitems. The test console window knows the format of the document and provides you with asimple version that contains sample data. You can leave the sample data in place, or replace itwith more specific data, as needed.

CHAPTER 6 ■ MESSAGE FLOWS 115

7974CH06.qxd 3/21/07 4:28 PM Page 115

Page 141: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

To ensure that the service is working as intended, set the last name to “Donaldson” to geta customer with a high credit score and click the Execute button. Because submitOrder is aone-way call, there’s no meaningful response from the web service. However, the test consolewill show you the invocation trace of the web service. Scroll down to the bottom of the testconsole and ensure that the route to preferred order processing node was executed, asshown in Figure 6-12.

Figure 6-12. Invocation trace for preferred orders

Now click the Back button and try the test again, but this time change the name to “Zim-merman.” The invocation trace for that call should be routed to the “normal order processing”node via the default branch. You can also examine the console output of the ALSB server tosee the debugging messages from the processOrder and processPreferredOrder Java methodsto confirm that everything is working correctly.

SummaryThat’s it for the three processing node types. They might appear a little confusing at first, butnow that you’ve used them, their purposes should be much more evident. Route nodes areused to transfer the processing to the primary web services. Pipeline Pairs are used to provideyou, the service composer, with an additional level of detail and control over the service proxy,especially in the area of error handling. Last, you use the Branch nodes to make runtime deci-sions within your proxy services. You can assemble these three node types to meet the needsof any proxy service.

CHAPTER 6 ■ MESSAGE FLOWS116

7974CH06.qxd 3/21/07 4:28 PM Page 116

Page 142: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Advanced Messaging Topics

Messages are at the heart of an ESB, and ALSB is no exception. Therefore, it’s worth yourwhile to ensure you have a solid understanding of the principles of messages and invocationmodels. Much of this chapter is more specific to WLS than it is to ALSB. It’s important to knowboth sides of the “services equation,” and creating WebLogic web services will figure promi-nently in your ALSB work.

Synchronous InvocationSynchronous messaging is by far the most common messaging model in use today. A synchro-nous call is one where the caller waits for the called operation to complete before the callercan take another action. Synchronous calls are often the norm because they’re easier tounderstand and easier to perform (from a developer’s point of view).

At times, you might hear people disparage synchronous calls, mistakenly believing thatasynchronous calls are somehow “better.” Such zealotry should be avoided. Synchronous callsare just another tool in your tool chest and are often the appropriate choice. For example, ifa customer logs onto your web site and requests to see his billing details for the last month,you would most likely implement this function synchronously; your customer is waiting for aresponse, and you don’t want to keep the customer waiting for an indeterminate amount oftime.

You’ve already used synchronous messaging in the HelloWorld project in Chapter 3. You’llimplement another synchronous service here to help illustrate the benefit of using asynchro-nous services (which we’ll cover shortly). Your synchronous service will accept an order forprocessing. Order processing (also known as fulfillment) often takes an extended amount oftime. For our purposes, the process will take 30 seconds to complete, though real-worldimplementation often requires days to complete, depending on the nature of the productsand services ordered.

As in the previous chapter, we begin our service definition with a WSDL file and thengenerate code from this service contract. You can find the source code for this chapter inthe AdvancedMessaging project in Eclipse (download the source code from the SourceCode/Download area at http://www.apress.com). The business service (see Listing 7-1) isquite simple, in order to illustrate clearly what’s important to us in this chapter: the mechanicsof synchronous and asynchronous messages, and how to best employ them using ALSB.

117

C H A P T E R 7

7974CH07.qxd 3/21/07 4:44 PM Page 117

Page 143: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Listing 7-1. A Synchronous Business Service

package com.alsb.advmessage.syncbusiness;import javax.jws.WebService;import weblogic.jws.*;

/*** SyncBusinessImpl class implements web service endpoint interface SyncBusiness */

@WebService(serviceName="SyncBusiness",targetNamespace="http://www.alsb.com/SyncBusiness/",endpointInterface="com.alsb.advmessage.syncbusiness.SyncBusiness")

@WLHttpTransport(contextPath="advmessage",serviceUri="SyncBusiness",portName="SyncBusinessSOAP")

public class SyncBusinessImpl implements SyncBusiness {

private static long thirtySeconds = 30000;private static long timeDelay = thirtySeconds;private static int orderID = 100;

public SyncBusinessImpl() {}

public com.alsb.order.Order submitOrder(com.alsb.order.Order submitOrder) {// Assign an order ID to the ordersubmitOrder.setId(orderID++);System.out.println("Starting to process the SYNC order id "

+ submitOrder.getId());com.alsb.order.Order result = new com.alsb.order.Order();result.setFirstName(submitOrder.getFirstName());result.setId(submitOrder.getId());result.setLastName(submitOrder.getLastName());result.setLineItem(submitOrder.getLineItem());

if (result.getId() % 2 == 0) {// Even numbered order succeedresult.setOrderStatus(com.alsb.order.OrderStatus.completed);

} else {// Odd numbered orders failresult.setOrderStatus(com.alsb.order.OrderStatus.error);

}

try {Thread.sleep(timeDelay);

} catch (InterruptedException ex) {ex.printStackTrace();

} finally {

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS118

7974CH07.qxd 3/21/07 4:44 PM Page 118

Page 144: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

System.out.println("Completed processing the SYNC order id "+ submitOrder.getId());

}return result;

}}

If you examine the business service source code, you’ll see where we put in aThread.sleep(timeDelay) call to force the call to take 30 seconds to complete. This is to simu-late a long-running process. Certainly, asking your user to wait for 30 seconds or more isunreasonable by today’s standards. Such a length of time should make you either think of away to optimize this process so that it runs faster, or to implement the process asynchro-nously. In the next section, you’ll see how you can take this synchronous process and wrap itin an asynchronous wrapper.

Asynchronous InvocationA strong component of all loosely coupled systems is asynchrony: the ability for a caller to starta process (work) without having to wait for that process to complete before the caller moveson to its next task. For example, a web site may gather up the details of an order for a cus-tomer. When the customer is through shopping, he or she clicks the Submit Order button andthe web site then submits the order to the back-end order processing system for fulfillment.The order fulfillment process might take days to complete. It isn’t reasonable to ask the clientto wait for that order to be fully processed before the client can do anything else. You don’twant to tie up the execution threads of your web server waiting for back-end systems to com-plete long-running processes.

In fact, such a situation demands asynchronous processing. The client just wants to sub-mit the order and get on with his life. The client wants to tell the back-end system to “do thisunit of work and don’t bother me again.” That’s an asynchronous call. In missile terminology,this is referred to as “fire and forget.” Lock the missile onto the target, click the fire button, andthe missile does the rest. You can think of asynchronous calls as “fire and forget” technology.

However, there are some subtleties here that you must think about when you begin todesign asynchronous services. First, a web service may be asynchronous; second, a proxyservice in the service bus may be asynchronous. Furthermore, not all asynchronous servicesare “fire and forget.” A better analogy for this second type of asynchronous service would be tothink of asking your teenage son to mow the lawn, and then to let you know when he has com-pleted the mowing (usually so you can ask him to do the next chore). These are known asAsynchronous Request-Response services.

Bear in mind that asynchronous services are a bit harder to use than synchronous serv-ices. Don’t go crazy and start designing all your services as asynchronous. It adds someoverhead to the caller (especially in the Request-Response model) and is often not appropri-ate for the problem you need to solve. For example, many queries need to be synchronous. If acustomer logs into your web site and navigates to the page that shows him his bill, he’s waitingfor an immediate response. Making the bill retrieval service asynchronous in this instancemight not be useful.

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS 119

7974CH07.qxd 3/21/07 4:44 PM Page 119

Page 145: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Setting up WebLogic ServerIn this experiment, you’ll create an asynchronous “business” web service. To do this, youneed to create a web service that is both “one way” (that is, the operation returns a void) and“buffered” (messages are stored in a JMS queue until the web service can handle them).

Creating a JMS server and a message queue in WebLogic 9 is considerably simpler than inpast versions. Using the WLS console, first, navigate to Services ➤ Messaging ➤ JMS Servers.Click the Lock and Edit button and then the New button to create a new JMS Server. Name theserver WebServiceJMS and set the Persistent Store field to File Store. Click the Next button.Target the new JMS server to your AdminServer. Click the Finish button.

Next, you’ll create the JMS queue that will be used to deliver the buffered requests to theweb service. Navigate to Services ➤ Messaging ➤ JMS Modules and click the New button.Set the Name field to WebServiceQueue. Leave the Descriptor File Name and the Location inDomain fields blank. Click the Next button. Select the AdminServer as the target and click theNext button.

Now you need to add some resources to your JMS module. Click the “Would you like toadd resources” checkbox and click the Finish button.

Next you need to create your single resource: the message queue. Click the New buttonunder the Summary of Resource label. Select Queue as the Type of resource and click the Nextbutton. Set the Name to WebServiceQueue, set the JNDI Name to alsb.WebServiceQueue, andset the Template field to None. Click the Next button.

Now you need to create a subdeployment. Click the Create a New Subdeployment button.Name the subdeployment WSSubDeployment and click the OK button.

Now target the subdeployment to the WebServiceJMS server and click the Finish button.Your last step is to create a Store And Forward (SAF) agent. In the navigation bar on the

left side of the WebLogic console, select Services ➤ Messaging ➤ Store-and-Forward-Agents.Click the New button to create a new agent. Name the agent WebService SAF Agent, select theFileStore as the persistent store, and set the Agent Type to Both so that it can enable bothsending and receiving agents. Click the Next button, target the agent to the AdminServer, andclick the Finish button.

Finally, click the Activate Changes button to activate your newly created JMS server andits message queue. Now that the WLS is configured with a JMS queue for handling asynchro-nous messages, let’s take a quick look at the business service that provides the functionality.

Asynchronous Business ServiceCreating an asynchronous web service is a straightforward process. The asynchronous serviceyou’re going to create is modeled in Figure 7-1. You need to keep in mind a couple “rules”when creating an asynchronous web service:

• Asynchronous operations return a void data type.

• Asynchronous operations have the @Oneway() attribute.

• Asynchronous operations can specify message delivery retries using the@MessageBuffer() attribute.

• Asynchronous services use the @BufferQueue() attribute to specify the JMS queue towhich they listen.

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS120

7974CH07.qxd 3/21/07 4:44 PM Page 120

Page 146: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 7-1. Asynchronous web service

Your asynchronous business service is simple. Let’s take a quick look at the WSDL for theasynchronous service (see Listing 7-2). It’s almost identical to the synchronous business serv-ice WSDL from Listing 7-1. The main difference in this WSDL file is that there is no returnmessage. It has only a single operation called submitAsyncOrder that takes an Order message.

Listing 7-2. The AsycBusiness WSDL

<?xml version="1.0" encoding="UTF-8"?><definitions xmlns="http://schemas.xmlsoap.org/wsdl/"

xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"xmlns:tns="http://www.alsb.com/AsyncBusiness/"xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="AsyncBusiness"targetNamespace="http://www.alsb.com/AsyncBusiness/"><types>

<xsd:schema targetNamespace="http://www.alsb.com/AsyncBusiness/"xmlns:xs="http://www.w3.org/2001/XMLSchema"xmlns:order="http://www.alsb.com/order"><xs:import namespace="http://www.alsb.com/order"

schemaLocation="./order.xsd" /><xsd:element name="submitOrder" type="order:Order" />

</xsd:schema></types><message name="submitOrder">

<part element="tns:submitOrder" name="submitOrder" /></message><portType name="AsyncBusiness">

<operation name="submitOrder"><input message="tns:submitOrder" />

</operation></portType><binding name="AsyncBusinessSOAP" type="tns:AsyncBusiness">

<soap:binding style="document"transport="http://schemas.xmlsoap.org/soap/http" />

<operation name="submitOrder"><soap:operation

soapAction="http://www.alsb.com/AsyncBusiness/submitOrder" />

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS 121

7974CH07.qxd 3/21/07 4:44 PM Page 121

Page 147: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

<input><soap:body parts="submitOrder" use="literal" />

</input></operation>

</binding><service name="AsyncBusiness">

<port binding="tns:AsyncBusinessSOAP"name="AsyncBusinessSOAP"><soap:address

location="http://localhost:7001/advmessage/AsyncBusiness" /></port>

</service></definitions>

If you examine the source code for the AsyncBusinessImpl.java file in Listing 7-3, twoannotations are of specific interest in this situation. The first is the @BufferQueue annotation.It’s used to specify the JMS queue to which the web service will listen. You supply the JavaNaming Directory Interface (JNDI) name of the queue in the name attribute of the annotation.

The second annotation of interest is @MessageBuffer, where you specify the retryCountand the retryDelay attributes. As the attribute names imply, these allow you to specify theretry count and delay values that will be used when listening to the JMS queue.

Listing 7-3. The AsyncBusinessImpl.java File

package com.alsb.advmessage.syncbusiness;import javax.jws.WebService;import weblogic.jws.*;

/*** AsyncBusinessImpl class implements web service endpoint interface * AsyncBusiness */@WebService(serviceName="AsyncBusiness",targetNamespace="http://www.alsb.com/AsyncBusiness/",endpointInterface="com.alsb.advmessage.syncbusiness.AsyncBusiness")

// Use the following JMS queue to get buffered JMS messages@BufferQueue(name="alsb.WebServiceQueue")@WLHttpTransport(contextPath="advmessage",serviceUri="AsyncBusiness",

portName="AsyncBusinessSOAP")public class AsyncBusinessImpl implements AsyncBusiness {

private static long fiveMinutes = 300000;private static long thirtySeconds = 30000;private static long timeDelay = thirtySeconds;

public AsyncBusinessImpl() {}

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS122

7974CH07.qxd 3/21/07 4:44 PM Page 122

Page 148: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

@MessageBuffer(retryCount=5, retryDelay = "10 seconds")public void submitAsyncOrder(com.alsb.order.Order submitOrder) {

Date now = new Date();System.out.println("Starting to process the async order id "

+ submitOrder.getId() + " at " + now.toLocaleString());try {

Thread.sleep(timeDelay);} catch (InterruptedException ex) {

ex.printStackTrace();} finally {

now = new Date();System.out.println("Completed processing the async order id "

+ submitOrder.getId()+ " at " + now.toLocaleString());}

}

Just to make things interesting, you’re going to create a proxy service that workssynchronously, but calls the asynchronous business service. This is a technique for takingasynchronous services and presenting them in a synchronous manner to the service clients.To do this, you make a copy of the AsyncBusiness.wsdl file, name it AsyncProxy.wsdl, andmake a few minor adjustments to it so that the proxy service will behave synchronously. Youcan find the WSDL files in the Advanced Messaging project at src\com.alsb.wsdl. We’veincluded a excerpt of the file in Listing 7-4 that highlights the important changes.

Listing 7-4. The AsyncProxy.wsdl file

<?xml version="1.0" encoding="UTF-8"?>...

<message name="submitOrder"><part element="tns:submitOrder" name="submitOrder" />

</message>

<message name="submitOrderResponse"><part element="tns:submitOrder" name="submitOrder" />

</message>

<portType name="AsyncProxy"><operation name="submitAsyncOrder">

<input message="tns:submitOrder" /><output message="tns:submitOrder" />

</operation></portType>

<binding name="AsyncProxySOAP" type="tns:AsyncProxy"><soap:binding style="document"

transport="http://schemas.xmlsoap.org/soap/http" /><operation name="submitAsyncOrder">

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS 123

7974CH07.qxd 3/21/07 4:44 PM Page 123

Page 149: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

<soap:operationsoapAction="http://www.alsb.com/AsyncProxy/submitOrder" />

<input><soap:body parts="submitOrder" use="literal" />

</input><output>

<soap:body parts="submitOrder" use="literal" /></output>

</operation></binding>

...</definitions>

You can use the test console to test the proxy service and see how it behaves synchro-nously while the business service labors asynchronously in the background. Run several testsusing the test console as quickly as you can, then monitor the text console of the WLS to seethe output from the business service.

If it weren’t for the operation name of submitAsyncOrder(), the programmer who wrotethe client would have no way of knowing if this was an asynchronous operation, or merely anoperation with no return value. However, the behavior of the client demonstrates a clear dif-ference. This client will execute much faster, with per-call times around the 60ms mark on ourtest machine, as opposed to the synchronous version that takes a full 30-plus seconds for eachmethod invocation.

■Note The first time you run the client, you’ll notice a delay as the test console makes each of the parallelservice invocations. That is because the WLS is creating the process threads to handle each test console’srequests. The second time you run the client, you’ll see it execute at full speed, because the WLS will havethe threads pooled and ready to go.

There’s a drawback to writing asynchronous web services though, and that is the use ofJMS. If your client cannot “speak” JMS, then this approach will become especially importantbecause it allows you to wrap a synchronous HTTP service around an asynchronous JMS serv-ice. This is a prime example of the importance of service mediation and the flexibility thatservice mediation provides.

Service Types and Transport ProtocolsSo far we’ve taken an in-depth look at the invocation models used by our messages. Now it’stime we take a look at the service types and transport protocols. A “service type” represents amessage format type. For example, ALSB supports the following service types: SOAP or XMLdefined by a WSDL, SOAP without a WSDL, and XML without a WSDL and a Messaging Type(Binary, Text, MFL, or XML).

A transport protocol is a protocol that’s used to transport messages from sender toreceiver. JMS, HTTP, and HTTPS are all transport protocols.

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS124

7974CH07.qxd 3/21/07 4:44 PM Page 124

Page 150: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

You start creating a service by first determining the service type that you’ll need to use.Most commonly, this is a SOAP with WSDL service type. However, you might opt to use a dif-ferent service type, depending on your specific needs. For example, if you’re providing aservice to clients that can’t speak SOAP or WSDL, you might opt to implement an XML servicetype instead. If your service clients can only communicate in some proprietary binary format,you’d choose the Binary Messaging Type, and so on.

Once you know the service type you’ll use, you then select the transport protocol. Not alltransport protocols are available to every service type (see Table 7-1).

Table 7-1. Service Types and Transport Protocols

Service Type Transport Protocol

SOAP or XML with WSDL JMS, HTTP, HTTPS

SOAP (no WSDL) JMS, HTTP, HTTPS

XML (no WSDL) JMS, HTTP, HTTPS, Email, File, FTP

Messaging Type (Binary, Text, MFL, or XML) JMS, HTTP, HTTPS, Email, File, FTP

■Note All service types can send and receive attachments using Multipurpose Internet Mail Extensions(MIME).

The rest of this chapter is devoted to examining various combinations of service type andtransport protocols.

SOAP with WSDLCertainly, SOAP with WSDL is one of the most popular message types, especially in the webservice world. Originally SOAP was an acronym for Simple Object Access Protocol. Today, SOAPis generally recognized as a name only, as the old acronym no longer applies. Today, SOAP isan XML protocol for encoding and transmitting data. A SOAP message is comprised of anenvelope, which in turn is made up of a header section and a body section. Listing 7-5 showsa sample SOAP message sent to the AsyncProxyService you created earlier.

Listing 7-5. Sample SOAP Envelope

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soap:Header xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"></soap:Header><soapenv:Body>

<asy:submitOrder xmlns:asy="http://www.alsb.com/AsyncProxy/"><FirstName>string</FirstName><LastName>string</LastName><!--Zero or more repetitions:--><LineItem>

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS 125

7974CH07.qxd 3/21/07 4:44 PM Page 125

Page 151: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

<Product><CreditNeeded>3</CreditNeeded><Name>string</Name>

</Product><Quantity>3</Quantity>

</LineItem></asy:submitOrder>

</soapenv:Body></soapenv:Envelope>

We won’t take the time to provide a SOAP example here because all the samples in thisbook, other than some of those defined in this chapter, are examples of using the SOAPprotocol.

SOAP Without WSDLAt first glance, SOAP without WSDL might seem like an odd combination. Why would you everwant to use SOAP without a WSDL to define its structure? You’ll most likely need this sort of aservice type when dealing with legacy SOAP clients that were written without using a WSDL.Another use for this approach is when you want to have a single SOAP port exposed for allmessages. All message received by this single SOAP port can then be examined and routed tothe appropriate web services.

Creating this type of service is simple. You need to create a proxy service using Any SOAPService as the service type (see Figure 7-2). For this example, just select the default for the restof the Proxy Service creation wizard.

Figure 7-2. Creating a SOAP proxy service that doesn’t use a WSDL

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS126

7974CH07.qxd 3/21/07 4:44 PM Page 126

Page 152: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Next, you need to create a simple message flow for the service. Add a Pipeline Pair node tothe message flow that has a single stage in the request pipeline. In that stage, you’ll add twoactions. The first action will be to Assign the contents of the $body variable into a local variablenamed soapMsg.

The second action will be a Log action using the following expression:

concat('Received the following SOAP Any message: ', $soapMsg).

Be sure to set the Severity level to Error so that it shows up in the ALSB console and sys-tem log. Save all your changes and activate them in the Change Center.

Testing the service is straightforward. Bring up the test console, and you’ll see that theservice expects a document. Notice that the test console doesn’t provide you with a defaultdocument format, with good reason: because the service will accept any SOAP document,the test console has no way of knowing what document you want to send.

To simplify testing, you’ll find a sample SOAP document located in the WSDL directoryof the SOAPAttachmentsClient project in the Eclipse workspace. The document is namedSOAPnoWSDL.soap and is the same SOAP document that’s sent to the AsyncBusinessServiceyou created earlier. Take the liberty of changing the structure of the document to see how anyvalid SOAP document is accepted. The response of the proxy service is to echo whatever docu-ment was submitted.

In a nutshell, this type of service will accept any SOAP document you throw at it. You doneed to exercise caution when using this service type. Your proxy service might end up beingresponsible for parsing every possible type of content for a service of this type. This structureis akin to a Java method (pre-1.5) that takes a Collection as an argument and returns aCollection: it’s flexible because it can mean anything, and it’s complex for the same reason.

XML with WSDLAlthough SOAP is increasingly popular, it’s not the only way to send a message. You can alsouse a pure XML file, and you can enforce the structure of the XML message by mapping it to aWSDL. The key here is to create a WSDL that doesn’t rely on the SOAP protocol. Instead, it willuse the HTTP POST/GET protocols. Our sample will use the HTTP POST protocol.

A WSDL that doesn’t use SOAP is pretty uncommon, so it’s worth taking a closer look atone to understand how it’s put together. You can find the source file for Listing 7-6 in theWSDL directory of the SOAPAttachmentsClient Eclipse project.

Listing 7-6. A WSDL for an XML Service That Does Not Use SOAP

<?xml version="1.0" encoding="UTF-8"?><wsdl:definitions xmlns:http="http://schemas.xmlsoap.org/wsdl/http/"

xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/"xmlns:alsb="http://www.alsb.com"xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="XMLWSDLDefinitions"xmlns="http://www.alsb.com"targetNamespace="http://www.alsb.com">

<wsdl:message name="getGreetingRequest"><wsdl:part name="name" type="xsd:string" /></wsdl:message>

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS 127

7974CH07.qxd 3/21/07 4:44 PM Page 127

Page 153: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

<wsdl:message name="getGreetingResponse"><wsdl:part name="response" type="xsd:string" /></wsdl:message><wsdl:portType name="XMLWSDLPortType" xmlns="http://www.alsb.com"><wsdl:operation name="getGreeting"><wsdl:input message="alsb:getGreetingRequest" /><wsdl:output message="alsb:getGreetingResponse" /></wsdl:operation></wsdl:portType><wsdl:binding name="XMLWSDLHTTP" type="alsb:XMLWSDLPortType"><http:binding verb="POST" /><wsdl:operation name="getGreeting"><http:operation location="/GetGreeting" /><wsdl:input><mime:content type="application/x-www-form-urlencoded" /></wsdl:input><wsdl:output><mime:content type="text/xml" /></wsdl:output></wsdl:operation></wsdl:binding><wsdl:service name="XMLWSDLService"><wsdl:port binding="alsb:XMLWSDLHTTP" name="XMLWSDLHTTP"><http:address location="http://localhost:7001/xmlwsdl/XMLWSDLService" /></wsdl:port></wsdl:service></wsdl:definitions>

You can see from the listing that the SOAP binding has been replaced by an HTTP bindingthat uses the verb POST. The getGreeting operation exists at /GetGreeting (the fully qualifiedlocation is http://localhost:7001/xmlwsdl/XMLWSDLService/GetGreeting), and it takes aninput argument that is encoded in the manner used by HTTP POST. The operation returns anXML document.

Create a new proxy service with the name XMLWSDLService, and base it on the WSDL fromListing 7-6. Be sure to set the Endpoint URI to /XMLWSDLService. Select the defaults for the restof the proxy service creation wizard. Next, you’ll create a simple message flow that gets thename from the XML document that was submitted, and returns an XML document that con-tains the response. Figure 7-3 shows the message flow graphically.

First, you need to create the get name stage in the request pipeline. This stage containsa single Assign action that assigns the expression $body/name/text() to the local variablename. Next, you create the create greeting stage in the response pipeline. This stage hastwo actions. The first action is an Assign action that assigns the value of the expressionconcat('Hello ', $name) to the local variable greeting. The second action is a Replace thatreplaces the contents of the SOAP Body element, represented by the variable $body, with thevalue of the expression <response>{$greeting}</response>, as shown in Figure 7-4.

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS128

7974CH07.qxd 3/21/07 4:44 PM Page 128

Page 154: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 7-3. The XMLWSDLService message flow

Figure 7-4. The “create greeting” stage definition

Be sure to save all your changes, then activate them in the Change Center. You can use thetest console to test your XMLWSDLService to ensure that it’s working. Just for fun, let’s write aJava client to demonstrate how you’d use such a service programmatically (see Listing 7-7).

Listing 7-7. Java Client for the XMLWSDLService

public static void main(String[] args) {// Construct the XML document that we will POSTString doc = "<?xml version='1.0'?><name>John</name>";String hostname = "localhost";int port = 7001;try {

InetAddress addr = InetAddress.getByName(hostname);Socket sock = new Socket(addr, port);

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS 129

7974CH07.qxd 3/21/07 4:44 PM Page 129

Page 155: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

//Send the headerString path = "/XMLWSDLService/GetGreeting";BufferedWriter wr = new BufferedWriter(new

OutputStreamWriter(sock.getOutputStream(),"UTF-8"));wr.write("POST " + path + " HTTP/1.0\r\n");wr.write("Host: " + hostname + "\r\n");wr.write("Content-Length: " + doc.length() + "\r\n");wr.write("Content-Type: text/xml; charset=\"utf-8\"\r\n");wr.write("\r\n");

//Send the documentwr.write(doc);wr.flush();

// Read the responseBufferedReader rd = new BufferedReader(

new InputStreamReader(sock.getInputStream()));String line;while((line = rd.readLine()) != null)

System.out.println(line);} catch(UnknownHostException ex) {

ex.printStackTrace();} catch(IOException ex) {

ex.printStackTrace();}

}

As you can see from Listing 7-7, writing the Java client requires a fair bit of knowledgeabout the HTTP protocol, but it’s not that difficult if you have an example to work with. Whenyou run this client, you’ll see the following (raw HTTP) output as the XMLWSDLService providesits response (see Listing 7-8).

Listing 7-8. HTTP Response from the XMLWSDDLService

HTTP/1.1 200 OKConnection: closeDate: Thu, 27 Apr 2006 20:07:41 GMTContent-Type: text/xml; charset=utf-8X-Powered-By: Servlet/2.4 JSP/2.0

<?xml version="1.0" encoding="utf-8"?><response>Hello John</response>

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS130

7974CH07.qxd 3/21/07 4:44 PM Page 130

Page 156: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

XML Without WSDLThe next service type is an XML service that doesn’t use WSDL. It’s similar to the SOAPwithout WSDL service that you defined earlier. Create a new proxy service and set its name toXMLnoWSDLService. Select the Service Type as Any XML Service. Set the Endpoint URI for thissample to /XMLnoWSDLService and accept the rest of the default values in the Proxy Servicewizard.

To keep things simple, our message flow for this service will consist of a Pipeline Pair witha single stage in the request pipeline. That stage will have a single action: an Assign action thatwill take the value of the $body variable and assign it to the input local variable.

Save all your work and activate your changes in the Change Center. Now use the testconsole to test the XMLnoWSDLService. Simply enter any valid XML document into the test console and you’ll see that the service accepts it just fine. It isn’t necessary to enter the<?xml version="1.0" encoding="UTF-8"?> directive at the top of the request document totest your XML.

The XML without WSDL service type suffers from the same malady as the SOAP withoutWSDL service type: it’s simply too flexible to be useful at scale. It’s tempting to believe thatsuch a service will simplify your life. Proponents might argue that “I only have one service tomaintain, so it must be simpler.” However, that is misleading. Although it’s true that they’dhave only one service interface to maintain, who knows how many services would be imple-mented underneath the “cover” of this broadly defined service? To make matters worse, youhave no way to control service proliferation, nor do you have any visible mechanism for han-dling version changes. Finally, the service contract is so broad as to be useless. The only wayfor a service consumer to know how to make use of this service is to contact the serviceprovider and ask for the secret XML format to use in order to get his or her work done.Although technically this is a service, it isn’t service oriented in any way.

Messaging TypesThis service type permits one form of message as the request and (possibly) a different mes-sage format as the response. For example, you might need a service that accepts an XMLrequest, but returns a binary file. Proxy services based on the Message Type service type cangive you a lot of flexibility when integrating directly with legacy systems.

■Note The Message Type service type also supports File, FTP, and Email transport protocols. However,there is one caveat here. The File, FTP, and Email transport protocols are all “one-way” protocols, not“request-response.” Therefore, if you wish to use File, FTP, or Email, you need to define the response mes-sage type as None. If you specify a return type, ALSB will only let you specify HTTP, HTTPS, or JMS as thetransport protocols.

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS 131

7974CH07.qxd 3/21/07 4:44 PM Page 131

Page 157: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Message Type: BinaryAs the name implies, this message type allows you to send binary messages. You can use aservice such as this to communicate legacy or other proprietary data across the service bus.Your sample binary service will binary “message” and send it to a message-driven bean overJMS for processing. To accomplish this, you need to take the following steps:

1. Create the JMS assets on the WLS. You need a JMS Server, a JMS topic namedbinaryFile, and a connection factory named alsbConnectionFactory.

2. Create a Message-Driven EJB (also known as an MDB) that listens to thebinaryFileTopic topic. The bean will take the binary message and write it out to a temporary file.

3. Define a business service named BinaryBusinessService that knows how to route thebinary message payload to the JMS topic.

4. Define a proxy service named BinaryService that accepts a binary formatted messageand routes the message to the business service.

Creating the JMS Assets

To create the JMS assets, you must log into the WebLogic console by opening your webbrowser at the address http://localhost:7001/console. Log into the console and click theLock & Edit button in the Change Center so you can make some changes to your system.

First, navigate to Services ➤ Messaging ➤ JMS Servers. Click the New button to create anew JMS server. Name the service alsbJMSServer and set the persistent store to “(none),” asshown in Figure 7-5.

Figure 7-5. Creating a JMS server

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS132

7974CH07.qxd 3/21/07 4:44 PM Page 132

Page 158: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Click the Next button to move to the window that allows you to target the server. SelectAdminServer from the combo box (it should be the only server listed) and click the Finish but-ton. At this point, your JMS server has been created, but you need to create a connectionfactory and a topic for the server before it is useful to you. JMS connection factories and topicsare categorized as types of JMS Module Resources in WebLogic 9. So, your next step is to createa JMS module for your newly created JMS server. Navigate to the Services ➤ Messaging ➤ JMSModules section in the WLS console. Click the New button to create a new JMS module.

In the Create JMS System Module window, fill in the Name field with alsbJMSResourcesand leave the other two fields blank. Click the Next button to continue. Target the AdminServerand click the Next button. The next window asks you if you would like to add resources to theJMS system module. Check the checkbox and click the Finish button. The console now pre-sents you with the window that shows the summary of resources for the alsbJMSResourcesmodule, as shown in Figure 7-6.

Figure 7-6. The alsbJMSResources—Summary of Resources window

Click the New button. The next window prompts you for the type of resource to create(see Figure 7-7). Select the Connection Factory radio button and click the Next button. Namethe connection factory alsbConnectionFactory and set the JNDI Name to the same.

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS 133

7974CH07.qxd 3/21/07 4:44 PM Page 133

Page 159: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

■Tip Keep your names simple and as self-explanatory as possible. This includes the JNDI names. If youhave the need to create JNDI names in a hierarchy, be sure to define naming standards to make it easy foryour developers, quality assurance, and production services folks to find whatever they’re looking for. Using“cute” names such as “Calvin” and “Hobbes” will only cause confusion, especially as the scale of your workgrows.

Click the Next button once you’ve defined the names for the connection factory. Selectthe AdminServer as the target for the connection factory and click the Finish button. Your con-nection factory is now defined.

You’ll follow a similar process to create your JMS topic. Back in the Summary of Resourcespage, click the New button and select the Topic radio button. Click the Next button tocontinue.

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS134

Figure 7-7. Selecting the type of JMS resource

7974CH07.qxd 3/21/07 4:44 PM Page 134

Page 160: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Now in the JMS Destination Properties page of the wizard, set the name tobinaryFileTopic and set the JNDI Name to the same value. You aren’t using a JMS template,so leave that field as None.

On the next window, click the Create a New Subdeployment button and accept the defaultvalue of binaryFileTopic (subdeployments default to the name of the first resource they con-tain). Click the OK button to continue.

The last step is to target the alsbJMSServer, as shown in Figure 7-8. Click the Finish but-ton. Your work with regard to creating the JMS resources for the WLS is complete.

Figure 7-8. Targeting the topic

Activate the changes you’ve made via the Change Center.

Creating the Message-Driven Bean

Your next step is to create a message-driven bean that will listen to the binaryFileTopic JMStopic for binary messages. It will then save those binary messages to the local file system. Youcan find the source code for the MDB in the ServiceTypes project in Eclipse. You can find theimportant details of the MDB in Listing 7-9. If you examine the @MessageDriven annotation,you can see that the JMS topic JNDI name to which the bean will listen is defined in thedestinationJNDIName attribute.

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS 135

7974CH07.qxd 3/21/07 4:45 PM Page 135

Page 161: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Listing 7-9. BinaryMDB.java

package com.alsb.business;import ...@MessageDriven(maxBeansInFreePool = "200",

destinationType = "javax.jms.Topic",initialBeansInFreePool = "20",transTimeoutSeconds = "0",defaultTransaction = MessageDriven.DefaultTransaction.REQUIRED,durable = Constants.Bool.FALSE,ejbName = "binaryMDB",destinationJndiName = "binaryFileTopic")

public class BinaryMDB implements MessageDrivenBean, MessageListener {public final static long serialVersionUID = 1L;private static final boolean VERBOSE = true;private MessageDrivenContext m_context;

/*** Retrieve the BytesMessage and save that data as a file*/public void onMessage(Message msg) {

BytesMessage bm = (BytesMessage) msg;try {

long length = bm.getBodyLength();byte[] binaryData = new byte[(int)length];int numRead = bm.readBytes(binaryData);// Create a temporary file on the local file system.File outputFile = File.createTempFile("mdb_", "xxx");log("Created the file: " + outputFile.getAbsolutePath() +

" with a file size of " + numRead + " bytes");FileOutputStream fos = new FileOutputStream(outputFile);fos.write(binaryData);fos.close();

} catch(IOException ex) {ex.printStackTrace();

} catch(JMSException ex) {System.err.println("An exception occurred: "+ex.getMessage());

}}...

}

The onMessage method is the entry point of every MDB. This method shows how to accepta binary message from ALSB. You start by converting the input message into a BytesMessage.You then find the length of the binary message and create a byte array to hold the messagecontents. After you read the bytes into the array, you create a temporary file and write thebytes out to the file. You send a System.out.println to the console so that it’s easy to see wherethe file was created. This will be handy later on when you’re testing the system end to end.

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS136

7974CH07.qxd 3/21/07 4:45 PM Page 136

Page 162: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

To compile and deploy the MDB, open the associated build.xml file in Eclipse and run thebinary.mdb task. Once this task has completed successfully, you’re ready to move to the nextstep: defining the business service.

Defining the Business Service

Next you need to define a business service that represents the BinaryMDB you just created. Thisbusiness service needs to route messages to the correct JMS topic. In the ServiceTypes projectin the ALSB console, create a folder named Business Services. In the new folder, create a busi-ness service named BinaryBusinessService and select as the Service Type a MessagingService. Click the Next button. Set the Request Message Type to Binary and the ResponseMessage Type to None, as shown in Figure 7-9. Click the Next button to continue.

Figure 7-9. Defining the BinaryBusinessService request and response types

You need to communicate with your MDB over a JMS topic, so your Protocol must be setto jms. The Endpoint URI is composed of the JNDI name of your connection factory and theJMS topic name. Because you’re connecting to a JMS server on your local machine, you can setthe Endpoint URI to the following:

jms://localhost:7001/alsbConnectionFactory/binaryFileTopic

Click the Next button.Use the default values on the JMS Transport Configuration window. Click the Next button

and then the Save button.Your BinaryBusinessService is now defined and ready to be called from your proxy service.

Creating the Proxy Service

Creating a binary proxy service follows the same pattern we have used throughout this book.Name the proxy BinaryService and select Messaging Service as the service type. Click the Nextbutton.

The second window in the wizard allows you to define the request and response messagetypes. For this exercise, you’ll set the request message type to Binary. Because we’re demon-strating the use of the File transport protocol (which is a one-way protocol), you must set theresponse to None.

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS 137

7974CH07.qxd 3/21/07 4:45 PM Page 137

Page 163: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Select the File protocol and set the Endpoint URI to the following:

file:///{drive ID}/filedir

Be sure to substitute the correct drive ID for your system.The next step in the wizard is to define the details of the File transport protocol. The fields

with red asterisks next to them are required fields. The File Mask field is pretty straightforward.You’ll leave it with the default value of *.* so that you can send any type of file to the service.

The Polling Interval specifies the number of seconds between each polling event. Whenthe polling event occurs, ALSB will examine the directory (specified by the Endpoint URI) tosee if any files match the file mask. The read limit specifies the maximum number of files toprocess during each polling event. The default value is 10. If you set this value to zero, all filesthat match the file mask at the time of the polling event will be processed.

The Sort By Arrival checkbox forces the selection of files from the directory based on theircreate date. The Scan SubDirectories checkbox instructs ALSB to look for files recursively inany existing subdirectories.

The Pass By Reference checkbox tells ALSB to copy the file to the Archive Directory andpass a reference to the file in the message itself. The Post Read Action tells ALSB either todelete the file or to copy it to the Archive Directory after the message has been processed. TheStage Directory specifies where the files should be stored while they’re being processed.

The Archive Directory defines a directory in the file system that will store the files afterthey’ve been processed. Of course, this only has significance if the Post Read Action is set toArchive.

The Error Directory specifies where messages and attachments are posted if there is aproblem. The “Request encoding” checkbox specifies the character encoding scheme used forFile requests. The default is utf-8.

Be sure your configuration matches the one in Figure 7-10.

Figure 7-10. Defining the details of the File transport protocol

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS138

7974CH07.qxd 3/21/07 4:45 PM Page 138

Page 164: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

■Tip Be careful when defining your Stage, Archive, and Error directories. Give them absolute paths so youcan be sure of their location. This is especially true if you have the Scan SubDirectories checkbox checkedand you inadvertently place your archive directory within the directory specified by the Endpoint URI; this cancause an infinite loop.

Click the Finish button to save your proxy service. Your next step is to route requests fromthe proxy service to the business service.

Routing the Proxy to the Business Service

We’re going to keep it simple here. Edit the message flow for your proxy service and add aRoute node. Route the message to the BinaryBusinessService, as shown in Figure 7-11. Nofurther actions are needed. Save all your work so far and activate your changes in the ChangeCenter. It’s testing time!

Figure 7-11. The message flow and Route node for the BinaryService

End-to-End Testing

To test a binary service, we prefer to use image files. If an image is corrupted, it’s much easierto notice the corruption in an image, video, or sound file than it is to look through a text file,especially if the files are significant in size. Image files are a good compromise because theycan be fairly large.

Start by selecting the file you wish to use for the test. Copy the test file into the directorydefined by the Endpoint URI for the proxy service. If your system is set up like mine, thatmeans you need to copy the file into the D:\filedir directory on your local hard drive. Oncethat’s done, it might take up to a minute before the proxy service polls the directory and picksup the file for processing. You’ll know when the file has been processed by watching the out-put console for the WLS that’s hosting ALSB. You should see output similar to the following:

Created the file: D:\TEMP\mdb_6801xxx with a file size of 171366 bytes

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS 139

7974CH07.qxd 3/21/07 4:45 PM Page 139

Page 165: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

When you see this message, navigate to the file that the MDB just created and give it thecorrect file extension so that it matches the file extension of the source file (usually a JPG orPNG). When the file is appropriately renamed, open it up to ensure that it appears in goodcondition.

Message Type: TextText messages are useful when you need to exchange non-XML text information. Sample usesof this service type include exchanging plain text files or comma-separated values. In thissample, you’ll create a Text service that uses FTP as its transport protocol. To make use of theFTP transport protocol, you’ll need access to an FTP server. We used the FileZilla FTP server,available from SourceForge at http://sourceforge.net/projects/filezilla/. Of course, youcan opt to use any FTP server you like, but we’ll walk you through some details of setting upthe FTP server for use by a specific account, so you might have some translation to do to meetthe specifics of your FTP server.

The installation program for FileZilla is easy to run. Once you install the FTP server andstart it, you’ll need to create a user account. Your proxy service will log into the FTP serverusing this account. We selected this scenario for two reasons. First, it seems more realistic thatthe FTP server would apply some level of security when communicating business informationto external entities. Second, it give you a chance to see how you create and use ServiceAccounts in ALSB.

To create a user account in FileZilla, click the icon. This brings up the Users dialogbox. Click the Add button underneath the Users listbox, and a new dialog appears where youcan enter the username for the account you’re creating. Name the account tester and clickthe OK button.

Now that the account is created, you need to set some properties for the account. Back inthe Users dialog, be sure the “Enable account” and Password checkboxes are checked. Set thePassword field to password (see Figure 7-12).

Figure 7-12. Setting the user password

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS140

7974CH07.qxd 3/21/07 4:45 PM Page 140

Page 166: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Next, you need to define a home directory for this user account. Click the “Shared folders”entry in the Page listbox on the left side of the dialog. Next, click the Add button in the “Sharedfolders” portion of the dialog box. A new dialog appears that allows you to select a directory onyour computer. We chose to create an ftproot directory, but you can select any directory youwish.

Click the OK button to close the Users dialog in FileZilla. FileZilla is now properly config-ured for your needs.

Your next step is to create a Service Account in ALSB. A Service Account allows you tocreate account names and passwords so that ALSB can log into external services and systems.In your case, you need to create a Service Account so that you can log into the FileZilla FTPserver using the account tester/password.

To create a Service Account, be sure to start a new change in the Change Center. Thennavigate to the Message Type project in the Project Explorer. In the root directory of the proj-ect, create a Service Type resource. Name the resource FTP Account and provide a meaningfuldescription, as shown in Figure 7-13.

Figure 7-13. Creating a Service Account

Be sure to set the Resource Type to Static. This allows you to define a static usernameand password. Click the Next button. Enter the username as tester and set the password topassword. Click the Last button, then the Save button, and then activate the change in theChange Center. Prior to version 2.5 of ALSB, you would define the important aspects of theService Account outside the Change Center, in the Security Configuration section of the ALSBconsole. With the release of ALSB 2.5, this has been changed. Service Accounts are now part ofa project and no longer a part of the overall ALSB system configuration.

Next, you need to create the proxy service itself. Start by creating a new proxy service inthe ServiceTypes project. Name the service TextFTP and be sure to select the Service Type asMessaging Service. Click the Next button.

Set the protocol to “ftp” and then provide the URI of the FTP service. The URI to use isftp://localhost:21/ftp_in.

■Caution The Endpoint URI of an FTP transport protocol is pretty darned picky. If the URI contains a direc-tory name, then the URI must not end with a /. If the URI does not refer to a directory, then the URL must endwith a /.

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS 141

7974CH07.qxd 3/21/07 4:45 PM Page 141

Page 167: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Click the Next button to get to the FTP Transport Configuration window, shown inFigure 7-14.

Here is where you get to make use of the Service Account you created earlier. Select the“external user” radio button for the User Authentication. The Service Account field appears.Click the Browse button and select the FTP Account from the list of Service Accounts.

Figure 7-14. Defining the FTP transport protocol details

Most of these setting are self-explanatory, especially if you read the previous section onthe BinaryService.

Click the Next button and then click Save to save the definition of this proxy service. Next,you’ll create a simple message flow for this proxy service. Add a Pipeline Pair to the Start nodeand then add a stage to the request pipeline. Name the stage show text info.

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS142

7974CH07.qxd 3/21/07 4:45 PM Page 142

Page 168: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

In the show text info stage, we’ll create two new variables to demonstrate where to getthe most pertinent information. The contents of the text file are held in the $body variable. Youcan extract just the text by using the expression $body/text(). Create an Assign action to savethis data to the local variable textContents. Add a Log action to display the contents of the file.

You can find the name of the file that the proxy server is using by using the followingexpression:

$inbound/ctx:transport/ctx:request/tp:headers/ftp:fileName

Create an Assign action and a matching Log action to retrieve this data and send it to thelog, as shown in Figure 7-15.

Figure 7-15. TextFTP stage definition

Testing this service can take several forms:

• You can use the test console.

• You can use an FTP client, connect to the FileZilla server, and put a text file onto theFTP server.

• You can just make a local copy of a text file into the D:\ftproot directory.

We prefer the second approach because it more closely simulates how this service willoperate in the real world. To run the test, first create a new directory where you’ll hold yoursample files. For this example, name the temporary directory /ftptemp. Navigate into FTPtemp and create a couple short text files. We created files named a.txt and b.txt with just afew words in each file. Open up a command prompt and navigate to the /ftptemp directory.Enter the command ftp. This starts the FTP client program on most Windows machines. Next,you need to connect to the FTP server on your local machine with the following command:

open 127.0.0.1

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS 143

7974CH07.qxd 3/21/07 4:45 PM Page 143

Page 169: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

You will be prompted for a username and password, in turn. Enter tester for the user-name and password for the password. After you receive the “Logged on” message, type in theFTP command mput *.txt (mput stands for multi-put, which allows you to send multiple filesto the FTP server). The FTP client then prompts you to confirm each file (a.txt and b.txt, if youfollowed the earlier instructions). Press the “y” key to confirm each file. After the files are sent,you can type the commands close and quit to close the FTP connection and quit the FTPclient.

In the ALSB output console, you should see the results of the Log action that you definedfor your proxy service. The output should look similar to the following:

<May 7, 2006 10:11:29 AM PDT> <Error> <ALSB Logging> <000000> < [PipelinePairNode1, PipelinePairNode1_request, stage1, REQUEST] Text contents = Sample text file named b.txt><May 7, 2006 10:11:29 AM PDT> <Error> <ALSB Logging> <000000> < [PipelinePairNode1, PipelinePairNode1_request, stage1, REQUEST] TextFTP proxy received a file named: ftp_in/b.txt2325484791769069271-214ec371.10b0f56dcbd.-7dd4.Stage><May 7, 2006 10:11:29 AM PDT> <Error> <ALSB Logging> <000000> < [PipelinePairNode1, PipelinePairNode1_request, stage1, REQUEST] Text contents = Sample text file named a.txt><May 7, 2006 10:11:29 AM PDT> <Error> <ALSB Logging> <000000> < [PipelinePairNode1, PipelinePairNode1_request, stage1, REQUEST] TextFTP proxy received a file named: ftp_in/a.txt2325484791769069271-214ec371.10b0f56dcbd.-7dd5.Stage>

Notice that the name of the file, as far as the proxy service is concerned, is greatly “deco-rated,” and the file type is set to .Stage. You’ll need to account for this if the name of the file isimportant to your processing requirements.

We won’t bother to write a business service for this proxy service. The usage of the textdata should be a trivial exercise for you by now.

Message Type: XMLThere’s no difference between an XML with no WSDL and this message type. There are tworeasons you might use this message type. The first reason is if XML was needed in the requestor response, but not both. The second reason for using this message type is if you want todeclare the schema of the XML message. If XML is needed in both the request and response,then you should use the XML without WSDL service type, described earlier.

MFL stands for Message Format Language. You can use MFL any time you need to processdata that is formatted in some method other than XML. MFL allows you to define data formattypes, and then apply those types to messages that are sent and received from ALSB.

In this exercise, you’ll create a proxy service that’s invoked by an e-mail message. The e-mail message will contain a formatted text message. The proxy service will read the e-mailand convert the formatted text message from its original format into a different text formatthat’s expected by the business service. You’ll also create a matching business service that willbe invoked via FTP, building on some of the work you did in a previous section.

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS144

7974CH07.qxd 3/21/07 4:45 PM Page 144

Page 170: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

There are a lot of moving parts in this exercise, so it will help if you keep an overview inmind of the various artifacts that you need to create and the steps you need to perform tomake this exercise complete. Use the following list as a mental guide for the rest of thissection:

1. Install an e-mail server on your machine and create an e-mail account [email protected].

2. Create a Service Account to the e-mail server.

3. Create a user account on the FTP server named customerftp. Assign the root directoryof this user to D:\ftproot or C:\ftproot, whichever is appropriate for your environment.Be sure you manually create the ftproot/customerftp directory or FileZilla might com-plain later about not being able to create the file.

4. Create a Service Account to the FTP server.

5. Create an MFL file that defines the data format that will be e-mailed to your proxyserver.

6. Create an MFL file that defines the format of the file the business service will send tothe FTP server.

7. Create an XQuery Transformation file that converts Email MFL format into the FTPformat.

8. Add both MFL files and the XQuery to the ServiceTypes project.

9. Create a proxy service based on the CustomerEmailFormat MFL resource and tell theproxy to poll the e-mail account for messages.

10. Create a business service based on the CustomerFTPFormat MFL resource and tell it tosend the data as a file to the FTP server.

11. Write a message flow for the proxy service that uses the XQuery transformation andinvokes the business service.

12. Test the whole thing, end to end.

Simple, isn’t it? Let’s get started.You’ll need an e-mail address that the proxy service can use when it checks to see if it has

received an e-mail. Because it’s unlikely that your system administrator will want you mon-keying around with your company’s real e-mail server, you’ll set up your own e-mail server.For this you’ll use the Java EMail Server, an open source project from SourceForge. You candownload this file yourself at the following URL:

http://prdownloads.sourceforge.net/javaemailserver/jes-1.4.zip?download

Alternatively, you can use the version included with this book’s downloadable code in theSource Code/Download area at http://www.apress.com.

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS 145

7974CH07.qxd 3/21/07 4:45 PM Page 145

Page 171: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

To install the e-mail server, just open the ZIP file and extract the contents (preserving thedirectory structure) into a new directory. Once the files are in place, navigate into the directorywhere you extracted the files and edit the user.conf file. In this file, add the following lines atthe end:

[email protected][email protected][email protected][email protected]=

This creates a new e-mail user named proxy with a password of password. Accept thedefault values in the mail.conf file. If you should have trouble running the e-mail server, youshould check the mail.conf file first. However, the defaults are fine for most developermachines.

Next, you need an e-mail client so that you can send e-mails to [email protected] toinvoke the service. You’ll write a simple e-mail client that will send e-mails to your proxy serv-ice. You can find the code in the ServiceTypes project in the Eclipse workspace.

As mentioned earlier, your service will accept a formatted text message. If you take a lookat the e-mail client that sends the formatted text message, you’ll see in the body of the e-mailthat the message has the following format:

[first name]\t[last name]\t[middle initial]\t[customer id]\r

The \t represents a tab. This is simply a tab-delimited message format. You could just aseasily have used commas or another text character instead of the tab character. The importantpoint is to understand how the body of the e-mail is formatted.

MFL is a notation that allows you to define arbitrary message formats, such as the tab-delimited format you’ll use in this exercise. Your next step is to create an MFL file that definesthis message format. Once you have the MFL file, you’ll add that file as an MFL resource toyour ServiceTypes project so you can make use of it in your proxy service.

ALSB ships with a tool that makes the creation and editing of MFL files simple. It’s calledthe Format Builder, and you can start it from within Eclipse by right-clicking the MFL direc-tory in the ServiceTypes project in Eclipse and selecting New ➤ Other. Next, from the “Selecta wizard” dialog box in Eclipse, select the Message Format File file type from the AquaLogicService Bus folder.

You’ll first build an MFL file that matches the tab-delimited format that will be e-mailedto your proxy service. You’ll then build a second MFL file that represents the data format thatwill be sent to the FTP business service.

In the Format Builder application, select File ➤ New from the menu bar. You see the inter-face change and you have the opportunity to name the new message format. Change themessage format name to CustomerEmailFormat and click the Apply button.

Now you define the message format in detail. Right-click the envelope icon in the left nav-igation bar of the Format Builder and select Insert Field. Name the field firstName and be surethe Optional checkbox is unchecked. The field type is a String value. This field will occur onlyonce. The field is terminated by the \t delimiter and the code page is UTF-8. Repeat thisprocess for the lastName and MI fields.

The last field you’ll create is the CustomerID field. It’s similar to the other fields in allrespects, save one: the delimiter value is set to \r. Your window should look similar to that

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS146

7974CH07.qxd 3/21/07 4:45 PM Page 146

Page 172: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

shown in Figure 7-16. Please note that the order of the fields is critical. If your order isdifferent, simply click and drag on the fields in the left navigation bar to put them into thecorrect order.

Figure 7-16. Defining the String data fields

Save the CustomerEmailFormat.mfl file in the ServiceTypes/MFL directory of the Eclipseproject. Next you’ll create the CustomerFTPFormat.mfl file that defines the file formatexpected by the FTP server. This format has the following structure:

[ID]\t[Name]\r

As you can see, the format required by the FTP server is significantly different from theformat you receive in the e-mail. A little transformation is in order to make this communica-tion work. To further complicate matters, the FTP format requires that the ID field be anumeric field, while the Email format defines it as a String field. The game is afoot!

To define the CustomerFTPFormat.mfl file, you’ll need to create a new file in the FormatBuilder. Name the new file CustomerFTPFormat.mfl. Create the ID and Name fields, followingthe same processes you just performed for the CustomerEmailFormat.mfl file. The only differ-ence is that the ID field must be defined as Numeric. Be sure the ID field is terminated withthe \t character, while the Name field is terminated with the \r. Your file should look likeFigure 7-17.

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS 147

7974CH07.qxd 3/21/07 4:45 PM Page 147

Page 173: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 7-17. Defining the CustomerFTPFormat.mfl file

Save this file in the ServiceTypes/MFL directory in the Eclipse project workspace. Welldone so far. You have defined your input and output formats. Now you need to define anXQuery resource that will perform the transformation of the data from the input format(CustomerEmailFormat.mfl) into the output format (CustomerFTPFormat.mfl). Fortunately,you have a tool in Eclipse that makes this process significantly less tedious: the XQueryMapper.

You begin in Eclipse. Left-click the ServiceTypes/MFL directory and press the F5 key toupdate the folder so that Eclipse knows about the two MFL files you created there. Right-clickthe ServiceTypes/MFL directory and select New ➤ Other from the pop-up menu in Eclipse.This brings up the “Select a wizard” dialog box in Eclipse. Navigate to the AquaLogic ServiceBus folder and select XQuery Transformation. Click the Next button to start the XQuery Trans-formation wizard.

The first step in the wizard is to define the file name. Set the file name tocustomerMFLTransform. Be sure the parent folder is set to /ServiceTypes/MFL and click the Next button.

Now you can specify the source of the XQuery transformation. Because MFL is a non-XML format, select the Non-XML radio button above the listbox on the left side of the dialogbox, as shown in Figure 7-18. Expand the node named MFL/CustomerEmailFormat.mfl, selectthe CustomerEmailFormat object, and click the Add button.

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS148

7974CH07.qxd 3/21/07 4:45 PM Page 148

Page 174: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 7-18. Selecting the XQuery source type

Click the Next button to select the target type. Once again, select the Non-XML radio but-ton, then expand the MFL/CustomerFTPFormat.mfl node so that you can select and then addthe CustomerFTPFormat object.

Click the Finish button. You’ll now see the customerMFLTransform.xq file in Eclipse. Bydefault, you should see the design view, as shown in Figure 7-19.

Figure 7-19. XQuery Transform design view

The design view of the XQuery Transformation editor is a powerful tool that allows you towork graphically and generate XQuery scripts. You have two things to do in this transforma-tion. First, you’ll map both the last name and then the first name from the source format tothe Name field of the target format. Along the way, you’ll ensure that the Name field of the target

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS 149

7974CH07.qxd 3/21/07 4:45 PM Page 149

Page 175: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

format ends up as [lastName], [firstName]. Adding the comma will help for human readabil-ity. Second, you’ll map the CustomerID from the source to the ID field of the target, convertingit from a String to a Numeric along the way.

Let’s get started with the first and last names. Click the lastName and drag it onto the tar-get’s Name field, then release the mouse button. A green arrow will show up, visually linking thetwo fields. Next, click and drag the firstName field from the source onto the Name field of thetarget and release the mouse. Your XQuery Transformation should look like Figure 7-20.

Figure 7-20. Mapping the name fields to the target

However, you need to do a little extra formatting in the Name field of the target format.Click the Source view of the XQuery Transformation to see the raw XQuery text that has beengenerated so far. There is a single XQuery function declaration. In that function, look for thetext between the <Name></Name> tags. That text should be as follows:

<Name>{ concat($customerEmailFormat/lastName, $customerEmailFormat/firstName)}</Name>

You want to add a comma and a white space between the last name and the first name, soyou modify this line of code as follows:

<Name>{concat($customerEmailFormat/lastName, ', ' $customerEmailFormat/firstName)}</Name>

Switch back to the design view. Now you want to map the CustomerID source field into theID field of the target format. If you click and drag, as you did before, you’ll get the followingerror message:

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS150

7974CH07.qxd 3/21/07 4:45 PM Page 150

Page 176: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

That’s because you can’t map a String into a Numeric. The XQuery Transformation toolisn’t able to make a judgment call on this kind of transformation, but you know that the Stringversion of the CustomerID field will always be a numeric value, so you need to create this map-ping yourself. Go back into the Source view of the transformation and add the following line ofcode just below the CustomerFTPFormat tag:

<ID>{ $customerEmailFormat/CustomerID/text() }</ID>

Switch back to the design view and it should look like Figure 7-21. Note the little “f” on theicons next to the ID and Name attributes of the target. They indicate that the mapping uses oneor more XQuery functions and is not a straight copy of the data in the fields.

Figure 7-21. The complete XQuery transformation

Save the XQuery transformation file. Then, in the ALSB console, navigate to theServiceTypes project. Create an XQuery folder in the project, and in that folder add the XQuerytransformation file as an XQuery resource. Name the new resource CustomerEmailToFTP. You’llfind the XQuery by clicking the Browse button and navigating to \ServiceTypes\MFL\customerMFLTransform.xq.

Navigate into the MFL folder of the ServiceTypes project and create an MFL resource forthe CustomerEmailFormat.mfl and the CustomerFTPFormat.mfl files. Use the file names forthe resource names (omitting the MFL file extension).

Next, you need a Service Account to log into the e-mail server to retrieve the e-mail. Inthe ServiceTypes project in ALSB, create a new Service Account as shown in Figure 7-22. Besure to select Static as the Resource Type. Click the Next button and set the username [email protected] and the password to password. Click the Save button to save this ServiceAccount.

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS 151

7974CH07.qxd 3/21/07 4:45 PM Page 151

Page 177: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 7-22. Creating a Service Account for the MFLEmail2FTP proxy

The Service Account for the e-mail account is now defined and active. Next, you mustdefine a new Service Account to connect to your FTP server using a different login name. Fol-low the same process as you just did for creating the e-mail Service Account, but with thefollowing changes:

1. In the ServiceTypes project folder (in the ALSB console), create a new Service Accountnamed customerftp. Be sure to select the Resource Type as Static again.

2. Click the Next button, set the username to customerftp, and set the password topassword.

Those are all the Service Accounts you need for this exercise. You’re now ready to createyour proxy service. In the ServiceTypes project, create a new proxy service resource. Name theproxy MFLEmail2FTP. You can optionally provide a description of the service (remember, this isa best practice when doing this in the real world), and select the Messaging Service as the Ser-vice Type. Click the Next button.

Configure the message type. Select the Request Message Type as MFL and select theCustomerEmailFormat. For the response message type, select None. Click the Next button.

Select the “email” protocol (see Figure 7-23). Be sure to set the Endpoint URI to use thePOP3 port, not the SMTP port, because you’re reading e-mail via POP3 in this exercise.

Figure 7-23. Configuring the “email” protocol

On the next page of the wizard (see Figure 7-24), you need to select the e-mail ServiceAccount, so that your proxy service will be able to log into the e-mail server to retrieve theemails. The Polling Interval defines, in seconds, how often the proxy service will connect to

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS152

7974CH07.qxd 3/21/07 4:45 PM Page 152

Page 178: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

the e-mail server to check for new e-mails. The Read Limit specifies the maximum number ofe-mail messages to process each time the proxy service connects to the e-mail server. The PostRead action of “delete” specifies that the e-mails that are read will then be deleted. Set theAttachments combo box to “ignore,” because you aren’t interested in any e-mail attachments.

Figure 7-24. Configuring the e-mail transport details

The IMAP Folder is the directory used when processing. The IMAP Move Folder is onlyused if the Post Read Action is set to “move.” The Download Directory specifies the directoryinto which the e-mail messages are downloaded when they are about to be processed. TheArchive Directory specifies the directory where the e-mail messages are archived if the PostRead Action is set to Archive. The Error Directory is where the e-mail messages are stored ifthere is an error processing them. Last, the Request Encoding specifies the encoding schemeused to encode the e-mail messages. This is used to ensure that the proxy server parses the e-mail messages using the correct character encoding scheme.

Click the Next button and then click the Save button on the following window. The basicsof the proxy service are now defined.

You must now create a business service that will accept a text message using theCustomerFTPFormat. Name the business service MFLBusiness and select Messaging Serviceas the service type.

Set the request message type to MFL and select the CustomerFTPFormat MFL resource. Besure that the response message type is set to None; otherwise you won’t be able to use the FTPtransport protocol.

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS 153

7974CH07.qxd 3/21/07 4:45 PM Page 153

Page 179: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Next, you define the transport protocol. Select FTP as the protocol and leave the loadbalancing algorithm at the default value of round-robin. Add an Endpoint URI of ftp://localhost:21/customerftp. Accept the remaining default values and click the Next button.

On the next window (see Figure 7-25), set the user authentication to “external user,” thenselect the customerftp Service Account. Set the prefix field to customer and the suffix field totext. You should set the transfer mode to binary, simply because it allows a greater variety ofcharacter encodings to be transferred. Last, use the default request encoding of utf-8.

Figure 7-25. Setting the transport configuration

Save all your work and activate the change in the Change Center.Next, you define the message flow for your proxy service. Create a new change in the

Change Center and edit the message flow for the MFLEmail2FTP proxy service. Add a PipelinePair node to the message flow. In the request pipeline, add a stage and name it get EmailInfo. This stage is not necessary to the function of the proxy service, but we wanted to demon-strate where you find some of the important information about the e-mail message.

Edit the get Email Info stage and create some Assign actions. First, you’ll create Assignactions to get the firstName, lastName, and CustomerID from the e-mail message. Click the<Expression> link for the Assign statement, then select the Variable Structures link in the leftnavigation pane. Open the $body (request) node and the nested CustomerEmailFormat node,and voilà! You can see the structure of the MFL file represented in the format to which youshould now be accustomed (see Figure 7-26). No parsing is necessary from you; ALSB takescare of all those boring details.

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS154

7974CH07.qxd 3/21/07 4:45 PM Page 154

Page 180: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 7-26. Accessing MFL data is easy within the body variable.

Click the firstName node and paste it into the expression edit box. Assign the value of thatexpression to a variable named firstName. Do the same for the lastName and CustomerID fields,assigning them to local variables.

The To and From fields of the e-mail are accessed through the $inbound structure. Figure 7-27 shows the exact location of this information. If you need to know the date of the e-mail or if you make service routing decisions based upon who sent the e-mail, the $inboundvariable is a rich source of that information.

Figure 7-27. The $inbound structure holds the rest of the commonly needed e-mail information.

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS 155

7974CH07.qxd 3/21/07 4:45 PM Page 155

Page 181: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Just for completeness, create two new local variables and assign their values based on theFrom and Date fields of the $inbound structure. Add a few log statements that output this infor-mation at the Error severity level so you can see the debug information on the ALSB console asyou run your tests.

Next, you need to add a Route node to the Pipeline Pair to route the request to theMFLBusiness service. Edit the Route node and add a Replace action to the Request Actionssection. Define the XPath as “.” in the variable body. Click the <Expression> link and in theXQuery Expression Editor, click the XQuery Resources link on the page.

Click the Browse button to select the specific XQuery resource you wish to use. In thiscase, the resource is the CustomerEmailToFTP resource you defined earlier.

In the Bind Variables section, the console is asking you to bind the customerEmailFormatvariable (this is an external variable defined in the customerEmailToFTP.xq file you createdearlier) to the local variable that contains that data. That information happens to be at$body/CustomerEmailFormat, so enter that as the binding.

You want to replace the node contents, not the entire body node (see Figure 7-28). Withthis step complete, save everything and activate the change in the Change Center. It’s time totest your service.

Figure 7-28. The Route node to the MFLBusiness service

To make life a little simpler, a MailClient program in the Eclipse ServiceTypes project willsend a properly formatted e-mail to the [email protected] e-mail account. Open the sourcefile for the MailClient.java program in Eclipse and right-click in the source code. Select Run As➤ Java Application from the pop-up menu and the client will send an e-mail. You might haveto wait up to two minutes to see the proxy service receive the e-mail and the MFLBusinessservice fire off the FTP event, but you should see the following output on your WLS console:

<May 11, 2006 6:26:07 PM PDT> <Error> <ALSB Logging> <000000> < [PipelinePairNode1,PipelinePairNode1_request, get email, REQUEST] first name: John, Last Name:Doe,Customer ID: 75><May 11, 2006 6:26:07 PM PDT> <Error> <ALSB Logging> <000000> < [PipelinePairNode1,PipelinePairNode1_request, get email, REQUEST] From: [email protected]><May 11, 2006 6:26:07 PM PDT> <Error> <ALSB Logging> <000000> < [PipelinePairNode1,PipelinePairNode1_request, get email, REQUEST] Subject: Order>

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS156

7974CH07.qxd 3/21/07 4:45 PM Page 156

Page 182: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Next, check the file that was sent to the FTP server and open it up. You should see a filewith a highly decorated name, similar to the following:

c486083985906103420-53cbe67b.10b25da1470.-7e4e.txt.

Open the file to ensure that it’s a properly encoded, tab-delimited file whose contentlooks like the following:

75 Doe,John

What this exercise impresses on us is the amount of coding and complexity that wasinvolved in getting it to work. There are a lot of moving parts in this exercise. It’s pretty cool tosee this beast run. However, this level of complexity runs completely counter to good SOApractices. There’s a reason why e-mail and FTP are considered legacy connection mechanisms.Although it’s good to know you have this level of flexibility with ALSB, you should never con-nect a system of this complexity directly to your main ESB. Instead, you can use specificinstances of ALSB to act as an adapter to these legacy systems, converting these file formatsinto proper XML Schema objects and exchanging the data via web services.

Transport Typed Service: EJBIn the past, you could use a JWS to wrap an EJB and publish it as a service. ALSB now allowsyou to define EJBs as business services and call them directly from a business service. Ourexample will show a SOAP proxy service invoke a stateless session bean (the only kind of EJByou can invoke from ALSB) to calculate the amount of tax on a given price. This exerciserequires the following steps:

1. Create and deploy the EJBBusiness stateless session bean to the WLS.

2. Create a business service that knows how to invoke the EJB.

3. Create a proxy service that returns the tax for any amount given to it.

4. Create the message flow that routes the proxy message to the EJB, then returns thecalculated tax amount via the proxy service.

Creating the EJBBusiness BeanIn the EJBCallout project in Workshop, you can build and deploy the EJBBusiness bean byselecting the project in the Workshop Package Explorer pane and then selecting Project ➤Build Project from the menu bar. You also need to add the project to the WLS (namedalsb_book) so that you can deploy the EJB onto the server. Once you have successfully builtand deployed the EJB, your final step is to create a client JAR file.

You create a client JAR file for an EJB by right-clicking the project name in the PackageExplorer window and then selecting Export from the pop-up menu. This brings up Workshop’sExport dialog (see Figure 7-29). Select “EJB JAR file” from the list of export destinations. Selectthe EJBCallout in the EJB module combo box. For the Destination field, browse to theEJBCallout project directory where your EJBCalloutWorkshop project resides on your harddrive. This creates a JAR file that contains both the implementation files and the client filesfor the EJB.

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS 157

7974CH07.qxd 3/21/07 4:45 PM Page 157

Page 183: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 7-29. Exporting a client JAR file for the EJBCallout project

Let’s take a quick look at the code for this EJB (see Listing 7-10). If you’re an experiencedEJB developer, you’ll quickly appreciate the value that annotation brings to EJB development.

Listing 7-10. The EJBBusiness Bean

package com.alsb.ejb;

import javax.ejb.SessionBean;import weblogic.ejb.GenericSessionBean;import weblogic.ejbgen.Session;import weblogic.ejbgen.JndiName;import weblogic.ejbgen.FileGeneration;import weblogic.ejbgen.Constants;import weblogic.ejbgen.RemoteMethod;

/*** <code>GenericSessionBean</code> subclass automatically generated by Workshop.** Please flush out the {@link #ejbCreate()} method; add all desired* business methods; and review the Session, JndiName, and FileGeneration* annotations to ensure the settings match your intended use.*/@Session(ejbName = "EJBBusiness")@JndiName(remote = "ejb.EJBBusinessRemoteHome")@FileGeneration(remoteClass = Constants.Bool.TRUE,

remoteHome = Constants.Bool.TRUE, localClass = Constants.Bool.FALSE,localHome = Constants.Bool.FALSE)

public class EJBBusiness extends GenericSessionBean implements SessionBean {private static final long serialVersionUID = 1L;

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS158

7974CH07.qxd 3/21/07 4:45 PM Page 158

Page 184: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

/* (non-Javadoc)* @see weblogic.ejb.GenericSessionBean#ejbCreate()*/public void ejbCreate() {

// IMPORTANT: Add your code here}

// IMPORTANT: Add business methods@RemoteMethod(transactionAttribute=Constants.TransactionAttribute.SUPPORTS)public double calculateTax(double taxableAmount) {

return taxableAmount * 0.08d;}

}

The majority of the file is annotation. This greatly simplifies EJB development becauseyou can now generate the boilerplate EJB code from the annotations in the implementationfile.

As you can see in the source code, the tax rate is defined at 8 percent. The method returns8 percent of the taxableAmount argument. No effort is made to qualify the taxable amount(that is, it will calculate negative numbers also) simply because this is demo code.

With your EJB built and deployed, let’s move on to building the business service.

Creating the Business ServiceALSB 2.5 introduced a new resource type: the JAR file. JAR files were introduced specifically tosupport calling EJBs. Just like any other EJB client, ALSB needs a client JAR to access an EJB.Your first step will be to add the client JAR as a resource so that your business service will beable to reference it.

In the ServiceTypes project in the ALSB console, create a new folder named JARs. Thisfolder will hold the client JAR file that you need to access the EJBBusiness EJB. In the new JARsfolder, add a JAR resource. Fill in the fields as shown in Figure 7-30.

Figure 7-30. Defining an EJB client JAR resource

Click the Save button. Next, in the Business Services folder, create a new business servicewith the name EJBBusiness. EJBs are categorized at Transport Typed Services, so select theappropriate radio button. Click the Next button to continue.

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS 159

7974CH07.qxd 3/21/07 4:45 PM Page 159

Page 185: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Select the ejb protocol. For the Endpoint URI use the following:

ejb::EJBBusinessHome

You have the luxury of leaving the <provider> field blank because you’re calling an EJB onthe local machine. If you need to invoke a remote EJB, then read the following section, aboutcreating a JNDI provider and using it in the URI. Click the Next button to continue.

We’ve always felt that the next page in the wizard was cool (see Figure 7-31). ALSB interro-gates the JAR file resource to discover the important aspects of the EJB. Click the Browsebutton for the Client Jar field and select the JAR file you added as a resource earlier in thisexercise. Like magic, the metadata defined in the JAR file is populated into the appropriatefields in the window.

Figure 7-31. Defining the EJB invocation details

By default, the Style is set to Document Wrapped and the Encoding is set to Literal. Theseoptions provide the greatest level of interoperability. Change the name of the parameter totaxableAmount. Click the Next button and then the Save button to save your business service.You can see the WSDL that was generated for the business service by clicking the Export WSDLicon .

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS160

7974CH07.qxd 3/21/07 4:45 PM Page 160

Page 186: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Creating a JNDI ProviderIn our simple example, we left the provider blank because the EJB is deployed onto the sameservers as the service bus. However, in real-world deployments, you’ll often have to create aJNDI provider. In fact, you’ll create a JNDI provider to your local machine, just to get a feel forthe process.

First, navigate to the System Administration ➤ JNDI Providers window. Click the Add but-ton and then fill in the window as shown in Figure 7-32.

Figure 7-32. Defining a JNDI provider

Note the use of the t3 protocol in the provider URL. Only t3 is supported here. Set the UserName and Password fields appropriately (set both to weblogic if you followed the instructionsin Chapter 2 for creating your ALSB domain) and save the JNDI provider. Now you can editthe EJB protocol for the same business service that you defined in this exercise and use thelocalProvider that you just created. The behavior will be the same. The proper Endpoint URIis as follows:

ejb:localProvider:ejb.EJBBusinessRemoteHome

Creating the Proxy ServiceTo create the proxy service, you begin by creating a WSDL folder in the ServiceTypes project.In this new folder, create a WSDL resource. Name the resource EJBTaxProxy, then browse tothe TaxProxy.wsdl file located in the WSDL directory of the EJBCalloutWorkshop project onyour hard drive.

Next, you’ll create the proxy service in the Proxy Services folder. Name the proxy serviceEJBTaxProxy and set the Service Type as a WSDL Web Service. Click the Browse button tobrowse for the WSDL resource that you just added. Once you’ve selected the WSDL, click theNext button.

Select the protocol to be HTTP. Set the Endpoint URI to /EJBTaxProxy. Click the Next but-ton. Accept the default values in the next two windows and then click the Save button to saveyour proxy service.

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS 161

7974CH07.qxd 3/21/07 4:45 PM Page 161

Page 187: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Creating the Message FlowThe last item you need to create is the message flow that routes the data from the proxy serv-ice to the business service. Open the message flow for the proxy service, and create a Routenode. Edit the Route node and set it to route to the EJBBusiness service, invoking thecalculateTax operation, as shown in Figure 7-33.

Figure 7-33. Route node for the EJBBusiness message flow

You need an Assign action to assign the value of the expression:

$body/alsb:calculateTaxRequest/alsb:taxableAmount/text()

Set the value to a local variable named amount. Next, you need a Replace action to replacethe contents of the entire SOAP Body element contained in the $body variable with the follow-ing expression:

<open:calculateTax><open:taxableAmount>{$amount}</open:taxableAmount>

</open:calculateTax>

Notice that the business service uses the namespace label open. For the preceding expres-sion to be valid, you need to define the open namespace in the ALSB console. To define thenamespace, click the Add Namespace link in the expression editor. This link is highlighted inFigure 7-34.

Remember that namespaces are defined by their text value, not by their labels. Therefore,it’s critical that you get the string values correct. We spent 20 minutes debugging this simpletransformation simply because we had originally omitted the trailing slash and defined thenamespace as http://www.openuri.org instead of http://www.openuri.org/!

After you complete the Route node, including the creation of the user-defined open name-space, save all your work and then activate the change. Test the service by placing differentamounts into the test browser to see the responses.

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS162

7974CH07.qxd 3/21/07 4:45 PM Page 162

Page 188: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 7-34. Adding a user-defined namespace

Why Use EJBs?There are a lot of EJBs in the world. Odds are pretty good that if your company uses J2EE, thenyou have legacy EJBs that implement business logic. It might make sense for you to wrap theseEJBs in web services to make them more easily accessible to your enterprise. ALSB allows youto connect to these assets without recompiling them or otherwise having to modify them,thereby reducing the level of effort to publish the functionality of these EJBs.

However, there’s a downside to this strategy, or at least a subtle and insidious danger. EJBsare usually not written with services in mind. Entity EJBs usually contain little abstractionfrom the data source and primarily function as a mechanism to mediate between data con-sumers and the database. Even stateless session beans, implementing the Façade pattern tohide the complexity of underlying EJB interdependencies, are rarely written to service-oriented standards. Publishing them directly as services might well reduce the level of abstrac-tion and loose coupling in your ESB. Low-level implementation details contained in commonEJB interfaces can have a dire effect on an enterprise-level service bus.

Although it’s possible to write service-oriented EJBs, it’s rare that an EJB is written to thatlevel. By their very nature, EJBs are designed to implement IT and business concepts close tothe physical level. Usually you’ll find it necessary to create proxy services at a greater level ofabstraction. These proxy services act more as an adapter for the EJBs. It’s these low-level proxyservices that can then participate in the overall SOA.

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS 163

7974CH07.qxd 3/21/07 4:45 PM Page 163

Page 189: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

POJOAnother new feature of ALSB, introduced in version 2.5, is the ability for a Service Calloutaction to invoke Java code directly. Colloquially known as POJOs (an acronym for Plain OldJava Objects), they are simple Java classes without the overhead associated with EJBs and JavaWeb Services.

The benefit of POJOs is that they are technically simple to create and have little overhead,at least compared to an EJB. The drawbacks of the POJO are the same as the benefits. Becausethey have little overhead, there’s no thread management (as you would have in a J2EE con-tainer), and their very simplicity means that without some sort of IT governance, anyone whocan write even the simplest Java code can create resources for your service bus. Use POJOswith caution.

There’s an important restriction to using a POJO in ALSB: only static methods are recog-nized by the service bus. However, there’s nothing to stop you from instantiating Java objectsor threads from within the POJO itself. This is similar to EJBs where the J2EE specificationstates that you may not create threads within an EJB, but it’s still possible to do it. Similarly,BEA strongly discourages the creation of threads and object instantiation within a POJO.

Okay, with all the legal disclaimers aside, let’s hammer out a POJO to see just how easy itis. Listing 7-11 shows the source code for a simple POJO that, like the previous EJB exercise,calculates the 8 percent tax of any amount that you give it. Now this is easy code!

Listing 7-11. A Sample POJO

package com.alsb.pojo;public class Pojo {

/*** ALSB can only call static methods in a POJO.* @param taxableAmount* @return The additional tax to be paid*/public static double calculateTax(double taxableAmount) {

double taxRate = 0.08;return taxableAmount * taxRate;

}}

You can find this code in the ServiceTypes project in Workshop. If you wish to create yourown POJO project, simply follow these steps:

1. Create a new Java project in Workshop. Name it POJO.

2. Add a source code folder to the project. Traditionally, this is named src.

3. Create a package in the source code folder called com.alsb.pojo.

4. Create a new Java class in the com.alsb.pojo package. Name the class Pojo and use thecode in Listing 7-11 to define the class.

5. To build the project, right-click the POJO project in Workshop and select Build Projectfrom the pop-up menu.

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS164

7974CH07.qxd 3/21/07 4:45 PM Page 164

Page 190: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

6. After the project is built, you need to create a JAR file for the Pojo project. Right-clickthe Pojo project and select Export from the pop-up menu.

7. In the Export dialog, select “JAR file” from the list of file types you can export. Click theNext button.

8. Select the file name and the destination of your JAR file. We prefer to put them in theroot directory of our projects, as shown in Figure 7-35.

9. Click the Finish button.

Figure 7-35. Specifying the location of the JAR file

This builds the JAR file for the POJO project. Next, you need to import it into ALSB for usein an ALSB project.

Back in the ALSB console, navigate to the JARs directory in the ServiceTypes project. Adda new JAR resource, name the resource Pojo, and select the pojo.jar file that you just compiled.

Next, navigate to the Proxy Services directory in your ServiceTypes ALSB project and cre-ate a new proxy service called PojoProxy. Select the Message Type radio button under ServiceType and click the Next button. Select Text for both the request message and the responsemessage (we’re more concerned with demonstrating the invocation model of a POJO in thisexercise than we are with rehashing our previous integration demonstrations), and click theNext button.

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS 165

7974CH07.qxd 3/21/07 4:45 PM Page 165

Page 191: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Set the protocol to HTTP and the Endpoint URI to /PojoProxy. Accept the default valuesfor the rest of the Proxy Service wizard and save the proxy service. Next, you need to create amessage flow for the proxy.

Add a Pipeline Pair to the message flow. In the request pipeline, create a calculate taxstage. Create a return tax due stage in the response pipeline. Edit the calculate tax stage.

In the calculate tax stage (shown in Figure 7-36), add an Assign action that assigns thevalue of the $body/text() expression to the taxableAmount local variable.

Figure 7-36. The “calculate tax” stage definition

Next, add a Java Callout action. Click the Method link, then click the Pojo link in theSelect a JAR window. This brings up the Select a Class and Method window, as shown inFigure 7-37.

Figure 7-37. Selecting a class and method

Click the plus sign next to the com.alsb.business.Pojo line to expose the methods avail-able. Click the radio button for the calculateTax() method and click the Submit button. Fill inthe fields of the Java Callout so that it matches those shown in Figure 7-37. Save this stage.

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS166

7974CH07.qxd 3/21/07 4:45 PM Page 166

Page 192: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Next, edit the return tax due stage in the response pipeline. Because you didn’t route to aservice, the Pipeline Pair simply echoes the request document back to you, but you can placea Log action in this stage so that you can see the results of the Pojo invocation. Use the follow-ing expression in the Log action:

concat('Tax due is ', $taxDue)

Save all your work and activate the change in the Change Center. When you test the serv-ice you just enter a number in the large text area. There is no XML involved in this invocation.Look in the WebLogic console to see the log output and verify that the POJO executed prop-erly.

In the real world you probably wouldn’t use a POJO to calculate a tax. In the United States,tax rates vary at the federal, state, and local levels, depending on the product. Most countrieshave similarly complex rules and calculations for their taxes. However, there are some applica-tions where a POJO makes sense. If you have logic that’s better expressed in Java code than it isin a database or an XQuery, POJOs are a perfect match.

SOAP with AttachmentsIt’s possible to send a SOAP message with one or more attachments. This is similar to attach-ing a file to an e-mail. ALSB supported SOAP with Attachments starting in version 2.0. SOAPwith Attachments supports any arbitrary MIME type. Typically, attachments are defined in theWSDL, as you will do in this exercise. However, no special considerations are required whendefining the WSDL for the proxy service, because attachments can be considered orthogonalto the message content and data types.

■Best Practice Declare all expected or optional attachments to operations in the WSDL.

Your business service is located in the SOAPwithAttachment project in Workshop. Thisservice has one operation that takes a message that contains a String file name and a MIMEattachment as the arguments. The operation then returns the name of the newly created localfile. You’ll use this to send the name of a ZIP file, plus the file itself, to the business service. Thebusiness service will then save the attachment to the local file system (in the root directory ofthe C: drive).

Listing 7-12 shows the WSDL for the business service. The important parts of the WSDLare in bold to highlight them. To define attachments in your WSDL, you need to change themessage that will carry the attachment and the soap:operation that handles the message. Inthis case, only the <input> message of the operation is concerned with the attachment. How-ever, you can also have an operation return (that is, <output>) a message with an attachment.

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS 167

7974CH07.qxd 3/21/07 4:45 PM Page 167

Page 193: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Listing 7-12. The WSDL for the SOAPwithAttachment Business Service

<?xml version="1.0" encoding="UTF-8"?><wsdl:definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"

xmlns:tns="http://www.alsb.com/SOAPwithAttachment/"xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/"name="SOAPwithAttachment"targetNamespace="http://www.alsb.com/SOAPwithAttachment/"><wsdl:types>

<xsd:schematargetNamespace="http://www.alsb.com/SOAPwithAttachment/"><xsd:element name="submitAttachmentResponse" type="xsd:string" /><xsd:element name="fileName" type="xsd:string" />

</xsd:schema></wsdl:types>

<wsdl:message name="submitAttachmentResponse"><wsdl:part element="tns:submitAttachmentResponse"

name="submitAttachmentResponse" /></wsdl:message>

<wsdl:message name="submitAttachment"><wsdl:part element="tns:fileName"

name="fileName" /><wsdl:part name="file" type="xsd:base64Binary" />

</wsdl:message>

<wsdl:portType name="SOAPwithAttachmentPort"><wsdl:operation name="submitAttachment">

<wsdl:input message="tns:submitAttachment" /><wsdl:output message="tns:submitAttachmentResponse" />

</wsdl:operation></wsdl:portType>

<wsdl:binding name="SOAPwithAttachmentSOAP"type="tns:SOAPwithAttachmentPort"><soap:binding style="document"

transport="http://schemas.xmlsoap.org/soap/http" /><wsdl:operation name="submitAttachment">

<soap:operationsoapAction="http://www.example.org/SOAPwithAttachment/➥

submitAttachment" /><wsdl:input>

<mime:multipartRelated><mime:part>

<soap:body parts="fileName" use="literal" />

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS168

7974CH07.qxd 3/21/07 4:45 PM Page 168

Page 194: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

</mime:part><mime:part>

<mime:content part="file" type="application/zip" /></mime:part>

</mime:multipartRelated></wsdl:input><wsdl:output>

<soap:body parts="submitAttachmentResponse" use="literal" /></wsdl:output>

</wsdl:operation></wsdl:binding>

<wsdl:service name="SOAPwithAttachment"><wsdl:port binding="tns:SOAPwithAttachmentSOAP"

name="SOAPwithAttachmentSOAP"><soap:address location="http://localhost:7001/SOAPwithAttachment" />

</wsdl:port></wsdl:service>

</wsdl:definitions>

First, you’ll create a new WSDL resource in the WSDL folder for your business service. Usethe Resources from URL option to import the WSDL from its URL. This ensures that the busi-ness web service has been compiled and deployed properly onto your server. The followingURL points to the WSDL on your server:

http://localhost:7001/SOAPwithAttachments/SOAPwithAttachment?WSDL

Name the WSDL SOAPwithAttachment and complete the import process.Next, move into the Business Service folder of the ServiceTypes project and create a new

business service named SOAPwithAttachmentBusinessService. Base this business service onthe WSDL that you just imported. Click the Last button to skip the other pages of the wizard.Then click the Save button to save this business service.

Next, create a proxy service named SOAPwithAttachmentProxy in the Proxy Services folder.You’ll base this proxy service directly on the SOAPwithAttachmentBusinessService. Accept alldefault values for the proxy service and then save it.

The test console is insufficient for testing services with attachments. As a result, you needto create a client for your proxy service in Java code. You’ll use this client to test your serviceand ensure that the attachment is passed through the proxy service to the business serviceand ultimately saved as a file on the local hard drive.

The client code relies on the existence of a test.zip file in the root directory of the C:drive. You can create any ZIP file and simply save it as C:\test.zip to meet the needs of yourclient. We like using ZIP files for attachments for two reasons:

• They are commonly used as attachments in the real world.

• You can easily tell if a ZIP file is corrupted because it won’t open.

Your client project is located in the Workshop project named SOAPwithAttachmentClient.You use the build.xml file for building and running the client. Open the build.xml file in Work-shop and be sure that the Outline window is open also. The Outline window shows you the Ant

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS 169

7974CH07.qxd 3/21/07 4:45 PM Page 169

Page 195: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

tasks that you can run. Begin by running the generate task, followed by the build task, andfinally execute the run task. Assuming that everything went properly, you should now find atestX.zip file in the root directory of your C: drive. Open this file and confirm that the contentsmatch the contents of the original test.zip file.

Now that you have a proxy service that can accept attachments, it’s time to explore whatyou can do with these attachments in the proxy service. The possibilities are almost limitless,but we’ll confine ourselves to some of the more basic tasks that demonstrate how you interactwith attachments in a proxy service.

In the ALSB console, create a new change in the Change Center and then open up themessage flow for the SOAPwithAttachmentProxy service. The message flow should only containtwo nodes: a Start node and the Route. Click the Start node and add a Pipeline Pair. In therequest pipeline, add a new stage and name it examine attachment. Next, edit the examineattachment stage.

You’re going to add a few logging statements so you can see the type of metadata that’sassociated with attachments. Start by adding an Assign statement that assigns the expressionfn:count($attachments/attachment) to a variable named numAttachments. The $attachmentsstructure contains all the attachments that are associated with a message. Each child attach-ment has a specific structure. The structure and the meaning of the fields are shown inTable 7-2.

Table 7-2. Attachment Metadata

Field Description

Content-ID The MIME type ID for the content. This is reported to be aglobally unique value, but we find it tends to be the partname from the <mime:content part="" .../> section of the<soap:operation> declaration in the WSDL file. If you run thisexample, you’ll see that the Content-ID value is file.

Content-Type The MIME type for the content. This is represented as major typeor subtype. In your WSDL you declared the attachment to be anapplication/zip. Your debugging statement will show it as anapplication/octet-stream.

Content-Transfer-Encoding Specifies how the attachment is encoded. This is sometimesempty.

Content-Description A text description of the content. This is sometimes empty.

Content-Location A locally unique URI that identifies the attachment. This issometimes empty.

Content-Disposition Declares how the attachment is to be handled. This is sometimesempty.

body Holds the attachment data.

Figure 7-38 shows a set of actions in the examine attachments stage that loop through allthe attachments of a message.

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS170

7974CH07.qxd 3/21/07 4:45 PM Page 170

Page 196: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 7-38. An example of looping through the attachments of a message

The Log action nested in the For Each action contains a single statement that sends all theattachment information to the test console of ALSB where you can read it. This rather com-plex statement follows:

concat('Attachment ', string($index), ' of ', string($totalAttachments),fn:codepoints-to-string(10),'Content-ID: ', $attach/ctx:Content-ID, fn:codepoints-to-string(10),'Content-Type: ', $attach/ctx:Content-Type, fn:codepoints-to-string(10),'Content-Transfer-Encoding: ', $attach/ctx:Content-Transfer-Encoding, fn:codepoints-to-string(10),'Content-Description: ', $attach/ctx:Content-Description, fn:codepoints-to-string(10),'Content-Location: ', $attach/ctx:Content-Location, fn:codepoints-to-string(10),'Content-Disposition: ', $attach/ctx:Content-Disposition, fn:codepoints-to-string(10),'body: ', $attach/ctx:body, fn:codepoints-to-string(10))

By the way, you use the fn:codepoints-to-string(10) function to print a newline charac-ter to the console to make the text output more legible.

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS 171

7974CH07.qxd 3/21/07 4:45 PM Page 171

Page 197: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

SummaryYou might have noticed that this is one of the longest chapters in the book, and for good rea-son: ALSB provides you with myriad ways of connecting to and communicating with externalsystems. It provides an excellent mechanism for performing intelligent routing and data trans-formation. We’ve gone into great detail here and exercised almost every major capability of theservice bus. At this point you should have a solid understanding of the primary capabilities ofALSB, and therefore a good idea of where you could use ALSB within your architecture.

CHAPTER 7 ■ ADVANCED MESSAGING TOPICS172

7974CH07.qxd 3/21/07 4:45 PM Page 172

Page 198: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Reporting and Monitoring

Although reporting and monitoring are discrete capabilities of the service bus, they’reclosely related. Monitoring is the ability to collect runtime information, while reporting isfocused on delivering message data and alerts. There’s also some overlap between monitoringand reporting. For example, you can monitor the number of alerts that have been reported.Monitoring is focused on operational information: the general health of the service bus, howmany alerts have been generated and of what type, the status of Service Level Agreements(SLAs), and the gathering of related statistics. A simple way to differentiate between monitor-ing and reporting is this: monitoring is strategic, reporting is tactical.

MonitoringFigure 8-1 shows the operational health of your ESB. This is the default view of the servicebus console. You can see this on your service bus by pointing your browser at http://localhost:7001/sbconsole. The Service Summary portlet shows the number and severity ofall alerts thrown into the alert log within the last 30 minutes. Because you have no alertsdefined yet, your Service Summary should show no alerts at this time.

The Server Summary portlet on the right shows the overall health of the servers in yourcluster. Because your domain contains only a single server, the entire pie chart represents thissingle server and should be colored all green to indicate that your single server is runningjust fine. If you were running a cluster of service bus servers, the pie chart would be dividedamong the different servers. However, to run a cluster of servers, you must have a clusterlicense from BEA, and cluster licenses are not freely downloadable.

Both the Service Summary and Server Summary portlets show, in addition to theirrespective pie charts, up to ten of the top alerts and most critical servers. You can click theinformation in these summaries and drill down into greater detail. This information is pro-vided by the WebLogic Diagnostic Framework.

At the bottom of the page is the Alert Summary portlet that shows all the alerts over theinterval used by the Service Summary portlet. You can customize this portlet by selecting onlythe fields you want displayed. By default, all fields are displayed (that is, severity, time stamp,service, and Alert Rule name). We’ll cover alert creation later, in the “Reporting” section.

Typically, an operator looks at this window and is aware of a problem when an alert isgenerated. The window automatically refreshes after every minute, but the interval is config-urable. When an alert is generated, the operator will drill down into details for the service,including detailed performance reporting windows.

173

C H A P T E R 8

7974CH08.qxd 3/28/07 12:43 PM Page 173

Page 199: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 8-1. The Dashboard

The Temperamental ServiceAs long as all your services are working as expected, the Monitoring portlet is quite boring. Tojazz things up a bit, you need to create a web service whose performance you can control pro-grammatically. You also need to create some SLAs so that your web service can violate thoseagreements, and you need to throw some alerts into the monitoring portlet. To achieve this,you’ll create two web services that contain various operations. These web services will containa built-in delay mechanism. You need to be able to set the delay value from your client so youcan be sure to violate your SLAs at will. Finally, you’ll create a client program that can invokeyour web services to help you test various scenarios and to illustrate the monitoring capabili-ties of the service bus.

Creating the Business ServicesListing 8-1 shows the source code from the business service. The service provides threedifferent operations. Each operation will respond back to the caller within a semi-randomtimeframe. The time delays are contained in the behaviors array. Compile and deploy thisweb service before moving to the next step, in the section “Creating the ALSB Project.”

CHAPTER 8 ■ REPORTING AND MONITORING174

7974CH08.qxd 3/28/07 12:43 PM Page 174

Page 200: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Listing 8-1. The TemperamentalCreditService

package business;import javax.jws.*;import javax.jws.soap.SOAPBinding;import weblogic.jws.WLHttpTransport;import weblogic.jws.WSDL;

@WebService(targetNamespace="http://www.alsb.com",serviceName="TemperamentalCreditBS", name="TCrBS")

@WLHttpTransport(serviceUri="business/credit", portName="TCrBSSoapPort")@WSDL(exposed=true)@SOAPBinding(parameterStyle=SOAPBinding.ParameterStyle.WRAPPED)public class TemperamentalCredit {

/** The amount of time (in seconds) the web service will delay */private static int DELAYINSECONDS = 0;

@WebMethodpublic String variableCreditCheck(String arg0) {

delay();return arg0 + DELAYINSECONDS;

}

@WebMethodpublic String variableOpA(String arg0) {

delay();return arg0 + DELAYINSECONDS;

}

@WebMethodpublic String variableOpB(String arg0) {

delay();return arg0 + DELAYINSECONDS;

}

@WebMethodpublic String variableOpC(String arg0) {

delay();return arg0 + DELAYINSECONDS;

}

@WebMethodpublic String rapidCreditCheck(String arg0) {

return arg0;}

CHAPTER 8 ■ REPORTING AND MONITORING 175

7974CH08.qxd 3/28/07 12:43 PM Page 175

Page 201: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

@WebMethodpublic int setDelay(int delayInSeconds) {

DELAYINSECONDS = delayInSeconds;return DELAYINSECONDS;

}

private void delay() {try {

Thread.sleep(DELAYINSECONDS * 1000);} catch(InterruptedException ex) {

ex.printStackTrace();}

}}

The code itself is straightforward. Near the end of the listing is the setDelay() operation.This operation allows the service test client to set the delay (in seconds) that it wants eachof the other operations to use. The other operation call the delay() operation, which sleepsthe thread for the specified number of seconds. The methods variableCreditCheck(),variableOpA(), variableOpB(), and variableOpC() all delay for whatever amount of time isspecified. Only the rapidCreditCheck() operation ignores the delay and returns immediately.We’ll use this operation later to show how you can fail over between services.

The second web service is the TemperamentalCustomerService. However, because itsimplementation is remarkably similar to that of the TemperamentalCreditService, we won’tbother to list it in the text.

Creating the ALSB ProjectYour next step is to create a project named Temperamental in the ALSB console. In this projectyou need to create WSDL resources, based on the WSDLs of the business services. If you suc-cessfully compiled and deployed the business services in the previous step, you can get theWSDLs of the services at

http://localhost:7001/TemperamentalService/business/credit?WSDL

and

http://localhost:7001/TemperamentalService/business/customer?WSDL

Once you have the WSDL resource created, create the business service for the WSDL.Name the business services TemperamentalCreditBS and TemperamentalCustomerBS, respec-tively. Next, create proxy services named TemperamentalCredit and TemperamentalCustomerand set the URLs for the proxy services to /esb/TemperamentalCredit and /esb/TemperamentalCustomer. Once you create the proxies, you need to edit the Route nodes of

CHAPTER 8 ■ REPORTING AND MONITORING176

7974CH08.qxd 3/28/07 12:43 PM Page 176

Page 202: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

each message flow. Your proxy services only need to pass the message from the service clientthrough to the business service. Figure 8-2 shows how simple this is. Just check the “Useinbound operation for outbound” checkbox. This allows your proxy to route to the correctoperation on the business service, based on the name of the inbound service operation.

Figure 8-2. Creating a simple “pass-through” Route node

Defining the Service Level AgreementsCreating an SLA is almost an art form. Often, you’ll hear people talk about setting SLAs todetect failures. This is certainly a good idea, but if you only create SLAs to detect failures,you’re doing your customers a disservice! We believe it’s even more important to create SLAsthat show successful service calls that are approaching their performance limit. For example,if your service must be able to respond to a service request in less than 2 seconds, and nor-mally responds to these requests in 0.8 seconds, you should consider using multiple SLAs:one for the failure condition (that is, > 2 seconds) and others to help alert your operationsteam when the service time begins to exceed its normal time (that is, > 1 second and possibly> 1.8 seconds). The purpose of the SLA is not only to notify you of a failure, but to act as a toolto help you prevent failures in the first place!

SLAs are based on alerts. Alerts are comprised of an Alert Destination and one or moreAlert Rules. To help you understand the capabilities of ALSB monitoring, and following thetrue nature of this book, let’s dive right in and create a few SLAs for our TemperamentalProxyservice. Be sure you’ve started a change in the Change Center. Your first action is to create anew resource in your Temperamental project: a Notification type of resource called an AlertDestination. Name this Alert Destination “Console Alert” and fill in the rest of the parametersas shown in Figure 8-3.

CHAPTER 8 ■ REPORTING AND MONITORING 177

7974CH08.qxd 3/28/07 12:43 PM Page 177

Page 203: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 8-3. Creating an Alert Destination

As you can see from the Alert Destination creation window, alerts can be sent to themonitoring console, an SNMP trap, a report, an e-mail address, JMS queues, or a combinationof any of the aforementioned tools. For our purposes, we need to create a destination thatreports solely to the console for now. Click the Save button. With our Alert Destination cre-ated, let’s create some rules for our Temperamental services. Click the Monitoring icon for theproxy service, as shown in Figure 8-4.

Figure 8-4. The location of the Monitoring icon

CHAPTER 8 ■ REPORTING AND MONITORING178

7974CH08.qxd 3/28/07 12:43 PM Page 178

Page 204: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

This brings up the Monitoring Configuration window, as shown in Figure 8-5. Be sure thatthe checkboxes to Enable Service and Enable Monitoring are checked. For this exercise, goahead and set the Aggregation Interval to ten minutes and click the Update button. Thisenables the Add New button at the bottom of the page. The aggregation interval is the movingwindow of time over which the statistics for the service are aggregated. The window movesforward every minute.

Figure 8-5. Enabling monitoring of a service

Let’s create an alert. Click the Add New button. Your first alert will be to report on failuresof the variableCreditCheck() maximum response time. For this operation, a failure occurs ifthe maximum response time exceeds 20 seconds.

Name the new rule Credit Check Failure and fill in the remainder of the page as shown inFigure 8-6. A few fields here are worthy of special mention. First are the Start Time, End Time,and Rule Expiration Date fields. These fields allow you to specify when you want the rule toapply. For example, you might set the rule to apply from midnight to one minute before mid-night each day until Jan 1, 2100 (effectively forever). You might want to monitor performancefor only part of each day as part of your SLA. This would allow you to be concerned with theperformance during working hours, or hours that are important to the consumers of yourservices. Similarly, providing an end date for the monitoring might make sense if your serviceconsumer is only concerned about the performance for a limited number of days (that is,during a sales promotion, or similar promotional activity).

CHAPTER 8 ■ REPORTING AND MONITORING 179

7974CH08.qxd 3/28/07 12:43 PM Page 179

Page 205: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 8-6. Creating an Alert Rule

The Rule Enabled field allows you simply to turn the rule on or off, as needed. Becausemonitoring does consume extra clock cycles on the servers, some customers run with themonitoring turned off for maximum efficiency. Some companies only monitor services whenthey are first introduced into production. After those new services have run without any prob-lems for a week or so, these companies relax or eliminate their monitoring. There is no rightway to monitor your services. It all depends on your specific needs.

The Alert Severity field allows you to specify the severity level of the alert. You may choosefrom Normal, Warning, Minor, Major, Critical, and Fatal. The Alert Frequency field allows youto define when the alert is fired, either Every Time or “Once when Condition is True.” The lastfield on this window is Stop Processing More Rules. Select Yes if the alert is so bad that youwant all further rule processing to stop. Normally you leave this field set to the No position.

■Tip Name your alerts carefully. If your alert is specific to an operation in the web service, then we recom-mend that you put the operation name into the name of the alert. However, if the alert applies to the entireservice, there’s no need to include the service name in the alert, simply because the table of alerts in themonitoring console will show the name of the service.

Click the Next button, and a new window appears that allows you to define the conditionsthat trigger the alert. These rules are completely customizable. Before you configure your con-ditions, let’s take a walk through the types of conditions you can detect in ALSB (see Table 8-1).

CHAPTER 8 ■ REPORTING AND MONITORING180

7974CH08.qxd 3/28/07 12:43 PM Page 180

Page 206: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Table 8-1. Alert Expressions

Type Subtype Description

Count Success Ratio (%) Test against the percentage ofsuccessful service calls andoperations.

Count Failure Ratio (%) Test against the percentage offailed service calls andoperations.

Count Message Count Test against the number ofmessages sent across servicesand operations.

Count Error Count Test against the number ofmessages that have errors.

Count Validation Error Count Test against the number ofmessages that have validation.

Count Operation.<operation name>.Message Count Test against the number ofmessages routed to a specificoperation.

Count Operation.<operation name>.Error Count Test against the number of errorsgenerated from a specificoperation.

Count <flow element>.Message Count Test against the number ofmessages sent to a specific flowelement.

Count <flow element>.Error Count Test against the number of errorsgenerated from a specific flowelement.

Count WSS Error Count Test against the number of WebService Security–related errors.

Minimum Response Time Test against the minimumresponse.

Minimum <flow element>.Response Time Test against the minimumresponse time for all invocationsof this flow element.

Minimum Operation.<operation name>.Response Time Test against the minimumresponse time to a specificoperation.

Maximum Response Time Test against the maximumresponse.

Maximum <flow element>.Response Time Test against the maximumresponse time across allinvocations of the specifiedservice.

Maximum Operation.<operation name>.Response Time Test against the maximumresponse time to a specificoperation.

Average Response Time Test against the average response.

Continued

CHAPTER 8 ■ REPORTING AND MONITORING 181

7974CH08.qxd 3/28/07 12:43 PM Page 181

Page 207: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Table 8-1. Continued

Type Subtype Description

Average RouteTo_<service name>.Response Time Test against the average responsetime of all operations within aspecific service.

Average RouteTo_<operation name>.Response Time Test against the average responsetime of a specific operation.

■Tip Name your alerts carefully. If your alert is specific to an operation in the web service, then we recom-mend that you put the operation name into the name of the alert. However, if the alert applies to the entireservice, there’s no need to include the service name in the alert, simply because the table of alerts in themonitoring console will show the name of the service.

A <flow element> is one of the following:

• A request pipeline in a Pipeline Pair

• A response pipeline in a Pipeline Pair

• A Route node

As an example, if you’re looking at the Count type for a service that contains a PipelinePair named Pipeline1, you would see the following subtypes in the combo box:

Pipeline1.request.Error Count

Pipeline1.response.Error Count

As you can see from Table 8-1, there are a considerable number of conditions againstwhich you can test. Knowing what to test and how to test is simply something that cannot belearned from a book. It’s highly specific to your services and the SLAs that your companywants to meet.

Let’s create an Alert Rule. For your first rule, you want to select Maximum from the combobox on the left. In the next combo box, select Operation.variableCreditCheck.Response Time.In the third checkbox, select the “>” (greater than) comparator. Finally, in the textbox, enter20000 to represent 20 seconds. Your window should look like Figure 8-7. When all this informa-tion is correct, click the Add button to create the simple expression.

CHAPTER 8 ■ REPORTING AND MONITORING182

7974CH08.qxd 3/28/07 12:43 PM Page 182

Page 208: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 8-7. Defining conditions for an alert

Click the Finish button to tell the service bus that you’re done with that expression. Thenclick the Save button to save your changes. Congratulations; you’ve just created your first alert.

■Tip It’s important to remember that this time, values are all specified in milliseconds. Jeff here—I can’ttell you how many times I’ve had to debug a rule because I did something silly. For example, I’ve accidentallycreated rules such as Operation.foo.Response Time > 2000 and Operation.foo.Response Time < 3.Obviously, the rule itself is invalid. If you find that some of your alerts aren’t firing off as expected, take acloser look at the time values you’ve specified for each rule.

At this point, you have a single alert that will fire upon a fatal condition becoming true.If this happens, your whole pie chart will turn black (the color of a fatal alert). To make thingsmore interesting, you need more alert types to be fired, and that means you need more alertsdefined in the system. Your next alert will be to create a warning if the maximum responsetime is greater than two seconds but less than three seconds. This requires you to create acomplex statement. Fortunately, the process for creating a complex statement is simple.

Navigate back into the Monitoring Configuration window for the TemperamentalCreditproxy service. Click the Add New button to create a new alert. Name the alert OpA Warn to indi-cate that the nature of the alert is a warning on the OpA operation performance. Be sure to setthe severity field to Warning and click the Next button.

Now you’re ready to create your complex expression. Complex expressions are merely twoor more simple expressions linked together via a conjunction (and/or). Begin by creating twosimple expressions. The first expression is to test for the maximum response time of OpA to be> 2000. Click the Add button and then create the second simple expression: max OpA responsetime < 3001. Click the Add button again so that both simple expressions are now listed in theComplex Expression section of the window, as shown in Figure 8-8.

CHAPTER 8 ■ REPORTING AND MONITORING 183

7974CH08.qxd 3/28/07 12:43 PM Page 183

Page 209: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 8-8. Creating a complex expression for an alert

Notice at this point that the Finish button at the bottom of the window is grayed out.That’s because you have two simple expressions defined, but you haven’t connected themwith an And or Or conjunction to create a single complex expression. Click the checkboxes nextto each expression and then click the And button. Voilà! You’ve created a complex expression.

If you look carefully at the complex expression in Figure 8-9, you’ll notice there are paren-theses around the newly created expression. It should also be obvious that you can now addmore simple expressions and combine them into complex expressions. You can also combinemultiple complex expressions into expressions of even greater complexity. There’s no limit tothe complexity of the expressions you can create here. Of course, evaluating expressions takestime, so it’s best to keep your expressions as simple as possible.

Figure 8-9. A fully formed complex expression

You have several more rules to create. Table 8-2 provides a summary of the rules. You’vealready created the first two rules in the table; you’ll need to add the rest of the rules to keepyour monitoring display in sync with the rest of this text.

CHAPTER 8 ■ REPORTING AND MONITORING184

7974CH08.qxd 3/28/07 12:43 PM Page 184

Page 210: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Table 8-2. TemperamentalCredit Alert Rules

Name Expression

Credit Check Failure Maximum Operation.variableCreditCheck.Response Time > 20000

OpA Warn Maximum Operation.OpA.Response Time > 2000 and < 3001

OpB Minor Maximum Operation.OpB.Response Time > 3000 and < 5001

OpC Major Maximum Operation.OpC.Response Time > 5000 and < 10001

Additionally, you need to create two rules for the TemperamentalCustomer service, asshown in Table 8-3.

Table 8-3. TemperamentalCustomer Alert Rules

Name Expression

getVariableCustomer Critical Maximum Operation.getVariableCustomer.Response Time >10000 and < 20001

OpA Fatal Maximum Operation.OpA.Response Time > 20000

Save all your work so far. It’s time to create your service client to invoke these services andcause your newly created alerts to fire!

Coding the Proxy ClientYour proxy client (see Listing 8-2) works like most of the POJO clients you’ve created so far.In WebLogic Workshop, open up the TemperamentalServiceClient project. Within the project,open the build.xml Ant script and execute the all target. When that target completes, executethe run.wsclient target to run the LoadTestClient against the proxy services.

Listing 8-2. LoadTestClient.java

package proxy;import proxy.TemperamentalCustomerBS;

public class LoadTestClient {private static final String customerUrl = "http://localhost:7001/esb/TemperamentalCustomer?WSDL";private static final String creditUrl = "http://localhost:7001/esb/TemperamentalCredit?WSDL";private static TCrBS creditPort = null;private static TCBS customerPort = null;

public static void main(String[] args) {runMonitoringTest();// Uncomment the following line to run the// failover test in chapter 9//runServiceFailoverTest();

}

CHAPTER 8 ■ REPORTING AND MONITORING 185

7974CH08.qxd 3/28/07 12:43 PM Page 185

Page 211: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

/*** Perform the necessary housekeeping to connect to the * proxy services*/private static void loadServiceReferences() {

try {System.out.println("Opening the credit service as " + creditUrl);TemperamentalCreditBS creditService =

new TemperamentalCreditBS_Impl(creditUrl);creditPort = creditService.getTCrBSSoapPort();System.out.println("Opening the customer service as " + customerUrl);TemperamentalCustomerBS customerService =

new TemperamentalCustomerBS_Impl(customerUrl);customerPort = customerService.getTCBSSoapPort();

} catch(Exception ex) {ex.printStackTrace();

}}

private static void runMonitoringTest() {try {

loadServiceReferences();System.out.println("Invoking the methods...");// Generate a warning on Op AcreditPort.setDelay(2);creditPort.variableOpA("foo");// Generate a minor alert on Op BcreditPort.setDelay(3);creditPort.variableOpB("foo");// Generate a major alert on Op CcreditPort.setDelay(6);creditPort.variableOpC("foo");// Generates a fatal alertcreditPort.setDelay(25);creditPort.variableCreditCheck("William Smith");// Generate a critical customer alertcustomerPort.setDelay(12);customerPort.getVariableCustomer(2);// Generate a fatal customer alertcustomerPort.setDelay(25);customerPort.getVariableCustomer(2);

} catch(Exception ex) {ex.printStackTrace();

}}

CHAPTER 8 ■ REPORTING AND MONITORING186

7974CH08.qxd 3/28/07 12:43 PM Page 186

Page 212: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

private static void runServiceFailoverTest() {try {

loadServiceReferences();// Generate a critical customer alertcreditPort.setDelay(60);String creditRating = creditPort.variableCreditCheck("timeout");System.out.println("Credit rating is: " + creditRating);

} catch(Exception ex) {ex.printStackTrace();

}}

}

The code is simple. The runMonitoringTest() method simply calls each of the proxy serv-ices that you’re monitoring, after setting the appropriate delay value. After you’ve run theLoadTestClient, there will be a number of alerts visible in the Dashboard view of ALSB (seeFigure 8-10).

Figure 8-10. The Dashboard after running the TemperamentalService tests

CHAPTER 8 ■ REPORTING AND MONITORING 187

7974CH08.qxd 3/28/07 12:43 PM Page 187

Page 213: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

ReportingReporting is a subset of the monitoring function of ALSB. Monitoring is based on the nearreal-time collection of SLA and Pipeline alerts. Reporting is based on the recording of parts ofa message into a database. You can then either view these report entries from the ALSB con-sole or you can access them from an external reporting tool. You can use a Report action in themessage flow of any proxy service. You can also embed Report actions in the error handlersassociated with pipelines and Route nodes. Both the SLA and Pipeline alert information areaggregated in a database. ALSB provides a reporting user interface to allow you to gather theinformation you need easily.

■Note You can create Report actions based on alerts. However, the default report provider that ships withALSB ignores these alerts. If you want to use customized reporting alerts, you must create your own report-ing provider. Furthermore, you’ll also need to configure ALSB to use your customized provider. The reportingprovider API is a public API supported by BEA.

In the Monitoring and Reporting project supplied with this book, there’s a Report Proxyproxy service that illustrates how you use the Report action. There are two main sections of aReport action. The first is the body of the report, which contains the message data that youwish to record. The second section is for the keys by which you wish to search for the reportrecord in the database. You can define as many keys as you would like for the message.

As a best practice, we recommend that you store the entire message as the <Expression>of the report. That way you’ll have all the information that was originally available when theReport action was triggered. However, if your message is very large, and all the data is storedelsewhere in your enterprise, you might wish to store only the ID in the <Expression> field.For example, if you’re referring to a customer order, it’s likely that you’ll have the entire orderstored in an order database somewhere in your enterprise. In such a case, we would recom-mend storing only the order ID in the Report action to save space in the reporting database.

■Tip Creating more than one key within the Report action might not be obvious to you. To create addi-tional keys, simply left-click the key icon, then select Add a Key from the pop-up menu.

The report keys are used to search for report expressions. The keys are treated as simpletext, so storing a date won’t allow you to search by a date range. However, each report event isautomatically assigned a date and time stamp, so you can search based on the time of thereport event.

Most often, you’ll create key values based on the content of the message you’re reporting.In your ReportProxy service, the Report action records both the id and name values of the <bar>section of the message, as shown in Figure 8-11.

CHAPTER 8 ■ REPORTING AND MONITORING188

7974CH08.qxd 3/28/07 12:43 PM Page 188

Page 214: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 8-11. An example of the Report action

We recommend that you try the ReportProxy service with the XML in Listing 8-3. Try vary-ing the data values within the XML and using the test console to generate your own reportingdata. That way you’ll have some data to view when you get to the next section of this chapter.

Listing 8-3. Sample XML File for Generating Report Events

<foo><bar>

<id>2</id><name>name2</name><id>3</id><name>name3</name>

</bar></foo>

Viewing Report InformationYou view report information from the Operations portion of the ALSB console. Within theReporting heading, click the Message Reports link to see the table of the most recent reports.You can quickly sort the information on this table by clicking the table headers. Clicking thesame header multiple times toggles the sort order between ascending and descending.

If you’re working with a large number of reporting events, simply sorting the records won’tbe sufficient. You can also select specific report records by clicking the Filter link near the topright side of the Summary of Message Reports window (see Figure 8-12). You can use the Filterto select report records based on their database timestamp, either by a specific date range, orby selecting the most recent records within a timeframe that you can specify.

Additionally, you can search for reports based on the name of the inbound service. Theinbound service name is the combination of the project name and the proxy service name,separated by a slash (“/”) character.

The Error Code is automatically assigned to the reporting event (if the Report action wascreated in an error handler), inside the pipeline. You don’t need to take any explicit action tosee this value.

The Report Index field allows you to search the keys that you’ve created with your Reportactions. This provides a simple text-based search within the key data. There are no compari-son operators for the Report Index expression. The text you enter is treated as if it had wildcards on both sides. For example, using Figure 8-12 as a reference, if you entered a value ofname for the report index, all six records would be returned as matches. The search function iscase sensitive, so a search for myid would return zero matches, whereas a search for myIDwould return four matches.

CHAPTER 8 ■ REPORTING AND MONITORING 189

7974CH08.qxd 3/28/07 12:43 PM Page 189

Page 215: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 8-12. The report filter

If you click the link for the report in the Report Index field, it will bring up the ViewMessage Detail window (see Figure 8-13). This window is rich in detail, allowing you to seeat a glance most of the information you might be interested in. At the bottom of this windowis a Detail link. Clicking this link brings up another browser window that contains the<Expression> of the Report action.

Most of Figure 8-13 is self-explanatory. We want to add a little detail here for the fields thatare blank in the current figure. The Outbound Service section is only filled with data if theReport action is contained within a Route node. It’s similar in structure to the Inbound Servicesection above it. The Fault section is only filled with data if the Report action is included insidean error handler, whether it is a pipeline error handler or a Route node error handler. This isoften a better approach to debugging errors than using the Log action, especially if you’relooking for problems at runtime when the proxy service is in a production environment.

CHAPTER 8 ■ REPORTING AND MONITORING190

7974CH08.qxd 3/28/07 12:43 PM Page 190

Page 216: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 8-13. The View Message Detail window for a report event

Purging Report InformationInformation is like fruit—it ages quickly. The Purge Messages link in the Operations ➤ Reportingsection of the ALSB console provides a simple user interface for purging messages. You caneither purge all messages in the reporting database or you can purge messages within a spe-cific date and time range, as shown in Figure 8-14.

CHAPTER 8 ■ REPORTING AND MONITORING 191

7974CH08.qxd 3/28/07 12:43 PM Page 191

Page 217: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 8-14. The interface for purging report messages

Purging messages occasionally helps to keep your reporting data store performing at anoptimal speed. It also makes managing the report records much more manageable.

Reporting ProvidersA reporting provider provides both transport and storage for reporting events. If you deployALSB in a cluster, then all the managed servers within the domain will use the reportingprovider to aggregate the reporting data. By default, ALSB comes preconfigured with a JMSreporting provider. The JMS reporting provider is used because it first queues the reportingrecord, and then dequeues and writes the records to the database. This asynchronous designimproves the performance of the reporting modules within ALSB. The name of the JMS serveris wlsbJMSServer, and the name of the data store is wlsbjmsrpDataStore. You can find boththese artifacts using the traditional WLS console.

You can change the data store associated with the JMS reporting provider. In a productionenvironment, you’ll probably want the report messages stored in a production-quality data-base, such as Oracle, Microsoft SQL Server, or MySQL. To do this, you can use the databasescripts stored in the <%BEA_HOME%>\weblogic92\integration\db\scripts\[database] direc-tory. There’s no script for MySQL, PostgreSQL, or some of the other unsupported open sourcedatabases, but if you examine the scripts for the supported databases, creating a script spe-cific for the database you wish to use should be fairly simple.

Listing 8-4 shows the basic table structures used for ALSB reporting. The MSG_GUID fieldis the primary key for the WLI_QS_REPORT_ATTRIBUTE table and is the foreign key for theWLI_QS_REPORT_DATA table. With this knowledge, you can create custom reports in externalreporting tools such as Crystal Reports, or execute your own SQL statements directly againstthe reporting tables.

Listing 8-4. The Table Definitions for the Reporting Events

CREATE TABLE WLI_QS_REPORT_ATTRIBUTE (MSG_GUID VARCHAR(64) NOT NULL,DB_TIMESTAMP DATETIME DEFAULT CURRENT_➥

TIMESTAMP NOT NULL,

CHAPTER 8 ■ REPORTING AND MONITORING192

7974CH08.qxd 3/28/07 12:43 PM Page 192

Page 218: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

LOCALHOST_TIMESTAMP DATETIME NOT NULL,HOST_NAME VARCHAR(50) NOT NULL,STATE VARCHAR(8) NOT NULL,NODE VARCHAR(128) NULL,PIPELINE_NAME VARCHAR(128) NULL,STAGE_NAME VARCHAR(128) NULL,INBOUND_SERVICE_NAME VARCHAR(256) NOT NULL,INBOUND_SERVICE_URI VARCHAR(128) NOT NULL,INBOUND_OPERATION VARCHAR(64) NULL,OUTBOUND_SERVICE_NAME VARCHAR(256) NULL,OUTBOUND_SERVICE_URI VARCHAR(256) NULL,OUTBOUND_OPERATION VARCHAR(64) NULL,MSG_LABELS VARCHAR(512) NULL,ERROR_CODE VARCHAR(64) NULL,ERROR_REASON VARCHAR(1024) NULL,ERROR_DETAILS VARCHAR(2048) NULL,CONSTRAINT PK_WLI_QS_REPORT_ATTRIBUTE PRIMARY KEY(MSG_GUID)

)

-- WLI_QS_REPORT_DATA

CREATE TABLE WLI_QS_REPORT_DATA(MSG_GUID VARCHAR(64) NOT NULL,DATA_TYPE SMALLINT NULL,ENCODING VARCHAR(24) NULL,DATA_VALUE IMAGE NULL,CONSTRAINT FK_WLI_QS_REPORT_DATA FOREIGN KEY(MSG_GUID)REFERENCES WLI_QS_REPORT_ATTRIBUTE(MSG_GUID) ON DELETE CASCADE

)

Finally, it’s possible to run ALSB without a reporting provider of any kind. You can still usethe Report action in your message flows, but no data will be written. The only real reason tostop and/or remove a reporting provider is to remove the only database dependency com-monly used by ALSB. For most customers, this database dependency is not an issue, but ifyou want to run ALSB without any database connections, you’ll need to stop the reportingprovider and possibly remove it entirely from the supporting WLS configuration.

To stop a reporting provider, you use the WebLogic console. Click the Deployments link inthe left navigation bar of the console. Navigate through the list of deployed applications untilyou come to the JMS Reporting Provider (or the specific reporting provider you’re using, if youaren’t using the default JMS Reporting Provider). Click the checkbox next to the JMS ReportingProvider, then click the Stop button. Similarly, if you wish to undeploy the JMS ReportingProvider, simply click the Lock & Edit button on the console’s Change Center, click the check-box next to the JMS Reporting Provider, and then click the Delete button to remove itcompletely from the server or cluster.

CHAPTER 8 ■ REPORTING AND MONITORING 193

7974CH08.qxd 3/28/07 12:43 PM Page 193

Page 219: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

SummaryIn this chapter, you learned how to create alerts in support of SLAs. You learned how to createcomplex rules to fire those alerts and how to use the Dashboard to monitor the alerts andgather information about the state of your ALSB deployments. Additionally, you learned howto use the built-in reporting tool to record events within a message flow, and even how youcan access that raw reporting data from an external tool. What strikes us most about thischapter is the simplicity of the interfaces, especially when juxtaposed against the power ofthe monitoring and reporting tools. These tools really “open up” the service bus in a way thatmakes it a valuable tool for your operation support personnel and developers alike.

CHAPTER 8 ■ REPORTING AND MONITORING194

7974CH08.qxd 3/28/07 12:43 PM Page 194

Page 220: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Security Models and Service Bus

Using SOA-enabling applications and creating fine-grained services significantly increasesthe number of services for you to manage. Composite applications and services consumethese additional services, which are distributed across the enterprise for orchestration or toprovide high-level services or functionality to meet IT and business needs. The permissions toaccess to these services must conform to the security policies of the enterprise. If services arenot secure, discerning legitimate requests from rogue access attempts is a daunting task.Unauthorized access to a service may result in degraded service performance or even inunavailability.

Many factors drive security requirements in the SOA world. Regulatory compliance needsforce policies on businesses and IT departments. Internal policies that describe how to accessservices and what data should be protected are quite common within enterprise environ-ments. Another important issue driving security requirements is the ability to securelyinteroperate with other systems and services. New standards, such as Web Services Security,promote secure interoperability among disparate and distributed service implementations.Business needs, such as single sign-on, further underscore the need for policy-driven interop-erable security in SOA-enabled enterprise systems.

This chapter is intended for architects, developers, administrators, and SOA analysts whoare interested in using a service bus as an intermediary to secure a service provider, enforcesecurity policies, and provide a single security model to the service consumers while orches-trating services with multiple security models.

Security Paradigms with SOA ChallengesAs an intermediary, ALSB is ideally suited for defining, configuring, and enforcing securitypolicies and thus securing existing enterprise services without having to rewrite them whenbusiness requirements change. The service bus can secure access to a backend application orservices and provide interoperability and security brokering capabilities that are truly configu-ration driven.

Table 9-1 shows some common security scenarios in enterprise systems and the chal-lenges associated with adopting SOA within those scenarios. We will discuss these scenarios ingreater detail in the remainder of this chapter.

195

C H A P T E R 9

7974CH09.qxd 3/29/07 1:04 PM Page 195

Page 221: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Table 9-1. Scenarios and Challenges with Security in Adopting SOA

Scenario Challenge

Identity management How can you access a secured resource, such as a database orfile system, or a legacy backend application that requires asimple username/password to allow access?

Privacy protection of messages How can you ensure that only the right service provider can and their payloads access the message?

Authenticity How can you know that the message is authentic and has notbeen issued by someone not authorized to access the serviceprovider?

Integrity How can you know that the message and its payload have notbeen tampered with during transmission?

Security enforcement How can you ensure, or apply and enforce, security rules andpolicies to restrict access to a resource, application, or servicethat is not secure?

Security interoperability How can you enforce single security standards like WebService Security, SAML, SSL, digital signatures, encryption,and so forth?

In a metadata-driven architecture, ALSB can be implemented to dynamically evaluateand enforce security policies without coding, allowing you to evolve and customize your secu-rity enforcement runtimes and architectures.

The following sections explain the most common types of security schemes or policiesthat can be applied by an SOA architect who’s defining an SOA solution and architecture.

Transport-Level SecurityTransport-level security refers to securing transports used during communication between aclient and an application or through an intermediary such as ALSB. This includes the ability todefine policies, such as requiring clients to use SSL for privacy and authentication purposeswhen communicating over HTTP. Other transports may specify different methods of securingcommunications, such as use of SFTP, a secure-shell-based (SSH-based) FTP protocol that isquite popular in SOA and has significant advantages over the relatively insecure username-and password-based FTP.

Figure 9-1 shows ALSB acting as an active or passive intermediary to support the enforce-ment of security at the transport level. Let’s take a look at a typical example for securinginbound communications to a proxy service. A proxy service can be configured to use HTTPSas transport for communication and would enforce authentication of clients against a set ofusers, groups, or roles configured as a part of Access Control List (ACL) policy for the proxyservice by simply including it as part of the security configuration in ALSB. As for the backendapplication, when the business service is created, ALSB will automatically honor the securitysettings and take appropriate action while communicating with the backend at runtime.

CHAPTER 9 ■ SECURITY MODELS AND SERVICE BUS196

7974CH09.qxd 3/29/07 1:04 PM Page 196

Page 222: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

ACTIVE VS. PASSIVE INTERMEDIARIES

We commonly use the terms active intermediary and passive intermediary when discussing security scenar-ios using ALSB. An active intermediary refers to the situation where ALSB enforces the web service securitypolicy. ALSB acts as a passive intermediary whenever it does not enforce the web service security policy, andinstead, the security policy is enforced by the service endpoint to which ALSB routes the message.

Figure 9-1. ALSB as an active or passive security intermediary

Message-Level SecurityMessage-level security refers to the efforts to secure the payload of a message itself. This is aparticularly attractive option if you want to define confidentiality and integrity policies in amanner that is neutral to transports. By removing the dependency on transports for security,you can make security policy and its implementation easier and more portable. This approachis useful in SOA, since it facilitates interoperability and reuse of services that require thosepolicies. Web Service Security specifications define the types of message-level security optionsthat are available currently for an SOA architect.

Ad-Hoc, Custom, Token-Based SecurityAd-hoc, custom, token-based security refers to the capability in the bus to recognize andassert identity based on a field in the transport header (HTTP/HTTPS), SOAP header (WebServices), or an XML payload (XML) that contains a user-defined custom token. There is alsoan option to declare and configure arbitrary fields in the SOAP header or an XML payload as ausername/password pair. Such capability makes ALSB interoperate with a broad range oflegacy integration applications and services that are not capable of Web Service Security.

Figure 9-2 shows support in ALSB for Web Service Security profiles for an active interme-diary case. For example, a proxy service can be enabled to enforce a WS-Policy statement suchas to use a Web Service Security Username Token profile when clients connect to the proxyservice. At the time of proxy configuration, ALSB will automatically recognize the supportedWS-Policies shown in Figure 9-2 when referenced in the WSDL for the proxy, thereby automat-ing the process of enabling message-level security and making it extremely simple for thedesigner. The ALSB runtime engine will expect a valid security header with a username andpassword that belong to an ACL policy configured for this proxy service.

CHAPTER 9 ■ SECURITY MODELS AND SERVICE BUS 197

7974CH09.qxd 3/29/07 1:04 PM Page 197

Page 223: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 9-2. Using ALSB as an active intermediary

ALSB Security ModelIn this section, we will elaborate on the security model for ALSB. All security in ALSB is config-urable and policy driven. Proxy service security can be configured independently of thebusiness service endpoints. At runtime, the bus automatically mediates and enforces securityas prescribed by the policy attached to the proxy service (inbound) and the business servicebeing accessed by the proxy at runtime (outbound).This makes it particularly attractive foruse as a security intermediary that can operate in either Active or Passive (pass-through)mode with built-in configuration-driven options for overriding default security settingsdynamically. The declarative nature of security in ALSB makes implementing and modifyingvarious security set ups a breeze.

Several general rules to use when configuring and enabling security in ALSB follow:

• Define a policy for securing the proxy. The various security schemes are combinationsof transport- and message-level security.

• Configure the security providers that will be used for enforcing security policiesattached to the proxy service.

• Set up the bus to propagate identity to the business service.

Since the outbound invocations from the bus automatically conform to the securityrequirements of the business service endpoints, let’s focus on security strategies for inboundcases and the options for propagation of identity to bridge inbound/outbound securityparadigms.

Inbound Security in ALSBThe default setting in ALSB is such that any client can access the proxy service. To restrictaccess to the proxy, there are authentication and authorization policies that must be config-ured. The access to a proxy service can be secured by the following methods:

• Basic authentication at the transport level provides the simplest authentication andauthorization mechanism—a client is required to pass credentials as part of thetransport headers as defined by the protocol for the transport.

CHAPTER 9 ■ SECURITY MODELS AND SERVICE BUS198

7974CH09.qxd 3/29/07 1:04 PM Page 198

Page 224: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

• Basic authentication at the message level, also known as Web Services Security User-name Token Profile authentication, requires a client to send the credentials as SOAPheaders rather than in transport headers. The obvious advantages of such message-level security are that it is standards based and agnostic to the underlying transportprotocol.

• Public Key Infrastructure (PKI) authentication at the transport or message level isanother way to secure access to a service by using a certificate for establishing authen-ticity. PKI-based authentication at the transport level uses SSL authentication. At themessage level, it uses the Web Service X.509 profile.

• Web Services Security authentication is available using the Security Assertion MarkupLanguage (SAML) profile for end-to-end web-services–based orchestrations amongclients, ALSB, and web-services–based business services.

• ALSB supports access to proxy services from nonstandard legacy clients, genericHTTP clients, or XML clients. In these cases, the ad hoc custom token or user/passwordpair can be declared in the proxy service configuration. The token or credential willbe extracted by the bus and used for authentication, authorization, and identitypropagation.

As we mentioned earlier, ALSB has a declarative security model that extends to creden-tials and certificates mapped through references to a credential provider. There are two typesof credential providers:

• Proxy Service Provider: This credential provider is an artifact that refers to a set of cre-dentials that can be used while enforcing security policies on the proxy, for example,looking up a certificate from the proxy provider to be used for Web Service Securitydecryption.

• Service Account: This credential provider is an artifact that holds reference to credentialsfor an outbound service that is used by a proxy service at runtime, such as a username/password pair for accessing a data service. Credential Mapping will be needed to prop-agate the right credential when a proxy invokes a business service (Credential Mappingrefers to the situation where the client of the proxy service is mapped to a user ID/password to be used to invoke the business service that the proxy service is routing to).The types of credentials that can be mapped for a business service follow:

• Fixed: A static credential is mapped to the service account and used when invokingthe business service to which it is attached. This option works well for global serv-ices such as accessing a file system or a database for lookup.

• Pass-through: A username/password pair from inbound headers is directly passedto business service as headers. This option works well when the ALSB is being usedas a pass through to loosely couple a backend service. This is a one-to-one map-ping that uses HTTP basic authentication headers or SOAP headers when using aWeb Service Security Username Token profile.

• Mapped: A mapping is configured in the service account that returns an appropri-ate username/password pair based on the client of the proxy service that isemployed by the proxy service for authenticating to the business service.

CHAPTER 9 ■ SECURITY MODELS AND SERVICE BUS 199

7974CH09.qxd 3/29/07 1:04 PM Page 199

Page 225: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Identity Propagation in ALSBSecurity mediation in ALSB from inbound request to outbound request requires identity to bepropagated from the service consumer to the proxy to the backend business services. ALSBcan automatically propagate the identity to the business service depending on the securitypolicy for that service. The identity scheme to be propagated can be declared while configur-ing the proxy and business services. The identity propagation options are as follows:

• Propagate the username/password pair using credential mapping for transport andmessage-level security on the outbound message. The inbound security could be anytype listed in the “Inbound Security in ALSB” section of this chapter.

• Propagate the username/password pair to the outbound request using pass-throughcredential mapping when inbound security is configured to be transport-level ormessage-level for legacy cases. The ALSB may or may not handle authentication.

• When the business service requires an SAML security token, ALSB can act as an activeintermediary to propagate identity by generating a SAML token based on any inboundauthentication security policy.

• Propagation of message payload and identity to outbound request can also be accom-plished by using a Web Service Security policy on the inbound request but configuringALSB as a passive or pass-through intermediary. The intermediary does not authenti-cate the client.

• When inbound proxy service is secured by authentication policy at both transport leveland message level, the identity propagated to the outbound service is the message-levelidentity.

SSL AuthenticationUsing only basic authentication at the transport level is weak security. Typically, it is backed bySSL encryption or even replaced by SSL-based authentication as a strategy to provide secureaccess to an ALSB proxy. There are two types of authentication mechanisms using SSL certifi-cates: one-way and two-way SSL authentication.

One-way SSL authentication refers to a mechanism where the server (ALSB) is required topresent a digital certificate to the client to prove its identity. The client performs checks likethe following ones to validate the digital certificate:

• Is the certificate is trusted and issued by the client’s trusted certificate authority?

• Is the validity certificate expired?

• Does the certificate subject’s common name (CN) value match the hostname to whichit is connecting?

Two-way SSL authentication refers to an authentication mechanism where both the clientand the server must present digital certificates before the SSL connection is established. Inthis case, the web server itself will validate the client’s digital certificate in addition to theclient’s validation in the one-way case. This is a very useful scheme when one would like torestrict the access to a proxy to only trusted clients.

CHAPTER 9 ■ SECURITY MODELS AND SERVICE BUS200

7974CH09.qxd 3/29/07 1:04 PM Page 200

Page 226: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

How do these SSL options affect the ALSB proxy security configuration? Well, first, thereis a single web server in case of ALSB. Therefore, only one SSL certificate is available, and it’sshared by all proxies. Another way the configuration is affected is in the need to use proxyservice providers to store the client certificate used to invoke a business service.

An underlying application server feature called Certificate Lookup and Validation (CLV) isalso used to validate X.509 digital certificate chains for inbound two-way SSL, outbound SSL,and Web Services Security profiles.

Digital Signatures and EncryptionSo far, we have discussed mechanisms for securing access to the proxy service in ALSB. Inaddition to that, you can secure the payload itself to prevent tampering with a message pay-load while data is in transit.

Encryption provides privacy protection on the messages and communication. At thetransport level, SSL will encrypt every piece of data that is transmitted between a client andALSB proxy. At message-level, using Web Services Security standards, one can provide anencryption policy to securely encrypt the message payload in part of or the whole SOAPenvelope.

Using a digital signature provides capability to enforce nonrepudiation of both the originand receipt of messages. This is a message-level security policy and can be applied to part ofthe payload or the entire SOAP envelope.

ALSB provides the following web service policies out of the box:

• Auth.xml: Contains the default authentication policy to be used by web service clientsto connect to an ALSB proxy service that is enabled using this policy

• Encrypt.xml: Contains the default policy to be used by web service clients to encryptthe SOAP body using 3DES-CBC when connecting to an ALSB proxy service that isenabled using this policy

• Sign.xml: Contains the default policy to be used by web service clients to sign the SOAPbody using RSA-SHA-1 when connecting to an ALSB proxy service that is enabled usingthis policy

■Note RSA is an encryption and authentication system that uses an algorithm created in 1977. The RSA isan abbreviation of the last names of the authors of the algorithm: Ron Rivest, Adi Shamir, and LeonardAdleman. The SHA in SHA-1 stands for “Secure Hash Algorithm.”

Using ALSB SecurityIn the previous section, we described the security model for ALSB and explained the basicsecurity functionality in ALSB with a brief overview of how it allows policy-based security tobe enforced on inbound clients and outbound services. We also outlined various typical iden-tity propagation scenarios that are supported by ALSB.

CHAPTER 9 ■ SECURITY MODELS AND SERVICE BUS 201

7974CH09.qxd 3/29/07 1:04 PM Page 201

Page 227: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

In this section, we will explain how to configure ALSB to enable end-to-end security.There are certain combinations of inbound and outbound services that occur commonly. Wewill provide a recipe to configure ALSB for such scenarios. You might very well consider thesescenarios as patterns or best practices in ALSB.

Let’s look at an example scenario that involves a web service username token authentica-tion in ALSB. In this case, message-level security is being used. Listing 9-1 shows a snippet ofthe Web Service Policy representing the web service username token authentication.

Listing 9-1. A Sample WS-Policy for Web Service Username Token Authentication

<wsp:Policyxmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"xmlns:wssp="http://www.bea.com/wls90/security/policy"xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-➥

wssecurity-utility-1.0.xsd"xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-➥

wssecurity-secext-1.0.xsd"xmlns:m="http://example.org"wsu:Id="encrypt-custom-body-element-and-username-token"><!-- Require messages to provide a user name and password token

for authentication --><wssp:Identity>

<wssp:SupportedTokens><wssp:SecurityToken IncludeInMessage="true"

TokenType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-➥

wss-username-token-profile-1.0#UsernameToken"><wssp:UsePassword Type="http://docs.oasis-open.org/wss/➥

2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText"/></wssp:SecurityToken>

</wssp:SupportedTokens></wssp:Identity>

</wsp:Policy>

Figure 9-3 shows a service consumer invoking a proxy that is secured by a Web ServiceSecurity username token authentication policy while the backend application uses a basicauthentication policy.

Figure 9-3. An example of using username token authentication

CHAPTER 9 ■ SECURITY MODELS AND SERVICE BUS202

7974CH09.qxd 3/29/07 1:04 PM Page 202

Page 228: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

The steps in invoking the proxy shown in Figure 9-3 follow:

1. A client sends a request to a proxy service. The request contains the username andpassword credentials. Clients can send other types of tokens for authentication, suchas X.509 certificates. If a client sends a certificate token, you must configure an identityassertion provider to map the identity in the token to an ALSB security context.

2. The proxy service asks the domain’s authentication provider if the user exists in itsprovider store. If the user exists, the proxy service asks the domain’s authorizationprovider to evaluate the access control policy that you have configured for the proxyservice.

3. If the proxy service’s access control policy allows the user access, the proxy serviceprocesses the message. As part of generating its outbound request to a business serv-ice, the proxy service asks the business service to supply the username and passwordthat the business service requires.

4. The business service asks its service account for the credentials. Depending on howthe service account is configured, it does one of the following:

a. Requires the proxy service to encode a specific (static) username and password

b. Requires the proxy service to pass along the username and password that theclient supplied

c. Maps the username that was returned from the authentication provider to someother (remote) username, and requires the proxy service to encode the remoteusername

5. The proxy service sends its outbound request with the username and password thatwere returned from the service account.

Now that you’ve seen how the flow of Web Service Security authentication works in ALSB,let’s look at other recommendations.

RecommendationsThe challenge with securing an SOA is that most services and applications aren’t stand-alone;they are already connected—with or without security. The challenge is to introduce SOA orservice-enable service endpoints without having to write extensive code, incur additionalmaintenance costs, or leave loopholes that compromise sensitive data.

Some services and applications provide their own preferred security protocol. Leveragingthese in an SOA is a challenge. For example, one application’s security protocol may differfrom the security protocol of the application with which it is communicating.

ALSB is one of the simplest interoperable, easy-to-use, configuration-based products tohelp address security concerns at all levels.

Policy-based enforcement allows access to services, and ALSB can act as an intermediaryand a single point of enforcement for policies that can be centrally governed. The mainte-nance of security policies becomes much more manageable as a result.

CHAPTER 9 ■ SECURITY MODELS AND SERVICE BUS 203

7974CH09.qxd 3/29/07 1:04 PM Page 203

Page 229: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

ALSB provides a configuration-driven approach that bridges multiple security protocolswith minimal coding. It also provide flexible authentication for transports, including username/password basic authentication in transport headers and certificate-based authentication.Message-level encryption can also be added, including the use of security credentials in SOAPheaders. SSL or HTTP can provide encryption for confidentiality.

Creating secure service-enabled processes for integration using ALSB as a central securitybridge makes it easy to secure new and existing services and to manage those services on anongoing basis.

SummarySecurity is a broad topic and demands a formal strategy for proper implementation. The com-mon patterns for using ALSB as a security intermediary are using ALSB for proxy inboundsecurity enforcement and propagating user identity to the business service endpoint. In thischapter, we covered the basics of security as they apply to ALSB to help you understand howto plan and implement ALSB security as part of your overall security strategy.

CHAPTER 9 ■ SECURITY MODELS AND SERVICE BUS204

7974CH09.qxd 3/29/07 1:04 PM Page 204

Page 230: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Planning Your Service Landscape

Designing an enterprise SOA is a huge task. Although tools that help make creating andmanaging your SOA easier are advancing at a rapid pace, these tools cannot provide a substi-tute for the amount of human effort required to design the SOA itself. Many of the customerswe meet are eager to start designing their SOA but almost immediately get “lost” in the details.Determining where to start can be a daunting task in itself.

To help with this, we have developed a service “GPS” (Global Positioning System) to helparchitects, service designers, and developers to get their bearings quickly within their SOA forthose moments when they start to get the feeling of being lost in the details. What follows inthis chapter is a set of principles and a methodology for successfully designing your SOA.

In the real world, a GPS shows your location by providing you with latitude and longitudecoordinates. If you understand the latitude and longitude system, and have a map thatincludes the surface of the earth that incorporates the coordinates, you get a pretty good ideaof your location. The more exact the coordinate and the more detailed your map, then thegreater the accuracy of your understanding of your position.

The problem with designing your SOA is that you have neither a map nor a coordinatesystem, making an SOA GPS impossible. In this chapter, we’ll create a coordinate system, andwe’ll then teach you how to map your enterprise services. With some effort, you’ll be able topopulate your map fully, and using the SOA Coordinate System, you’ll never feel “lost” again.Let’s begin by creating the coordinate system.

The SOA Coordinate SystemCoordinates are just a union of one-dimensional scales. For GPS systems, coordinates use thelatitude scale (how far to the north or south you are) and the longitude scale (how far to theeast or west you are) to determine your position on the surface of the earth. You need to createa set of scales. Once you have your scales, you can join them together to create your SOACoordinate System. From there, you’ll create your Enterprise Service Map.

The Software Abstraction ScaleThe first scale is that of abstraction. Architects and developers know that abstraction is a use-ful tool, and we don’t dispute that. However, not everything needs to be highly abstract. Some

205

C H A P T E R 1 0

7974CH10.qxd 4/2/07 9:53 PM Page 205

Page 231: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

things must be literal and concrete for there to be any possibility of higher-level abstractions.We work with a natural scale of abstraction as software developers every day.

The Software Abstraction Scale (see Figure 10-1) begins at the bottom with artifacts thathave very little abstraction. For example, a database implementation is about as concrete or“physical” as things get in the software world. We don’t mean to imply that there’s no room forabstraction and good design within a database schema; certainly database design is vitallyimportant. The point we make is that in the grand view of enterprise software development,databases are the least abstract elements. Similarly, physical devices, such as routers,modems, and switches are also at the bottom of this scale.

Figure 10-1. Software Abstraction Scale

Moving up a level on our Abstraction Scale are low-level software components, such asdevice drivers and database drivers. These components provide a layer of abstraction abovethe devices they represent. This is an expression of the Façade design pattern, where the com-plexity and interdependencies of lower-level components are hidden. This is the fundamentalpattern of abstraction, and we’ll see it repeated in each successive layer.

Next we see object-relational mapping tools and frameworks. This includes softwarepackages such as Hibernate (http://www.hibernate.org), Kodo (http://www.bea.com/kodo),and Cayenne (http://incubator.apache.org/cayenne). These tools make it easy to persist theobject data within an object-oriented application. Software applications, in turn, provide agreater level of abstraction, and are often the lowest level of interaction where a non-softwaredeveloper becomes involved. For most of the history of software, applications represented theapex of abstraction.

CHAPTER 10 ■ PLANNING YOUR SERVICE LANDSCAPE206

7974CH10.qxd 4/2/07 9:53 PM Page 206

Page 232: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Service orientation began quietly, many years ago, under the name of “application inte-gration.” As enterprises became more adept at creating software applications to automatetheir processes, there arose a need to have these applications share information with oneanother. Application developers began to create public Application Programming Interfaces(APIs) to provide a controlled way to allow other applications to make use of their functionality.Looking back, we can see that these APIs were really the first step toward service orientation.Today we create these APIs as web services; hence the name “Application Services” in thefigure.

In modern IT shops, the number of applications range from the dozens to many hun-dreds. Although each application might have distinctive features and capabilities, therealways emerges a natural “clustering” of applications, based on their business function. Anorder management application is often tightly integrated with other applications that playsupporting roles in the order fulfillment process. These clusters of applications represent thefunctionality required by the “business domain” they inhabit. We’ll talk more about businessdomains later on in this chapter. For now, think of a business domain as a higher level ofabstraction above application services.

Finally, the highest level of abstraction is the Enterprise Service Layer (ESL). We think ofthis layer as the API for the entire enterprise. Services at this level of abstraction don’t recog-nize the arbitrary boundaries of databases, applications, or business domains. These servicescan go anywhere and do anything (by making use of lower levels of abstraction). However,services at the top level of the Abstraction Scale must not know the implementation details ofthe hundreds of components that live further down the Abstraction Scale. Enterprise services“paint with a broad brush,” issuing commands to the enterprise and expecting timely results.

Now you know what the first dimension of our SOA GPS is. You must understand severalprinciples to make use of this scale. The first principle is that of knowledge dependency; eachlayer on the scale “knows” about the layer beneath it. A JDBC driver “knows” (that is, is config-ured to talk to) about an instance of a database. Databases do not “know” about JDBC drivers.The dependency is directional. The second principle is that of diminishing detail. As youtravel up the scale of dependency, the amount of technical implementation detail containedin each higher layer must be less than the layers below it. This doesn’t imply that there’s lessinformation at the higher levels of abstraction. It simply means that the amount of “low-level”technical information decreases rapidly. Components at the bottom of the scale contain atremendous amount of technical and implementation detail because they’re doing the realwork. Components at the bottom know exactly what to do to make their little piece of theenterprise function correctly. Components at the top of the scale know what to do (that is,process an order), but have no detailed knowledge of how that work gets done.

A byproduct of these principles is the location and density of the resulting services in yourSOA. Figure 10-2 represents this graphically. At the lower levels of abstraction, you’ll find thatyou’re creating exponentially more services than you are near the top of the Abstraction Scale.This is as it should be. If your ESL publishes 100 services while the sum total of all your appli-cation services is also 100, then you have provided no abstraction at all! However, if your ESLpublishes one to ten services for every hundred services in your Application Service Layer(ASL), then you’re likely providing a good amount of abstraction. These numbers aren’t hardand fast, but are representative of the orders of magnitude that naturally occur with SOA.

CHAPTER 10 ■ PLANNING YOUR SERVICE LANDSCAPE 207

7974CH10.qxd 4/2/07 9:53 PM Page 207

Page 233: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 10-2. Service population

If you don’t respect (and by respect we mean design and code) with these two principlesin mind, you’ll effectively destroy your software Abstraction Scale and your SOA.

We won’t ask you to accept these numbers blindly. Let’s double-check these assumptionsagainst current, successful models to see how well they match up. Let’s begin with a technol-ogy we all know and love: television (see Figure 10-3).

There’s a tremendous amount of complexity and detail in any television set. The vastmajority of the details involved in presenting you—the TV viewer—with the images andsounds on your set are hidden from you. You use a remote to send commands to your TV. Youcan perform three basic functions with your television: change the channel, adjust the vol-ume, and turn the TV set on and off. That’s really it. If you examine all those buttons on yourremote, those are the services that your remote provides.

Those services, in turn, are handled through a motherboard on your TV set. The mother-board aggregates circuit boards (many of them integrated so they physically appear as part ofthe motherboard) that perform finer-grained functions. Those circuit boards are comprised ofhundreds of integrated circuits, each of which is comprised of millions of individual transis-tors. This is abstraction at its best.

Abstraction isn’t a technology-specific concept. We see it in human organizations also.Even the largest companies on the planet are organized into hierarchies (see Figure 10-4).

CHAPTER 10 ■ PLANNING YOUR SERVICE LANDSCAPE208

7974CH10.qxd 4/2/07 9:53 PM Page 208

Page 234: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 10-3. Television abstraction model

Figure 10-4. Organizational abstraction model

CHAPTER 10 ■ PLANNING YOUR SERVICE LANDSCAPE 209

7974CH10.qxd 4/2/07 9:53 PM Page 209

Page 235: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Again, we see abstraction in our daily lives. The CEO cannot possibly know the details thateach worker must know for that worker to be effective at his job. In fact, even the worker’smanager cannot know all the details that the worker performs on a daily basis. The importantthing to remember here is that this is a good thing (though you might question that on yournext annual review). As you move down the Abstraction Scale, the level of detail and theamount of work increases dramatically. This is a natural organizational principle. As archi-tects, service designers, and service developers, we must embrace this principle to designand manage our enterprise architecture successfully.

The Service Domain ScaleOur second scale is that of service domains (see Figure 10-5). This scale categorizes the vari-ous functions that every enterprise must have in order to succeed. Service domains aredirectly related to business domains. We use the phrases “service domain” and “businessdomain” interchangeably because they’re so closely related. A domain is simply an area oflogically related knowledge or expertise. Most companies are divided into domains. We com-monly see companies divided into departments such as sales, marketing, human resources,IT, and so on. Service domains are an important concept in enterprise architecture; they pro-vide us with a logical demarcation between applications. This demarcation allows us to makebetter decisions about how to integrate individual applications.

Figure 10-5. Service domain scale

Each company may modify its list of service domains. For example, the Service Manage-ment domain only applies to companies that provide services, as opposed to products, totheir customers—for example, telephone companies, utilities, and the like. If your companysells products, then there isn’t need for a Service Management domain.

Table 10-1 lists the service domains and provides a description for each. It’s important tothink of each service domain as a co-equal peer in the enterprise architecture. Human

CHAPTER 10 ■ PLANNING YOUR SERVICE LANDSCAPE210

7974CH10.qxd 4/2/07 9:53 PM Page 210

Page 236: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

resources might not have the same priority within your organization as does Customer Rela-tionship Management (CRM) or billing, but it plays an important role in keeping yourenterprise in compliance with government rules regarding employment, and also helps tokeep your employees happy, which in turn benefits the enterprise.

Table 10-1. Service Domain Descriptions

Service Domain Description

Customer Customer Relationship Management. This domain is responsible formaintaining accurate customer information. CRMs are commonly foundin this domain, as are other customer/lead tracking types of software.

HR Human resources. PeopleSoft and related software products are often foundhere. For example, in pharmaceutical companies, you would find employeetraining records for using respirators, CPR training, and so on.

Product Products are a marketing concept. Marketing defines and promotes products,and this domain contains the software tools to allow the marketingdepartment to do its job.

Inventory Inventory is a count of physical items that are either sold to customers, or inthe case of service providers, are physical elements that allow the company toprovide service to its customers (for example, telephone switches, line cards,and so on).

Services This domain is used exclusively by service providers. If a company sellsservices (such as communication service, electrical service, natural gas, andso on), this is where those services are defined and maintained.

Order Order management. Here orders are collected and processed/fulfilled.

Asset Every organization has assets. As asset is an item used by the company orby its employees and contractors. For example, a building owned by thecompany is an asset, the computers used by the employees are assets, as isthe furniture, vehicles, and so on.

Accounting Accounts receivable/accounts payable. Commonly referred to as billing.This domain contains the majority of the accounting systems used by thecompany.

Partner Partner relationship management. This domain is responsible for keepingrecords of the various partners of the company.

Supply Supply chain management. This domain contains information aboutsuppliers.

With your two scales in hand, you’re ready to create your coordinate system.

The Coordinate SystemWhen you put these two scales together, you get a coordinate system for your services in yourSOA. Figure 10-6 shows the coordinate system that applies to every enterprise. This willbecome a useful tool when you begin to map your SOA.

CHAPTER 10 ■ PLANNING YOUR SERVICE LANDSCAPE 211

7974CH10.qxd 4/2/07 9:53 PM Page 211

Page 237: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 10-6. The SOA Coordinate System

However, before you start the mapping process, there’s one more concept to introducewith regard to the coordinate system that isn’t well represented by a grid.

As we mentioned earlier in this chapter, there’s a natural clustering of applications in anyIT department. Upon careful examination, you’ll usually find that this clustering falls alongthe lines of the service domains. You need to formalize this clustering of applications to createyour service landscape. To do this, you must begin to think of your architecture in terms oftrees, not just simple stacks or layers. Using a tree as a conceptual model will simplify yourability to navigate through the enterprise.

Figure 10-7 points out (and overcomes) one of the shortcomings of the grid approach: theEnterprise Services layer is not divided into domains. The whole point of the Enterprise Ser-vices layer is that it’s designed to integrate the different service domains below it. Similarly, anindividual domain in the Domain Services layer contains multiple application services.

Figure 10-7. Enterprise architecture sample tree

Keep in mind that this map is a logical map. It breaks down functionality into logicalgroups. In practice, you’ll find that some of your applications will cross domain boundaries.This is especially true of large, packaged applications such as Siebel and SAP. You’ll mostlikely find the same issue with the software that you have developed in house. This is commonand doesn’t present a problem for the architecture. Remember, we’re modeling applicationservices, not applications. Application services are still divided into their respective domains,no matter where the applications are physically deployed. For example, imagine that yourcompany uses Siebel for its CRM and order management capabilities. Furthermore, some ofthe customer information resides in a customer database that came to your IT shop throughthe acquisition of another enterprise a year ago.

CHAPTER 10 ■ PLANNING YOUR SERVICE LANDSCAPE212

7974CH10.qxd 4/2/07 9:53 PM Page 212

Page 238: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

As you can see in Figure 10-8, Siebel is a single application that hosts two services thatlogically belong in different domains. Siebel’s Customer Service is mapped into the Applica-tion Services layer beneath the CRM Domain, while Siebel’s Order Service is mapped into theApplication Services layer beneath the Order Management Domain. Applications routinelycross domain boundaries. Always keep in mind that the logical view is what’s important inenterprise architecture. When we lose sight of this logical view (our SOA “map”), that’s whenwe become lost in the details again.

Figure 10-8. Physical application deployment doesn’t impact the logical map.

Mapping Your SOANow that you have a coordinate system, it’s time to create your Enterprise Service Map.Although the SOA Coordinate System remains relatively unchanged from one enterprise tothe next, the service map is always highly specific to each enterprise. Therefore, we cannotprovide you with a map of your enterprise here. Instead, we’ll provide you with the methodol-ogy for creating your own Enterprise Service Map.

Using this methodology provides considerable benefit for you and your organization.First, it helps to provide a high-level taxonomy for categorizing your services. This in turnmakes it easier to find—and thereby reuse—existing services. Second, it helps architects anddevelopers to determine quickly which services need to be created and where they must existin the SOA Coordinate System. This methodology will help to eliminate much of the confusionthat naturally occurs when first moving to an SOA.

There are two approaches to defining and discovering services: top-down and bottom-up.We’re often asked which approach is “best.” The top-down approach means that you startfrom a high-level business need and then create the services that are required to fulfill thatneed. The bottom-up approach is where you look for existing business functionality thatyou believe will be useful in the future, and service-enable that existing functionality. Bothapproaches have their place in enterprise architecture, and this mapping methodology fitsboth approaches nicely.

The Top-Down ApproachOur first mapping example will use the top-down approach. This approach is generally initi-ated by a line-of-business leader who has a specific business need. These needs tend to beexpressed in general terms with little or no technical detail. For our first example, the businessneed is expressed as, “We need to allow our customers to view their bills online.”

CHAPTER 10 ■ PLANNING YOUR SERVICE LANDSCAPE 213

7974CH10.qxd 4/2/07 9:53 PM Page 213

Page 239: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 10-9 shows a service map that can fulfill the business need. Right from the start, weknow that we need a service in the ESL because the service needs to access information fromtwo distinct domains (the Customer and the Accounts Receivable/Accounts Payable domainsspecifically). This brings us to our first rule of service mapping:

Enterprise Service Mapping Rule 1: If the service must cross domain boundaries to do its

job, it must exist in the Enterprise Service Layer.

Service 1 must aggregate information from the two service domains that are logicallyresponsible for the customer and billing information, so the service in the ESL invokes thetwo services in the Domain Service Layer (DSL). As Enterprise Service Mapping (ESM) Rule 1declares, the service in the ESL absolutely cannot skip over the DSL and get the informationdirectly from the various application services. Doing so violates the fundamental principle ofabstraction and will quickly render the coordinate system (and therefore your ESM) com-pletely useless. It would be akin to putting a button on your TV remote control to change asingle transistor state on a microchip in the TV.

Figure 10-9. Mapping your first service

If the ESL could skip the DSL, you would lose a fundamental layer of abstraction, and theESL would then have to know about the physical deployment details of the applications inthe Application Service Layer (ASL). This not only increases the amount of maintenance thatneeds to happen each time a change is made to a physical application deployment (a serveris added or deleted), but also eliminates a key layer of transformation. This forces the ESL to“speak” the same language as the application, therefore reducing the possibility of everachieving a canonical service model at the ESL. This leads us to ESM Rule 2:

Enterprise Service Mapping Rule 2: The Enterprise Service Layer cannot “skip” the

Domain Service Layer.

CHAPTER 10 ■ PLANNING YOUR SERVICE LANDSCAPE214

7974CH10.qxd 4/2/07 9:53 PM Page 214

Page 240: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Each respective domain service then makes use of any number of application servicesand Relational Database Management System (RDBMS) services to fulfill its service contract.In this case, we see that the Customer DSL can skip the application layer and access theRDBMS Service Layer (RSL) directly. That is because a data service and an application serviceare components of the domain itself. Domain services must understand the physical deploy-ment nature of their applications, databases, and services, so it’s completely acceptable for aDSL-level service to invoke any service within its domain directly. In the case of the AR/APdomain service, the Customer DSL simply uses an application service. This is often the casewith packaged applications, where they either don’t publish their supporting database struc-ture, or they prohibit you from making calls to the application database directly.

Each higher-level service may be dependent on lower-level services. The SOA CoordinateSystem makes the direction of these dependencies implicit. The ESL calls the DSL. The DSLin turn, calls the ASL or the RSL. The ASL may also call the RSL. We’ll cover this later in thechapter in the section “Communication Principles and Patterns.”

The Bottom-Up ApproachThe IT department generally initiates the bottom-up approach. The members of the ITdepartment have a detailed understanding of the daily operations and interactions of thesoftware systems they manage. This detailed knowledge is used to predict which technicalfunctions are likely candidates to become reusable services.

For our second example of service mapping, a software developer makes this recommen-dation to the IT department: “We do a lot of sales where credit cards are used as the method ofpayment, and we use several different credit card payment companies to charge credit cards,depending on which application is taking the order. Furthermore, if one processing agency isresponding too slowly, we have logic written in each sales application to fail over to a differentcredit card processing agency. We should create a single service for credit card processing andencapsulate the fail-over logic so it’s reusable.”

See the difference in the level of technical detail? The bottom-up approach is appliedwhen the details are well known. The IT department is fixing an important issue, but one thatis so low level that most line-of-businesspeople aren’t aware of it.

As you can see in Figure 10-10, the service map is simple. The decision-making process todetermine the map should be straightforward after our first exercise. First, you need an appli-cation service that encapsulates both the fail-over logic and the agency-specific connectioninformation. If you need to add or remove a credit card processing agency, then that functionwill need to happen at the ASL level, and the changes shouldn’t affect any of the serviceconsumers.

Next, you know that this credit card service will be invoked by your sales applications;therefore, you must have an ESL-level service (because you’re crossing domains). Last,because the ESL cannot communicate directly with the ASL, you must create a DSL serviceto route the service request to the appropriate application service.

We deliberately left the Order domain in Figure 10-10 to show that even though the appli-cations in the Order domain need to use the credit card service, the Order domain is merely aconsumer of the credit card service, and therefore isn’t a part of the service map.

CHAPTER 10 ■ PLANNING YOUR SERVICE LANDSCAPE 215

7974CH10.qxd 4/2/07 9:53 PM Page 215

Page 241: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 10-10. A bottom-up approach for our second service map

SOA Mapping Test 1As you can see, the methodology is simple. To help ensure that you understand the process,let’s try a test. We’ll describe the scenario, and you use the methodology to create a servicemap on a piece of scrap paper. Also, make a note of whether you’re using a top-down orbottom-up approach, based on the scenario description.

Scenario: “Our suppliers need to interrogate our systems and check our current inven-

tory levels. Based on our inventory levels, they will ship additional products to us. We

need a way to allow our suppliers to see our current inventory levels. However, each of

our suppliers has a proprietary format for the inventory data they’ll receive from us, so

we need to adapt our inventory information into their data format.”

See Figure 10-11 to see the service map and the approach used.Despite the fact that the scenario sounds so complex, the service map is pretty straight-

forward. In the Supply domain, you’ll create your supplier-specific adapters (each supplierexpects its own data format to be returned to it). Whether you create an application for eachadapter or have a single application that’s used by each supplier-specific adapter is a designchoice you need to make. However, from the point of view of the service map, it’s not impor-tant. The direct result of this is that we have an application in the Supply domain/ASL.

Next, you know that the application in the Supply domain needs information from theInventory domain. Because you’re crossing domain boundaries, you must have an enterprise-level service. To get to the application service that holds the inventory information, the ESLmust make a call through the DSL, so you create a service in the Inventory domain’s DSL also.

CHAPTER 10 ■ PLANNING YOUR SERVICE LANDSCAPE216

7974CH10.qxd 4/2/07 9:53 PM Page 216

Page 242: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 10-11. Our service map for Test 1

One thing to note: if a supplier was able to use the data format provided by your enterprise-level service, then that could be an entry point into your enterprise. It’s an architecturaldecision as to whether or not to publish enterprise-level services directly to your suppliers.Our personal preference is to isolate partner and supplier integration within their respectivedomains, and keep the ESL as a resource solely for the use of the enterprise itself.

Last, we took a top-down approach to this. We worked from the business need, not from atechnical improvement.

SOA Mapping Test 2This will be our last test for mapping services. Just to make sure you really understand theprocess, we’ll make this test a whopper. Let’s dive right in.

Scenario: Your manager says, “I need a 360-degree view of the customer. I want to be

able to know at a glance the customer contact information, the products they’ve pur-

chased, and when they purchased them. I also want to know how they paid for those

products so I can target a promotional campaign based on past purchases and payment

methods.” Furthermore, your lead developer says, “Getting the product and order data

would be a lot faster if we got it directly from our data warehouse, rather than from our

online databases.”

This sounds a lot harder than it turns out to be. Figure 10-12 shows the service map forthe “Customer 360° View” service. To begin with, there’s no question that you’re crossingdomains with this map, so you know you need a service in the ESL. Also, you know that you’llneed a service in each of the DSLs that participate in this overall service.

CHAPTER 10 ■ PLANNING YOUR SERVICE LANDSCAPE 217

7974CH10.qxd 4/2/07 9:53 PM Page 217

Page 243: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 10-12. Our service map for Test 2

We threw a bit of a monkey wrench into this test with the engineer’s comment on usingthe data warehouse. A data warehouse with order information would contain product infor-mation by default. Obviously, this is an RDBMS-layer service, but in which domain: Order orProduct? The answer is up to you. In our opinion, this service is centered more on the orderthan the products, but that’s a personal call. You’d be just a correct to place such an RDBMSservice in the Product domain.

Data warehouses are like applications in that they almost always cross domain bound-aries. Just like applications, it’s up to you to decide which domain best fits the RDBMS serviceyou’re creating. There’s no right or wrong answer here, just as long as you document your deci-sions and provide a mechanism to allow your development teams to find and reuse theseservices easily.

Service Maps at ScaleSo far, we’ve drawn service maps for individual services. Let’s create a single service map thatcontains all the mapping information we’ve created so far.

Figure 10-13 shows the map of all our services so far. As you can see, it’s already cluttered.Imagine the service map for a real enterprise with hundreds of services; the map would beunintelligible due to the amount of data on it. It might be visually impressive, but other thanthat, it would be completely useless.

■Tip Do not store service maps that show multiple services. In practice, we find the ESM so straight-forward that we usually do not store service maps at all.

CHAPTER 10 ■ PLANNING YOUR SERVICE LANDSCAPE218

7974CH10.qxd 4/2/07 9:53 PM Page 218

Page 244: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 10-13. Mapping multiple services

Service mapping isn’t designed to be visually stunning. It’s a simple methodology fordefining a high-level view of which services need to exist, and where they need to exist. It alsoprovides guidance on the level of abstraction of those services. It reduces confusion and argu-ment about what services need to be created (or reused), and where and how those servicesshould be deployed.

Service ToolingHowever, as the number of your services grows, the ability to find existing services becomesincreasingly difficult. Furthermore, mapping the interdependencies of each service alsobecomes exponentially more difficult. Making a change to your service landscape, atenterprise-level as complex a task as making a change in a point-to-point architecture.

Fortunately, new tools are emerging to help you manage this ocean of data. Service reg-istries operate like a phone book for services, allowing you to look up the locations of theservices quickly and retrieve their runtime design information (Service Level Agreements andother metadata). Service repositories are great tools for tracking design-time metadata aboutservices, such as their interdependencies. As your SOA grows, your need for professionalservice management tools will grow also. BEA is the only company, at the time of this writing,that provides a complete suite of SOA tools, including an enterprise-quality service registryand a service repository.

Architectural TransformationOdds are that your current enterprise architecture doesn’t formally recognize service domains.If your company is like the vast majority of companies, then your current enterprise architec-ture will resemble that shown in Figure 10-14.

CHAPTER 10 ■ PLANNING YOUR SERVICE LANDSCAPE 219

7974CH10.qxd 4/2/07 9:53 PM Page 219

Page 245: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 10-14. Point-to-point integration

This is commonly referred to as a point-to-point (P2P) integration strategy. We’ve alsoheard people refer to it as a “rat’s nest” of integrations. The illustration shows 28 circles. Eachcircle represents an application in the enterprise. The arrows show the dependencies betweenthe applications. Although the figure shows only a modest number of applications (mostmedium-sized enterprises have well over a hundred software applications running at anytime), it represents sufficient complexity for our purposes.

The big question is, “How do I transform my architecture from this rat’s nest to use servicedomains and the SOA Coordinate System?”

First, it’s important to recognize that your enterprise didn’t implement this rat’s nestovernight. It took years—even decades—to build that point-to-point architecture, and youwon’t correct it overnight. However, we have an approach that will simplify this process, allow-ing you to implement enterprise-wide SOA without having to rewrite your entire enterprise.

As we write this, SOA is at a high point in its “hype cycle.” SOA advocates earnestly prom-ise that SOA will cure all your ills and make you more attractive to the opposite sex. Thesepromoters will promise that everything you ever learned about software engineering and run-ning an IT shop is now outdated. SOA makes it all so easy a trained monkey can do it!

If you’ve spent any amount of time in the software industry, you recognize this hype cyclepretty quickly. You know that the old “80/20” rule applies: about 80 percent of the hype willturn out to be exaggerations or outright lies, while the other 20 percent is the really useful stuffthat you need to learn and apply immediately. The difficulty is in knowing which statementsbelong in the “hype” bucket and which statements are true.

Let us debunk a commonly held belief in our industry: “Point-to-point integrations areevil.” In fact, there are advantages to using a P2P integration strategy. First, P2P is usually fairlyquick to implement. Once you know how to communicate to the foreign software system, it’sjust a matter of doing the work to make the various API calls. Second, P2P is fairly easy. Youdon’t have to be a software design expert: the foreign software system is written and there’susually nothing you can do to improve it. Just write the code and go home. Third, P2P isusually fast from an execution time point of view. Not a lot of translation happens in a P2Pintegration, thereby eliminating any translation or transformation overhead.

CHAPTER 10 ■ PLANNING YOUR SERVICE LANDSCAPE220

7974CH10.qxd 4/2/07 9:53 PM Page 220

Page 246: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Of course, P2P also has some serious drawbacks. P2P systems are difficult to maintainover time, and there tends to be little abstraction in the interfaces of some of these softwaresystems, so making any changes to them tends to affect every client that’s integrated with thesystem. Because every little change requires significant engineering effort, a greater percent-age of the IT budget goes to maintaining existing systems, and less money is spent on creatingnew systems or improving existing ones. This phenomenon leads directly to IT (and thereforethe business itself) becoming lethargic and resistant to change.

As you can see, P2P has strengths and weaknesses, like every other software strategy. P2Pisn’t evil, nor is it “blessed.” It’s simply an integration strategy that makes sense to use in cer-tain situations. The simple fact is that P2P is already present and pervasive in your enterprise.You cannot ignore it; you must deal with it. If your enterprise is like most, you have neither thetime nor the money to fix it, so there’s only one thing left to do: embrace it.

The approach we suggest here is simply to accept that you’re going to live with largepockets of P2P for some years to come. The trick is to know where P2P is acceptable in theshort term, and where you really have to buckle down and fix it. Now that we have an SOACoordinate System and an SOA map, we can tell you where you need to fix P2P and whereyou can safely ignore it for the time being. It all comes back to service domains. Applicationswithin a service domain are already implemented using P2P. Because the work they do is soclosely related anyway, it’s perfectly acceptable to allow them to remain that way. However,you must break this P2P model when it comes to operations that cross service domains.

Your first step is to take an inventory of all your applications and begin to categorize theminto the appropriate service domains. Once that’s done, you can begin a series of engineeringprojects to refactor the various applications so that they’re appropriately represented by theservice domains. Figure 10-15 shows this process in principle.

Figure 10-15. Isolate applications and services that belong in the same service domain.

CHAPTER 10 ■ PLANNING YOUR SERVICE LANDSCAPE 221

7974CH10.qxd 4/2/07 9:53 PM Page 221

Page 247: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

When you’re identifying applications and services, it’s important that you understandthe dependencies between the applications in sufficient detail to make a good decision.Each dependency has a direction associated with it, and you must understand the directionof each dependency. With this knowledge, you’re able to begin to move applications and appli-cation services into a logical domain layer. Figure 10-16 shows how this is done. Only oneapplication (A) needs to be modified to call the new Domain Service Layer, instead of callingthe application directly.

Figure 10-16. Create a DSL.

Notice how application B is still directly dependent on application C. For the time being,this is acceptable. Because application C is not yet in a defined Domain or Application ServiceLayer, the outgoing call from B to C in unavoidable.

Our next step is to repeat the process. Once again we isolate applications and servicesthat belong in the same logical domain, playing close attention to their dependencies. We cre-ate a second service domain and ASL. At this stage, we break the direct dependency betweenapplication B and C and refactor application B to call the newly created DSL.

CHAPTER 10 ■ PLANNING YOUR SERVICE LANDSCAPE222

7974CH10.qxd 4/2/07 9:53 PM Page 222

Page 248: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 10-17. Repeat the process for each domain.

There is no hard-and-fast rule about when to introduce an ESB, but we recommend thatyou introduce it as the second project (immediately after you create your first service domain)or as the third project (after the second service domain is complete). It’s important to introducethe ESB fairly early in the process of creating domains to reduce the amount of refactoringthat must be performed for each application that invokes services in other domains. Forexample, if you examine Figure 10-17 you’ll notice that application B is now dependent onDomain Service Layer 2, while application A is dependent on Domain Service Layer 1. Yet aquick examination of Figure 10-18 shows that applications A and B are now dependent on theESL. This implies a double refactoring of those applications (from the DSL to the ESL). Obvi-ously, each of these refactoring efforts takes time and money to complete, so you want tominimize the number of such projects.

Of course, you might ask, “Why not start by creating the ESL and completely avoid thedouble refactoring effect?” That sounds good in principle, but we find that creating at leastone DSL helps the architects and developers to get their minds wrapped around new tech-nologies and new design patterns required by SOA. We find that this helps to diffuse theattendant fears of experiencing so much change, which in turn increases the success ratesof these early projects.

CHAPTER 10 ■ PLANNING YOUR SERVICE LANDSCAPE 223

7974CH10.qxd 4/2/07 9:53 PM Page 223

Page 249: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 10-18. Introduce the ESB early in the process.

There are two main advantages of the service domain methodology. First, it leveragesyour existing P2P architecture, minimizing the amount of change. Fewer changes means lessdevelopment time and less cost. Second, it provides you with a defined process that’s easilyexplainable to technologists and businesspeople alike. Trying to get your projects fundedunder the banner of “SOA” is a difficult proposition. However, once you clearly explain howyou can achieve your SOA goals and can break the process down into discrete projects, you’llincrease your odds of success. People rarely fear what they understand. Last, organizing ITassets into a series of service domains that make sense to most business people will increasethe level of alignment between your IT shop and your business leaders.

Communication Principles and PatternsWe’d now like to explain three communication principles and four basic communicationpatterns in this architectural approach. These principles and patterns should be clearlyunderstood by each architect, service developer, and software engineer involved with realizingthis architecture. Fortunately, they’re simple and easy to understand.

CHAPTER 10 ■ PLANNING YOUR SERVICE LANDSCAPE224

7974CH10.qxd 4/2/07 9:53 PM Page 224

Page 250: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Communication Principle I

Each service layer knows about the layer below it, but not the layer above it.

Each service layer acts as a façade for the layer below it. Clients of the ESL should have noknowledge of the various service domains below it. Similarly, the ESL has no knowledge ofthe ASL beneath the DSL.

Communication Principle II

Every service layer can know about the Enterprise Service Layer.

The ESL is the public API for the enterprise. As a result, it must be available as a resource forany component in the enterprise. This is the only time when it’s permissible for a componentin a layer to know about a layer above it.

Communication Principle III

Web services are used between the service layers.

By using web services to communicate between the service layers, you create the ability tohave a rationalized monitoring strategy for your enterprise. This approach also promotesreuse of services at each layer by providing a standard service format and the ability to useUniversal Discovery, Description, and Integration (UDDI) as a tool for discovering services.Last, it provides an enterprise standard for integration. There are many different ways to inte-grate disparate systems; settling on a standard will reduce your training and maintenancecosts and enhance your operational efficiency.

Communication Pattern I: Flow of GravityThis is the model that immediately springs to mind for most people when they imaginemessages flowing through their enterprise. As shown with the large arrows in Figure 10-19,messages flow from the top downwards. As the message passes through each layer, there’s anopportunity for the message to be transformed and enriched. This demonstrates Communica-tion Principle I and shows how a single message invocation from an enterprise service clientcan span service domains and multiple application services in a manner completely transpar-ent to the client.

CHAPTER 10 ■ PLANNING YOUR SERVICE LANDSCAPE 225

7974CH10.qxd 4/2/07 9:53 PM Page 225

Page 251: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 10-19. The Flow of Gravity pattern

CHAPTER 10 ■ PLANNING YOUR SERVICE LANDSCAPE226

7974CH10.qxd 4/2/07 9:53 PM Page 226

Page 252: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Communication Pattern II: Direct Use of Enterprise ServicesThis pattern demonstrates the use of Communication Principle II. As shown in Figure 10-20,the ESL is being invoked by a DSL and an individual application service. Many modern appli-cations are now capable of invoking external web services (that is, web services that areimplemented outside of the invoking application). We expect this trend to continue, makingthis pattern increasingly common.

Figure 10-20. Direct use of the ESL

CHAPTER 10 ■ PLANNING YOUR SERVICE LANDSCAPE 227

7974CH10.qxd 4/2/07 9:53 PM Page 227

Page 253: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Communication Pattern III: Indirect Use of Enterprise ServicesThe third pattern, illustrated in Figure 10-21, is really a minor variation of pattern II. Oldersoftware systems that aren’t capable of using web services to integrate with other systemscan still participate fully in the ASL. The key is to create an adapter that can translate betweenthe application-specific data formats and the enterprise message formats. This pattern onlyapplies to the ASL because the DSL is fully web service enabled (Communication Principle III).

Figure 10-21. Indirect use of the ESL

■Caution One thing to beware of with Communication Patterns II and III is the possibility of putting yourentire enterprise into an infinite loop. It has always been possible to do this, even with a P2P architecture.However, an SOA makes it much easier to create infinite loops inadvertently. This is one area where yourSOA Governance group earns its keep. The Governance groups are commonly charged with understandingthe interrelationships between enterprise, domain, and application services.

CHAPTER 10 ■ PLANNING YOUR SERVICE LANDSCAPE228

7974CH10.qxd 4/2/07 9:53 PM Page 228

Page 254: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Communication Pattern IV: Inter-Application CommunicationsWithin a DomainThe fourth and final pattern covers communication and integration within the ASL. Figure 10-22shows how this pattern allows you to leverage your existing tightly coupled systems in a posi-tive way. The number of system interactions (and therefore the number of messages orprocedure invocations) at this level of abstraction is high. We routinely find very “chatty”applications here—applications that are poorly suited for web service interfaces—but that’sperfectly acceptable in this layer. As long as those “chatty” applications are chatting with otherapplications within the same application domain, they can continue to work without anymodifications.

Figure 10-22. Inter-application communications within a domain

Geared for PerformanceBy applying these rules, you help to ensure robust performance in your SOA. Without theserules, it can be difficult to predict how each of your services will perform. Let’s use an exampleto help illustrate this.

For our first example, let’s start with an SOA built on this methodology. In this scenario,you’re creating new business functionality in the ASL of your customer domain. Your newfunction needs to access the customer’s residential address history. For the sake of this argu-

CHAPTER 10 ■ PLANNING YOUR SERVICE LANDSCAPE 229

7974CH10.qxd 4/2/07 9:53 PM Page 229

Page 255: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

ment, assume that your company tracks the different locations where customers have residedin the past ten years for insurance purposes. You look into your service catalog and you seeseveral existing services that can return this information. Examining the service maps for eachservice, it becomes clear which service will both meet your needs and perform quickly.

Figure 10-23 shows a sample service map. We are creating service F. Our service mapshows that service E provides the information we need. However, service D also providesthat information. Communication Pattern I prohibits the application layer from calling thedomain layer, so having service F call service D is out of the question. However, service A alsoprovides the information needed by service F, but service A acquires that information throughservice D, which in turn gets the information from service E. Obviously, accessing service Edirectly will be much faster than accessing it through service A. The methodology has madethe decision-making process simple and unambiguous.

Figure 10-23. Using the service map to make good choices

However, let’s try this same exercise without the use of service maps for an SOA Coordi-nate System. The relationships between the services are exactly the same as was shown inFigure 10-23. However, without using the SOA Coordinate System or the Service Mappingmethodology, you have no idea about the interrelationships between the services (becausethat’s implementation information and your client shouldn’t be exposed to that). Figure 10-24shows a pool of services without this critical information.

Figure 10-24. A pool of services with no coordinate system or map

CHAPTER 10 ■ PLANNING YOUR SERVICE LANDSCAPE230

7974CH10.qxd 4/2/07 9:53 PM Page 230

Page 256: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Using the metadata descriptions of each service in your service catalog, you would againsee that services A, D, and E all meet your needs. But how do you determine which service touse? You can’t easily make the right decision about which service to use because you’re miss-ing the information that’s critical to your decision-making process.

SummaryWe’ve gone through a lot of theory quickly in this chapter. We’d like to close this chapter with afew ideas about the practical application of ALSB, especially with regard to your service land-scape. Keep in mind that BEA did not name the product “AquaLogic Enterprise Service Bus.”Certainly, ALSB is designed to operate under the rigors and stresses of the ESL. However, ALSBis also well suited to perform in areas of your enterprise that aren’t immediately evident.

For example, ALSB is well suited to operate in the DSL. Just point it at the various applica-tion services below it and create a more abstract set of proxy services. That alone will create anentire DSL for one of your domains.

ALSB doesn’t just “speak” services, though. Starting with ALSB version 2.5, you can alsoeasily connect to Java code and EJBs, either of which gives you access to databases. Thesecapabilities make ALSB a candidate to act as an adapter within the ASL, allowing legacy appli-cations to participate in your SOA by service-enabling them, even though they were neverdesigned with services in mind.

It can be difficult to integrate an old mainframe system into your SOA. Mainframe appli-cations are rarely designed to integrate with anything at all. They all see themselves as thecenter of their software universe and often don’t even have a public API. One integration trickwe’ve used in the past is to integrate at the database level. Mainframe applications commonlyuse an RDBMS to store data. By adding or modifying insert, update, and delete triggers, youcan often push data to an outside application, such as ALSB. This is especially easy in an Ora-cle application, because Oracle provides the capability to write triggers and stored proceduresin Java. We prefer to keep our code at this level asynchronous if possible, so it doesn’t interferetoo much with the normal execution time of any existing triggers in the database. We usuallyopt to publish a database “event” over a JMS queue and have ALSB receive the JMS message.We don’t mean to represent this process as being overly simple, but it is possible and it doeswork.

Similarly, many older systems use FTP as their messaging systems. Exchanging formattedfiles was probably the earliest messaging system in wide use. Using ALSB, you can receive orcopy these files, monitoring the file transfers, and even reading the data in these files to per-form content-based routing.

Don’t let the name fool you. ALSB has a lot of functionality. Use it wherever its functional-ity matches the needs of your architecture. As the feature list of ALSB grows with each release,you’ll find more and more ways to use it.

CHAPTER 10 ■ PLANNING YOUR SERVICE LANDSCAPE 231

7974CH10.qxd 4/2/07 9:53 PM Page 231

Page 257: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

7974CH10.qxd 4/2/07 9:53 PM Page 232

Page 258: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Versioning Services

Change is inevitable. That’s a basic fact of life and SOA doesn’t change that. SOA promises tomake your company and IT systems more tolerant of change, more agile. You need to do yourpart by understanding the different types of change that can occur, and then developing andenforcing governance policies to manage changes in your services. Managing change is notjust a technology problem; it’s also a governance problem that requires the full participationof the people responsible for IT governance.

Tools do play a role in governing the service life cycle of services. Your particular strategywill depend on the tools you have available to manage changes to services. For example, ifyou’re writing web services without using ALSB, or any other tools, you might opt to track yourservices using a simple text document. Not a very robust solution, but a perfectly acceptablesolution, especially if you have a small number of services.

At the other end of the tooling spectrum, if you have a service registry or service reposi-tory, then you’d want to leverage the capabilities of that tool for helping with tracking differentversions of the same service and dependencies between services, and allowing the serviceclient either to specify the specific service characteristics it’s looking for, or allowing develop-ers to reliably discover the most recent version of the service.

However, not everyone has a service registry or service repository. Because you’re readingthis book, it’s a pretty safe bet that you do have ALSB. As a result, we’ll focus on scenarios thatleverage ALSB.

Before we jump into strategies for managing changes in your service offerings, you needto spend a little time understanding what we mean by “change” when it comes to services.People often jump directly to various versioning strategies without understanding the prob-lem space first. By understanding the basic principles of the service life cycle, you’ll be able toapply that knowledge to any supporting toolset that you might use, whether it’s ALSB or aservice registry or repository. Let’s start at the beginning.

What Is a Service?Let’s step back from the technical world of web services for a moment and take some time toclarify our definition of a service. Let’s examine some of the services we use on a daily basis:real-world services that can help us to understand the term service better. This clearer under-standing of a service will yield three principles that apply to all types of services. We’ll thenbe able to use these principles to help guide us when we begin looking at web servicesspecifically.

233

C H A P T E R 1 1

7974CH11.qxd 3/28/07 1:28 PM Page 233

Page 259: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

One service that we use every day is an electrical service. Here in the United States, resi-dential electrical service comes in two forms: 110 volt AC and 220 volt AC. Ninety-five percentof the appliances in our homes use the 110 volt service, while only a select few use the 220 voltservice (primarily electric stoves and some electric water heaters and clothes dryers). Theactual voltage that’s delivered to a US home varies somewhat. The 110 volt service can bebetween 105 and 120 volts, depending on local conditions. Controlling this variation in volt-age is part of the Quality of Service that the electric company promises in its contracts. Both110 volt and 220 volt services have standard interfaces (that is, the plugs and sockets) that areincompatible. You cannot plug a 110 volt device into a 220 volt receptacle unless you (as theservice client) break your agreement with the electrical provider (and state and federal laws)and alter the 110 volt plug to connect to the 220 volt plug somehow. Because 220 volt service isdeadly to human beings, those foolish enough to attempt such a feat are rarely allowed theopportunity to reproduce.

Telephones represent another commonly used service type. You can buy a telephone fromvirtually any phone producer, plug it into the phone receptacle in your home, and it will workjust fine. Again, the phone service defines a standard physical interface (the RJ-11 phone jack)combined with standardized transport protocol (tone dialing and analog signals) to deliverthe service to your home and the local telephone device that you’ve chosen to use.

Another example service is a postal service. If you follow the defined protocol for how apostal address is formatted (street, city, state, and ZIP code) and the placement of theaddresses (sender’s address in the top-left corner, recipient’s address in the middle) and applythe correct postage, you can send a letter or package with a high level of confidence that it willreach the intended recipient. The postal service even provides error handling mechanisms incase something goes wrong. For example, if the recipient is no longer at the address, the cur-rent person at the address can simply write “return to sender” on the package and the postalservice will return it to the sender.

We could go on with this list for a long time. You receive service at restaurants, bookstores, car dealerships, home contractors, public transit organizations, airlines and their reser-vation desks, and so on. The fact of the matter is that we all know what a service is. Yet forsome reason when we think specifically of web services, the definition of a service begins toget complex. Throw that thought out of your head. Services really are simple. The implementa-tions behind the services are often complex; they are supposed to be complicated. A large partof the benefit of any service is hiding the complexity from the service consumer. When weorder a meal at a restaurant, we want to pay some money to get some food. It’s that simple. Wedon’t want to know about the difficulties involved with running a restaurant. We don’t want toknow about labor laws or the tax code. We don’t want to know about the highly complex sup-ply chain that reliably provides the materials for our meal to the restaurant. We pay forsimplicity. Don’t lose sight of the simplicity; it is the key to your success in this area.

From this simple position, we can draw a conclusion about a general service concept thatwill provide value to us in the web services world: implementation is unimportant. When wepurchase a meal at a restaurant, we don’t care how they create the meal, as long as the mealmeets our expectations. If we order a steak cooked rare with a baked potato, and they deliver aHappy Meal, they have not met our expectations. Similarly, if they deliver the items, but theyaren’t prepared as ordered (the steak is overcooked, and so on), the restaurant has not met ourexpectations for the service. If they deliver what we ordered, cooked the way we ordered it,then we don’t really care how they did it. In fact, we probably don’t have any way to know thedetails of the preparation of the food, or from whom they ordered the raw food materials. So,we come to our first rule of services:

CHAPTER 11 ■ VERSIONING SERVICES234

7974CH11.qxd 3/28/07 1:28 PM Page 234

Page 260: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Implementation is not part of the service.

Obviously, implementation is important to delivering a service, but implementationresides purely in the domain of the service provider. The service consumer should be com-pletely ignorant of the implementation. The minute you break this rule, you begin creatingtightly coupled systems. Continuing the food service analogy, if we asked for meat from a spe-cific ranch and a potato from a specific farm, the restaurant might well refuse our request. If itwas willing or able to comply, it would have to charge us extra to cover its additional costs tomeet our expectations. Furthermore, we could not go to any other restaurant and have anyhope of it being able to meet those same expectations when we walk through the door. Byplacing constraints on the implementation of a service, we have tightly coupled ourselves tothat particular restaurant.

Based on what we’ve learned so far, we can draw another conclusion and derive our sec-ond rule of services:

Everything that requires client knowledge is part of the service.

What does (or should) a client know about a service? Well, the client ought to know whatservices the service provider makes available. You can’t order a rare steak and a baked potatoat McDonald’s and reasonably expect to get it. Therefore, services must be published or some-how be made available to potential clients. Next, client expectations must be met. Back at ourrestaurant, if we order a rare steak and baked potato but it’s served cold, then the restauranthas failed to meet our expectations. Similarly, if we order ice cream, we expect it to be cold andin the form of a solid or semi-solid mass. Bring us a bowl of melted ice cream and there will betrouble.

Meeting client expectations is a fundamental part of any service. Therefore, a servicemust be defined by an agreement between the service provider and a service consumer (alsoknown as the client). The agreement covers both what will be delivered and how it will bedelivered. For example, we know we’ll get a rare steak with a baked potato at temperaturesthat both meet our need for warmth, and that have met federal requirements for sanitation(that is, cooked at 160+ degrees to kill any organisms on the meat). Furthermore, we knowhow it will be delivered to us: the waitperson will pick it up in the kitchen and deliver it to ourtable, and he or she will perform this task in a “reasonable” amount of time. Therefore, we canderive our third principle:

Services are governed by contracts.

Contracts define what the service does: how the service is delivered to the client, alongwith any time constraints on either the service provider or the service client. Contracts arereally the star of the services show. As stated in the third principle of services, a contract gov-erns the service. This includes the intent of the service, operations and exceptions, semantics,invocation style, policies, quality of service, security, and pre/post conditions. The contractalso defines how the service is delivered, including the transport protocol (HTTP, JMS, and soon), the wire protocol (SOAP), and the invocation model (synchronous or asynchronous).

CHAPTER 11 ■ VERSIONING SERVICES 235

7974CH11.qxd 3/28/07 1:28 PM Page 235

Page 261: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

■Note Do not confuse the contract with a WSDL. A WSDL is a contract, but the current specification of aWSDL doesn’t address many of the characteristics that also belong in a contract. When we use the term“contract” in this chapter, we mean a contract as used in our three principles, not a WSDL.

Let’s take a look at the electrical service for a second. You move into a new house and youcall the electric company and order service for your home. Imagine your surprise when anelectrical technician appears on your doorstep with a truckload of batteries! Your expectationwas that the service would be delivered over the existing wiring, not through some device thatwould take up half of your basement. Also, when you ordered electrical service, you specifiedwhen you wanted the service activated (it’s dangerous to move furniture in the dark). If youask for service to begin on the first of the month, you certainly expect those lights to come onwhen you flip the switch. Similarly, once the service is activated, you expect it to stay acti-vated, barring some unusual circumstance, such as a severe storm. Timeliness is an importantattribute of services.

Additionally, a service contract may define what happens if the service fails to meet yourexpectations for whatever reason. In the case of the electrical service, you might be compen-sated for a service outage if the service provider makes a mistake of some sort, whereas eventsthat qualify as “acts of God” always exempt the service provider from any culpability.

THREE PRINCIPLES OF SERVICES

• Implementation is not part of the service.

• Everything that requires client knowledge is part of the service.

• Services are governed by contracts. Contracts define what the service does and how and when theservice will be delivered.

At this point, we can define a service:

A facility providing the client with some benefit, such as food or electricity, or some

capability, such as communication or access to information. Services act on behalf of

the client, shielding the client from the implementation details.

That’s what a service is. It is simple. It is something that human beings understand withease. Now that you know what a service is, it’s time to look at service orientation and what itmeans to you.

CHAPTER 11 ■ VERSIONING SERVICES236

7974CH11.qxd 3/28/07 1:28 PM Page 236

Page 262: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Service OrientationIf you think about it, a well-designed web service is object-oriented by nature. A well-designedservice acts on behalf of the service client. We see this principle on object-oriented systems allthe time. Poorly designed services often arise because they weren’t implemented using object-oriented principles. For example, let’s look at a poorly implemented service that doesn’t followgood OO design practices (see Figure 11-1).

Figure 11-1. An example of poor service design

In this example, you can see that there’s little encapsulation of the implementation detailsfrom the client. The client can see the balance in his checking account (which is a good thing)and can set the balance in his checking account (which is a bad thing, especially from thepoint of view of the bank). The client can simply ignore his current balance and send througha command to set a new balance to some astronomical number. Instead of acting on behalf ofthe client, this kind of design places all the required intelligence on the side of the client.Remember our earlier discussion about the restaurant? Part of the reason we pay money isbecause the restaurant hides all the complexity of food preparation from us. We ask therestaurant to give us a meal and it does. That kind of simplicity should also exist in your serv-ices. Let’s take another crack at this design and see if we can improve it (see Figure 11-2).

CHAPTER 11 ■ VERSIONING SERVICES 237

7974CH11.qxd 3/28/07 1:28 PM Page 237

Page 263: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 11-2. An improved service design

In this second version, you see how the system provides a service to the client. The clientacts on the service by interacting with the service using operations that insulate the clientfrom the necessary implementation logic. The CheckingAccount service takes action on behalfof the client, allowing the client to deposit money, withdraw money, and check his balance. Allthe logic regarding withdrawing more than is available can now be encapsulated within theCheckingAccount, where it should be.

Once you get comfortable with designing services, you’ll see that many of the skills youlearned during object-oriented design apply equally well to service orientation. In fact, we’dgo so far as to say that if your object-oriented design skills are poor, then your service designskills will be just as poor. Service orientation is simply object orientation at the enterpriselevel.

What Is Versioning?Versioning arose from source code control (SCC) systems as a mechanism for controllingchange within a software application. The value of an SCC system is the ability to “go back intime” to an earlier version of a single file or a group of files. You usually go back to previousversions to figure out what you messed up in the current version. “That code was working finein the last version” is usually the first thing a developer says before he uses the SCC system toget a previous version of the code and compare files using a “differencing” tool.

SCC systems are also great tools for team development, helping to keep all the developerson a development team in sync with the correct versions of the source code files. This becamea critical feature once software programs grew so large that large teams of developers wereneeded to complete a project. The need for SCC was further increased when developmentteams became geographically dispersed.

Finally, SCC systems provide the capability to archive source code, allowing corporationsto protect their development investment. SCC systems are critical tools in modern softwaredevelopment. Through these tools, the concept of versions became universal in the softwareindustry.

CHAPTER 11 ■ VERSIONING SERVICES238

7974CH11.qxd 3/28/07 1:28 PM Page 238

Page 264: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

The concept of versions might not be specific to software development, but it certainlyhas a vise-like grip on the thinking of most software professionals. We commonly apply ver-sions to our various files, both the source code and the executable code. We even apply theconcept of a version where it really has no place: have you heard the term “wife 2.0”?

Remember, versioning rose to prominence as a byproduct of change management tools.Specifically, versions are used to name a specific instance of a changing artifact, usually afile or a set of files. Therefore, we’re only concerned with defining versions for artifacts thatchange. If the implementation changes, you can use SCC to manage (or at least track) thosechanges. As long as the change to the implementation doesn’t affect the contract, the changecan be managed wholly within the SCC system. Versioning still applies at this level—theimplementation code.

Outside the software industry, the concept of “version” is far less prevalent. In thepublishing industry, there are sometimes second and third (or more) editions of a book.Sometimes those editions contain changes beyond fixing mere typos; sometimes they’re justreprints of popular books that have sold out of the previous edition, and no significantchanges are included. In most industries, the mental model of the “version” isn’t used. Instead,each product stands on its own. Newer products are released to replace earlier products in thesame family. For example, the Lexus ES 300 was superseded by the ES 330, which in turn wassuperseded by the ES 350. There is a general concept of a product family and a loose conceptof a version of these cars, but for all practical purposes, they are completely different, stand-alone products.

Do We Version Services or Operations?Let’s make the argument here and now that the concept of “version” has little or no usefulnessin web services. It simply does not apply. This also explains why so many people have workedso hard and for so long to figure out a way to apply the version concept to web services, withlittle or no success. It’s like working hard to give the ability of flight to pigs. Even if you couldfigure out some way to do it, you’d need to ask yourself, “Does this really help anything?” Theanswer is “no.” In the rest of this section, we intend to prove conclusively that applying theconcept of “version” to web services is as useful as adding wings to pigs.

We need to look at services in a new light. Just as we needed to adjust our mental modelsas we got our minds wrapped around procedural programming, event-driven programming,object-oriented programming, messaging, and so on, we need a new mental model for man-aging changes to services. If you were an expert at procedural programming and started tolearn object-oriented programming, you quickly found that your procedural mental modelsimply was not sufficient to cope with the new concepts of object orientation. Similarly, ourEJB, J2EE, C#, and .NET views of the world are insufficient to understand service orientation.As a result, we are forced to abandon these now-foreign mental models and focus our energieson understanding services and how we manage them in a new way.

Changing your mental model is easier said than done. We don’t profess to have all theanswers here, but we do have a number of questions that will help you to begin the construc-tion of a new mental model for service versions. These questions must not be philosophicalin nature; they must be finite, pointed, and answerable. Mental models are (or should be) amechanism by which we’re able to understand reality. Object orientation is a reality that hasexisted in this universe since the beginning; it was only when we learned to construct ourmental model of object orientation were we able to use object orientation as a tool.

CHAPTER 11 ■ VERSIONING SERVICES 239

7974CH11.qxd 3/28/07 1:28 PM Page 239

Page 265: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

The real point of interest for change management (and therefore versioning) occurs at thecontract level. There are a lot of moving parts at this level, and we must agree on what we’remanaging. For example, are we managing versions of the overall service, or do we want tomanage changes at the service operation level? What about the data types defined in a webservice? Do we care if we change a data type that is an argument to an operation? Is changingsuch a data type really a change to the operation? The versioning of web services appears tobe a vastly complex issue.

If you examine Java, you’ll see that Sun Microsystems performs some coarse-grained ver-sioning by being able to deprecate individual methods, but it tracks the version numbers atthe class level. This is further enforced by most SCC systems. You may change an operation,but the version is associated with the file, not the operation. This is because SCC systems arefile oriented, with little or no concept of operations or methods.

Versioning OperationsI find that when most people talk about versioning web services, what they really mean is ver-sioning the operations of a web service.

Let’s start with some basic questions. Consider this: you’ve defined a brand-new webservice with a single operation. The operation is named getGreeting and it takes a string argu-ment that contains the name of the person. The operation returns a string greeting. The UMLnotation for this operation would be the following:

public getGreeting(String name) : String

Obviously, because this web service is new, it’s version 1.0. (We’ll get into version numberslater on; bear with us for now.) Next, you’re going to make a small change to this operation.You decide that the operation should take two arguments: a first name and a last name. So youredefine the operation to become the following:

public getGreeting(String firstName, String lastName) : String

Here’s the question: have you created a new version of the operation, or have you simplyremoved the old operation and created a brand-new one? The answer is important here, sotake a moment to think about it. Has the operation been changed or replaced?

You might argue that the operation has been changed because it has the same name asbefore. There’s some logic to such a statement. Let’s test that logic a bit. At the heart of anyoperation is the fact that it does something. It might do something big or it might do some-thing small, but it does something, otherwise you wouldn’t waste your time writing theoperation in the first place.

An operation is defined by what it does, not by its name. In the first getGreeting example,the operation takes a String argument and returns a String greeting. The second getGreetingoperation takes two String arguments and returns a String greeting. They are two differentoperations, even though they share the same name. This should be patently obvious simplyfrom the fact that you have to create and maintain each of these operations.

CHAPTER 11 ■ VERSIONING SERVICES240

7974CH11.qxd 3/28/07 1:28 PM Page 240

Page 266: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

So, you can safely conclude that the name of the operation is incidental and doesn’tdefine the operation in any meaningful way, at least with regard to versions. Therefore,naming strategies such as getGreetingV1(String name) and getGreetingV2(StringfirstName, String lastName) are exercises in futility and shouldn’t be pursued as realisticstrategies.

Similarly, the argument that “operation names are important in the context of the overallservice” is equally specious. If names don’t sufficiently represent operational relationshipswithin a service definition (WSDL), then they surely cannot represent those relationshipsacross different service definitions.

Remember that the operation lives inside a service (that is, a service may have multipleoperations). Let’s say that your getGreeting operation (with a single argument) lives inside aservice defined in a file Hello.wsdl. The Hello service is deployed at the URI http://localhost:7001/Hello.

Next, you create a new WSDL. Let’s call it Foo.wsdl, and it defines a Foo service with agetGreeting operation that takes a String argument and returns a String response. It behavesidentically to the same operation defined in the Hello.wsdl file. Is this a different service or thesame service? The name of the operation and the behavior is identical in both instances, yetthe definitions of the operation are contained in two different contracts or files. Take a look atFigure 11-3 and Figure 11-4 for a graphic representation of these ideas.

Figure 11-3. Single service and WSDL deployed on two nodes

CHAPTER 11 ■ VERSIONING SERVICES 241

7974CH11.qxd 3/28/07 1:28 PM Page 241

Page 267: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 11-4. Single service represented by two WSDLs, each deployed on a single node

We submit that even though they’re defined in different WSDL files, they are the sameservice. Don’t let the coding artifacts confuse you. A service does something for you. This isfundamental to the definition of a service.

Let’s go back to the restaurant analogy. A restaurant provides food and beverages to itscustomers. If we were to look at a restaurant through WSDL glasses, we might say that theoperations of a restaurant, from the customer’s point of view, are as follows:

getProducts() : ProductListsubmitOrder(ProductList) : BillpayBill(PaymentInfo) : Receipt

These are all operations within an overall Food service. Now let’s assume that our favoriterestaurant has bought the tire company next door. The owner of the newly combined restau-rant/tire company believes that there’s a strong market for customers who need to eat whilethey wait for their new tires to be installed. Unfortunately, the owner’s Food service has aProduct definition (the ProductList document is comprised of Product objects) that is tightlycoupled to food items. So, he needs a new version of the Product object that can representboth food items and tires. However, he has invested a lot of money and time in creating hiscurrent food-oriented systems and in training his waitstaff how to use it.

“I know,” he says to himself, “I’ll just create a new version of Product and ProductList,along with new getProducts() and submitOrder() operations that can handle both food itemsand tires. I’m a genius!”

Besides being the company owner, he is also a handy software developer. He sets aboutcreating new document types and new operations in his web service, thereby creating a newversion of his service. He creates document types called NewProduct and NewProductList that

CHAPTER 11 ■ VERSIONING SERVICES242

7974CH11.qxd 3/28/07 1:28 PM Page 242

Page 268: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

can represent both his product types, and hopefully any other new products that he mightchoose to sell in the future. Similarly, he adds the operations submitNewOrder() andgetNewProducts() to his web service.

Are submitNewOrder() and getNewProducts() newer versions of their submitOrder() andgetProducts() counterparts? The answer is “no.” In fact, they are new operations that provideexpanded service capabilities to the customers. Conceptually you might think of them asnewer version of old capabilities, but as far as WSDL and your web services server are con-cerned, they are entirely different operations. It’s impossible to apply a version to operationswithout creating new operations.

Versioning ServicesThat leaves us with applying versions to the service itself. At first, this appears to make moresense, because there’s a close correlation between a file and a web service. Because versioningworks well with source code, it should work well with web services also. Let’s continue thisscenario and see how that pans out for our restaurateur.

Selling tires is a lot like selling a meal. The customer can select the tires he or she wantsfrom a “menu” of tires. However, tires come in different sizes, and you don’t want to sell thecustomer tires that are the wrong size. Furthermore, tires are usually installed onto a vehicleat the time of purchase. Meals are not installed; they are simply delivered.

At first our restaurateur considers “overloading” the getProducts() method with a versionthat takes a TireSize argument, as in getProducts(TireSize): ProductList. However, hequickly realizes that WSDL doesn’t allow method overloading, so this approach is impossible.He then considers creating a getTireProductList(TireSize): TireProductList operation.Similarly, he considers creating a submitTireOrder(TireOrder) operation. Adding these twooperations to his existing FoodService would work, but his gut instincts tell him it would bethe wrong approach. He’s mixing different concerns within his FoodService. “Tires,” he rea-sons, “are really part of a different business domain. They have nothing to do with food.” As aresult, he creates a TireService to handle these automotive tasks. Once again, the concept of aversion doesn’t apply. The real solution is to create an entirely new service.

The versioning concept has taken a bit of a beating so far, but it’s not out of the runningyet. There are two other scenarios to explore; perhaps versioning will yet prove to be useful. Inthis next scenario, our entrepreneur expands his tire service to include oil changes. He createsa new operation in his TireService called changeOil(CarInfo). This new operation shares noinformation with the other operations in the TireService. He implements this service quicklyand continues to be a successful businessperson.

Here’s the question: when he added the changeOil operation and the CarInfo data type,did he create a new version of the service? If you say “yes,” can you explain why? Let’s examinethis in more detail.

Certainly, there are existing clients for his getTireProductList and submitTireOrder oper-ations. If he called the older service “version 1.0” and the changed service “version 1.1,” wouldthe current service clients care? Of course the clients doesn’t care. As far as his current clientsare concerned, they are still working with the original service. The fact that new capabilitieshave been added is of no concern to them.

What about the new clients—the ones who will use the new changeOil operation andpossibly the older operations? Will these new clients care which “version” they’re using? Again,the answer is “no.” The only person who cares about this change is our business owner who’s

CHAPTER 11 ■ VERSIONING SERVICES 243

7974CH11.qxd 3/28/07 1:28 PM Page 243

Page 269: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

writing the implementation. He cares, as does his SCC system. Remember the rule: imple-mentation is not part of the service. If we apply that principle here, then we can see that the“version” again doesn’t apply because the clients are unaffected by the change.

That brings us to the last scenario. What happens when we make a change to an existingoperation or data type in a service that will affect the current service clients? Is that changereason enough to introduce “versions” to your web services? To answer this question, we needto examine the effects of such a change in detail.

In this case, you’ll make a change to the CarInfo data type, adding a new field that mustbe set to a specific range of values and for which there is no default. This change will affectevery client of the changeOil(CarInfo) operation. Now you have a choice to make: you caneither update every client of the changeOil(CarInfo) operation to submit the new version ofCarInfo, or you can create a new “version” of the service.

Let’s start with the first option. To do this, you must know every client instance of thechangeOil operation in the TireService., and you must have the capability to change them alland deploy them at the same time you deploy your modified version of the changeOil service.If you’re fortunate enough to find yourself in these circumstances, then you must ask yourself,“Why would I version this service?” If you have the ability to change all the clients at the sametime you change the service, what’s the point of having a “version” of the service? The answeris simple. There’s no reason to “version” a service under these circumstances, because the pre-vious “version” of the service is immediately decommissioned.

Now let’s turn our attention to the much more interesting second option. With thisoption, you don’t know where all your service clients are. Similarly, even for the service clientsthat you do know, you might be unable to make the necessary changes to that client. Perhapsyou’ve lost the source code, or perhaps the service client is owned and operated by a customerwho refuses to upgrade his or her client. Either way, you’re forced to continue to run the firstversion of the service to meet your obligations with your current service client and introduce anew version of the service that uses the new data type.

So, here we come to the $64,000 question: are you maintaining two versions of the sameoperation in your service? Or are these really two different operations that simply behave simi-larly? To begin with, you cannot maintain a new “version” of the CarInfo data type in the sameWSDL. The newer version of CarInfo either has to reside in a different XML namespace thanthe current CarInfo data type, or its name must be changed so that there are no namingconflicts within the WSDL. Similarly, because WSDL doesn’t allow operation names to beoverloaded, the new version of the changeOil operation must be different. Perhaps you canchange the name to changeOilv2 to reflect this fact.

We argue that all this is a waste of time. The new version of changeOil isn’t a new versionat all. It’s an entirely new service. If you treat this as a new service, the level of complexity formaintaining these services will be reduced, and you won’t have to engage in any operation-naming shenanigans.

You can see why there’s such confusion around versioning operations or services: it’s thechanges to the operations (or the data types upon which the operations depend) that concernus and the service clients. However, now that you’ve walked through the issues in detail, youcan easily answer the question we posed at the top of this section: do you version services oroperations?

The answer is “neither”!

CHAPTER 11 ■ VERSIONING SERVICES244

7974CH11.qxd 3/28/07 1:28 PM Page 244

Page 270: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Constrained by RealityDespite our best wishes, the realities of web services intrude upon us. First and foremost isthat WSDLs are an imperfect service-expression mechanism. As a result, we’re accustomed tosome versioning scenarios in the traditional source code world that don’t work with web serv-ices; namely, extension or inheritance. For example, take the getGreeting(String name) :String operation. In a traditional object-oriented language, you could add a second methodwith a different signature—for example, getGreeting(String firstName, String lastName) :String. In the object-oriented world, there’s no conflict because the method signatures aredifferent, and that’s enough for the compiler to understand your intent. When you check thesource code back into SCC, your source file version would change from 1.0 to 1.1 (or some-thing similar, depending on the numbering strategy employed by the SCC system).

XSDs do have the core object-oriented concept of extension (and restriction for that mat-ter), but they don’t run on a smart compiler. Services live at service endpoints—distinct URIsthat are remarkably intolerant of the simple object-oriented concept of method overloading.This has significant ramifications. It means that if you want to deploy the getGreeting(StringfirstName, String lastName) : String operation, you must define it on a different web serv-ice endpoint than the getGreeting(String name) : String operation.

What about the clients? The clients depend on these contracts and interfaces. If you wereimplementing an EJB system, you’d have the benefit of having a pretty good idea who theclients are. However, in the world of SOA, it’s quite likely that clients that are either completelyunknown or that didn’t exist at the time the service was created might be consuming the serv-ices. This is another design decision point: do you try to track your service clients to helpmanage changes to your service landscape? If you do, you have an opportunity to notify thepeople who run the client applications so that they can maintain their client software as yourservice matures over time.

Ask yourself this: can you guarantee with absolute certainty that you will always knowexactly who the clients are of your services? Amazon.com has a public web service that allowsyou to write a client that will pass an ISBN to the web service and receive the price of the book,the title, and so on. If Amazon.com changed that service interface, how could it possibly knowhow many distinct service clients are calling it? Perhaps Amazon.com could change the serv-ice interface, so that along with the ISBN you could give it your e-mail address. That way, itssystem could keep track of who was using its service, so it could send you an e-mail when itmakes a significant change to the service. If there was a business case to support such aprocess, maybe Amazon.com would do so. Overall, such a strategy seems convoluted andcontrived. When you have to put this much effort into making reality fit your view of howreality should be, it’s time to find a new reality.

If Not Versions, Then What?At this point you have hopefully abandoned all thought of service versioning. It’s a wrong-headed idea. However, we still need a strategy for dealing with the inevitable changes in ourservices! Once again, let’s look to the real world for a better approach.

CHAPTER 11 ■ VERSIONING SERVICES 245

7974CH11.qxd 3/28/07 1:28 PM Page 245

Page 271: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Jeff here—I travel a fair bit and I’m no stranger to the rental car companies of the world.When I rent a car, I always try to rent the cheapest one I can get that will meet my needs.Because I often travel alone or with one other person, a compact car usually suits my needsjust fine. One time I went to the rental car counter in the airport and the following conversa-tion ensued:

Me: “I’d like to rent the cheapest car you have.”

Agent: “Great. Let me get that booked for you.”

The agent looked at her computer screen, performed the usual rental-agent voodoo andthen looked at me again.

Agent: “I’m sorry; we are all out of our compact cars. However, I can upgrade you to a mid-size car at the same rate as the compact car. Would that be okay?”

Notice that the agent didn’t offer me a different version of a car; it was an upgrade.Upgrades are usually “new and improved” or “better than” their predecessor. Think of thethings you can upgrade in your life. You can upgrade your cable TV to the “Platinum” or “Gold”level from your current “Bronze” level. You can upgrade your DSL to a faster speed. You cantrade in your old car for this year’s model (another form of an upgrade). Newer is better in theadvertising world and the IT world. No one is talking about replacing their current web-enabled systems with older client-server solutions or mainframes. The past is dead in the ITworld. Long live the future!

Let’s go back to our getGreeting(String name) operation and look at it with new eyes.When this operation was first implemented, it met the requirements of the time just fine.However, over time the requirements changed. Requirements always change. Eventually therequirements changed sufficiently to warrant the development of the new service getGreeting(String firstName, String lastName). This new getGreeting operation is an upgrade overthe previous one.

IT people need to consider themselves as businesspeople first, and technical expertssecond. The IT business is to deliver services (think products) to its customers (the line-of-business folks, partners, suppliers, and so on). With this view of the world, things start to makemore sense, especially when you provide new and better products for your customers to use.

For example, an automotive company produces new vehicle models every year. As muchas it would like to, it cannot force its customers to upgrade to the new models. In fact, it willcontinue to produce machine parts to service the vehicles it produced in prior model years.However, as time moves forward, it begins to sunset the production of the machine parts forthe very oldest (or least popular) models, eventually ceasing their manufacture completely.Try finding a carburetor for a Ford Model T sometime. You can find it, but it isn’t made by FordMotor Company any more.

The service-oriented IT shop works the same way. They produce services (think “products”)to meet the needs of their customers. As time moves forward, new and improved services willbe made available to the IT customer base. Just like the automobile company, as much as theIT shop would like to force its customers to upgrade to the newest services, it simply mustmaintain the previous services until it becomes feasible to retire them. The time to retire aservice is determined by the level of demand for that service and the cost of maintaining thatservice. It’s a business decision made in the same manner that the other lines of businessmake on a daily basis. If IT determines that a service needs to be retired due to cost, but a line

CHAPTER 11 ■ VERSIONING SERVICES246

7974CH11.qxd 3/28/07 1:28 PM Page 246

Page 272: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

of business (LOB) still relies on it, then that LOB might have to resort to hiring a custom pro-grammer to maintain the service on its behalf, just like a Model T owner might have to hire amachinist to manufacture a new carburetor if he or she wants to keep driving that Model T!

Notice with this new mental model of “upgrade,” we don’t seem to be fighting reality any-more. It parallels the real world and behaves in a more natural fashion. That is not to say thattransitioning to this new view of the world will be easy. Many procedural programmers neverunderstood the need for event-driven or object-oriented programming models. Similarly,many people will cling to the idea that web services must be versioned, especially when wesee so much discussion about it in today’s press. In our mind, those arguments are meaning-less. The new view of the world has arrived.

As any salesperson will tell you, you cannot rely solely on the customer to buy the productthat’s best for him or her. This applies to the IT department and its products as well. The ITdepartment needs its own “salespeople”: experts in the IT products that can help to advise andguide customers to the right products and services. The “right” products and services arethose that will best meet the customers’ needs now and into the foreseeable future.

Imagine for a moment that you’re relatively ignorant about today’s networking technol-ogy. Your roommate has a wireless-B router and you would like to connect to it. So you go toyour local electronics store and ask the sales associate there to help you pick a wireless-B cardfor your computer. If the sales associate is unskilled, he or she will direct you to the aisle wherethey are selling wireless-B adapters at a bargain price. However, if the salesperson is moreskilled, he or she will ask you a few questions first. Here’s an example conversation:

Customer: “I need a wireless-B adapter for my computer.”

Salesperson: “Great. We have some on sale for a very good price today because they’rebeing discontinued.”

Customer: “They’re being discontinued?”

Salesperson: “Yes. Hardly anyone uses wireless-B technology anymore. The predominanttechnology is wireless-G. It’s much faster than B and far more common in airports andcoffee houses. Plus, it’s backward compatible with wireless-B routers.”

Customer: “Are they very expensive?”

Salesperson: “They run about $50. They’re half the price of the new wireless-N technologycards. Wireless-N is 12 times faster than wireless-G and it has 4 times the range. Thoseadapters cost around $120.”

Now the customer has some very good information to use to make a decision that’s rightfor him. Perhaps, as a poor college student, he’s better off buying a wireless-B adapter fromthe discount bin for $9.99. Or it might be that $50 is well within his price range and now hegets the benefit of using his wireless laptop at many more places. Perhaps he’s a big iPodjunkie and downloads music and videos on a daily basis. In this case, the wireless-N is theright purchase for him. It’s the responsibility of the salesperson to help a customer identifythe product that’s right for him or her.

The process is exactly the same at a service-oriented IT shop. There must be a salespersonwho knows the IT product line well. Like the different wireless adapters, the services offeredby the IT shop also have a life cycle. Some are brand new and more expensive, while othersmight be dirt cheap but at the end of their life. IT must employ these sales experts to ensurethat its customers are informed enough to make good decisions.

CHAPTER 11 ■ VERSIONING SERVICES 247

7974CH11.qxd 3/28/07 1:28 PM Page 247

Page 273: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Now, it might seem crazy to have a salesperson in an IT shop. These folks don’t need tobe sales professionals per se. More often than not, they will be architects who can advise cus-tomers as to the services that would best meet the customer’s needs. The architects will knowwhich services are deprecated (at the end of their life), which ones are current, and whichones are either brand new or are in development.

From this scenario you see that it’s critical to know where each service is in the servicelife cycle. The service life cycle is fairly straightforward (see Figure 11-5). Services begin life assoon as planning begins. A planned service has a name and a general description of its pur-pose. Assuming that the service is approved for development, it moves into the developmentstage. When development is complete, it’s released into the IT department’s service portfolio.A service portfolio is simply the group of services that are currently offered to customers. Asthe service ages (that is, it becomes less and less useful), the IT department might release anupgrade to the service. When the upgrade is released, the older service becomes deprecated.A deprecated service is still in production and is still available for customers to use, but it isn’trecommended that any new service consumers use the service. The last step in the cycle is toretire the service. A retired service is removed from the production environment and is nolonger offered by the IT department.

Figure 11-5. The service life cycle

Naturally, the steps in the service life cycle can be modified by each IT department to bet-ter meet the needs of its company. For example, your company might want to insert a“funded” stage between planning and development. Alternatively, your company might opt tocreate a “quarantined” stage between the deprecated and retired stages to ensure that theservice really is no longer in use before it’s completely retired. You can customize the servicelife cycle to meet your needs.

Because it’s important to know the stage of each service in the service life cycle, you mustrecord that information for later retrieval. There are a number of ways to record service lifecycle information; the method you choose will be influenced by the tools you have at your dis-posal. Before deciding on where to store the information, let’s first consider where you’d like tofind this information. Using our wireless networking scenario as a guide, we’d strongly suggestthat this information be available at design time. That means that the current life cycle stageof the service should be easily found in your service catalog or portfolio.

In addition, it might be useful to provide this information during runtime to the serviceclients. This means either providing the life cycle stage as metadata in a service repository oras header information in the SOAP message itself. How the client handles this information is

CHAPTER 11 ■ VERSIONING SERVICES248

7974CH11.qxd 3/28/07 1:28 PM Page 248

Page 274: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

the business of the client and not something that we, as service providers, should dictate.However, we always want to give our service clients the most opportunity to receive criticalinformation about our services, so we highly recommend making this information available atruntime.

Some life cycle stages deserve additional metadata to be truly effective. For example, ifthe service is in the Development stage, you should also include the planned release date ofthe service. Obviously that date might change, but the planned release date will be importantinformation to potential consumers of that service. Similarly, a service in the Released stageshould provide the date of its release. A Deprecated service should record the planned date ofits retirement, and Retired services should record the actual date they were retired.

In the real world, services represent business functionality. Rarely does a business func-tion disappear completely. Usually it’s upgraded. Therefore, when a service is deprecated andmarked for eventual retirement, you’ll usually have its replacement either planned, in devel-opment, or released into production. You might even have several different upgraded versionsof a service in production at the same time. Wireless-B adapters were still big sellers when thewireless-G adapters were first introduced. In terms of our service life cycle, both those prod-ucts were in the Released stage at the same time, but every wireless salesperson could tell youthat wireless-G was the successor of wireless-B. You need the same ability with your services.Therefore, you need an additional bit of metadata that points to a newer service that super-sedes the service in question.

Let’s take a look at some examples of this information. Imagine for a moment that youneed to retrieve customer information to fulfill the needs of a service you’re creating. Your cur-rent service portfolio information is held in a database. You search the database for servicesthat contain the word “Customer” in hopes of finding a service that will meet your needs. Yoursearch returns several records, as noted in Tables 11-1 through 11-3. Beginning with Table 11-1,you can see immediately that the service is still available, but it has been deprecated on July2006. You can also see from the metadata that the successor to the service is also namedgetCustomerInfo and exists at http://esb.mycorp.com/customer2.

Table 11-1. Multiple Services Representing the Service Life Cycle in Action

Tag Value

Service name getCustomerInfo

URI http://esb.mycorp.com/customer

Life cycle stage Deprecated

Life cycle date July 2006

Successor getCustomerInfo

Successor URI http://esb.mycorp.com/customer2

Next we examine the successor URI, as shown in Table 11-2. From the life cycle stage youcan see that the service is in production and was released on June 2006; perfect! But wait;you can also see that this current service already has a successor defined for it. You need toexamine the record of this successor service before you make any final decisions about whichservice to use.

CHAPTER 11 ■ VERSIONING SERVICES 249

7974CH11.qxd 3/28/07 1:28 PM Page 249

Page 275: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Table 11-2. The Current getCustomerInfo Service Metadata

Tag Value

Service name getCustomerInfo

URI http://esb.mycorp.com/customer2

Life cycle stage Released

Life cycle date June 2006

Successor getCustomerInfo

Successor URI http://esb.mycorp.com/customer3

Table 11-3 shows the metadata for the getCustomerInfo service that’s in development.If you intend to release your service on or after July 2007, you should seriously consider usingthis service instead of the getCustomerInfo service that is currently operational. If this servicedoesn’t meet your timeline needs, then you need to use the service that’s currently inoperation.

Table 11-3. The Future getCustomerInfo Service Metadata

Tag Value

Service name getCustomerInfo

URI http://esb.mycorp.com/customer3

Life cycle stage Development

Release date July 2007

Successor None

Successor URI

As you can see, maintaining standard metadata about each service in your portfolio iscritical to your success in SOA. You not only need to know what the service does, you need tounderstand where it is in its life cycle, and when the IT department intends to change the lifecycle status. You also need to know how this service relates to other services, at least withregard to the upgrade path of the service.

The Future of ITI’d like to invite you to take a walk with me into the future of IT, and the future of business in aservice-oriented world. In this future world, service orientation is the norm, not the exception.Services are fundamentally understood by all IT professionals to the point where they’re takenfor granted, similar to how we regard compiler technology today. In our service-oriented ITshop, the IT professionals’ foremost thought is to keep the customer happy. Customers areother departments within their enterprise. Additionally, they view their partners and suppliersas customers whenever those partners and suppliers need to make use of the enterprisearchitecture.

CHAPTER 11 ■ VERSIONING SERVICES250

7974CH11.qxd 3/28/07 1:28 PM Page 250

Page 276: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Our service-oriented IT department creates new products (that is, services) that are eithercurrently needed by its customers, or that will be needed in the near future. This IT shop willeven engage in some speculation and create products that it believes its customers mightneed in the immediate future. Its job is to meet and exceed the needs of its customers.

The customers (other departments in the company, or the company’s partners and sup-pliers) will often “shop” for the products that they need. Therefore, the IT department must beable to provide a menu of products and services that it can offer to its customers, along withan idea of the associated costs. Customers need to know what they’re buying and how much itwill cost them to make sound purchasing decisions.

Additionally, the customers have the option of using services provided outside of the ITdepartment. Application Service Providers (ASPs) have evolved to become Commercial ServiceProviders (CSPs): companies that make their living by selling service-oriented products tocustomers. These CSPs are able to leverage the costs of developing services across multiplecustomers, just as product companies do today. Service customers within an enterprise nowhave choices about where they’ll get their services. For some services, the CSPs are a cheap,fast, and reliable solution. For other services that are specific to their business, they might optto use services developed by their internal IT department.

As a result, some IT departments will disappear altogether. The enterprise simply won’trequire them. If CSPs can provide all the functionality needed by the enterprise, then main-taining an IT shop won’t make financial sense. However, for the majority of larger enterprises,their need to differentiate themselves from their competitors will force them to become agile,composing atomic services provided by the CSPs along with custom services developed in-house into processes and higher-level services. Only a small number of companies will needto employ highly specialized developers and architects to create completely new services.

That last paragraph might worry you. We don’t predict the end of the software profession,only another evolutionary change in our industry. There was a time in computing historywhen large “armies” of key punch operators were required to enter software commands onpunch cards that were used to program mainframe computers. The advent of compilers andinterpreters (along with an increase in the power of the computers themselves) put an endto that job description. However, no one laments the loss of key punch operators today. Thepeople who worked as key punch operators moved on to other jobs. (Jeff here—I know thisbecause my mother used to be a key punch operator.) They adapted to a new reality. Similarly,with outsourcing in many of today’s companies, software professionals are adapting to a newmarketplace. Service orientation brings its own share of changes. Low-level coding willbecome commoditized. Service creation, orchestration, and optimization will arise as a newfrontier.

SummaryChange is inevitable. You can fight against it, but history teaches us that such efforts arelargely a waste of time. The Luddites of the world don’t make history, except as curiosities andhistorical footnotes. To rail against change is to make yourself a dinosaur and doom yourselfto extinction. The key to success is the ability to adapt; to thrive in chaos while your competi-tors drown in it. SOA won’t just change your IT shop—it will change your company, yourmarketplace, and the way the world does business.

CHAPTER 11 ■ VERSIONING SERVICES 251

7974CH11.qxd 3/28/07 1:28 PM Page 251

Page 277: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

7974CH11.qxd 3/28/07 1:28 PM Page 252

Page 278: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Administration, Operations,and Management

Design and development is only part of the ALSB life cycle. Modern IT shops usually deploytheir software into distinct environments. Commonly, these environments can be classified asDevelopment, Testing, Stage, and Production. That list is by no means definitive, but it is rep-resentative. As software is developed, it is deployed into multiple environments. This processis complicated by the fact that the software deployed in each environment is often tied to localsoftware assets that are part of the environment, not part of the software itself. No product iscomplete without providing capabilities to ease these operational challenges. In this chapter,we will discuss administration, operations, and management capabilities of ALSB.

Support for Team DevelopmentModern software is rarely developed by a single person. Today, software is developed, tested,released, and maintained by specialized teams of people. ALSB is written to allow these teamsto perform their jobs in unison.

The Change CenterThe Change Center is a session controller that solves the problem of a shared design environ-ment for team development where multiple users could simultaneously access the web-baseddesign environment to configure a project. This could create conflicts if one user’s changesoverride another user’s work. The Change Center allows for team collaboration by providingeach user with a unique session that represents his or her sandbox. Users can modify the arti-facts, such as routing policies or pipelines, or add and remove resources, such as WSDL orXML schema, within their own sessions. Once satisfied with the changes, users can thenenable or activate all the changes in a single transaction that commits the session.

Conflict ManagementAn ALSB developer must first create a session before making changes. ALSB provides a built-inreferential integrity checker that keeps track of the various resources (WSDLs, XSDs, webservices, etc.) and their interdependencies. For example, if a WSDL imports an XSD, thenthe WSDL depends on the XSD. This dependency is metadata that is stored within the ALSBmetadata repository. The checker makes sure that there are no broken references and will

253

C H A P T E R 1 2

7974CH12.qxd 3/28/07 1:41 PM Page 253

Page 279: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

automatically detect conflicts between resources and their references. Conflicts may show upin your session as a result of session activation by another user. The system will prompt youwhether to accept the change or try to resolve the conflict in another way. A session with con-flicts cannot be checked in without first resolving those conflicts.

Some types of conflicts are detected only when you activate the session or at executiontime, but the vast majority of conflicts are detected early, while you are creating resources.These types of conflicts arise because of missing underlying server resources configured aspart of a URI or other parameters while defining a service. For example, you can define adata source name as a parameter in the URI for a business service endpoint, but the actualresource may not be present. Since the referential integrity checker does not actually knowabout this resource, the conflict is not flagged, and a user may continue working on the proj-ect. When trying to commit such a session or during execution time, the underlying resourcesthat are specified, such as the URI, are checked and conflicts are raised. To avoid such con-flicts, I recommend that you first create your application server resources (data sources,queues, topics, etc.) before referencing them through a field in the service definition.

Undo and RedoThe Change Center in ALSB keeps an audit trail of all the changes and sessions, so the changescan be easily undone, and conflicts on concurrent modification of artifacts can be resolvedthrough administrative means. The ALSB Change Center has a smart interface that allows youto create incremental shadow copies of artifacts from the original repository to the sandbox.This means that, unless you modify a particular resource such as an XSD, no resource will becopied into the session even though the whole project can be accessed by the user. Thisshadow copy feature mitigates the conflicts that can occur because of unintentionally concur-rent modifications to artifacts.

How to Resolve ConflictsIn the Change Center, the user is notified of the conflicts in his or her project; a listing of allconflicts in the system is available for viewing by simply clicking the View Conflicts hyperlink.Let’s take an example project and walk through various conflicts and their resolutions. Assumethat we have a project called “Hello World” that has a Hello proxy service, a Hello WSDL, and aHello business service. Let’s say that there are two users, Jane and John, working to modify thesame project. At first, they will not notice each other’s changes, since John simply adds a newHello2 WSDL, which he commits by activating a session. He then intends to use this WSDL ina conditional routing policy that will modify the proxy service pipeline. Jane also has madechanges to the same proxy pipeline and added a stage for logging purposes. When John com-mits his changes, Jane will see a conflict, because John has committed changes that affect thepipeline Jane is still modifying, as shown in Figure 12-1.

CHAPTER 12 ■ ADMINISTRATION, OPERATIONS, AND MANAGEMENT254

7974CH12.qxd 3/28/07 1:41 PM Page 254

Page 280: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 12-1. Summary of conflict and notification

If you click the View Conflicts(2) link in the Change Center, you will navigate to the Con-flicts page, shown in Figure 12-2, which is a detailed view of the conflicts that conveys thefollowing information:

• The name of the service where the conflict occurs

• The nature of the change, whether it’s an update, addition, or deletion

• The user who made the change

• An option to resolve the conflict by synchronizing your changes with the updatedversion of the changed resource and accepting the change

CHAPTER 12 ■ ADMINISTRATION, OPERATIONS, AND MANAGEMENT 255

7974CH12.qxd 3/28/07 1:41 PM Page 255

Page 281: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

In our example, Jane decides to accept the changes by clicking the Synchronize icon. Inanother situation, the user could ignore the conflict, in which case the change to the conflict-ing artifact made by John will be overlaid by Jane’s change to that artifact.

System AdministrationSystem administration covers areas within ALSB that have a global impact and need to bedefined only once. The following list highlights some of the key areas that you can set globallyto ensure proper functioning of the service bus:

• UDDI configuration: UDDI is the default interface used by ALSB to access a service reg-istry, and more importantly, an AquaLogic Service Registry. This special registrycontains the model definitions of AquaLogic services and resources often referred to ast-models. You can set up multiple registries; for example, you can create one for pub-lishing for wide reuse of ALSB-hosted services and another from which productionservices can be consumed. There is also an option to enable autoimport of UDDI meta-data from a predefined registry so that the ALSB system can keep its internal metadataand registry in sync. And there is an option to autopublish proxy services to a desig-nated registry.

• JNDI providers: These are used as part of the EJB transport; they specify the JNDIprovider to look up to locate the EJB.

• Email/SMTP Servers: This specifies the e-mail server that is to be used globally forsending alerts and configuring notifications. Configuring multiple servers is supported.You can filter and search through the e-mail servers list and edit and view details ofeach server.

Operations SettingsUnder the Operations menu, you can configure settings to display and refresh the dashboard,as well as to handle monitoring and tracing. Tracing refers to a mode in which all informationabout the proxy service invocation and its runtime execution is recorded. This information isused for debugging and troubleshooting. Enabling global monitoring tells the monitoring sub-system to start collecting information for the services based on their individual settings. Youcan enable and disable the following options under the Operations tab:

CHAPTER 12 ■ ADMINISTRATION, OPERATIONS, AND MANAGEMENT256

Figure 12-2. View details of the conflict

7974CH12.qxd 3/28/07 1:41 PM Page 256

Page 282: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

• Monitoring

• SLA violation alerts

• Alerts generated from proxy pipeline execution

• Reporting system

• Logging

• Tracing for each proxy service

Access Control ConfigurationSecurity configuration deals with setting up console security, user management policies, roles,and Access Control Lists (ACLs) that govern the security of the console, the runtime, andaccess to the underlying resources utilized by ALSB. Setting up security for an applicationserver or the Java EE 5 resources is outside the scope of this book. Instead, we will focus onthe setting that you need to apply to make access to proxy services secure. There are two levelsof security that need to be configured to make a proxy service secure. As we discussed inChapter 9, numerous combinations of security strategies can be applied to provide access toonly authentic and authorized parties. All of those strategies require the user to configuresome authentication or authorization policies using the Security Configuration section of theALSB console.

When configuring a proxy, you must specify the security strategy, such as HTTPS ormessage-level security, to be enforced through a Web Service Security policy. Once the secu-rity is enabled, the proxy appears in the list of services that must be assigned access policies,as shown in Figure 12-3.

Figure 12-3. A list of proxy services under the security configuration section

For example, assume that we have enabled the Web Service Security username tokenprofile for the Hello Secure Proxy. In Figure 12-3, notice that there’s a View Policies hyperlinkunder the Service Authorization Policy column in addition to the one under TransportAuthorization Policy. Figure 12-4 shows the detailed page for configuring a policy where youcould restrict access to the proxy service based on the time of day, user, group, role, and soforth by choosing a predicate. More than one policy can be added as a predicate.

Once the policy is defined, only the users authorized by this policy can access the proxyservice. At runtime, ALSB extracts the username and password from the Web Service Securityheaders and delegates authentication and authorization checks to the underlying securitysubsystem.

CHAPTER 12 ■ ADMINISTRATION, OPERATIONS, AND MANAGEMENT 257

7974CH12.qxd 3/28/07 1:41 PM Page 257

Page 283: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 12-4. Configuring an access control policy

DeploymentDeployment is the process of installing software onto servers. For ALSB, it is the process ofmoving one or more projects and configurations onto a server or a cluster of servers. Whenyou move software from one environment to another, problems often arise because externalresources, such as database names and URIs, differ between environments.

For example, assume we are moving a proxy service that makes a call to a database. Thedatabase has the same schema in each environment (development, testing, etc.), but the con-nection information (the username, password, database URL, etc.) does change. The proxyservice needs the Java Database Connectivity (JDBC) driver in order to make the database call.How do we move the proxy service between environments without disrupting the dependencyon the JDBC driver? What happens when even the name of the JDBC driver changes?

The ALSB console gives you the ability to export and import projects and system configu-ration information. You can perform these functions from within the System Administrationsection of the console, under the heading Import/Export. This is fine for development pur-poses. However, when you are moving your configurations from one environment to the next,especially when those configurations grow complex, you need to automate the deploymentprocess.

ALSB versions 2.5 and later provide you, the administrator, with the ability to automatethe deployment process through the use of scripts. ALSB uses the WebLogic Scripting Tool(WLST). This scripting language is based on the Jython scripting language. The developers ofthe ALSB have provided public APIs that are easily accessible using WLST. These APIs aredesigned not only to make it easier to deploy ALSB projects between environments but toinclude a tremendous amount of administrative functionality. If you are in charge of main-taining ALSB instances in various environments, including production environments, youneed to make it a point to learn WLST and the public ALSB APIs.

As previously in this book, we will use real projects to demonstrate how to write and runthese scripts. We need to create a production environment so that we can take our sample

CHAPTER 12 ■ ADMINISTRATION, OPERATIONS, AND MANAGEMENT258

7974CH12.qxd 3/28/07 1:41 PM Page 258

Page 284: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

project from our traditional alsb_book domain into our ALSB_Prod domain. While our exam-ples will only cover moving projects in this simple set of environments, the principles areexactly the same when moving projects among any number of environments.

First, we need to create our production ALSB domain. Create the production domain inthe same parent directory in which you created the alsb_book domain in Chapter 2. Keepingall of your domains in the same parent directory is a good practice; it makes them easy to find,especially if you have multiple administrators.

Run the Configuration wizard. You can find this tool in the Start ➤ Programs ➤ BEA Prod-ucts ➤ Tools menu (if you are using Windows). Alternatively, you can find the script file thatruns the Configuration wizard in the <%BEA_HOME%>\weblogic92\common\bin directory. Run theconfig.cmd file if you are on a Windows platform or the config.sh file if you are on a Unixplatform.

Once you have the Configuration wizard running, follow the wizard’s steps and specifythe values defined in Table 12-1. If a screen appears in the Configuration wizard but you don’tsee the name in Table 12-1, just click the Next button to move to the next screen in the wizard.

Table 12-1. The Domain Creation Values for the alsb_prod Domain

Screen Name Value

Welcome Create a new WebLogic Domain Select

Select Domain Source Generate a domain Select

Select Domain Source WebLogic Server (Required) Checked

Select Domain Source Workshop for WebLogic Platform Checked

Select Domain Source ALSB Checked

Configure Admin User name weblogic

Configure Admin User password weblogic

Configure Admin Confirm user password weblogic

Configure Server Start Development Mode Select

Configure Server Start BEA Supplied JDKs Sun SDK

Customize Environment Yes Select

Configure the Administration Server Listen Port 7101

Configure JDBC Sources For Each Data Source Set the DBMS port to9193. (You will need todo this for all four JDBCdata sources.)

Run Database Scripts Run Scripts Press the button.

Create WebLogic Domain Domain name alsb_prod

Create WebLogic Domain Domain location d:\domains (or theparent directory whereyou previously installedthe alsb_book domain)

CHAPTER 12 ■ ADMINISTRATION, OPERATIONS, AND MANAGEMENT 259

7974CH12.qxd 3/28/07 1:41 PM Page 259

Page 285: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Do not run the Admin server in the last step of the wizard. You will need to do a little moremanual configuration of this domain, so you can run it and the alsb_book domain’s server atthe same time on your machine. Specifically, we will need to change the DEBUG_PORT setting toa value other than the default 8453, since that port will be used by the alsb_book domain. Todo this, you will need to find and edit the setDomainEnv.cmd file (setDomainEnv.sh for Unixusers) in the \bin subdirectory of the alsb_prod domain. Search for the string 8453 and replacethat value with the value 8553 (using our standard practice of adding 100 to the port numberfor the alsb_prod domain). Save the file.

You can now start the alsb_prod domain by running the startWebLogic.cmd script inthe alsb_prod domain directory. If the alsb_book server is not running, start that server nowalso. We will begin by moving the Hello World project into the alsb_prod domain. Since theHelloWorld project depends on the HelloWorldService web service, we will need to ensurethat the web service is also deployed on our new domain. This is a simple matter in Workshop.Ensure that you are using a Workshop perspective (so that the Servers tab appears at the bot-tom of the Workshop IDE). Right-click the Servers tab, create a new server to represent thealsb_prod domain, and assign the HelloWorld web service project to the alsb_prod server.

Deployment Automation BasicsWe will begin with a very simple example. We will export the HelloWorld project from thealsb_book domain and import it into the alsb_prod domain. In this example, we won’t worryabout environment variables; we’ll get to those more complex examples a little later on. Fornow, let’s focus on the basics, simply importing and exporting projects.

In Workshop for WebLogic, there is a project named Administration. Open that projectand look in the ExportImport folder, which includes a set of files that will allow you to exportthe HelloWorld project from the alsb_book domain and import the project into the alsb_proddomain. Table 12-2 provides a quick overview of the files and how they are used.

Table 12-2. Files for Exporting and Importing a Project

File Description

build.xml This is the Ant build script that contains the instructions for exportingand importing projects among ALSB servers. This is really boilerplatecode, because all of the customization is held in other files.

customize.xml This is a sample customization file that can be created when exportingprojects or resources from a server environment. You will often modifythis file after an export to configure the environment variables beforeyou perform the import step. This file is not always needed.

export.properties This is a property file used by Ant to specify the connection informationwhen connecting to an ALSB server, along with additional informationabout the project we are going to export and whether or not to use apassphrase on the exported file.

export.py This is the Jython script that contains the commands for exportingprojects and resources.

import.properties Like the export.properties file, this file contains connection informationand some other details to be used when importing the project.

import.py This is the Jython script that will run when we import the project.

CHAPTER 12 ■ ADMINISTRATION, OPERATIONS, AND MANAGEMENT260

7974CH12.qxd 3/28/07 1:41 PM Page 260

Page 286: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Your first step is to edit the export.properties and import.properties files to match yourenvironment. Listing 12-1 shows the export.properties file in detail. The bulk of the fieldsshould be self-explanatory.

Listing 12-1. The export.properties file from the ExportImport Folder

################################################################### ALSB Admin Security Configuration ###################################################################adminUrl=t3://localhost:7001exportUser=weblogicexportPassword=weblogic

################################################################### ALSB Jar to be exported ###################################################################exportJar=export.jar

################################################################### Optional passphrase and project name ###################################################################passphrase=aqualogicproject=HelloWorld

################################################################### Optional, create a dummy customization file ###################################################################customizationFile=customize.xml

There are two fields in the export.properties file that are worth mentioning specifically.The first is the passphrase variable, and it is used only if you want to use a password toprotect the file you are going to export from ALSB. It’s purely optional. The second field iscustomizationFile, and this variable allows you to specify the name of the customization filethat will be generated by the export process (or the import process, if you are editing theimport.properties file). The customizationFile variable is also optional. If you do not specifya file name, no file will be generated.

To perform the export, open a command prompt (a console window on Unix) and navi-gate to the bin directory of the alsb_book domain. On my machine, I use the followingcommand line:

Cd \domains\alsb_book\bin

Once you are in the bin directory of the alsb_book domain, execute the commandsetDomainEnv. This will run a script to correctly set all of the environment variables for theALSB domain. You must run this command first, or the Ant script will fail, because it iscounting on these environment variables to be set correctly when it runs.

CHAPTER 12 ■ ADMINISTRATION, OPERATIONS, AND MANAGEMENT 261

7974CH12.qxd 3/28/07 1:41 PM Page 261

Page 287: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Now, navigate to the ExportImport directory of the Administration project in the Work-shop workspace. Enter the command ant export to run the export process. Your consoleshould display a series of messages similar to those in Listing 12-2.

Listing 12-2. The Output of the Export Ant Task

Buildfile: build.xml

export:[echo] exportscript: export.py[java] Initializing WebLogic Scripting Tool (WLST) ...[java] Welcome to WebLogic Server Administration Scripting Shell[java] Type help() for help on available commands[java] Loading export config from : export.properties[java] Connecting to t3://localhost:7001 with userid weblogic ...[java] Successfully connected to Admin Server 'AdminServer' that belongs to

domain 'alsb_book'.[java] Warning: An insecure protocol was used to connect to the[java] server. To ensure on-the-wire security, the SSL port or[java] Admin port should be used instead.[java] Location changed to domainRuntime tree. This is a read-only tree

with DomainMBean as the root.[java] For more help, use help(domainRuntime)[java] ALSBConfiguration MBean found[java] default[java] Export the project default[java] ALSB Configuration file: export.jar has been exported[java] [Project default][java] EnvValueCustomization created[java] [com.bea.wli.config.customization.FindAndReplaceCustomization@cb6b96][java] ALSB Dummy Customization file: customize.xml has been created

BUILD SUCCESSFULTotal time: 37 seconds

With the export complete, we are ready to import the project into the alsb_prod environ-ment. When you do this in a real environment at your company, execute the appropriatesetDomainEnv script again. However, our two sample domains are similar enough that we don’tneed to do this. Simply run the Ant import command to import the HelloWorld project intothe alsb_prod server.

The import process will run as smoothly as the export process did. When the importcompletes, open a web browser and browse to the ALSB console for the alsb_prod server athttp://localhost:7101/sbconsole. Navigate to the HelloWorld project, and take a look atthe Configuration Details page shown in Figure 12-5. Do you see the problem illustratedin this Configuration Details page?

CHAPTER 12 ■ ADMINISTRATION, OPERATIONS, AND MANAGEMENT262

7974CH12.qxd 3/28/07 1:41 PM Page 262

Page 288: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 12-5. Endpoint URI is pointing to the wrong port!

When the project was imported, it used the endpoint URI that applies to the alsb_bookserver (port 7001). We need to update the endpoint URI to use port 7101, the port used by thealsb_prod server. We must alter the export.py file (see Listing 12-3) so that it looks for environ-ment variables that contain the string 192.168.1.100:7001 and replaces that string with thevalue localhost:7101.

Listing 12-3. The export.py File

from java.io import FileInputStreamfrom java.io import FileOutputStreamfrom java.util import ArrayListfrom java.util import Collectionsfrom com.bea.wli.sb.util import EnvValueTypesfrom com.bea.wli.config.env import EnvValueQuery;from com.bea.wli.config import Reffrom com.bea.wli.config.customization import Customizationfrom com.bea.wli.config.customization import FindAndReplaceCustomization

import sys

#==============================================================================# Utility function to load properties from a config file#==============================================================================def exportAll(exportConfigFile):

try:print "Loading export config from :", exportConfigFileexportConfigProp = loadProps(exportConfigFile)adminUrl = exportConfigProp.get("adminUrl")

CHAPTER 12 ■ ADMINISTRATION, OPERATIONS, AND MANAGEMENT 263

7974CH12.qxd 3/28/07 1:41 PM Page 263

Page 289: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

exportUser = exportConfigProp.get("exportUser")exportPasswd = exportConfigProp.get("exportPassword")

exportJar = exportConfigProp.get("exportJar")customFile = exportConfigProp.get("customizationFile")

passphrase = exportConfigProp.get("passphrase")project = exportConfigProp.get("project")

connectToServer(exportUser, exportPasswd, adminUrl)

ALSBConfigurationMBean = findService("ALSBConfiguration", ➥

"com.bea.wli.sb.management.configuration.ALSBConfigurationMBean")print "ALSBConfiguration MBean found"

print projectif project == None :

ref = Ref.DOMAINcollection = Collections.singleton(ref)if passphrase == None :

print "Export the config"theBytes = ALSBConfigurationMBean.export(collection, true, None)

else :print "Export and encrypt the config"theBytes = ALSBConfigurationMBean.export(collection, true,➥

passphrase)else :

ref = Ref.makeProjectRef(project);print "Export the project", projectcollection = Collections.singleton(ref)theBytes = ALSBConfigurationMBean.exportProjects(collection, passphrase)

aFile = File(exportJar)out = FileOutputStream(aFile)out.write(theBytes)out.close()print "ALSB Configuration file: "+ exportJar + " has been exported"

if customFile != None:print collectioncustomList = ArrayList()query = EnvValueQuery(None, ➥

Collections.singleton(EnvValueTypes.WORK_MANAGER), collection, ➥

false, None, false)customEnv = FindAndReplaceCustomization(➥

'Set the right Work Manager', query, ➥

'Production System Work Manager')customList.add(customEnv)

CHAPTER 12 ■ ADMINISTRATION, OPERATIONS, AND MANAGEMENT264

7974CH12.qxd 3/28/07 1:41 PM Page 264

Page 290: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

# Uncomment the next three lines to update the server and port to# the alsb_prod environment correctly#query = EnvValueQuery(None, ➥

Collections.singleton(EnvValueTypes.URI_ENV_VALUE_TYPE), ➥

collection, false, '192.168.1.100:7001', false)#customEnv = FindAndReplaceCustomization('Update to the correct ➥

server and port number', query, 'localhost:7101')#customList.add(customEnv)

print 'EnvValueCustomization created'print customListaFile = File(customFile)out = FileOutputStream(aFile)Customization.toXML(customList, out)out.close()

print "ALSB Dummy Customization file: "+ customFile + " has been created"except:

raise

#===================================================================================# Utility function to load properties from a config file#===================================================================================

def loadProps(configPropFile):propInputStream = FileInputStream(configPropFile)configProps = Properties()configProps.load(propInputStream)return configProps

#==================================================================================# Connect to the Admin Server#==================================================================================

def connectToServer(username, password, url):connect(username, password, url)domainRuntime()

# EXPORT script inittry:

exportAll(sys.argv[1])

except:print "Unexpected error: ", sys.exc_info()[0]dumpStack()raise

CHAPTER 12 ■ ADMINISTRATION, OPERATIONS, AND MANAGEMENT 265

7974CH12.qxd 3/28/07 1:41 PM Page 265

Page 291: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

There are two critical commands highlighted in Listing 12-3. The first is the EnvValue-Query() command. In reality, this is not just a command in a script; it is the Java constructorfor the EnvValueQuery class, which is found in the package com.bea.wli.config.env. This classallows you to specify the type of information you are looking for. In our example, we werelooking for endpoint URIs. ALSB does not differentiate between endpoint URIs and any otherURI. By passing in EnvValueTypes.URI_ENV_VALUE_TYPE, we can confine our search to URIswithin the system. If you passed a null value here instead, you would end up searching alltypes of environment values. Of course, you can look for other specific types of data. If youexamine the Javadoc for the com.bea.wli.sb.util.EnvValueTypes class, you will see a longlist of data types you can search—everything in ALSB from e-mail alert destinations to workmanagers is searchable.

The second important method is FindAndReplaceCustomization(). This method takesthree arguments: a description of the customization, the query that contains the informationwe want to replace, and the new string value.

The purpose of the export.py file is to specify the types of information that will need to becustomized when the project is deployed into a new environment. These customizations arestored in the customize.xml file that the export.py script creates. As a result, you will need tohave an export.py file for every project (or possibly a set of related projects) in your servicebus. For example, if you have a set of related projects that get deployed at the same time, youwould create a single export.py script to handle them.

Now that you understand what the export.py script is doing, the resulting customize.xmlfile (Listing 12-4) should make sense. The second customization looks for the string192.168.1.100:7001 among all of the URI resources in the configuration file and replacesit with the string localhost:7101—this is exactly what we want.

Listing 12-4. The Resulting customize.xml File

<?xml version="1.0" encoding="UTF-8"?><cus:Customizations xmlns:cus="http://www.bea.com/wli/config/customizations"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:xt="http://www.bea.com/wli/config/xmltypes"><cus:customization xsi:type="cus:FindAndReplaceCustomizationType"><cus:description>Set the right Work Manager</cus:description><cus:query><xt:envValueTypes>Work Manager</xt:envValueTypes><xt:refsToSearch xsi:type="xt:LocationRefType"><xt:type>Project</xt:type><xt:path>HelloWorld</xt:path>

</xt:refsToSearch><xt:includeOnlyModifiedResources>false</xt:includeOnlyModifiedResources><xt:searchString xsi:nil="true"/><xt:isCompleteMatch>false</xt:isCompleteMatch>

</cus:query><cus:replacement>Production System Work Manager</cus:replacement>

</cus:customization><cus:customization xsi:type="cus:FindAndReplaceCustomizationType"><cus:description>Update to the correct server and port number</cus:description><cus:query>

CHAPTER 12 ■ ADMINISTRATION, OPERATIONS, AND MANAGEMENT266

7974CH12.qxd 3/28/07 1:41 PM Page 266

Page 292: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

<xt:envValueTypes>URI</xt:envValueTypes><xt:refsToSearch xsi:type="xt:LocationRefType"><xt:type>Project</xt:type><xt:path>HelloWorld</xt:path>

</xt:refsToSearch><xt:includeOnlyModifiedResources>false</xt:includeOnlyModifiedResources><xt:searchString>192.168.1.100:7001</xt:searchString><xt:isCompleteMatch>false</xt:isCompleteMatch>

</cus:query><cus:replacement>localhost:7101</cus:replacement>

</cus:customization></cus:Customizations>

If you are interested in understanding the schema of the customization XML files, you canfind the schema file, Customization.xsd, in the <%BEA_HOME%>\weblogic92\servicebus\lib\sb-public.jar file.

Advanced Automation TechniqueThe real magic happens when we import the ALSB project into the alsb_prod server. Theimport.py script will read in the customize.xml file and use it as a template for makingchanges to the ALSB project when the project is imported—that is an important fact. Thecustomize.xml file acts to keep the export process and the import processes loosely coupled.Commonly, you take advantage of this loose coupling by creating a customize.xml file for eachof your environments. For example, you might copy the generated customize.xml file and saveit under multiple file names (e.g., helloworld_prod.xml, helloworld_stage.xml, etc.).

Saving customize.xml under multiple names allows your administrators to independentlymodify the environment variables for each deployment environment. Modifying the Ant scriptand the import.py file to take a specific customization file is then a small matter, which wouldallow your administrators to use commands like ant import helloworld_prod.xml. Ideally,you will need only a single import.py file in your entire enterprise, because it simply acts onthe commands in the customization file. The import.py file really needs no modification. Witha little bit of scripting work up front, you can automate the entire deployment process.

ALSB ClustersClustering allows the administrator to manage all of the individual servers in the cluster as asingle unit. A cluster is simply a collection of a single domain administration server and one ormore managed servers. A managed server is just a server that is not an administration server;the only difference between a managed server and an administration server is that the admin-istration server has a number of additional administration applications deployed on it. Everydomain must have an administration server. The administration server is created when youcreate the ALSB domain. When you created the alsb_book domain in Chapter 2 of this book,the Configuration wizard automatically created the administration server with the nameAdminServer. The same thing happened in this chapter when you created the alsb_proddomain.

CHAPTER 12 ■ ADMINISTRATION, OPERATIONS, AND MANAGEMENT 267

7974CH12.qxd 3/28/07 1:41 PM Page 267

Page 293: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Throughout this book, we have used single-server domains. This is the commonapproach for developing ALSB services. However, in a production environment, running ALSBin a cluster of servers is usually necessary. You use clustering in a production environment forseveral reasons:

• The amount of network traffic is too much for a single server to handle.

• The load is too much for a single server to handle.

• You want high availability. If a server goes down in the cluster, the rest of the cluster cancontinue to operate.

■Note The administration server does not represent a single point of failure in a cluster. If the administra-tion server fails, the managed servers continue to run and service requests as usual.

Figure 12-6 shows a typical physical deployment diagram for an ALSB cluster. The figurecontains a lot of information, so let’s go through it in detail. On the right side of the diagram,four main artifacts are defined. You can see in the diagram that the ALSB domain artifact is aspecialization of the WebLogic domain artifact. That’s because ALSB is, in fact, a specializationof a WebLogic domain; it is essentially a WebLogic domain with a number of ALSB-specificconfigurations applied.

The ALSB Domain artifact contains two other nested artifacts that represent ALSB-specific projects that are deployed in the ALSB domain: the HelloWorld project and theMessageFlow project. This nesting notation specifies that anywhere you see an ALSB domainartifact, the Hello World and Message Flow projects will exist.

The largest box in the diagram is the alsb_book domain instance. We can see that this isan instance of the ALSB Domain artifact explained in the previous paragraph. Inside of thisdomain are the individual server instances, the administration server, and five other managedserver instances. At the bottom of the box are the node instances. These are the specific com-puters on which the administration server and managed servers will run.

For the service clients, it is very important that the enterprise service bus perform as asingle entity. You don’t want your service clients to be aware of the fact that there is an ALSBserver running on the machine named ESB3. You also don’t want your service clients to haveto worry about the different ports used by each ALSB-managed server. Instead, you want yourclients to be able to reference the ESB through a single DNS name. That DNS name shouldthen use a standard DNS load balancing algorithm to distribute the calls among the varioussoftware servers. For example, the primary DNS alias should be a name like esb.mycorp.com.In our example, that DNS name would be a proxy for the following servers:

192.168.1.1:7001192.168.1.1:7101192.168.1.2:7001192.168.1.2:7101192.168.1.3:7001192.168.1.3:7101

CHAPTER 12 ■ ADMINISTRATION, OPERATIONS, AND MANAGEMENT268

7974CH12.qxd 3/28/07 1:41 PM Page 268

Page 294: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 12-6. A sample ALSB cluster physical deployment diagram

By using a DNS alias, you gain the operational freedom to add, move, and delete serversfrom the domain and cluster without affecting your service clients.

At this point, you are ready to create a cluster on your computer. In the following section,we create a new domain for our cluster. You can modify an existing domain and configure itfor a cluster, but this is a painstakingly detailed process that is prone to errors. Simply creatinga new domain is much easier.

CHAPTER 12 ■ ADMINISTRATION, OPERATIONS, AND MANAGEMENT 269

7974CH12.qxd 3/28/07 1:41 PM Page 269

Page 295: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Creating a ClusterWe will create our clustered domain using the Configuration wizard tool. You should be fairlycomfortable with the Configuration wizard tool at this point (as this is the third domain wehave created in this book), so I will just give you the highlights:

1. Create a new domain that supports WebLogic Server, WebLogic Workshop, and ALSB.

2. Specify the username and password as weblogic and weblogic.

3. Select Development mode, and use the Sun SDK.

4. When asked if you want to customize any settings, click Yes.

5. Keep the default AdminServer name, and listen on port 7001.

6. Add a managed server named ESB1. Set its listen port to 7101. Add a second managedserver named ESB2, and set its port to 7201.

7. Add a cluster named ESB_Cluster. Keep the default multicast address and port. Set theCluster Address to localhost:7101,localhost:7201.

8. Assign the ESB1 and ESB2 managed servers to the cluster.

9. Add a machine named MyComputer (select the Unix tab if you are working on a Unixbox). Keep the default Node manager listen address and the default Node managerlisten port of 5556.

10. Add the AdminServer, ESB1, and ESB2 servers to the MyComputer machine.

11. Accept the defaults for the JDBC data sources.

12. Run the database scripts, and be sure they all ran successfully.

13. Accept the defaults for the JMS file stores.

14. Accept the default values when reviewing the domain.

15. Name the domain alsb_cluster, and place it with the other domains you have createdfor this book.

16. At the end of the Configuration wizard, check the Start Admin Server checkbox, andclick the Done button.

That’s it. You have created a clustered domain with two managed servers.

CHAPTER 12 ■ ADMINISTRATION, OPERATIONS, AND MANAGEMENT270

7974CH12.qxd 3/28/07 1:41 PM Page 270

Page 296: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

CONFIGURING SERVER MEMORY

You are welcome to create more managed servers if you like. You are constrained only by the amount of RAMavailable on your computer. On a 2GB machine, you could easily run an administration server and a singlemanaged server. Trying to run a second managed server on a 2GB machine is tricky and will require you tomodify the memory settings on your servers. You do not need to perform the steps outlined in this sidebarunless you are going to try to fit an additional managed server onto your machine. I have been able to runtwo managed servers in a cluster on my 2GB laptop, but I had to constrict the memory requirements of theservers so severely that they were almost useless.

You can control the memory requirements of your ALSB servers by editing the setDomainEnv script inthe bin directory of your domain. The following code snippet shows how I reduced the primary server argu-ments from 512MB to 256MB:

@REM Reduced stack and heap size from the default 512m to 384m to ➥

run the cluster on a single machine.set MEM_ARGS=-Xms384m –Xmx384m

The next instruction in the setDomainEnv script specifies how much permanent memory the JVMshould set aside. This memory is used to store objects that the JVM will need throughout its entire life cycle.Finding the right part of the setDomainEnv script can be a little tricky, because you will see several differentcommands that include the MaxPermSize argument for each JAVA_VENDOR. It’s usually easiest just tochange all of the MaxPermSize instances in the script. The default MaxPermSize value is 128MB, but youcan get away with a value as low as 96MB:

if "%JAVA_VENDOR%"=="Sun" (set MEM_ARGS=%MEM_ARGS% %MEM_DEV_ARGS% -XX:MaxPermSize=128m

)

if "%JAVA_VENDOR%"=="HP" (set MEM_ARGS=%MEM_ARGS% -XX:MaxPermSize=128m

)

If you are running ALSB on a machine that is larger then 2GB, feel free to create additional managedservers for your cluster. Similarly, if you have access to several different machines on a network, you can cre-ate additional managed servers on other computers, which is the true purpose of clustering.

Introducing the Node ManagerAs you may have noticed when you were creating the alsb_cluster domain, the Configurationwizard asked you about the port that the Node Manager used on the machine you configured.The Node Manager is a utility that runs on every computer that hosts a managed server. TheAdmin server communicates to the Node Managers on each machine when it needs to start orstop a managed server, and the local Node Manager performs the commands it receives fromthe Admin server.

CHAPTER 12 ■ ADMINISTRATION, OPERATIONS, AND MANAGEMENT 271

7974CH12.qxd 3/28/07 1:41 PM Page 271

Page 297: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

You need to run the Node Manager on your computer. The easiest way to do this is toopen a command prompt. First, run the setDomainEnv script in the alsb_cluster\bin direc-tory. This will set all of the environment variables properly for the Node Manager. Next, startthe Node Manager by executing the command startNodeManager on the command line. If yourdomain exists on more than one computer, you will need to start a Node Manager on eachcomputer in your domain.

When the Node Manager starts up, you will see output at the end of the startup sequencewhere the Node Manager displays its configuration settings, as shown in Listing 12-5.

Listing 12-5. Configuration Settings of a Node Manager

Configuration settings:

NodeManagerHome=D:\BEAALS~1\WEBLOG~1\common\NODEMA~1ListenAddress=ListenPort=5556ListenBacklog=50SecureListener=trueAuthenticationEnabled=trueNativeVersionEnabled=trueCrashRecoveryEnabled=falseJavaHome=D:\BEAALS~1\JDK150~1\jreStartScriptEnabled=falseStopScriptEnabled=falseStartScriptName=startWebLogic.cmdStopScriptName=LogFile=D:\BEAALS~1\WEBLOG~1\common\NODEMA~1\nodemanager.logLogLevel=INFOLogLimit=0LogCount=1LogAppend=trueLogToStderr=trueLogFormatter=weblogic.nodemanager.server.LogFormatterDomainsFile=D:\BEAALS~1\WEBLOG~1\common\NODEMA~1\nodemanager.domainsDomainsFileEnabled=trueStateCheckInterval=500

Domain name mappings:

alsb_book -> D:\domains\alsb_bookwl_server -> D:\beaALSB26\weblogic92\samples\domains\wl_serveralsb_cluster -> D:\domains\alsb_clusterworkshop -> D:\beaALSB26\weblogic92\samples\domains\workshopalsb_prod -> D:\domains\alsb_prodmedrec -> D:\beaALSB26\weblogic92\samples\domains\medrecservicebus -> D:\beaALSB26\weblogic92\samples\domains\servicebus

CHAPTER 12 ■ ADMINISTRATION, OPERATIONS, AND MANAGEMENT272

7974CH12.qxd 3/28/07 1:41 PM Page 272

Page 298: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

You can customize these settings by editing the nodemanager.properties file in theBEA_HOME\weblogic92\common\nodemanager directory. Also in that directory is thenodemanager.domain file, which contains a list of ALSB domains that the Node Managercan handle. As you can see, the Node Manager is specific to a BEA_HOME, not to a domain.

Controlling Managed ServersWith the Node Manager running, you can now open your browser and point it to theWebLogic console at http://localhost:7001/console. Navigate to the Clusters window (youcan use the Domain Structure portlet on the console and select Environment ➤ Clusters), andselect the ESB_Cluster. You should now be viewing the Settings for ESB_Cluster window.

Among the set of tabs at the top of this window is a tab named Control. Click this tab tosee a list of managed servers in the cluster (see Figure 12-7).

Figure 12-7. The Settings for ESB_Cluster window

To start the ESB1 managed server from this window, select the checkbox next to the servername, and click the Start button. It may take a minute or two for the managed server to start.The first time you start a managed server, the administration server will not only have to startthe managed server but also synchronize some administrative files with the managed server,and this takes a bit of time.

■Note You can also start managed servers from the command line. Simply navigate to the bin directoryof the domain, run the setDomainEnv script, and start each managed server with the commandstartManagedWebLogic <ServerName> <AdminServerURL>. For example, you would start the ESB1managed server with the command startManagedWeblogic ESB1 http://localhost:7001.

CHAPTER 12 ■ ADMINISTRATION, OPERATIONS, AND MANAGEMENT 273

7974CH12.qxd 3/28/07 1:41 PM Page 273

Page 299: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Deploying to a ClusterOne of the benefits of using a cluster is that it simplifies the management of software deploy-ment. You can deploy ALSB projects to the entire cluster simultaneously. Whenever you deployan application to the administration server for the domain, the administration server auto-matically updates all of the managed servers.

■Caution An ALSB domain can support only one cluster. If you need multiple ALSB clusters, you mustcreate an ALSB domain for each cluster.

You can use the deployment scripts in the Administration project of Workshop to importthe EchoService project into the alsb_cluster domain. In the folder DeployCluster, open thebuild.xml file, be sure that you are viewing the Outline tab, and run the import Ant task. Theimport script will import the EchoService project to the administration server, which, in turn,updates the two managed servers.

You can test the deployment using the test console. When you use the test console on theadministration server of a cluster, you actually test the managed servers. To help illustrate this,EchoService contains a log action that will output a small message onto the text console of themanaged servers where it executes. Open the test console, and test EchoService. You will needto perform at least three tests before you see the round robin load balancing take place. Eachserver gets two service invocations before the round robin algorithm moves on to the nextserver in the cluster.

Location Transparency and ALSBAs you have seen in previous projects, ALSB provides location transparency to its businessservices by using proxy services. The client invokes the proxy server, and ALSB can thendecide which of the business service endpoints it will use. This helps to decouple the clientfrom the physical service endpoints. What about the ALSB proxy services? Aren’t the serviceclients going to be coupled to the physical endpoints of ALSB? To get a service client for theEchoService proxy, we would usually write something similar to the following:

public static void main(String[] args) {String url = "http://localhost:7101/sbresource?PROXY/EchoService/Echo";String[] names = new String[] {"Foo", "Bar", "Baby", "Test", "Simple",

"Arfy!" };try {

EchoService_Service service = new EchoService_Service_Impl(url);…

Obviously, this service client is coupled directly to the proxy service on port 7101. It willnot take advantage of the cluster we defined. If the server on port 7101 goes down, this clientwill fail. We need a way to give the client an endpoint that does not map to a physical server.Typically, there are two approaches for this: a hardware router or a software router.

CHAPTER 12 ■ ADMINISTRATION, OPERATIONS, AND MANAGEMENT274

7974CH12.qxd 3/28/07 1:41 PM Page 274

Page 300: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Hardware routing is usually done in a DNS server. You would create a virtual IP address(VIP), and assign multiple real IP:Port combinations to the VIP. Using the alsb_clusterdomain as an example, we could create a VIP with the name esb, and assign localhost:7101and localhost:7201 to the VIP. We would then modify our client to the following:

public static void main(String[] args) {String url = "http://esb/sbresource?PROXY/EchoService/Echo";String[] names = new String[] {"Foo", "Bar", "Baby", "Test", "Simple",

"Arfy!" };try {

EchoService_Service service = new EchoService_Service_Impl(url);…

This helps to loosen the coupling. Now, the client is coupled to a logical DNS name, not toa physical IP address and port combination. In production and staging environments, DNSservers commonly play this role, providing a looser, logical coupling between clients andservers. In some companies, the development and quality assurance (QA) departments oftendo not have the rights or the ability to makes changes to the DNS servers in those environ-ments. It is common for the operations folks (the people who maintain the networks of thecompany) to be the only people allowed to make changes to the DNS servers. Architects,developers, and QA staff can ask operations staff to make DNS changes, but this is often notfeasible. Developers and QA personnel will want to make DNS changes very frequently, farmore often than the operations department can support. This is the perfect case for the soft-ware router. A software router can simulate the DNS router without conflicting with the DNSservers. Also, since the software router is a software asset, developers and QA personnel canchange it as often as they like.

BEA provides a software router free of charge. The router is bundled in with the WebLogicserver that is bundled with ALSB. It does take a bit of configuration to get it set up, but we willwalk through that process now. The software router is named HttpClusterServlet and is usedto load balance HTTP traffic among any number of servers. To use HttpClusterServlet, createa dynamic web application in Workshop, and configure the web-inf\web.xml and web-inf\weblogic.xml files to route HTTP requests. Listing 12-6 shows a snippet of the web.xml filespecifically related to our routing needs. In the <servlet> declaration, we specify theHttpClusterServlet name and then point to the class that implements the code. The classexists in the weblogic.jar file, so you don’t need to write it.

■Note The text in the web.xml file is case sensitive.

The <init-param> tags specify the parameters that are passed to the HttpClusterServletclass on startup. Of the two parameters in Listing 12-6, the WebLogicCluster parameter is themost important. It specifies the servers in the cluster. Each server in the parameter is sepa-rated by a pipe character (|). There is no limit to how many servers you can specify in thisparameter.

CHAPTER 12 ■ ADMINISTRATION, OPERATIONS, AND MANAGEMENT 275

7974CH12.qxd 3/28/07 1:41 PM Page 275

Page 301: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Listing 12-6. Configuring the web.xml File

<servlet><servlet-name>HttpClusterServlet</servlet-name><servlet-class>weblogic.servlet.proxy.HttpClusterServlet➥

</servlet-class><init-param>

<param-name>WebLogicCluster</param-name><param-value>localhost:7101|localhost:7201</param-value>

</init-param><init-param>

<param-name>DebugConfigInfo</param-name><param-value>ON</param-value>

</init-param></servlet><servlet-mapping>

<servlet-name>HttpClusterServlet</servlet-name><url-pattern>/</url-pattern>

</servlet-mapping>

The modification needed in the weblogic.xml file is trivial. Just set the context root of theweb application to the forward slash character (/) as follows:

<wls:context-root>/</wls:context-root>

Of course, you need a place to run this HttpClusterServlet web application. Perform thefollowing steps to set up your alsb_cluster domain properly:

1. In the WebLogic Server console, create a new server named LoadBalancer on port 7301.Assign this new server to the MyComputer machine, as you did with the other servers inthis domain.

2. Do not add the LoadBalancer server to the ESB_Cluster.

3. Finish the server creation process as usual.

4. Open a command prompt, and navigate to the bin directory of the alsb_clusterdomain. Run the setDomainEnv script, and execute the following command:

startManagedWebLogic LoadBalancer http://localhost:7001

5. Once the LoadBalancer server is running, use the WebLogic Server console, and openthe Deployments page.

6. Click the Lock & Edit button in the Change Center.

7. Click the Install button on the Deployments page. Navigate to the directory of theHttpClusterServlet project in Workshop, and select the HttpClusterServlet.war file.

8. Select the “Install this deployment as an application” radio button, and click Next.

9. Target the deployment to the LoadBalancer server only, as shown in Figure 12-8. Clickthe Next button.

CHAPTER 12 ■ ADMINISTRATION, OPERATIONS, AND MANAGEMENT276

7974CH12.qxd 3/28/07 1:41 PM Page 276

Page 302: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

10. Click the Next button to accept the default deployment name.

11. Click the Finish button.

12. Click the Activate Changes button in the Change Center.

13. Still in the WebLogic Server console, go back to the Deployments page, and scrollthrough the deployments until you reach the HttpClusterServlet application (whichshould be on the third page).

14. Check the checkbox next to HttpClusterServlet, and click the Start button. Choose“Servicing all requests” from the pop-up menu to complete the installation of theapplication.

Figure 12-8. Targeting the HttpClusterServlet to the LoadBalancer server

In Workshop, open up the TestCluster project. This is a simple Java client that willinvoke our clustered EchoService via the LoadBalancer server. The TestCluster client code inListing 12-7 helps to demonstrate how load balancing works. We have highlighted the URLthat we use to create our EchoService_Service in bold type in Listing 12-7. The URL points tothe LoadBalancer server. After the port number, the rest of the URL is the traditional methodfor accessing the WSDL of a proxy service (see Chapter 14 for details on this URL structure).

Remember when we set the <context-root> of the web application to the forward slashcharacter? That command tells the server to treat HttpClusterServlet as the default webapplication. Therefore, everything that comes after the forward slash will be distributedamong the clustered servers.

CHAPTER 12 ■ ADMINISTRATION, OPERATIONS, AND MANAGEMENT 277

7974CH12.qxd 3/28/07 1:41 PM Page 277

Page 303: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Listing 12-7. The TestCluster Client Code

package com.alsb.client;

import java.rmi.RemoteException;import javax.xml.rpc.ServiceException;

public class Client {

/*** @param args*/public static void main(String[] args) {

String url = "http://localhost:7301/sbresource?PROXY/EchoService/Echo";String[] names = new String[] {"Foo", "Bar", "Baby", "Test", "Simple",

"Arfy!" };try {

for (int i = 0; i < names.length; i++) {EchoService_Service service = new EchoService_Service_Impl(url);EchoService_PortType port = service.getEchoServiceSOAP();String result = port.echo(names[i]);System.out.println("Received the string result: " + result);

}} catch(ServiceException ex) {

ex.printStackTrace();} catch(RemoteException ex) {

ex.printStackTrace();}

}}

In the preceding code, the load is balanced for each service object that is created, notfor each invocation of an operation on the web service. Notice that the client code creates aservice repeatedly in the for loop:

for (int i = 0; i < names.length; i++) {EchoService_Service service = new EchoService_Service_Impl(url);...

}

It is this call that binds the EchoService_Service object to one of the endpoints forEchoService. If you move that command above the for loop structure, the client would bind toa single endpoint for the duration of its existence, and all service invocation would go to thesame server. In production code, you want to bind to a service once, and then make multipleinvocations to the server—that’s the right way to go about it. However, such an approachwould not demonstrate the load balancing capabilities of HttpClusterProxy, so we deliber-ately took a poor design route to show off the capabilities of the load balancer.

CHAPTER 12 ■ ADMINISTRATION, OPERATIONS, AND MANAGEMENT278

7974CH12.qxd 3/28/07 1:41 PM Page 278

Page 304: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

SummaryA full treatise on the administration of any system, especially one as flexible and mature asALSB, could fill an entire book on its own. However, in this chapter we covered some of themost important aspects of administration that are not easily discovered by reading the prod-uct documentation. This chapter answered the most common questions we encounter in thefield by explaining how you can develop in a team environment, script the deploymentprocess, and configure ALSB for production-level loads and load balancing. With the informa-tion presented in this chapter, you are ready to put ALSB into production in a reliable andscalable manner.

CHAPTER 12 ■ ADMINISTRATION, OPERATIONS, AND MANAGEMENT 279

7974CH12.qxd 3/28/07 1:41 PM Page 279

Page 305: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

7974CH12.qxd 3/28/07 1:41 PM Page 280

Page 306: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Custom Transports

You can extend the capabilities of ALSB in several ways beyond those it has straight out ofthe box. The simplest way is to use the Java Callout action to invoke a POJO, as described inChapter 7. In this chapter, we’ll discuss how you can extend ALSB’s capabilities by addingadditional transports beyond the ones that come out of the box with ALSB, such as HTTPor JMS.

ALSB comes with a set of interfaces for creating a custom transport, called the TransportSDK (Software Development Kit). You can use these interfaces to create a transport that fitsinto ALSB as naturally as any of the standard transports. In fact, the transports that come withALSB are built using this very same Transport SDK! A custom transport can even have a trans-port configuration screen that’s presented to the user as one of the steps in creating a proxy orbusiness service. The later sections of this chapter will cover the Transport SDK in detail.

Introduction to Custom TransportsBefore we talk about the custom transports, let’s review the standard transports that comewith ALSB 2.5 (see Table 13-1). This list will likely grow with future releases of the product.

Table 13-1. Standard Transports

Transport Name Description

HTTP This is the most common transport used by web services, employing thestandard HyperText Transport Protocol used in the web.

HTTPS This is just HTTP over Secure Sockets Layer (SSL). Running over SSL providesa relatively efficient way to encrypt messages so that third parties cannoteavesdrop to get access to confidential information.

JMS Using the JMS transport is an easy way to transmit messages reliably. JMSmessages can also be transactional, providing “exactly once” quality ofservice (discussed later in the chapter).

File You use the File transport for processing messages to or from files in a locallymounted file system. This is commonly used for large messages.

FTP The FTP transport has similar use cases as the File transport, but is used forfiles in a remote file system, accessible via an FTP server.

Email The Email transport is used for processing e-mail messages, via POP3, IMAP(inbound), or SMTP (outbound).

Continued

281

C H A P T E R 1 3

7974CH13.qxd 4/2/07 9:43 PM Page 281

Page 307: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Table 13-1. Continued

Transport Name Description

EJB The EJB transport is an outbound-only transport for invoking Enterprise JavaBeans (EJBs), either locally in the same server running ALSB, or in a remoteserver.

Tuxedo The Tuxedo transport is for communicating with Tuxedo systems, supportingall the standard Tuxedo buffer types (such as VIEW, FML, CARRAY, and so on),and even supporting conversions between the typed buffers and standardXML messages.

You can mix and match different transports within a proxy service. That is, a proxy servicecan have one transport for receiving an inbound message, and have a different transport (ortransports) used to send outbound messages. For example, you can web service–enable anEJB or Tuxedo service by having a proxy that takes HTTP inbound and then invokes the EJB orTuxedo service on outbound, after doing the appropriate transformations.

Why Build a Custom Transport?That’s a good question! Indeed, many people will have no need to build a custom transport.The standard transports provide support for a wide range of transport scenarios, satisfyingmost needs. However, there are instances where it might be necessary to build a custom trans-port to work with a proprietary communication mechanism, or with a transport not yetsupported by ALSB, or even to work with a new protocol over one of the existing transports.

Some possible examples of new transports include the following:

• Raw sockets, perhaps with Text or XML messages (see the section “The Sample SocketTransport”)

• Using a native IBM WebSphere MQ API (instead of WebSphere MQ JMS)

• CORBA or IIOP protocol for communicating with CORBA applications

• Variations on FTP, such as Secure FTP (SFTP)

• A proprietary transport used by an organization in its existing applications

Alternatively, you can use the Transport SDK to support a specialized protocol over one ofthe existing transports. Examples of this include the following:

• Messages consisting of parsed or binary XML over HTTP

• Supporting Web Services Reliable Messaging (WS-RM) or other new web service stan-dards over HTTP

• Request-response messaging over JMS, but with a different response pattern than sup-ported by the ALSB JMS transport

One of the prime use cases for using the Transport SDK is for supporting a specializedtransport a company already employs for communication among its internal applications.Such a transport might have its own concept of setup handshake, header fields, metadata, ortransport-level security. You can create an implementation of the transport for use with ALSB

CHAPTER 13 ■ CUSTOM TRANSPORTS282

7974CH13.qxd 4/2/07 9:43 PM Page 282

Page 308: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

that allows configuring individual endpoints—either inbound, outbound, or both. You canmap the metadata and header fields nicely to context variables available in a proxy servicepipeline.

Creating a new ALSB transport using the Transport SDK can be a significant effort. TheTransport SDK provides a rich, full-featured environment, so that a custom transport has allthe usefulness and capabilities of the transports that come natively with ALSB. But such rich-ness brings complexity. For certain cases, you should consider easier alternatives.

If you need the desired extension merely to support a different type of message formatsent or received over an existing protocol, it might be possible to use the existing transportand use a Java Callout to convert the message. For example, suppose you have a specializedbinary format—for example, Abstract Syntax Notation number One (ASN.1) or a serializedJava object—being sent over the standard JMS protocol. An alternative to consider is to definethe service using the standard JMS transport with the service type being a messaging servicewith binary input and output messages. Then, if the contents of the message are needed in thepipeline, you can use a Java Callout action to convert the message to or from XML.

■Tip Implement a custom transport when you need to communicate over a completely different transportmechanism, or when using a different protocol over an existing transport. If you just need to support a newmessage format over an existing transport, instead of creating a custom transport, try creating a messagingproxy with a binary format and use a Java Callout to interpret the message.

How Does a Custom Transport Fit into ALSB?A custom transport built with the Transport SDK is a first-class citizen. It can do anything thatother standard transports can do. You can configure both proxy services and business servicesusing the custom transport (or the custom transport can support just proxy services or justbusiness services). The transport provider decides which—or all—of the service types to sup-port. (For example, it might not make sense to support SOAP services or binary services.)Business services defined using the custom transport can be used in Route, Publish, orService Callout actions (see Figure 13-1).

Figure 13-1. Where transports fit in at runtime

CHAPTER 13 ■ CUSTOM TRANSPORTS 283

7974CH13.qxd 4/2/07 9:43 PM Page 283

Page 309: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

The life of a message in ALSB starts in the inbound transport and ends with the outboundtransport. That is, the transport used by a proxy has some mechanism to listen for new mes-sages and then feed the incoming messages into the ALSB runtime. At the other end, when theprocessed message is being sent out to a business service, the last stop in the processing is thebusiness service transport, whose responsibility is to deliver the message. The runtime APIs inthe Transport SDK form the interface, or glue, between the transport and the rest of the ALSBruntime system.

The set of screens used to create a proxy or business service includes a generic transportconfiguration screen, followed by a configuration screen specific to the chosen transport. TheTransport SDK includes APIs for declaring the user interface fields that can be filled out whendeclaring a service using a custom transport (details will be covered in the section “Imple-menting Transport Provider User Interface Classes”). The system automatically creates thetransport-specific configuration screen based on the transport’s configured user interfacefields. A custom transport adds a new choice to the list of possible transports in the genericscreen, and then provides a unique transport-specific screen for configuring a service thatuses the custom transport.

For example, Figure 13-2 shows the configuration screen for the socket transport—thesample custom transport that comes with ALSB (details of the sample socket transport aregiven in the next section). You won’t see this in your standard install of ALSB. This screen willonly be available once you install the sample transport.

Figure 13-2. Socket Transport Configuration screen

A wide variety of UI elements are available to use in a custom transport configurationscreen. Notice how the Socket Transport Configuration screen includes checkboxes, pull-downs, and fill-in-the-blank–type fields. Browsing through the screens for the other transportswill give you a good idea of the various other kinds of available UI elements.

The result of using these user interface elements is that a custom transport configurationscreen looks like the other screens in ALSB. The transport provider can do full validation onthe entered fields to make sure good values have been entered. No one will know that thiscomes from a custom transport rather than a standard transport, except for the transportprovider.

CHAPTER 13 ■ CUSTOM TRANSPORTS284

7974CH13.qxd 4/2/07 9:43 PM Page 284

Page 310: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

■Caution Proxy and business services that use custom transports can be exported like any otherresources. However, if you import them into another ALSB domain that doesn’t include the customtransport, you’ll get validation errors and the import will fail.

There are many options to consider when designing a custom transport. A transport cansupport just inbound (proxy services) or outbound (business services), or both. It can supportone-way messages, or request-response. It can enforce transport-level security. Inboundtransports can achieve “exactly once” semantics by beginning and committing transactions,while outbound transports can participate in a transaction. A transport can even define a cus-tom message format for holding the message, and provide transformations to convert themessage into a format ALSB can understand (for example, XML) when needed.

If you don’t understand all the options discussed in the previous paragraph, don’t worry.We’ll be discussing these topics and more in later sections of this chapter.

Components of a Custom TransportHere’s a quick glimpse at the components you’ll need to create as part of a custom transport.We’ll go into this in much more detail, but this section will provide an overview of what needsto be built.

You’ll need a deployment unit, such as an EAR file, for deploying all the code for your cus-tom transport to WLS. You’ll use standard WLS application deployment tools to deploy yourfile. The deployment unit will contain the following:

• Design-time code that defines the user interface and configuration of services usingcustom transport. The ALSB console will call this code when a new service is created orupdated. This includes methods to validate the configuration data.

• Runtime code that’s used to receive or send messages. The receiving code delivers themessage to the ALSB runtime system along with any metadata or transport headers,while the sending code gets messages from ALSB for delivery to the external service.

• XMLBean classes and schemas defining how your custom transport is configured, anddefining metadata and headers used by your transport. These XML configuration filesare a key part of a custom transport.

• Registration code that will register your transport provider with the ALSB transportmanager on application deployment life cycle events, such as server startup.

The Sample Socket TransportThe easiest way to develop a new custom transport is by looking at an example. ALSB version2.5 and later comes with a sample custom transport that implements a simple socket mecha-nism for talking to services using raw TCP/IP. This transport is called the “socket transport.” Inthis section, we’ll describe this sample transport, how to build and install it, and how to use itin ALSB proxy and business services. We’ll use the sample custom transport as examples in thefollowing sections.

CHAPTER 13 ■ CUSTOM TRANSPORTS 285

7974CH13.qxd 4/2/07 9:43 PM Page 285

Page 311: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Capabilities of the Socket TransportYou can probably imagine many different interesting transports that could have been chosento form a sample custom transport. Why make a sample transport communicate over some-thing as simple as plain TCP/IP sockets? That simplicity is exactly the answer! The sampletransport can focus on demonstrating how to use the interfaces of the Transport SDK withoutgetting bogged down with complex transport logic, such as how to perform CORBA calls,interact with MQ interfaces, map some proprietary message format to XML, and so on.

The socket transport is a basic transport that can send and receive text messages (includ-ing XML) over sockets. Messages are terminated by a blank line (more explicitly, by two sets ofcarriage-return, line-feed characters). Because the message is terminated by a blank line,there’s no need for a message header describing the length of the message, and the messagecan be streamed in and out of the service.

You can use the socket transport with service types compatible with text messages—namely Any XML—and messaging services with messages that are either text or XML (with orwithout a schema). You can’t use the socket transport with SOAP-based services (though youcan use it with a WSDL service whose binding type is plain XML).

The socket transport has some configuration attributes for the underlying socket usage,such as Nagle’s Algorithm, an option that can help optimize the TCP/IP traffic. These attrib-utes are somewhat gratuitous. They are included just to have something to configure in thetransport-specific pages. In addition, the socket transport has some metadata and transportheaders associated with each message—again, mostly for the purpose of demonstrating howto support those features.

When you do a full install of ALSB, you’ll get the sample socket transport installed in theALSB samples directory, as indicated in Figure 13-3. The files included with the sampleinclude scripts for compiling and deploying the sample, configuration and schema files, andJava programs to help test ALSB services that use the socket transport. All source files areincluded.

Building and Installing the Sample TransportAt the top level of the sample transport directory is a README.TXT file that gives instructionson how to build, deploy, and test the socket transport. We’ll go through those steps here. We’lldescribe these steps in terms of Windows commands, but the steps are equivalent on Unixplatforms.

Before you can deploy the sample socket transport, you’ll need an ALSB domain. We’llassume you’ve already created an ALSB domain using the standard Domain Configurationwizard. For simplicity, put the location of your domain directory into a variable DOMAIN_DIR.Also, put the location of the “sample-transport” directory into another variable SAMPLE_DIR.

The first thing you need to do is to set the appropriate environment variables. The buildand deploy scripts use these. Execute the following commands:

cd %DOMAIN_DIR%\binsetDomainEnv

CHAPTER 13 ■ CUSTOM TRANSPORTS286

7974CH13.qxd 4/2/07 9:43 PM Page 286

Page 312: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 13-3. Location of the sample transport

Now you’re ready to build the sample socket transport. Simply execute the Ant buildscript:

cd %SAMPLE_DIR%ant build-jar

If everything builds correctly, you’ll get a message BUILD SUCCESSFUL, with the time takento do the build. The output will look something like the condensed output shown in Listing13-1 (some of the output has been omitted for brevity). Notice how at the end of the scriptexecution, the transport EAR file is placed in the servicebus\lib directory.

Listing 13-1. Output from Building Sample Socket Transport

D:>cd %DOMAIN_DIR%\bin

D:>setDomainEnvD:>cd %SAMPLE_DIR%

D:>ant build-jarBuildfile: build.xml

build-jar:[echo] --------------------------------------------------[echo] | Socket transport build starting |

CHAPTER 13 ■ CUSTOM TRANSPORTS 287

7974CH13.qxd 4/2/07 9:43 PM Page 287

Page 313: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

[echo] --------------------------------------------------[delete] Deleting directory D:\WL_HOME\weblogic92\samples\servicebus\

sample-transport\build[mkdir] Created dir: D:\WL_HOME\weblogic92\samples\servicebus\

sample-transport\build

create_directories:[echo] >>>>>> create_directories >>>>>>[mkdir] Created dir: D:\WL_HOME\weblogic92\samples\servicebus\sample-transport

\build\classes[mkdir] Created dir: D:\WL_HOME\weblogic92\samples\servicebus\sample-transport

\build\ear[echo] >>>>>> Done create_directories >>>>>>

xbean:

schema_compile:[java] Time to build schema type system: 1.352 seconds[java] Time to generate code: 0.311 seconds[java] Time to compile code: 5.019 seconds

compile:[echo] >>>>>> compile >>>>>>[echo] debug = on, optimize = off, deprecation = off

compile.i18n.catalogs:[echo] >>>>>> compiling i18n catalogs >>>>>>

::

fixup.i18n:[echo] >>>>>> Done compiling i18n catalogs >>>>>>

::

[echo] >>>>>> Done compile >>>>>>

create_jar:[jar] Building jar: D:\WL_HOME\weblogic92\samples\servicebus\sample-transport

\build\sock_transport.jar

create_ear:::

[ear] Building ear: D:\beas\WL92N0~4\WEBLOG~1\servicebus\lib\sock_transport.ear

create_test_client_jar:[echo] Creating test client classes directory[echo] compiling test client sources.

CHAPTER 13 ■ CUSTOM TRANSPORTS288

7974CH13.qxd 4/2/07 9:43 PM Page 288

Page 314: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

[echo] --------------------------------------------------[echo] | Socket transport build completed |[echo] --------------------------------------------------

BUILD SUCCESSFULTotal time: 18 seconds

Now that you’ve built the socket transport, you can deploy it to the running ALSB domain.However, the deploy script needs information about the running domain in order to deploythe transport EAR file. This requires editing the build.properties file to add information aboutthe domain (see Listing 13-2).

Listing 13-2. build.properties File

# What we get from the env.root.dir=${basedir}

# Compiler optionsoptimize=offdebug=ondeprecation=offbuild.compiler=modern# javac.lint.flag=-Xlint -Xlint:-pathjavac.lint.flag=

# Weblogic homebea.home=${env.BEA_HOME}wl.home=${env.WL_HOME}env.INSTALLDIR=${wl.home}/server

### Weblogic Server information ###wls.hostname=localhostwls.port=7001wls.username=weblogicwls.password=weblogicwls.server.name=AdminServer

The section “WebLogic Server information” (shown in bold) now requires filling out. You’llneed to specify the host name and port where your ALSB domain is running, the administrator’susername and password, and the managed server name. If your ALSB domain is running in acluster, you’ll need to run the deploy script for every managed server in the cluster. Luckily, ifyou’re running on your own local machine with the default settings, the values in that sectionshould already be set appropriately.

■Tip Before you deploy the sample socket transport, make sure you’ve already started your ALSB domain.

CHAPTER 13 ■ CUSTOM TRANSPORTS 289

7974CH13.qxd 4/2/07 9:43 PM Page 289

Page 315: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

With the build.properties file now describing how to access your running ALSB domain,you can simply deploy the built EAR file. Make sure you’re still in the sample-transport direc-tory (you should still be there) and execute the following command:

ant deploy

That’s it. You’ve now built and deployed the sample socket transport!

■Tip If you want to make changes to the socket transport and try out your changes, you can simply re-execute the Ant build command, and then restart your server. There’s no need to execute the deploystep a second time. In fact, doing so will cause problems with the deployed EAR file.

Using the Sample Socket TransportNow that you’ve built and deployed the sample socket transport, let’s take it out for a testdrive. We’ll describe these steps in a Windows environment, but these are readily translatableinto a Unix environment.

The first thing you need is a running service using sockets for ASLB to access. Luckily, justsuch a service comes with ALSB. The sample socket directory has a subdirectory “test” thatcontains source for a socket server and a socket client. As part of building the sample trans-port, you’ve already built these two programs. You can now run them.

The command to run the test server is as follows:

java -classpath .\test\build\test-client.jar -Dfile-encoding=<char-set> ➥

-Drequest-encoding=<char-set> com.bea.alsb.transports.sample.test.TestServer ➥

<port> <message-file-location>

The choice of encoding character sets is optional (it defaults to utf-8, which is closeenough to plain old ASCII). The message-file-location is also optional. The server alwaysgives a fixed, canned response, drawn from the message file. If you don’t provide the message-file-location, the server will just use the standard message, which is good enough for ourpurposes.

<?xml version="1.0" ?><project name="sock-transport" default="build-jar" basedir="."/>

Now start a command window. In that window, type the following commands to start theserver. This will start the server listening on port 8100 (use a different port if that one is in useon your machine already).

cd %SAMPLE_DIR%

java -classpath .\test\build\test-client.jar ➥

com.bea.alsb.transports.sample.test.TestServer 8100

Now, before you try to access this server from ALSB, make sure everything is working.Let’s invoke this service from the test client. The test client has a similar command to the testserver.

CHAPTER 13 ■ CUSTOM TRANSPORTS290

7974CH13.qxd 4/2/07 9:43 PM Page 290

Page 316: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

java -classpath .\test\build\test-client.jar -Dfile-encoding=<char-set> ➥

-Drequest-encoding=<char-set> com.bea.alsb.transports.sample.test.TestClient ➥

<host-name> <port> <thread-ct> <message-file-location>

You can do similar simplifications when running the test client as you did for running thetest server. So, start another command window, and type these commands to have the testclient talk to your running test server:

cd %SAMPLE_DIR%

java -classpath .\test\build\test-client.jar ➥

com.bea.alsb.transports.sample.test.TestClient localhost 8100 1

In the command-line window, you should get output like the following:

D: >java -classpath .\test\build\test-client.jarcom.bea.alsb.transports.sample.test.TestClient localhost 8100 1<Sun Sep 17 23:16:04 PDT 2006> ----> host = localhost<Sun Sep 17 23:16:04 PDT 2006> ----> port = 8100<Sun Sep 17 23:16:04 PDT 2006> ----> threadCt = 1<Sun Sep 17 23:16:04 PDT 2006> ----> file-encoding = utf-8<Sun Sep 17 23:16:04 PDT 2006> ----> sock.getPort() = 8100<Sun Sep 17 23:16:04 PDT 2006> ----> sock.getRemoteSocketAddress() = ➥

localhost/127.0.0.1:8100<Sun Sep 17 23:16:04 PDT 2006> ----> sock.getLocalSocketAddress() = /127.0.0.1:4637<Sun Sep 17 23:16:04 PDT 2006> ----> sock.getInetAddress() = localhost<Sun Sep 17 23:16:04 PDT 2006> ----> sock.getLocalPort() = 4637<Sun Sep 17 23:16:04 PDT 2006> Sent a message to the server on thread: Thread-0<Sun Sep 17 23:16:04 PDT 2006> ----> response for thread: Thread-0= ➥

<?xmlversion="1.0" ?> <project name="sock-transport" default="build-jar" ➥

basedir="."/>

Note how the response for the thread is exactly the canned response the server gives, asdescribed earlier. The server command-line window should have output like the following:

D: >java -classpath .\test\build\test-client.jarcom.bea.alsb.transports.sample.test.TestServer 8100<Sun Sep 17 22:26:57 PDT 2006>Started listening on socket:0.0.0.0/0.0.0.0on thread:main<Sun Sep 17 22:28:24 PDT 2006>Connection established for: /127.0.0.1 onthread:main<Sun Sep 17 22:28:25 PDT 2006>Request is:I am a Rimbaud with a leather jacket,If my poetry aims to achieve anything, it's to deliver people from the limitedways in which they see and feel-- the Lizard King -----JM

CHAPTER 13 ■ CUSTOM TRANSPORTS 291

7974CH13.qxd 4/2/07 9:43 PM Page 291

Page 317: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

That odd bit of text is the canned request the test client has sent to the server. Evidently,the developer who created the sample was a fan of Jim Morrison of the Doors, whose musicwas generally regarded as being much better than his poetry.

This is all well and good, but you haven’t done anything to demonstrate your transportworking with ALSB. It’s time to create an ALSB proxy service and business service that uses thesocket transport.

To begin, open up the ALSB console and click the Create button in the Change Center tostart a new session for your work. Then perform the following steps:

1. Create a new project and name it SocketTest.

2. In this new project, create a business service resource named SocketBS. Make theService Type Any XML Service and go to the next screen.

3. If the socket transport got deployed correctly, you should now see “socket” in theProtocol drop-down list. Select that.

4. Add an Endpoint URI to be that of your running test socket server. Enter the URItcp://localhost:8100 and click the Add button. The default Retry values are fine, so goon to the next screen.

5. This next screen is the socket transport configuration screen. This is the screen that gotautomatically created by ALSB. Because all the default values are fine, go on to the nextscreen.

6. Save.

The summary of the SocketBS business service should look like Figure 13-4.You could activate your session and test this business service. But, while you’re in the ses-

sion, go ahead and create a proxy that invokes this business service:

1. In the SocketTest project, create a Proxy Service resource named SocketProxy. Use theoption to create this service from the business service SocketBS.

2. Select “socket” from the Protocol drop-down list. Set the Endpoint URI to saytcp://7100. So, while your test server is listening on port 8100, your intermediary proxywill be listening on 7100.

3. Just accept the rest of the default values on the following screens until you’ve finishedcreating the proxy service, and save.

4. Because you created the proxy service from a business service, the pipeline has alreadybeen initialized with a Route node that has a Routing action that routes to SocketBS.

5. Activate the session.

Okay, you’ve now created both the business service for accessing your test server and aproxy service to act as an intermediary. Let’s test each of these.

CHAPTER 13 ■ CUSTOM TRANSPORTS292

7974CH13.qxd 4/2/07 9:43 PM Page 292

Page 318: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 13-4. SocketBS Business Service summary

Back in the Project Explorer screen for the SocketTest project, launch the test console forthe SocketBS. Enter any legal XML snippet, such as <MySocketTest/>, and hit Execute. Youshould see the same canned response in the response document that you saw earlier whenyou tested the server from the test client:

<project name="sock-transport" default="build-jar" basedir="."/>

Now go back to the ALSB console and launch the test console for the proxy SocketProxy.Follow the same steps to test SocketProxy as you did for SocketBS. You’ll get the sameresponse.

Finally, just to complete the whole cycle, bring up the command window where you ranthe test client. Let’s rerun that test client again, but this time specifying port 7100 rather thanport 8100:

D: >java -classpath .\test\build\test-client.jarcom.bea.alsb.transports.sample.test.TestClient localhost 7100 1<Sat Sep 23 23:21:06 PDT 2006> ----> host = localhost<Sat Sep 23 23:21:06 PDT 2006> ----> port = 7100<Sat Sep 23 23:21:06 PDT 2006> ----> threadCt = 1<Sat Sep 23 23:21:06 PDT 2006> ----> file-encoding = utf-8

CHAPTER 13 ■ CUSTOM TRANSPORTS 293

7974CH13.qxd 4/2/07 9:43 PM Page 293

Page 319: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

<Sat Sep 23 23:21:06 PDT 2006> ----> sock.getPort() = 7100<Sat Sep 23 23:21:06 PDT 2006> ----> sock.getRemoteSocketAddress() = ➥

localhost/127.0.0.1:7100<Sat Sep 23 23:21:06 PDT 2006> ----> sock.getLocalSocketAddress() = /127.0.0.1:4368<Sat Sep 23 23:21:06 PDT 2006> ----> sock.getInetAddress() = localhost<Sat Sep 23 23:21:06 PDT 2006> ----> sock.getLocalPort() = 4368<Sat Sep 23 23:21:06 PDT 2006> Sent a message to the server on thread: Thread-0<Sat Sep 23 23:21:06 PDT 2006> ----> response for thread: Thread-0= ➥

<?xml version="1.0" ?> <project name="sock-transport" default="build-jar" ➥

basedir="."/>

What’s happening here is that the test client is talking to the ALSB proxy on port 7100,over the socket transport. The ALSB proxy is forwarding the message on to the test server onport 8100, again using the socket transport on the outbound side. The socket transport isbeing successfully used on both the inbound and outbound sides!

Building a Custom TransportIn this section we’ll dive into the details of what needs to be done to build a custom transport.We’ll draw heavily from the sample socket transport discussed in the previous section, so referback to that section as necessary. We’ll cover the standard stuff that every transport needs toimplement, and later get into advanced topics whose usage can vary by transport.

Overview of the Transport SDK InterfacesBefore we get too deeply into the bits and bytes of building a transport, we want to give you ahigh-level overview of the main Transport SDK interfaces that are used to build a transport.More information about these classes is available in the Javadoc API documentation. This isn’ta comprehensive list, just the main classes that a transport provider will either implement orinvoke.

• Class TransportManagerHelper: A utility class that provides information about the ALSBdomain, accesses features of the domain such as security information or dispatchpolicies, and most importantly, can get an instance of the TransportManager.

• Class ServiceInfo: Information about a configured service (proxy or business service),including the transport configuration and binding type.

• Interface TransportManager: This is the key interface a service provider uses to interactwith ALSB. This includes methods to register a new transport provider and to pass anincoming message into the ALSB pipeline.

• Interface TransportProvider: This is the key interface a service provider must imple-ment. There are both design-time–oriented methods (for example, methods forcreating, updating, and deleting service endpoints that use this transport) as well asruntime methods (for example, methods sending an outbound message). ALSB callssome of the methods to query the capabilities of the provider.

CHAPTER 13 ■ CUSTOM TRANSPORTS294

7974CH13.qxd 4/2/07 9:43 PM Page 294

Page 320: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

• Interface EndPointOperations: Contains data that is passed to the TransportProviderwhen it needs to do an operation on a service endpoint, such as create, update, delete,suspend, or resume.

• Interface TransportWLSArtifactDeployer: A transport provider can optionally imple-ment this interface if it needs to interact with WLS management as part of deploying aservice endpoint; for example, if it needs to deploy an EJB, a JWS, or some other WLSartifact as part of activating a service.

• Interface ServiceTransportSender: An object of this type is passed to the outboundtransport when sending a message to contain the data and metadata associated withthe message.

• Interface TransportEndPoint: Represents a service endpoint; that is, the transport por-tion of a proxy service (inbound endpoint) or a business service (outbound endpoint).

• Interface Source: Messages are passed through the runtime system via classes imple-menting the Source interface. These classes are containers for representing the contentof a message. The common denominator of all sources is that they have to provide anInputStream to their contents and be able to write their contents to an output stream.There are many standard sources, including StreamSource, ByteArraySource,StringSource, XmlObjectSource, DOMSource, MFLSource, SAAJSource, MimeSource,MessageContextSource, and AttachmentsSource. You can also define your owncustom Source object.

• Interface Transformer: If you do define your own custom Source object, you can alsoprovide transformers that can convert your Source class to any of the other standardSource classes, without having to go through a stream.

• Class RequestHeaders, ResponseHeaders: Along with the Source representing the mes-sage, these classes contain transport header information associated with the message.

• Class RequestMetaData, ResponseMetaData: These extend the headers to provide addi-tional metadata associated with the message.

• Interface InboundTransportMessageContext, OutboundTransportMessageContext: Thetransport provider implements these interfaces to bring together all the informationassociated with a message under one object. This includes the Source for the payloadof the message, the headers, the metadata, and other information associated with themessage.

• Interface TransportSendListener: The callback object that the outbound transport usesto deliver a response message into the pipeline.

• Interface TransportUIBinding: The transport provider implements this interface to pro-vide all the information for rendering the provider-specific transport configurationscreen. This also includes the methods for validating the entered configuration data.

• Class TransportUIFactory: A utility class for creating various UI elements to be includedon the transport configuration screen. These include textbox, checkbox, select drop-down, password entry, browser textbox (for selecting ALSB artifacts such as a serviceaccount), text area, and dynamic table.

CHAPTER 13 ■ CUSTOM TRANSPORTS 295

7974CH13.qxd 4/2/07 9:43 PM Page 295

Page 321: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

The preceding list includes the main classes and interfaces of the Transport SDK. Thereare several more classes, which are essentially value objects for grouping together a bunch ofinformation into one interface. These only have getter- or setter-type methods for accessing orsetting their information.

Another set of classes is worth mentioning are classes that aren’t documented in theJavadoc API documentation. These are the XMLBean classes (of type XmlObject) that are gen-erated from the XML schema file TransportCommon.xsd. You’ll find this file in BEA_HOME/weblogic92/servicebus/lib/sb-public.jar. XMLBean technology is used heavily in ALSB; formore information on this technology, see http://xmlbeans.apache.org/. Although there isn’tJavadoc API documentation for these interfaces, the documentation for these XMLBeanclasses is in the TransportCommon.xsd schema file.

• EndPointConfiguration: The generic configuration for a service endpoint. This containsthe configuration data that applies to all transports. A custom transport providerdefines its own schema for the additional configuration necessary for endpointsusing the transport. This additional XML configuration data gets assigned to theprovider-specific element within EndPointConfiguration.

• RequestHeadersXML, ResponseHeadersXML: The base type for request and responseheaders. Custom transports extend these schemas to define their own headers.

• RequestMetaDataXML, ResponseMetaDataXML: The base type for request and responsemetadata associated with a message. Custom transports extend these schemas todefine their own metadata.

• TransportProviderConfiguration: An XMLBean providing configuration informationabout the transport; for example, whether it supports inbound (proxies), outbound(business services), or both.

We’ll describe how to create all these XMLBeans in the sections “Transport ProviderConfiguration XML File” and “Transport Provider Schemas.”

Overview of TasksHere are the tasks to implement a custom transport. This is a roadmap for the followingsections.

1. Create your custom transport provider configuration XML file.

2. Create schemas for your custom transport. This includes schemas for your serviceendpoint configuration, for your request and response headers (if any), and for yourrequest and response metadata.

3. Implement the custom transport user interface classes.

4. Deploy service endpoints using the custom transport.

5. Implement the message-processing runtime classes.

6. Register the custom transport provider.

CHAPTER 13 ■ CUSTOM TRANSPORTS296

7974CH13.qxd 4/2/07 9:43 PM Page 296

Page 322: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Transport Provider Configuration XML FilePart of the behavior of a transport provider is described via a simple XML file. The schema forthis file has only four elements, as shown in Figure 13-5.

Figure 13-5. Transport provider configuration schema

The configuration XML file declares whether the transport supports inbound (proxies),outbound (business services), or both. The optional self-described attribute declareswhether the endpoint configuration defines its own structure or schema. The EJB transport isthe only example of such a transport. Rather than being defined by a WSDL, the EJB transportgenerates its own WSDL by introspecting the target EJB.

That leaves the UDDI element, which requires a little explanation. This is a place for atransport to declare a UDDI tModel definition for the transport. ALSB can publish proxies to aUDDI registry. The published proxy has information describing its interface, including identi-fying the transport used by the service. The transport is identified by pointing to the tModelfor the transport. ALSB will publish all the transport tModels when you configure the UDDIregistry to be used by ALSB.

The sample socket’s configuration is given in Listing 13-3. Notice that it supports bothinbound and outbound, and provides a tModel definition.

Listing 13-3. Provider Configuration XML for the Socket Transport

<?xml version="1.0" encoding="UTF-8"?><ProviderConfiguration xmlns="http://www.bea.com/wli/sb/transports"><inbound-direction-supported>true</inbound-direction-supported><outbound-direction-supported>true</outbound-direction-supported><UDDIMapping><TModelDefinition><tModel tModelKey="uddi:bea.uddi.org:transport:socket"><name>uddi-org:socket</name><description>Socket transport based webservice</description><overviewDoc><overviewURL useType="text">http://www.bea.com/wli/sb/UDDIMapping#socket

</overviewURL></overviewDoc><categoryBag><keyedReference keyName="uddi-org:types:transport"

keyValue="transport"

CHAPTER 13 ■ CUSTOM TRANSPORTS 297

7974CH13.qxd 4/2/07 9:43 PM Page 297

Page 323: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

tModelKey="uddi:uddi.org:categorization:types"/></categoryBag>

</tModel></TModelDefinition>

</UDDIMapping></ProviderConfiguration>

So, how does this information get into the running transport? This XML file is includedin the final EAR file that you build. Listing 13-4 shows how this XML file gets parsed, andhow an XMLBean is created to contain this information. This code is extracted from theSocketTransportProvider class.

Listing 13-4. SocketTransportProvider getProviderConfiguration Method

/*** @return the XML document for the static properties for this provider* @throws TransportException*/public TransportProviderConfiguration getProviderConfiguration()throws TransportException {try {URL configUrl =this.getClass().getClassLoader().getResource("SocketConfig.xml");

return ProviderConfigurationDocument.Factory.parse(configUrl).getProviderConfiguration();

}catch (Exception e) {SocketTransportUtil.logger.error(e.getLocalizedMessage(), e);throw new TransportException(e);

}}

Transport Provider SchemasA transport needs to provide XML schemas for several items. It must have a schema for itsendpoint configuration describing what information must be configured for a service end-point. This schema is completely up to the transport provider. It may also have schemas formetadata and headers that accompany request or response messages using the transport.These last four schemas extend base schemas defined in TransportCommon.xsd.

The endpoint configuration schema for the socket transport is given in Figure 13-6. Thefields in this schema should look familiar. You saw those fields when you were configuringyour socket transport proxies and business services earlier.

CHAPTER 13 ■ CUSTOM TRANSPORTS298

7974CH13.qxd 4/2/07 9:43 PM Page 298

Page 324: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 13-6. Socket transport endpoint configuration schema

Headers are typically just name/value pairs. They are part of the information communi-cated with a message, though they’re separate from the message payload. Don’t confuseheaders with the SOAP header for SOAP messages. Transport headers come from the trans-port, not from the SOAP message. Good examples of headers are HTTP headers and JMSproperties. The main point of having a schema for transport headers is that it provides a wayto define the list of standard headers. These are presented to the user when he or she uses theTransport Headers action in the pipeline. You can still use headers that aren’t a part of thetransport; they’re just considered user-defined headers.

The socket transport defines some headers, primarily for the sake of demonstrating theuse of headers. These aren’t really natural for socket communication. Only the request mes-sage is defined as having headers. The schema to declare socket transport request headers isshown in Figure 13-7.

Figure 13-7. Socket transport request headers schema

Transport metadata is a superset of transport headers. In addition to the transport head-ers, it contains other metadata associated with a message. This metadata provides a contextfor the message. Unlike headers, this is not typically data that’s carried along with the mes-sage. It might be configuration data, or data about the message. Figure 13-8 shows how thesocket transport defines its request metadata.

CHAPTER 13 ■ CUSTOM TRANSPORTS 299

7974CH13.qxd 4/2/07 9:43 PM Page 299

Page 325: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 13-8. Socket transport request metadata schema

Notice how the socket request header schema and the request metadata schema extendthe corresponding base schema from TransportCommon.xsd, namely RequestHeadersXML andRequestMetaDataXML.

ALSB uses this metadata schema to define part of the contents of the message contextvariables $inbound and $outbound. These variables have an XML section (for example, at$inbound/transport/request) that conforms to the request metadata schema, and anothersection ($inbound/transport/response) that conforms to the response metadata schema. So,for example, if you log $inbound in your socket transport proxy, you’ll get XML looking likeListing 13-5. Some groups have been collapsed so you can focus on the request metadata.

Listing 13-5. $inbound for the Socket Transport

- <endpoint name="ProxyService$SocketTest$SocketProxy" xmlns=...><service />

- <transport><uri>tcp://7100</uri><mode>request-response</mode><qualityOfService>best-effort</qualityOfService>

- <request xsi:type="sock:SocketRequestMetaDataXML">- <tran:headers xsi:type="sock:SocketRequestHeadersXML">

<sock:message-count>5</sock:message-count></tran:headers><tran:encoding>utf-8</tran:encoding><sock:client-host>127.0.0.1</sock:client-host><sock:client-port>4513</sock:client-port>

</request>+ <response xsi:type="sock:SocketResponseMetaDataXML">

</transport>+ <security>

</endpoint>

Now, we must once again address how these schemas get turned into usable data struc-tures that affect how the socket transport actually works. First, you must compile the transportschema into Java classes representing the associated XMLBeans. This is done via theschema_compile step in the Ant build file. This uses the XMLBeans schema compiler to gener-ate Java classes from the XML schema. A Java class is generated for each type defined in theschema. These Java classes implement the XmlObject interface (part of the XMLBeans standard).

CHAPTER 13 ■ CUSTOM TRANSPORTS300

7974CH13.qxd 4/2/07 9:43 PM Page 300

Page 326: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

This has an attribute XmlObject.type that gives the SchemaType for the XmlObject: a Java objectrepresenting the associated schema.

Methods are defined on the TransportProvider for returning these schema objects. Recallthat the transport provider must implement the TransportProvider interface. For example, thesocket transport provider has a class, SocketTransportProvider, implementing this interface.The relevant methods are given in Listing 13-6.

Listing 13-6. Providing the Various Schema Types for the Socket Transport

/*** @return the XML schema type for the endpoint configuration for this* provider*/public SchemaType getEndPointConfigurationSchemaType() {return SocketEndpointConfiguration.type;

}/*** @return the XML schema type of the request message for this provider*/public SchemaType getRequestMetaDataSchemaType() {return SocketRequestMetaDataXML.type;

}/*** @return the XML schema type of the request headers for this provider. If* provider does not support request headers, return null.*/public SchemaType getRequestHeadersSchemaType() {return SocketRequestHeadersXML.type;

}/*** @return the XML schema type of the response message for this provider*/public SchemaType getResponseMetaDataSchemaType() {return SocketResponseMetaDataXML.type;

}/*** @return the XML schema type of the response headers for this provider. If* provider does not support response headers, return null.*/public SchemaType getResponseHeadersSchemaType() {return SocketResponseHeadersXML.type;

}

Implementing Transport Provider User Interface ClassesOne of the elegant capabilities of a custom transport is its ability to integrate with the ALSBconsole in a natural way. Services using the custom transport have a special console page for

CHAPTER 13 ■ CUSTOM TRANSPORTS 301

7974CH13.qxd 4/2/07 9:43 PM Page 301

Page 327: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

configuring transport-specific information. This is why custom transports are consideredfirst-class citizens and are indistinguishable from transports that come out of the box withALSB.

To provide this console integration, the transport provider implements a class supportingthe TransportUIBinding interface. This is the key class for defining the user interface for thecustom transport. It declares what kinds of service types the transport supports, describeswhat its URL should look like, lists the fields that should be given to the user to fill out todescribe a service endpoint, validates the user’s entry, and translates the user’s entry into atransport endpoint configuration (the XMLObject described in the earlier section “TransportProvider Schemas”). We’ll go through these steps.

Let’s first review the steps to take to create a proxy service (creating a business service issimilar). This will help us to relate the implementation tasks to what’s happening in the con-sole user interface. To create a proxy service, you go through the service creation wizard,which has these screens:

1. The General Configuration screen, where you name your service, declare its ServiceType, and fill in some other info

2. The generic Transport Configuration screen, where you select a transport and providetransport configuration data that applies to all transports, such as the Endpoint URI

3. The transport-specific Transport Configuration screen, where you provide configura-tion that’s specific to the transport provider selected in step 2

4. The Summary screen, where you confirm your configuration and save

The implementation of the TransportUIBinding comes in at screens 2, 3, and 4. In addi-tion, the Service Type from step 1 impacts the later screens, and is used in the validation.

The first thing to implement is the method isServiceTypeSupported(). In step 1, the userhas picked a service type, such as WSDL, Messaging, ANY SOAP, and so on. However, not alltransports support all service types. ALSB will call your transport with the chosen service typeand your transport can say whether it’s supported. Then the drop-down list of transports instep 2 will only show the transports that support the chosen service type.

For example, the socket transport’s implementation of this method is given in Listing 13-7.Some of the code has been eliminated for brevity. If your transport provider supports all serv-ice types, you can simply return true for this method.

Listing 13-7. Socket Transport isServiceTypeSupport Implementation

/*** Returns true if the message type is either TEXT or XML. Socket transport* supports XML and TEXT message types only for both the request and the* response messages.*/public boolean isServiceTypeSupported(BindingTypeInfo bindingType) {try {BindingTypeInfo.BindingTypeEnum type = bindingType.getType();/*** If the binding is mixed, request type should exist and it should be* either TEXT or XML type and if there is any response type,

CHAPTER 13 ■ CUSTOM TRANSPORTS302

7974CH13.qxd 4/2/07 9:43 PM Page 302

Page 328: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

* it must be either TEXT or XML.*/if (type.equals(BindingTypeInfo.BindingTypeEnum.MIXED)) {/* ... Return false if there is an unsupported type,

Else return true. */}/*** Binding type must be either ABSTRACT_XML or XML.*/return type.equals(BindingTypeInfo.BindingTypeEnum.ABSTRACT_XML)|| type.equals(BindingTypeInfo.BindingTypeEnum.XML);

} catch (TransportException e) {SocketTransportUtil.logger.error(e.getLocalizedMessage(), e);return false;

}}

There are a couple other ways that the screen in step 2 gets tailored by the custom trans-port. The custom transport provides the sample format for the Endpoint URI. It also providesthe starting URI value, which is typically the prefix of the given URI. This information is returnedin the value object TransportUIGenericInfo and is returned by the method getGenericInfo().This is also where you declare whether your transport supports WS-I compliance.

The socket transport’s implementation of this method is provided in Listing 13-8. This hasbeen simplified a little from the real implementation, which pulls the actual string values froman i18n file so that they can be localized for different languages.

Listing 13-8. Socket Transport getGenericInfo

public TransportUIGenericInfo getGenericInfo() {TransportUIGenericInfo genInfo = new TransportUIGenericInfo();if (uiContext.isProxy()) {genInfo.setUriFormat( "tcp://port" );genInfo.setUriAutofill( "tcp://9999" );

} else {genInfo.setUriFormat( "tcp://socket-ip-address:port" );genInfo.setUriAutofill( "tcp://localhost:8888" );

}return genInfo;

}

Before you leave the screen in step 2, you must validate the URI (or URIs for a businessservice) that the user has entered. This is done with the method validateMainForm(). However,to understand this method, you need to understand how fields are represented on the consoleUI pages.

A generic class TransportEditField represents an editable entry field on a console page.There are many types of user interface fields, but they all have some common characteristics,including a label, whether it is a required field, whether it is an advanced field (appears in theadvanced portion of the config page), whether it is disabled, and so on. The actual entry field

CHAPTER 13 ■ CUSTOM TRANSPORTS 303

7974CH13.qxd 4/2/07 9:43 PM Page 303

Page 329: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

is of type TransportUIFactory.TransportUIObject. There are many of these types of UI objects,including the following:

• TextBox: A single-line text area

• TextArea: A multiline text area

• BrowserTextBox: A selection textbox driven by a pop-up chooser window

• CheckBox: A simple Boolean checkbox

• Select: A drop-down list

• SimpleTable: A fixed table of values

• DynamicTable: A dynamic table of values

• ExpandableTable: A table of values that can grow as data is entered

• Password: A textbox where the values are not shown

For a complete list, see the Javadoc for TransportUIFactory.Now, we can discuss how the validateMainForm() method can validate the URI in the

generic Transport Configuration screen. This method takes an array of TransportEditFieldsrepresenting the fields on the screen. However, it’s more convenient to grab just the URI fieldby first turning this array into a map and mapping the field name into the correspondingTransportUIObject. You can then get the TransportUIObject for the URI field, extract the URIvalues from this field, and check them for syntactical correctness. Listing 13-9 shows how thesocket transport validates the URI field, which is a different validation for proxies and busi-ness services (the simpler proxy check is suppressed for brevity).

Listing 13-9. Socket Transport validateMainForm

public TransportUIError[] validateMainForm(TransportEditField[] fields) {Map<String, TransportUIFactory.TransportUIObject> map =TransportEditField.getObjectMap(fields);

List<TransportUIError> errors = new ArrayList<TransportUIError>();if (!uiContext.isProxy()) {List<String[]> uris = getStringValues(map, TransportUIBinding.PARAM_URI);for (String[] uristr : uris) {try {URI uri = new URI(uristr[0]);if (!(uri.getScheme().equals("tcp") && uri.getHost() != null &&uri.getPort() != -1)) {errors.add(new TransportUIError(TransportUIBinding.PARAM_URI,"Invalid URI"));

}} catch (URISyntaxException e) {errors.add(new TransportUIError(TransportUIBinding.PARAM_URI,e.getMessage()));

}

CHAPTER 13 ■ CUSTOM TRANSPORTS304

7974CH13.qxd 4/2/07 9:43 PM Page 304

Page 330: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

}} else {/* Do a similar check for proxy URLs, they should be of form "tcp:<port>" */

}return errors == null || errors.isEmpty() ? null :errors.toArray(new TransportUIError[errors.size()]);

}

You’re now ready to go on to screen 3: the transport-specific Transport Configurationscreen. The fields on this screen are completely prescribed by the transport. The transportprovides the list of fields to show on the screen via the method getEditPage(). This methodis given the EndPointConfiguration for the service (or a default one if the service is gettingcreated for the first time) and the BindingTypeInfo for the service. It must return an array ofTransportEditFields to be shown on the screen, with their values pulled from theEndPointConfiguration.

In the socket transport version of the getEditPage() method (shown in Listing 13-10), it’sconvenient to build up the array of TransportEditFields using a List, and then at the end,convert this list back to an array. Try looking back at the socket transport configuration pageshown in Figure 13-2 and compare that with this code. The code has been simplified, asshown, for brevity.

Listing 13-10. Socket Transport getEditField

public TransportEditField[] getEditPage(EndPointConfiguration config,BindingTypeInfo binding)

throws TransportException {List<TransportEditField> fields = new ArrayList<TransportEditField>();SocketEndpointConfiguration sockConfig = null;if (config != null && config.isSetProviderSpecific()) {sockConfig = SocketTransportUtil.getConfig(config);

}

/* Add requestResponse checkbox */boolean requestResponse =sockConfig == null || sockConfig.getRequestResponse();

TransportUIFactory.CheckBoxObject checkbox =TransportUIFactory.createCheckbox(null, requestResponse, true);

TransportEditField editField =TransportUIFactory.createEditField(REQUEST_RESPONSE, REQUEST_RESPONSE_LABEL,REQUEST_RESPONSE_TOOLTIP, false, checkbox);

fields.add(editField);/** If it is a proxy, add the Backlog field.* But in either case, get the timout and enableNagleAlgorith values.*/long timeout = 5000;boolean enableNA = true;if (uiContext.isProxy()) {

CHAPTER 13 ■ CUSTOM TRANSPORTS 305

7974CH13.qxd 4/2/07 9:43 PM Page 305

Page 331: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

int backlog = 5;if (sockConfig != null) {SocketInboundPropertiesType inboundProperties =sockConfig.getInboundProperties();

backlog = inboundProperties.getBacklog();timeout = inboundProperties.getTimeout();enableNA = inboundProperties.getEnableNagleAlgorithm();

}TransportUIFactory.TextBoxObject textBox =TransportUIFactory.createTextBox(backlog + "", 20);

editField = TransportUIFactory.createEditField(BACKLOG, BACKLOG_LABEL,BACKLOG_TOOLTIP, false, textBox);

fields.add(editField);} else {if (sockConfig != null) {SocketOutboundPropertiesType outboundProperties =sockConfig.getOutboundProperties();

timeout = outboundProperties.getTimeout();enableNA = outboundProperties.getEnableNagleAlgorithm();

}}

/* Add the Connection Timeout TextBox field *//* Add the Enable Nagle's Algorithm checkbox field *//* Add the Request Encoding TextBox field *//* Add the Response Encoding TextBox field *//* Add the Dispatch policy SelectObject (drop-down list) field */

return fields.toArray(new TransportEditField[fields.size()]);}

A transport might want to change the transport configuration screen depending on whatdata the user has entered. One of the attributes of a TransportUIObject is whether there is anevent associated with it. This acts like a callback mechanism, allowing the transport providerto change the UI fields, perhaps by adding or deleting fields, or by enabling/disabling fields.This is done with the UpdateEditPage() method.

Again, examples make this simpler to understand. In the socket transport, you shouldonly be able to set the Response Encoding if there is a response; that is, if Is ResponseRequired is checked. Hence, checking and unchecking the Response Required checkboxcauses the Response Encoding field to be enabled and disabled. The socket transport’sUpdateEditPage() method demonstrates this in Listing 13-11.

Listing 13-11. Socket Transport UpdateEditPage

public TransportEditField[] updateEditPage(TransportEditField[] fields,String name)

throws TransportException {/** update the values only for REQUEST_RESPONSE field. */

CHAPTER 13 ■ CUSTOM TRANSPORTS306

7974CH13.qxd 4/2/07 9:43 PM Page 306

Page 332: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

if (!REQUEST_RESPONSE.equals(name)) {return fields;

}/** RESPONSE_ENCODING field should be enabled only when REQUEST_RESPONSE* is true.*/Map<String, TransportEditField> fieldMap =TransportEditField.getFieldMap(fields);

TransportEditField editField = fieldMap.get(REQUEST_RESPONSE);TransportUIFactory.CheckBoxObject selectObject =(TransportUIFactory.CheckBoxObject) editField.getObject();

boolean b = selectObject.ischecked();fieldMap.get(RESPONSE_ENCODING).setDisabled(!b);return fields;

}

The service definition screen also supports validating the entered data. This provides anopportunity for the transport provider to give friendly diagnostics on this page before goingon with the rest of the service definition. This is done via the validateProviderSpecificForm()method, which is given the array of TransportEditFields and returns an array of Transport-UIErrordiagnostics.

The socket transport doesn’t do any validation of the entered data, so we’ll not bothershowing the code for the function. However, this is not the best practice; doing validation hereis useful. For example, the socket transport should validate that the data entered for a sockettimeout is an integer (not just a random string of characters), and should probably check toensure it is a nonnegative integer at that. It should probably also validate that any characterencoding entered is legitimate. The socket transport does none of these checks, although itwill catch entering string data into the timeout field at a later stage, in an unfriendly manner!We’ll leave adding this validation code as an exercise for the reader.

The last thing that happens before you leave this screen is that all the data entered intothe UI fields must be converted back to the provider portion of the endpoint configuration.This is the XMLObject for the provider-specific configuration, which should match the transportprovider schema described earlier. This is done via the getProviderSpecificConfiguration()method. This is another place to catch errors, but doesn’t allow for returning friendly diagnos-tic messages.

You can think of this as the inverse to the getEditPage() method, taking an array ofTransportEditFields and returning an XMLObject for the provider-specific configuration. Justnote this difference: getEditPage() gets the outer EndpointConfiguration object, which hasboth the generic transport information as well as the provider-specific information.

An abbreviated version of the socket transport getProviderSpecificConfiguration()method is shown in Listing 13-12.

Listing 13-12. Socket Transport getProviderSpecificConfiguration

public XmlObject getProviderSpecificConfiguration(TransportEditField[] fields)throws TransportException {

SocketEndpointConfiguration socketEndpointConfig =SocketEndpointConfiguration.Factory.newInstance();

CHAPTER 13 ■ CUSTOM TRANSPORTS 307

7974CH13.qxd 4/2/07 9:43 PM Page 307

Page 333: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Map<String, TransportUIFactory.TransportUIObject> map =TransportEditField.getObjectMap(fields);

socketEndpointConfig.setRequestResponse(TransportUIFactory.getBooleanValue(map, REQUEST_RESPONSE));

if (uiContext.isProxy()) {SocketInboundPropertiesType socketInboundPropertiesType =socketEndpointConfig.addNewInboundProperties();

socketInboundPropertiesType.setBacklog(TransportUIFactory.getIntValue(map, BACKLOG));

socketInboundPropertiesType.setEnableNagleAlgorithm(TransportUIFactory.getBooleanValue(map, ENABLE_NAGLE_ALGORITHM));

socketInboundPropertiesType.setTimeout(TransportUIFactory.getIntValue(map, TIME_OUT));

} else {/* Do the same for outbound properties for a business service */

}

String reqEnc = TransportUIFactory.getStringValue(map, REQUEST_ENCODING);if (reqEnc != null && reqEnc.trim().length() != 0) {socketEndpointConfig.setRequestEncoding(reqEnc);

}String resEnc = TransportUIFactory.getStringValue(map, RESPONSE_ENCODING);if (resEnc != null && resEnc.trim().length() != 0) {socketEndpointConfig.setResponseEncoding(resEnc);

}

String dispatchPolicy =TransportUIFactory.getStringValue(map, DISPATCH_POLICY);

socketEndpointConfig.setDispatchPolicy(dispatchPolicy);

return socketEndpointConfig;}

}

Wow! That was a lot of work just for screen 3. Luckily, that is the hard part of the transportUI binding work. There’s only one more small task to do before you’re completely finishedwith the UI work. That involves the last screen of the service creation wizard: screen 4, thefinal summary screen.

In the final summary screen, a portion of the page gives a read-only view of the summaryof the transport provider’s specific configuration. The transport provider can select whichfields should be present in the summary (all of them, or a subset). A general rule of thumb is toshow the fields whose values differ from their defaults, and perhaps the most critical fields.

The transport provider gives the list of fields to show in the getViewPage() method, whichreturns an array of TransportViewField objects. The interesting data in a TransportViewFieldis just the label and the value, so it’s a simplified version of a TransportEditField. getViewPage()

CHAPTER 13 ■ CUSTOM TRANSPORTS308

7974CH13.qxd 4/2/07 9:43 PM Page 308

Page 334: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

is similar to getEditPage(), except that the returned info is simpler and doesn’t need to becomplete. So, without further ado, let’s show the simplified form of the socket transport’s ver-sion of this method in Listing 13-13, and be done with implementing transport provideruser-interface classes.

Listing 13-13. SocketTransport getViewPage

public TransportViewField[] getViewPage(EndPointConfiguration config)throws TransportException {List<TransportViewField> fields = new ArrayList<TransportViewField>();SocketEndpointConfiguration socketEndpointConfiguration =SocketTransportUtil.getConfig(config);

/* Add requestResponse field */TransportViewField field =new TransportViewField(REQUEST_RESPONSE, REQUEST_RESPONSE_LABEL,socketEndpointConfiguration.getRequestResponse());

fields.add(field);/** If it is a proxy, add the Backlog field.* But in either case, add the timeout and enableNagleAlgorithm fields.*/if (uiContext.isProxy()) {SocketInboundPropertiesType inboundProperties =socketEndpointConfiguration.getInboundProperties();

field = new TransportViewField(BACKLOG, BACKLOG_LABEL,inboundProperties.getBacklog());

fields.add(field);

/* Add the Connection Timeout field from inboundProperties *//* Add the Enable Nagle's Algorithm field from inboundProperties */

} else {/* Add the Connection Timeout field from outboundProperties *//* Add the Enable Nagle's Algorithm field from outboundProperties */

}

/* Add the Request Encoding field *//* Add the Response Encoding field *//* Add the Dispatch policy field */

return fields.toArray(new TransportViewField[fields.size()]);}

CHAPTER 13 ■ CUSTOM TRANSPORTS 309

7974CH13.qxd 4/2/07 9:43 PM Page 309

Page 335: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Deploying Service Endpoints Using the Custom TransportNow that you have the user interface for configuring the custom transport done, it’s time todeploy the service. The transport provider must implement the support for deploying theservice endpoint, making it active for sending and receiving messages. This includes initiatingany listeners for incoming messages.

The methods for deploying and managing endpoints include operations create, update,delete, suspend, and resume. There are two sets of these methods. There are methods in thebasic TransportProvider interface that every transport must implement, and methods in theoptional TransportWLSArtifactDeployer interface. We’ll describe the difference between thesetwo sets of methods.

The methods in TransportWLSArtifactDeployer are for deploying WLS entities such asEAR or WAR files using the WebLogic configuration domain MBean. These methods are onlycalled in the admin server, because by using the domain MBean, the entities will automati-cally get propagated out to the cluster by WLS. Furthermore, because WLS persists thedeployment of these entities, the methods in TransportWLSArtifactDeployer are only calledupon activation of a session that has made changes to a service using the transport. Thesemethods are not called at server startup.

However, the endpoint management methods in the base TransportProvider interfaceare called in every managed server in the cluster and in the admin server (though they typi-cally wouldn’t do anything in the admin server). These methods are called upon activation of asession that has made changes to a service, and they’re also called at server startup for everydeployed service. These methods are for dynamically creating and starting an endpoint in amanaged server.

Because it’s more common to deploy endpoints via the methods in the TransportProviderinterface, we’ll focus our initial attention on those methods.

Deploying an endpoint is a two-stage process. ALSB first invokes the transport’s methodto do the operation (create, update, delete, suspend, or resume). It does this across all thechanged services, and after they have all been completed, it calls activationComplete(). Forexample, if 20 services are created, ALSB invokes the createEndpoint() 20 times, once for eachservice transport endpoint during the first phase, and then invokes the activationComplete()method for each service transport endpoint during the second phase.

During the first phase, the transport should do as much work as possible to deploy theendpoint and catch any errors that might exist in the runtime environment. If any phase 1 callto an endpoint operation results in an error, all the changes are backed out by ALSB issuingthe opposite call (compensating action) to undo the previous actions, and the session activa-tion fails. During the second phase, with the call to activationComplete(), there’s noopportunity to report an error.

The challenge in deploying an inbound endpoint is to do as much as possible during thatfirst phase to set an endpoint, but without actually starting to process messages. You shouldonly start processing messages once the activationComplete() call has occurred. Your call tocreate an endpoint might actually get backed out before activationComplete() is called, soyou don’t want to start processing messages until that second phase completes.

ALSB calls each endpoint operation with a value object containing data associated withthe operation. The following attributes are common to all operations:

• Type: The type of the operation; that is, CREATE, UPDATE, DELETE, SUSPEND, or RESUME

• Ref: A reference to the associated service

CHAPTER 13 ■ CUSTOM TRANSPORTS310

7974CH13.qxd 4/2/07 9:43 PM Page 310

Page 336: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

• ScratchPad: A map that can be used as a temporary holding place untilactivationComplete() is called

• Compensating flag: A Boolean determining whether the operation is undoing a previousaction due to the session activation being rolled back

The only operational-specific data that extends this is on the create and update opera-tions. Following are the extra attributes for the create operation:

• EndPointConfiguration: The transport endpoint configuration data with both thegeneric and provider-specific portions

• New flag: A Boolean determining whether this is a new endpoint being created or anexisting endpoint being reloaded on server startup

• Enabled flag: A Boolean determining whether the endpoint should initially be in theenabled or suspended state

The extra attributes for update are just the EndPointConfiguration and the Enabled flagdescribed in the preceding bulleted list.

The transport provider is responsible for keeping track of all its endpoints. It has to beprepared to return a collection of the endpoints when its getEndPoints() method is called.Hence, the create/update/delete operations should manage this collection.

Listing 13-14 shows the socket transport implementation of the create and update opera-tions. Actually, there’s a problem with these methods. Can you spot it?

Listing 13-14. Socket Transport Create and Update Endpoints

public TransportEndPoint createEndPoint(EndPointOperations.Create createContext) throws TransportException {Ref ref = createContext.getRef();createContext.getScratchPad().put(ENABLED, createContext.isEnabled());SocketTransportEndPoint endPoint = new SocketTransportEndPoint(ref,

createContext.getEndPointConfiguration(), this);endPoints.put(ref, endPoint);return endPoint;

}

public TransportEndPoint updateEndPoint(EndPointOperations.Update update)throws TransportException {Ref ref = update.getRef();SocketTransportEndPoint oldEp = endPoints.get(ref);/** oldEP can be null, when the socket transport is restarted* and existing configuration is updated.*/if (oldEp != null) {update.getScratchPad().put(UPDATE_OLD_ENDPOINT, oldEp);

}endPoints.remove(ref);update.getScratchPad().put(ENABLED, update.isEnabled());

CHAPTER 13 ■ CUSTOM TRANSPORTS 311

7974CH13.qxd 4/2/07 9:43 PM Page 311

Page 337: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

SocketTransportEndPoint endPoint = new SocketTransportEndPoint(ref,update.getEndPointConfiguration(), this);

endPoints.put(ref, endPoint);return endPoint;

}

public void activationComplete(EndPointOperations.CommonOperation context) {Ref ref = context.getRef();EndPointOperations.EndPointOperationTypeEnum type = context.getType();SocketTransportEndPoint endPoint = endPoints.get(ref);

try {if (EndPointOperations.EndPointOperationTypeEnum.CREATE.equals(type)) {

if ((Boolean) context.getScratchPad().get(ENABLED)) {endPoint.start();

}} elseif (EndPointOperations.EndPointOperationTypeEnum.UPDATE.equals(type)) {SocketTransportEndPoint oldEP = (SocketTransportEndPoint) context.getScratchPad().get(UPDATE_OLD_ENDPOINT);

if (oldEP != null) {oldEP.stop();

}if ((Boolean)context.getScratchPad().get(ENABLED)) {endPoint.start();

}} else/* Handle Delete/Suspend/Resume cases */

} catch (Exception e) {String msg = SocketTransportMessagesLogger.activationFailedLoggable(ref.getFullName()).getMessage();

SocketTransportUtil.logger.error(msg, e);}

}

Did you spot the problem? As we discussed earlier, the endpoint operation methods arecalled on each managed server and on the admin server. It’s uncommon for them to do anywork on the admin server. Indeed, we wouldn’t want to start listening on a port on the adminserver. So, these methods should suppress creating the endpoint if they’re running on theadmin server in a cluster configuration. Fortunately, helper routines make this determinationeasier. Listing 13-15 shows an updated version of the create method that fixes this problem.

Listing 13-15. Corrected Form of Socket Transport Create Endpoint Method

public TransportEndPoint createEndPoint(EndPointOperations.Create createContext) throws TransportException {if (TransportManagerHelper.isAdmin() && TransportManagerHelper.clusterExists())

CHAPTER 13 ■ CUSTOM TRANSPORTS312

7974CH13.qxd 4/2/07 9:43 PM Page 312

Page 338: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

/* Nothing to do on the admin server in a cluster */return null;

Ref ref = createContext.getRef();createContext.getScratchPad().put(ENABLED, createContext.isEnabled());SocketTransportEndPoint endPoint = new SocketTransportEndPoint(ref,

createContext.getEndPointConfiguration(), this);endPoints.put(ref, endPoint);return endPoint;

}

Notice that the socket is not actually started in the create or update method. Instead,that’s deferred to the activationComplete() method (and is only done there if the endpoint isenabled). That’s how endpoint management is supposed to work. The actual enabling of theendpoint to start processing messages shouldn’t happen until the activationComplete()method. By the way, for the socket transport, this start method is where a listening thread iscreated for a proxy (it’s a no-op for a business service).

Now, let’s go back and explain a little more about the TransportWLSArtifactDeployerinterface. The object that you register with TransportManager.registerProvider()implements the TransportProvider interface, but it may also optionally implement theTransportWLSArtifactDeployer interface. You’d do this if you wanted to deploy WLS artifacts,such as EAR files, JMS destinations, and so on.

The create, update, delete, suspend, and resume methods in TransportWLSArtifactDeployerparallel the ones in the base TransportProvider interface. One significant difference is that themethods in TransportWLSArtifactDeployer are given a reference to the WLS DomainMBean. Theycan use this MBean to deploy artifacts to WLS.

Prior to calling the methods in TransportWLSArtifactDeployer, the ALSB configurationsystem makes sure that a WLS edit session is created. Hence, all configuration updates donevia the MBean will be done in an edit session. This ensures they’ll all happen atomically, andwill only happen if the ALSB session activates successfully.

When the transport provider’s object implements TransportWLSArtifactDeployer in addi-tion to TransportProvider, both sets of endpoint methods are called. For example, if a sessionhas created a service using the custom transport, ALSB will first call makeWLSChangesOnCreate()(from TransportWLSArtifactDeployer) on the admin server, then call createEndpoint() (fromTransportProvider) on the admin server, and then call createEndpoint() on each of the man-aged servers in the cluster. The transport provider needs to determine which of these calls toimplement and which to ignore.

Implementing Transport Provider Runtime ClassesHaving worked our way through what it takes to configure and deploy a custom transport for aservice, we can now take a look at the primary function of a transport—how it transports mes-sages. It’s time for the rubber to meet the road as we show you how to process messages in acustom transport.

Let’s divide and conquer again. To keep this manageable, let’s divide the message process-ing into the following steps. These are listed from the point of view of a transport providerinteracting with the ALSB runtime:

CHAPTER 13 ■ CUSTOM TRANSPORTS 313

7974CH13.qxd 4/2/07 9:43 PM Page 313

Page 339: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

• Delivering an inbound request

• Receiving an inbound response

• Receiving an outbound request

• Delivering an outbound response

However, before we can discuss message processing by the custom transport, we need todigress and talk about how messages are represented in the Transport SDK. There are twoparts to this: how transport headers and metadata are represented, and how the actual mes-sage payload is represented. Both of these are put into a normalized form, so that ALSB canhandle them in a unified way. However, the solutions for each are much different.

Transport Headers and Metadata RepresentationALSB supports the notion of transport headers (information that’s transmitted with the mes-sage at the transport level, but is not part of the message payload) and metadata (attributesassociated with the message but that aren’t formal transport headers). For example, the HTTPtransport has HTTP headers such as Content-Type or Content-Encoding, and has metadatasuch as queryString and clientAddress.

Every transport provider must implement a Java class that extends the abstract classRequestHeaders, and another Java class that extends the abstract class RequestMetaData (ormore precisely, RequestMetaData<T extends RequestHeaders>). Similarly, it must have Javaclasses for ResponseHeaders and ResponseMetaData. These classes act as POJO containers forthe custom transport headers and metadata.

You might recall that in the earlier section “Transport Provider Schemas,” we mentionedthat the transport provider has to provide a schema for the request headers and another onefor the request metadata (ditto for response). We also described how to create XmlObjectclasses for these schemas. So, if we have XmlObject classes to hold this data, why do we needPOJO Java objects?

The answer is performance. Working with POJOs is much faster than working withXmlObjects. ALSB is optimized to always work with headers and metadata via their POJOrepresentation whenever possible. The only time that this data has to be represented asXmlObjects is if the user manipulates the headers or metadata via XPaths, XQueries, or XSLTsin the pipeline. For example, the use of the Transport Headers action goes directly against thePOJO representation rather than the XmlObject representation, so it’s much faster.

To have the best of both worlds, the transport provider supplies the message metadata(which contains the headers) in POJO form, but also supplies methods for converting betweenthe POJO form and the XmlObject form. The methods to convert to XmlObject are the toXML()methods on the classes extending RequestHeaders and RequestMetaData (ditto for response).To go from the XML form to the POJO form of metadata, the transport provider must imple-ment the createResponseMetaData() and createRequestMetaData() methods in theInboundTransportMessageContext and OutboundTransportMessageContext interfaces,respectively.

RequestHeaders and RequestMetaData are abstract classes, but the only abstract methodsin them are their toXML() methods. So, the purpose of having a transport-specific extension ofthese classes is twofold: to implement the toXML() method, and to extend these classes to addadditional headers or metadata attributes, respectively.

CHAPTER 13 ■ CUSTOM TRANSPORTS314

7974CH13.qxd 4/2/07 9:43 PM Page 314

Page 340: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

To make things even easier, a transport provider doesn’t even need to implement thetoXML() methods. There’s a concrete implementation of RequestHeaders and RequestMetaDatathat has the toXML() methods implemented by introspecting the schema for the headers andmetadata, respectively. These are called DefaultRequestHeaders and DefaultRequestMetaData.Hence, all a transport provider needs to do is to extend these classes if they have specificheaders or specific metadata. If a transport has no specific headers, it can use theDefaultRequestHeaders class without extension. Similarly, if a transport has no metadataassociated with requests, it can use the DefaultRequestMetaData without extension.

There are equivalents to all the preceding classes for responses. Looking at the sockettransport’s implementation will hopefully make this clearer. The socket transport arbitrarilydefines a single request header called message-count (this is kind of a misuse of transportheaders, but is included for demonstration purposes). Its request metadata extends the stan-dard metadata by adding the fields client-host and client-port. It doesn’t define anyresponse headers, but does define response metadata to include service-endpoint-host andservice-endpoint-ip.

Hence, the socket transport defines classes SocketRequestHeaders, SocketRequestMetaData,and SocketResponseMetaData. Each extends the DefaultXXX equivalent. Notice that there’s noSocketResponseHeaders. Because there are no response header fields, the socket transport canjust use the default implementation.

Listing 13-16 shows the implementation of SocketRequestHeaders, and Listing 13-17shows the implementation of SocketRequestMetaData.

Listing 13-16. SocketRequestHeaders

public class SocketRequestHeaders extendsDefaultRequestHeaders<SocketRequestHeadersXML> {/* Whenever a new header element is added its* get/set type methods can be added here.*/private static final String MESSAGE_COUNT = "message-count";

public SocketRequestHeaders(RequestHeadersXML headers) throwsTransportException {super(SocketTransportProvider.getInstance(), headers);

}

public long getMessageCount() {return (Long) getHeader(MESSAGE_COUNT);

}

public void setMessageCount(long messageCount) {setHeader(MESSAGE_COUNT, messageCount);

}}

CHAPTER 13 ■ CUSTOM TRANSPORTS 315

7974CH13.qxd 4/2/07 9:43 PM Page 315

Page 341: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Listing 13-17. SocketRequestMetaData

public class SocketRequestMetaDataextends DefaultRequestMetaData<SocketRequestMetaDataXML> {private int port = Integer.MIN_VALUE;private String hostAddress;

public SocketRequestMetaData(SocketRequestMetaDataXML rmdXML)throws TransportException {super(SocketTransportProvider.getInstance(), rmdXML);if(rmdXML != null) {if(rmdXML.isSetClientHost()) {setClientHost(rmdXML.getClientHost());

}if(rmdXML.isSetClientPort()) {setClientPort(rmdXML.getClientPort());

}}

}public SocketRequestMetaData(String requestEncoding) throws TransportException {/*not calling super.(TransportProvider provider, RequestHeaders hdr,String enc) because it does not create new headers if hdr is null.*/super(SocketTransportProvider.getInstance());setCharacterEncoding(requestEncoding);

}

protected RequestHeaders createHeaders(TransportProvider provider,RequestHeadersXML hdrXML)

throws TransportException {return new SocketRequestHeaders(hdrXML);

}

public SocketRequestMetaDataXML toXML() throws TransportException {SocketRequestMetaDataXML requestMetaData = super.toXML();// set socket transport specific metadata.if (hostAddress != null) {requestMetaData.setClientHost(hostAddress);

}if (port != Integer.MIN_VALUE) {requestMetaData.setClientPort(port);

}return requestMetaData;

}

public void setClientHost(String hostAddress) {this.hostAddress = hostAddress;

}

CHAPTER 13 ■ CUSTOM TRANSPORTS316

7974CH13.qxd 4/2/07 9:43 PM Page 316

Page 342: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

public void setClientPort(int port) {this.port = port;

}}

Message Payload RepresentationNow that we’ve described how to represent the metadata associated with a message, we turnour attention to representing the message itself. The Transport SDK provides ways to repre-sent the message data that can be simple for most use cases or can be flexible for optimizingother use cases. A transport provider can use one of the standard classes for holding its data(say if it’s in the form of a byte array, a string, or a simple input stream), or can use its ownnative representation, if that makes sense for the transport.

At the heart of the message representation is an interface called Source. This is the basicinterface that all classes representing message content must support. This interface consists oftwo methods, as follows:

Interface Source

• InputStream getInputStream(TransformOptions options) returns the contents of thissource as a byte-based input stream.

• void writeTo(OutputStream os, TransformOptions options) writes the contents of thissource to a byte-based output stream.

A Source has two methods for getting at the underlying message: a pull-based methodgetInputStream, and a push-based method writeTo. The methods in the Transport SDK thatpass a message around, either from a transport into the binding layer or vice versa, use aSource object.

A wide range of use cases can simply take advantage of one of the standard, simple Sourceclasses that comes with ALSB. For example, if a transport provider naturally gets the incomingmessage in the form of a byte array, a string, or an input stream, it can easily create a Byte-ArraySource, a StringSource, or a StreamSource, respectively. The transport provider can then leave to the binding layer the task of parsing the message into the form given by theservice type (for example, SOAP, XML, text, and so on).

The StreamSource deserves a little extra explanation. For a typical Source, you should beable to call either of the methods for getting at the underlying data multiple times. For exam-ple, the runtime might call the getInputStream() method once to get the underlying messagedata, consume the returned stream, and then call it a second time to get the underlyingmessage data via a stream a second time. However, there’s a special marker interface,SingleUseSource, extending Source, that declares that the underlying data can be consumedonly once. The StreamSource implements this SingleUseSource.

With a source that implements SingleUseSource, rather than just Source, ALSB will inter-nally buffer the contents of the source so that it can reuse the data from this buffer (forexample, for retrying of a message after a failure). For example, a stream coming from a socketor HTTP connection can only be read once—it cannot be reset back to the beginning as youcan for a byte array or string. Hence, such a stream will be encapsulated in a StreamSource, sothat ALSB will know to buffer the contents.

CHAPTER 13 ■ CUSTOM TRANSPORTS 317

7974CH13.qxd 4/2/07 9:43 PM Page 317

Page 343: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

For transports that get their data in a more structured form (rather than just a rawsequence of bytes), other standard sources come with ALSB. These generally follow the pat-tern of having one or more constructors that create the Source class from the underlyingstructured data, and a get method for directly getting the underlying structured data:

• ByteArraySource: A byte-based Source based on a byte array.

• StringSource: A text-based Source based on a string object.

• StreamSource: A single-use Source based on an InputStream.

• XmlObjectSource: An XML-based Source based on an XmlObject.

• DOMSource: An XML-based Source based on a DOM node.

• MFLSource: An MFL-based Source whose underlying content is represented byXmlObject and an MFL resource.

• SAAJSource: A SOAP-based Source based on a SAAJ javax.xml.soap.SOAPMessage.

• MimeSource: A MIME-based Source composed of MIME headers, and another Sourcefor the content. The serialization representation of a MIMESource is a standard MIMEpackage.

• MessageContextSource: A Source representing a message and its attachments, each ofwhich is another untyped Source. The serialization of this Source is always a MIMEmultipart/related package.

• AttachmentsSource: An XML-based Source representing a set of attachments. Its streamrepresentation is equivalent to the stream representation of the $attachments variable.

The last few Sources in this list are for handling messages with attachments, somethingthat few transports will have to face. For example, within ALSB, only the HTTP and e-mailtransport support messages with attachments.

■Tip Don’t confuse the Source object representation with the service type. The two are somewhat related,but are independent. However, the Source object representation should be at least compatible with theservice type.

The ALSB binding layer (look back at Figure 13-1) is responsible for converting contentbetween the Source representation used by the transport layer and the Message Context usedby the ALSB runtime. How that conversion happens depends upon the service type (its bind-ing type) and the presence of attachments.

When attachments aren’t present, the incoming Source represents just the core messagecontent. The incoming Source from the transport is converted to a specific type of Source,and then the underlying content can be extracted. For example, for XML-based services, theincoming Source is converted to an XmlObjectSource. The XmlObject is then extracted from the

CHAPTER 13 ■ CUSTOM TRANSPORTS318

7974CH13.qxd 4/2/07 9:43 PM Page 318

Page 344: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

XmlObjectSource and used as the payload inside the $body context variable. SOAP services aresimilarly converted to XmlObjectSource, except that the extracted XmlObject must be a SOAPEnvelope so that the <SOAP:Header> and <SOAP:Body> elements can be extracted to initialize the$header and $body context variables.

Following are the most natural Source types used for the set of defined service types:

• SOAP: XmlObjectSource

• XML: XmlObjectSource

• TEXT: StringSource

• MFL: MFLSource

For BINARY services, no Source conversion is done. Instead, the Source object is stored ina private repository, and a special <binary-content/> XML snippet that references the data isused as the payload inside $body. The pipeline only sees the XML snippet that refers to thebinary data, not the binary data itself. However, the binary data is available to ServiceCallout, Routing, Publish, and Java Callout actions.

A transport provider is free to implement its own XXXSource object representing its partic-ular message representation. At a minimum, this must implement the basic methods forstreaming the data (after doing appropriate conversions). The main advantage of creatingsuch a custom Source object is that if both the inbound and outbound transport recognize thistype of Source object, and if the message is not touched in the pipeline, the message represen-tation would never need to get converted.

Along with implementing a custom XXXSource object, a transport provider can registertransformations that can convert from this custom representation to one or more of the stan-dard representations. This can provide an optimal way to go from a custom representation to,for example, an XMLObject representation. This is done when the transport provider is regis-tered with the transport manager: TransportManager.registerProvider().

Let’s give a more concrete example. Suppose your custom transport supports some formof binary XML representation. You could define a BinXMLSource class, with a get and setmethod for accessing the underlying binary XML (BinXML). The stream methods would have toconvert from the BinXML representation to standard text XML. The binding layer could get thisstream of text XML and parse it to an XmlObject. But this is inefficient, because the BinXML isalready parsed and structured.

So, suppose there’s a more direct method for going from a BinXML representation to anXMLObject representation. Then you’d also register a transformer that can convert betweenthose two representations. In this way, you could eliminate the overhead of going from binaryXML to text XML, and then parsing the text XML back into an XmlObject.

When your custom transport is invoked on outbound with a Source object, it can first testwhether the Source object is an instance of BinXMLSource. If so, it can directly call the getmethod to get the BinXML representation and send it out. If the Source object isn’t already aBinXMLSource, it can use the master transformer—TransportManager.getTransformer()—toconvert from the given Source object to a BinXMLSource. ALSB creates this master transformeras being the transitive closure of all the built-in and registered transformers.

CHAPTER 13 ■ CUSTOM TRANSPORTS 319

7974CH13.qxd 4/2/07 9:43 PM Page 319

Page 345: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Inbound Message ProcessingWe’re finally ready to discuss how messages actually get processed. We’ll first discuss how theinbound transport passes a request message into the pipeline and how it receives theresponse to send back out. The next section will discuss the analogous processing for out-bound messages.

How an inbound service endpoint initially gets a message from the outside world is trans-port specific, and is outside the use of the Transport SDK. It might have a listener on somekind of communication channel, or it might poll for input, or it might rely on WLS services todeliver a message to it somehow. But however it receives a message, the transport must deliverthe message to the ALSB runtime.

To do this, the transport provider must implement a class supporting theInboundTransportMessageContext interface. This class serves multiple purposes: it packagesup all the information associated with the inbound message (for example, endpoint informa-tion, metadata associated with the message, and the actual message payload); it serves as acallback for the response, to receive the response metadata and payload; and it serves as afactory for creating ResponseMetaData objects, either from scratch or from an XMLrepresentation.

With a message in hand, the inbound transport provider attaches to the message anymetadata that came with the message and the endpoint that received the message, puttingall that information into the InboundTransportMessageContext object. It then invokesTransportManager.receiveMessage(), passing this InboundTransportMessageContext objectand some transport options (discussed in the following bulleted list). In the typical case, theTransportManager will invoke the following methods on the provider’sInboundTransportMessageContext:

• getEndpoint() to find out the endpoint delivering the message

• getMessageId() to get a message identifier (ideally unique) associated with the message

• getRequestMetaData() to get the metadata associated with the message

• getMessage() to get the Source object containing the message data, either a standardSource that comes with ALSB, or a custom Source

At this point, the runtime has all the information about the incoming request message.It then can invoke the pipeline and do the proxy service processing on the message. Wheneverything is complete, and it’s ready to deliver a response, it calls the following methods onthe provider’s InboundTransportMessageContext:

• createResponseMetaData() to create the object to hold the response metadata

• setResponseMetaData() to set the response metadata

• setResponsePayload() to set the source object containing the response message data

• close() to signal the provider that processing is complete and it can send the responsemessage back to the client

The call to close() is the final call. When the inbound transport provider receives this call,it not only sends the message back to the client, but it can also clean up any resources associ-ated with the message.

CHAPTER 13 ■ CUSTOM TRANSPORTS320

7974CH13.qxd 4/2/07 9:43 PM Page 320

Page 346: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

■Tip The call to close() typically comes from a different thread than the one that issued the call toTransportManager.receiveMessage(). This is the fundamental callback mechanism to invoke theinbound response processing from the proxy service response thread. It’s only after receiving this call thatthe provider should access the response metadata or response payload.

The other parameter to TransportManager.receiveMessage() is the value classTransportOptions. This class has a number of properties that are mostly self-explanatory. Acouple of the properties need further explanation. The property QoS represents Quality of Ser-vice, and can be either EXACTLY_ONCE or BEST_EFFORT. You should use EXACTLY_ONCE only whenthere’s a transaction associated with the incoming message. ALSB will use this value to set theQoS element in the message context variable $inbound, which is available in the pipeline, andcontrols the default quality of service used for outbound calls.

Another property closely related to QoS is ThrowOnError. This tells the runtime to throw anexception if an error is encountered during the request processing. If this is unset and an erroris encountered in the request pipeline, the runtime won’t return with an exception, but willinstead invoke the various response methods on the provider’s InboundTransportMessageContextobject, terminating with the close() call. The provider will recognize this as an error becausethe ResponseCode property in the ResponseMetaData will be set to TRANSPORT_STATUS_ERRORrather than TRANSPORT_STATUS_SUCCESS. This property only affects errors that are found during the request pipeline processing. Errors found during response pipeline processingalways result in setResponse() and close() calls being made on the provider’s InboundTransportMessageContext object.

Typically ThrowOnError is set only if the QoS is set to EXACTLY_ONCE. In this way, when anerror is encountered during request processing, the inbound transaction can be aborted. Forcertain transports, this can be done without returning a response, and can allow the transac-tion to be replayed (for example, JMS).

One other property of TransportOptions worth mentioning is Mode. This can be eitherREQUEST_ONLY or REQUEST_RESPONSE. If the Mode is REQUEST_ONLY, then the runtime won’t makethe calls to the response methods on the provider’s InboundTransportMessageContext object.It will only call the close() method at the end of message processing.

So, you can see that the properties described earlier affect the sequence of methods calledon the provider’s InboundTransportMessageContext object. Although the methods relating togetting the inbound request message will always be called, the methods relating to setting theoutbound response message might not be called, depending on TransportOptions and possi-ble error conditions. For example, the transport provider should be prepared to have theclose() method called without a call to set the response payload.

To give an example of this inbound processing, let’s look at the socket transport. Thesocket transport has an implementation of InboundTransportMessageContext, calledSocketInboundMessageContext. A subset of this class is shown in Listing 13-18. Parts (includingmost of the simple get methods) have been omitted for brevity.

An interesting method to look at is the constructor of the class, which initializes all thefields that the transport manager will later query, such as the endpoint, the message ID, therequest metadata, and the message payload. The get routines are then just mostly returningthese instance variables. The getRequestPayload() method takes the incoming message,which is in the form of a String, and simply turns it into a StringSource.

CHAPTER 13 ■ CUSTOM TRANSPORTS 321

7974CH13.qxd 4/2/07 9:43 PM Page 321

Page 347: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

The other interesting method to look at is the close() method. The transport managercalls this method after setting the response metadata and response message payload. Theclose() method is responsible for sending the response back to the client. At the end of theclose() method, all processing for this invocation is complete.

Listing 13-18. Simplified SocketInboundMessageContext

public class SocketInboundMessageContextimplements InboundTransportMessageContext {private SocketTransportEndPoint endPoint;private Socket clientSocket;private String msgId;private String msg;private SocketRequestMetaData requestMetadata;private SocketResponseMetaData responseMetaData;private Source responsePayload;private static int count = 0;

/*** Constructor of SocketInboundMessageContext. Initializes the field* variables.*/public SocketInboundMessageContext(SocketTransportEndPoint endPoint,

Socket clientSocket, String msgId,String msg) throws TransportException {

this.endPoint = endPoint;this.clientSocket = clientSocket;this.msgId = msgId;this.msg = msg;

String requestEncoding = endPoint.getRequestEncoding();if(requestEncoding == null) {requestEncoding = "utf-8";

}requestMetadata = new SocketRequestMetaData(requestEncoding);((SocketRequestHeaders)requestMetadata.getHeaders()).setMessageCount(++count);requestMetadata.setClientHost(clientSocket.getInetAddress().getHostAddress());requestMetadata.setClientPort(clientSocket.getPort());

}

/*** @return returns the source reading the inbound message or null if* there is no body of the request.*/public Source getRequestPayload() throws TransportException {if (msg == null) {return null;

}

CHAPTER 13 ■ CUSTOM TRANSPORTS322

7974CH13.qxd 4/2/07 9:43 PM Page 322

Page 348: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

return new StringSource(msg);}

/*** @return empty (new) metadata for the response part of the message, e.g.* headers, etc. Used for initializing the inbound response*/public ResponseMetaData createResponseMetaData() throws TransportException {SocketResponseMetaData responseMetaData =new SocketResponseMetaData(endPoint.getResponseEncoding());

return responseMetaData;}

/*** @return metadata for the response part of the message, e.g. headers, etc* initialized according to transport provider-specific XMLBean. Used* for initializing the inbound response*/public ResponseMetaData createResponseMetaData(XmlObject rmdXML)throws TransportException {SocketResponseMetaDataXML xmlObject =SocketResponseMetaData.getSocketResponseMetaData(rmdXML);

if (xmlObject != null) {return new SocketResponseMetaData(xmlObject);

}return null;

}

/*** sets the response metadata of the message.*/public void setResponseMetaData(ResponseMetaData rmd)throws TransportException {if (!(rmd instanceof SocketResponseMetaData)) {throw new TransportException(SocketTransportMessagesLogger.invalidResponseMetadataType(SocketResponseMetaData.class.getName()));

}responseMetaData = (SocketResponseMetaData) rmd;

}

/*** sets the response payload of the message.*/public void setResponsePayload(Source src) throws TransportException {responsePayload = src;

}

CHAPTER 13 ■ CUSTOM TRANSPORTS 323

7974CH13.qxd 4/2/07 9:43 PM Page 323

Page 349: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

/*** Sends the response back to the client.*/public void close(TransportOptions transportOptions) {

OutputStream outputStream = null;try {/** If message pattern is one way, return immediately.*/if (endPoint.getMessagePattern().equals(TransportEndPoint.MessagePatternEnum.ONE_WAY)) {return;

}/** Write the response back to the client. */String reqEnc =endPoint.getSocketEndpointConfiguration().getRequestEncoding();

if(reqEnc == null) {reqEnc = "utf-8";

}outputStream = clientSocket.getOutputStream();if (responsePayload != null) {TransformOptions options = new TransformOptions();

options.setCharacterEncoding(reqEnc);responsePayload.writeTo(outputStream, options);

} else {SocketTransportMessagesLogger.noResponsePayload();

}/** write \r\n\r\n at the end. */outputStream.write(SocketTransportUtil.D_CRLF.getBytes(reqEnc));outputStream.flush();

} catch (Exception e) {/* Log an error */

} finally {try {// closing the socket stream.clientSocket.close();

} catch (IOException ignore) {}

}}

}

To complete the picture, let’s discuss where the SocketInboundMessageContext object getscreated. This occurs in the SocketTransportReceiver class. This class has a listener on the con-figured port, and spawns off a worker thread when a new incoming message is available. A lotof socket-specific work is done in this class that’s not worth describing here. The basic idea is

CHAPTER 13 ■ CUSTOM TRANSPORTS324

7974CH13.qxd 4/2/07 9:43 PM Page 324

Page 350: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

that a worker thread is created to read the message off of the socket and pass it, along with theassociated metadata, to the transport manager. Listing 13-19 shows the simplified version ofthat worker thread.

Listing 13-19. WorkerThread Handling the Inbound Message

static class WorkerThread implements Runnable {private Socket clientSocket;private SocketTransportEndPoint endPoint;private int timeout;private boolean enableNagleAlgorithm;

public WorkerThread(Socket clientSocket, SocketTransportEndPoint endPoint,int timeout, boolean enableNagleAlgorithm) {

this.clientSocket = clientSocket;this.endPoint = endPoint;this.timeout = timeout;this.enableNagleAlgorithm = enableNagleAlgorithm;

}

public void run() {try {/** set the socket properties. */clientSocket.setSoTimeout(timeout);clientSocket.setTcpNoDelay(!enableNagleAlgorithm);String msgId = new Random().nextInt() + "." + System.nanoTime();InputStream inputStream = clientSocket.getInputStream();

/** read the incoming message */String msg = ;/* Message from input stream. Details omitted */

/** if it's one way close the connection. */if (endPoint.getMessagePattern().equals(TransportEndPoint.MessagePatternEnum.ONE_WAY))

InputStream.close();

SocketInboundMessageContext inboundMessageContext =new SocketInboundMessageContext(endPoint, clientSocket, msgId, msg);

/** send inbound context to SDK, which sends it to the pipeline */TransportManagerHelper.getTransportManager().receiveMessage(inboundMessageContext, null);

} catch (Exception e) {/* log an error */

}}

CHAPTER 13 ■ CUSTOM TRANSPORTS 325

7974CH13.qxd 4/2/07 9:43 PM Page 325

Page 351: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Outbound Message ProcessingOutbound messages are sent on behalf of a business service. Outbound processing is theinverse of inbound processing. In this case, the ALSB runtime delivers the outgoing requestmessage to the transport provider, and the transport provider delivers the response message(if any) back. We’ll walk you through this mechanism.

The transport manager delivers the outgoing request message by calling thesendMessageAsync() method on the provider’s implementation of the TransportProvider inter-face. We discussed the TransportProvider interface in earlier sections; this is the one methodthat’s used for runtime message processing (the other methods are used at design and deploytime). This method gets invoked with three parameters, as follows:

• TransportSender: A container for the request message, metadata, endpoint info, andcredentials

• TransportSendListener: The callback object for sending the response message

• TransportOptions: A value class containing properties affecting how the messageshould be sent

The TransportSender parameter can be one of two subclasses. However, for customtransports, it’s always a ServiceTransportSender, so we won’t bother describing aNoServiceTransportSender (it’s used internally within ALSB). The transport provider can pullall the data for the outgoing request message from the ServiceTransportSender. This consistsof the message payload, the RequestMetaData associated with the message, the endpoint desti-nation for this message, and the security credentials for the message.

The TransportOptions parameter can affect how the provider should send out the mes-sage. The following properties can affect how the message is sent:

• Mode: One way or request/response

• OperationName: For SOAP services, the name of the invoked operation

• QoS: The quality of service, which potentially affects whether the operation istransactional

• URI: A URI that can override the one configured in the endpoint (the pipeline canchange this value)

■Tip The outbound transport can ignore several properties in TransportOptions, such as RetryCount,RetryInterval (retries are all handled by the transport manager), and ThrowOnError (outbound canalways raise an exception; this only applies to inbound).

So, now the transport provider, having all the data associated with the message and theoptions for sending the message, can send out the request message in the manner specific tothe transport. That is pretty straightforward.

What gets a little trickier is providing the response message back to the ALSB runtime (orat least signaling the ALSB runtime to do response processing when there’s no response). The

CHAPTER 13 ■ CUSTOM TRANSPORTS326

7974CH13.qxd 4/2/07 9:43 PM Page 326

Page 352: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

rule for outbound transport providers is that the response must come back on a differentthread than the request. In other words, the call to TransportProvider.sendMessageAsync()should return prior to giving the response, and the response should be given on a differentthread by calling one of the two methods in TransportSendListener.

Creating a new thread for the response might be an inherent part of the transport; that is,the response might just naturally come in on a different thread (for example, a JMS listener).However, if the message is one way or the response doesn’t naturally come in on a differentthread, the transport has to allocate a new thread for the response processing. You can allocatethis thread using TransportManagerHelper.schedule(), which can optionally be given a dis-patch policy if the business service endpoint configuration contains one.

The outbound transport provider also must implement a class supporting theOutboundTransportMessageContext. The only requirement for this class is that it be a containerfor response message payload and associated metadata (including the URI and message ID).These can be null in the case of a one-way message. The OutboundTransportMessageContext ispassed back to the TransportSendListener method.

Note that the TransportSendListener has two callback methods: onReceiveResponse() andonError(). As their names suggest, the outbound transport should call onReceiveResponse() inthe successful case, and onError() in the error case.

So, in total, there are three ways for the outbound transport to initiate response process-ing in the ALSB runtime: calling onReceiveResponse() in a new thread, calling onError() in anew thread, or raising a transportException in the original thread (from TransportProvider.sendMessageAsync()). The outbound transport should raise the transportException if it hadproblems in even sending out the request message (for example, due to having a connectionproblem).

It is useful to understand how the transport manager handles retries. When retries areconfigured (either because multiple Endpoint URIs are configured for the business service, orthe retry count is greater than zero), they might or might not be used depending on the qualityof service, on the transactional status, and on how the error was reported. The transactionstatus could be Tx Null (there is no transaction), Tx Okay (there is a good transaction), or TxRollback (there is a transaction, but it is marked as rollback only due to the error). Table 13-2describes the combinations.

CHAPTER 13 ■ CUSTOM TRANSPORTS 327

Table 13-2. Retry Semantics

QoS Error Mechanism Tx Null Tx Okay Tx Rollback

BEST_EFFORT transportException Retry outbound N.A. N.A.in request Transaction suspended Transaction pipeline. by the transport manager. suspended by the

transport manager.

BEST_EFFORT onError() Retry outbound N.A. N.A.in response Transaction suspended Transaction pipeline. by the transport manager. suspended by the

transport manager.

EXACTLY_ONCE transportException Retry outbound Retry outbound in No retries.in request request pipeline. Error handler in pipeline. request pipeline.

EXACTLY_ONCE onError() No retries. No retries. No retries.Error handler in Error handler in Error handler in response pipeline. response pipeline. response pipeline.

Request rolled back.

7974CH13.qxd 4/2/07 9:43 PM Page 327

Page 353: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

So, to summarize, the sequence of events for an outbound transport is as follows:

1. TransportProvider.sendMessageAsync() gets called by the transport manager.

2. The transport provider extracts the endpoint data, message payload, metadata, andpossibly the credentials from the ServiceTransportSender.

3. The provider examines the options in TransportOptions.

4. The provider sends out the request message using a transport-specific mechanism.

5. If necessary, the provider creates a new thread using TransportManagerHelper.schedule().

6. The provider gets the response message using a transport-specific mechanism.

7. The provider creates an OutboundTransportMessageContext object to contain theresponse message and associated metadata.

8. The provider invokes one of the callback methods in TransportSendListener on thenew thread.

One special case needs mentioning. That is the case of a proxy service invoking anotherproxy service. We call this a colocated call. In this case, the transport provider’ssendMessageAsync() method gets invoked, but the supplied endpoint is an inboundendpoint, rather than an outbound endpoint; that is, a proxy service rather than a businessservice. A transport provider would typically bypass the whole transport mechanism anddirectly invoke the targeted proxy. The Transport SDK makes this easy, by supplying aCoLocatedMessageContext class. The transport provider can extend this class by simply addingthe methods for creating the request metadata. The sample socket transport demonstratesthis simple concept in its implementation of SocketCoLocatedMessageContext, which can becopied verbatim.

Now, let’s take a look at the socket transport’s outbound implementation. The sockettransport puts the majority of the implementation of the outbound transport into its classimplementing the OutboundTransportMessageContext: the SocketOutboundMessageContextclass. Hence, the sendMessageAsync() implementation merely creates and invokes this object.The code for this method is given in Listing 13-20.

Listing 13-20. SocketTransportProvider sendMessageAsync

public void sendMessageAsync(TransportSender sender,TransportSendListener listener,TransportOptions options)

throws TransportException {/** whether the the other endpoint is inbound */boolean isInbound = false;

if (sender instanceof ServiceTransportSender) {isInbound = ((ServiceTransportSender) sender).getEndPoint().isInbound();

}

CHAPTER 13 ■ CUSTOM TRANSPORTS328

7974CH13.qxd 4/2/07 9:43 PM Page 328

Page 354: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

if (!isInbound) {// other endpoint is an out-boundSocketOutboundMessageContext socketOutboundMessageContext =new SocketOutboundMessageContext(sender, options);

socketOutboundMessageContext.send(listener);} else { // other endpoint is an inbound.SocketCoLocatedMessageContext socketCoLocatedMessageContext =new SocketCoLocatedMessageContext((ServiceTransportSender) sender,options);

socketCoLocatedMessageContext.send(listener);}

}

So, the heart of the outbound socket transport implementation is in theSocketOutboundMessageContext class, whose implementation is given in Listing 13-21. It’srather long, but the points to consider are how the send() method makes a connection andsends the outbound request, using the Source for the outbound request; how it uses theTransportManagerHelper.schedule() method to create a new thread to get the response; andhow it invokes the TransportSendListener methods to return that response. Some details havebeen omitted for brevity.

Listing 13-21. SocketOutboundMessageContext

public class SocketOutboundMessageContextimplements OutboundTransportMessageContext {private TransportSender sender;private TransportOptions options;private String msgId;private EndPointConfiguration config;private InputStream responseIS;private SocketResponseMetaData responseMetadata;

/*** Initializes the field variables.*/public SocketOutboundMessageContext(TransportSender sender,

TransportOptions options)throws TransportException {this.msgId = new Random().nextInt() + "." + System.nanoTime();this.sender = sender;this.options = options;if (sender instanceof ServiceTransportSender) {this.config =((ServiceTransportSender) sender).getEndPoint().getConfiguration();

} else {throw new TransportException(SocketTransportMessagesLogger.illegalTransportSender());

}}

CHAPTER 13 ■ CUSTOM TRANSPORTS 329

7974CH13.qxd 4/2/07 9:43 PM Page 329

Page 355: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

public ResponseMetaData getResponseMetaData() throws TransportException {return responseMetadata;

}

public Source getResponsePayload() throws TransportException {return responseIS == null ? null : new StreamSource(responseIS);

}

public URI getURI() {return options.getURI();

}

public String getMessageId() {return msgId;

}

/*** Sends the message to the external service, schedules a Runnable which sets* the response metadata, and reads the response from the external service.*/public void send(final TransportSendListener listener)throws TransportException {String address = options.getURI().toString();try {String host = null;int port = 0;try {URI uri = new URI(address);host = uri.getHost();port = uri.getPort();

} catch (URISyntaxException e) {new TransportException(e.getMessage(), e);

}SocketTransportMessagesLogger.ipAddress(host, port);final Socket clientSocket = new Socket(host, port);

SocketEndpointConfiguration socketEndpointConfiguration =SocketTransportUtil.getConfig(config);

SocketOutboundPropertiesType outboundProperties =socketEndpointConfiguration.getOutboundProperties();

clientSocket.setTcpNoDelay(!outboundProperties.getEnableNagleAlgorithm());clientSocket.setSoTimeout(outboundProperties.getTimeout());

String reqEnc = socketEndpointConfiguration.getRequestEncoding();if (reqEnc == null) reqEnc = "utf-8";

CHAPTER 13 ■ CUSTOM TRANSPORTS330

7974CH13.qxd 4/2/07 9:43 PM Page 330

Page 356: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

// Send the message to the external service.OutputStream outputStream = clientSocket.getOutputStream();TransformOptions transformOptions = new TransformOptions();transformOptions.setCharacterEncoding(reqEnc);sender.getPayload().writeTo(outputStream, transformOptions);outputStream.write(SocketTransportUtil.D_CRLF.getBytes(reqEnc));outputStream.flush();SocketTransportMessagesLogger.flushed();

PipelineAcknowledgementTask task =new PipelineAcknowledgementTask(listener, clientSocket,socketEndpointConfiguration);

TransportManagerHelper.schedule(task, socketEndpointConfiguration.getDispatchPolicy());

} catch (Exception e) {/* log the error */;throw new TransportException(e.getMessage(), e);

}}

/*** This task does the acknowledgement work of the outbound to the pipeline.*/class PipelineAcknowledgementTask implements Runnable {private TransportSendListener listener;private Socket clientSocket;private SocketEndpointConfiguration epc;

public PipelineAcknowledgementTask(TransportSendListener listener,Socket clientSocket,SocketEndpointConfiguration epc) {

this.listener = listener;this.clientSocket = clientSocket;this.epc = epc;

}

/*** It reads the response sent from the external service, sets the headers,* and invokes the pipeline.*/public void run() {try {// if the end-point is one-way, don't read the response.if (!epc.getRequestResponse()) {SocketTransportMessagesLogger.oneWayEndpoint();listener.onReceiveResponse(SocketOutboundMessageContext.this);return;

CHAPTER 13 ■ CUSTOM TRANSPORTS 331

7974CH13.qxd 4/2/07 9:43 PM Page 331

Page 357: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

}String resEnc = getResponseEncoding();responseMetadata = new SocketResponseMetaData(resEnc);InetAddress inetAddress = clientSocket.getInetAddress();responseMetadata.setEndPointHost(inetAddress.getHostName());responseMetadata.setEndPointIP(inetAddress.getHostAddress());

// Read the response from the external service./* CODE FOR READING THE MESSAGE HAS BEEN OMITTED */String msg = omittedStuff();responseIS = new ByteArrayInputStream(msg.getBytes(resEnc));listener.onReceiveResponse(SocketOutboundMessageContext.this);

} catch (Exception e) {listener.onError(SocketOutboundMessageContext.this,TransportManager.TRANSPORT_ERROR_GENERIC,, e.getLocalizedMessage());

} finally {try {clientSocket.close();

} catch (IOException e) {}

}}

}}

Registering the Transport ProviderThere’s one last implementation job to take care of. You need to get the custom transportimplementation hooked into the ALSB runtime. Earlier, we discussed packaging all the piecesof the custom transport into a deployable EAR file. You can deploy the custom transport intoan ALSB domain using any of the standard mechanisms of WLS:

• Using the WebLogic Administration Console

• Using WLS programmatic APIs

• Adding an entry to the ALSB domain config.xml file (see Listing 13-22).

Listing 13-22. Deployment Entry to Add to config.xml to Deploy a Custom Transport

<app-deployment><name>My Transport Provider</name><target>AdminServer, myCluster</target><module-type>ear</module-type><source-path>$USER_INSTALL_DIR$/servicebus/lib/mytransport.ear</source-path><deployment-order>1234</deployment-order>

</app-deployment>

CHAPTER 13 ■ CUSTOM TRANSPORTS332

7974CH13.qxd 4/2/07 9:43 PM Page 332

Page 358: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

However, you still need to register the custom transport with the transport manager. Youdo this using the method TransportManager.registerProvider(). You can call this method fromthe postStart() method of the ApplicationLifecycleListener for the EAR file. The sockettransport provides a simple example, as shown in Listing 13-23, that can be copied verbatim.

Listing 13-23. Socket Transport ApplicationListener

public class ApplicationListener extends ApplicationLifecycleListener {/*** After an application is initialized, this method is invoked by the Deploy* framework. Socket transport is registered with TransportManager.*/public void postStart(ApplicationLifecycleEvent evt)throws ApplicationException {try {TransportManager man = TransportManagerHelper.getTransportManager();SocketTransportProvider instance = SocketTransportProvider.getInstance();man.registerProvider(instance, null);

} catch (Exception e) {/* Log an error */

}}

}

■Caution You cannot unregister the transport provider or undeploy the custom transport EAR file. As youdo development, and you want to update the custom transport, you can update the EAR file and then restartthe server.

SummaryAs you’ve seen in this chapter, there are quite a few things to consider when implementing acustom transport. We discussed why you’d build a custom transport and when it is appropri-ate to do so (and when you can avoid doing so). We introduced the sample socket transport,which is an excellent starting point for creating a custom transport, and we used it to provideexamples of how to implement the various aspects of a custom transport. We gave an overviewof the Transport SDK interfaces, describing which interfaces you’ll invoke and which inter-faces you’ll implement to build a custom transport. Finally, we covered each of the stepsinvolved in implementing a custom transport, including creating the various XML andschema files, implementing the user interface and deployment classes, executing the actualmessage processing, and registering the provider. Once you’ve implemented all those steps, acustom transport will be a first-class transport in ALSB, indistinguishable from the out-of-the-box transports.

Using this information, you can build new custom transports tailored for your company’sbusiness, allowing even greater integration of your company’s services via ALSB.

CHAPTER 13 ■ CUSTOM TRANSPORTS 333

7974CH13.qxd 4/2/07 9:43 PM Page 333

Page 359: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

7974CH13.qxd 4/2/07 9:43 PM Page 334

Page 360: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

How Do I . . . ?

Although this book covers the details of using ALSB, we’ve found over the years that there area set of commonly asked questions by our customers about specific uses of ALSB. They rangefrom the simple to the unusual. In this chapter, we’ll provide answers to the most commonlyasked questions. Furthermore, we’ve picked out a few questions that might be uncommon,but that demonstrate just how flexible ALSB is in practice. The questions are broken downinto different categories, to help you find the answers. Some questions cross these categoricalboundaries. Where appropriate, we’ve given credit to the folks who answered the originalquestions.

Be sure to visit http://www.dev2dev.com. That site contains thousands of tips, codesamples, and technical articles on ALSB and other BEA products. It’s an invaluable resourcefor developers and architects.

SecurityHere are some questions and issues that commonly come up in the field.

Is ALSB certified by a security assessment?Yes, ALSB is Federal Information Process Standard 140-2 certified, which certifies the useraccess, cryptographic, and SSL capabilities of the product. Additionally, the product is inprocess for Common Criteria Certification at Evaluation Assurance Level (EAL) 4, the highestsecurity level attainable for an ESB product.

Thanks to Suman Cuddapah for this tip!

I have to build a test client to invoke a web service on ALSBusing HTTPS with basic authentication enabled. Are any sampleclients out there that are already doing something similar?Listing 14-1 provides a sample HTTPS client. Thanks to Nadim Samad for this solution.

335

C H A P T E R 1 4

7974CH14.qxd 3/29/07 2:46 PM Page 335

Page 361: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Listing 14-1. A Sample HTTPS Client

import tests.util.HTTPHelper;import tests.util.Credentials;import tests.util.SecurityTestUtils;import java.security.KeyStore;import java.security.PrivateKey;import java.security.KeyStoreException;import java.security.NoSuchAlgorithmException;import java.security.cert.Certificate;import java.security.cert.X509Certificate;import java.security.cert.CertificateException;import java.util.List;import java.util.ArrayList;import java.io.IOException;import java.io.FileInputStream;import weblogic.xml.crypto.wss.provider.CredentialProvider;import weblogic.wsee.security.bst.ClientBSTCredentialProvider;

public class InboundHTTPSClient {public static void main (String args[]) {

System.setProperty("weblogic.security.TrustKeyStore", "CustomTrust");System.setProperty("weblogic.security.CustomTrustKeyStoreFileName",

"C:\\bea\\user_projects\\domains\\tranSecTestDomain\\TestTrust.jks");System.setProperty("weblogic.security.SSL.ignoreHostnameVerify","true");System.setProperty("keystores.path",

"C:\\bea90_1027\\user_projects\\domains\\tranSecTestDomain");InboundHTTPSClient ihttpsc = new InboundHTTPSClient();try {

ihttpsc.testInboundHttpsWithClientCert();} catch (Exception e) {

e.printStackTrace();}

}

public void testInboundHttpsWithClientCert() throws Exception {String iserviceName = "transport/inbound/https/clientCert/proxy";

HTTPHelper httpHelper = new HTTPHelper();String requestMsg = "<bea>BEA Bobble Dreams</bea>";Credentials cred = loadCredentials();System.out.println("cred: " + cred.toString());// send 5 requestsHTTPHelper.HttpResponse httpResponse;

for (int i = 0; i < 1; i++) {httpResponse = httpHelper.doRequest("POST", requestMsg,

"https://fifa:7002/" + iserviceName, cred, 100, null);

CHAPTER 14 ■ HOW DO I . . . ?336

7974CH14.qxd 3/29/07 2:46 PM Page 336

Page 362: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

System.out.println(httpResponse.getBody());}

}

private Credentials loadCredentials() throws Exception {String ks_path = "C:\\bea90_1027\\user_projects\\ ➥

domains\\tranSecTestDomain\\client_keystore.jks";KeyStore ks = getClientKeyStore(ks_path, "password");Certificate clientCert = ks.getCertificate("transport-test-key");PrivateKey clientKey = (PrivateKey) ks.getKey("transport-test-key",➥

"password".toCharArray());Credentials cred = new Credentials();cred.useClientKeySSL(true);cred.setClientKey(clientKey);cred.setClientCerts(new Certificate[] {clientCert});return cred;

}

public static KeyStore getClientKeyStore(String ks_path, String ks_password)throws KeyStoreException, NoSuchAlgorithmException, IOException,

CertificateException {FileInputStream fis = new java.io.FileInputStream(ks_path);KeyStore ks = KeyStore.getInstance("JKS");ks.load(fis, ks_password.toCharArray());fis.close();return ks;

}}

AdministrationThis section covers topics administrators of an ALSB system commonly need.

How do I import a WSDL (or other resource type) from a URL?Perform the following steps to import a WSDL from a URL:

1. Use the ALSB console to create a change in the Change Center.

2. Navigate to the project into which you want to import the WSDL. Open the folder inthe project where you want to store the WSDL.

3. In the Create Resource field, select the Resources from URL item under the Bulk head-ing. This displays the Load Resources page.

4. In the URL/Path field, enter the URL of the WSDL.

CHAPTER 14 ■ HOW DO I . . . ? 337

7974CH14.qxd 3/29/07 2:46 PM Page 337

Page 363: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

5. In the Resource Name field, provide a name for the WSDL you’re going to import.

6. In the Resource Type field, select the resource type you’re importing.

7. Click the Next button, review, and accept the import information.

8. Be sure to activate your changes in the Change Center.

How do I run multiple instances of the PointBase database on asingle machine?When developing on a single machine you sometimes need to run multiple domains. ThePointBase database that ships with WebLogic and ALSB defaults to use port 9093. There will bea conflict if you are running multiple domains on the same computer. You can easily changethe PointBase port used by a server by editing the setDomainEnv.cmd (or .sh) script in the bin/directory of your domain. Look for the line

set POINTBASE_PORT=9093

and change the port number to an unused port on your computer. Remember that you’ll alsoneed to change any Java Database Connectivity (JDBC) drivers in your domain to point to thenew port number!

Thanks to James Bayer for this tip.

How do I set up an ALSB server as a Microsoft Windows service?A script was provided with ALSB version 2.1 to do this. That script is no longer included withALSB 2.5. The following listings show how to install ALSB 2.5 (and WLS 9) as a Windows serv-ice. You can download the code for all these scripts from the Source Code/Download area ofthe Apress web site at http://www.apress.com.

Listing 14-2 is the low-level script file that does the heavy lifting in this process. You don’tneed to call this script directly. Instead, you would call the install AdminSrvrSvc.cmd (see List-ing 14-3) to install the admin server as a Microsoft Windows service, or you would call installMgdSrvr1Svc.cmd to install managed server 1 as a Windows service. Notice that the managedserver scripts apply to individual managed servers, requiring you to modify Listing 14-4 foreach managed server in your ALSB cluster.

Thanks to John Graves for this solution!

Listing 14-2. The installSvc.cmd File

@rem *************************************************************************@rem This script is used to install WebLogic Server as a Windows Service.@rem@rem To create your own start script for your domain, simply set the@rem SERVER_NAME variable to your server name then call this script from your@rem domain directory.@rem@rem This script sets the following variables before installing@rem WebLogic Server as a Windows Service:

CHAPTER 14 ■ HOW DO I . . . ?338

7974CH14.qxd 3/29/07 2:46 PM Page 338

Page 364: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

@rem@rem WL_HOME - The root directory of your WebLogic installation@rem JAVA_HOME - Location of the version of Java used to start WebLogic@rem Server. This variable must point to the root directory of a@rem JDK installation and will be set for you by the installer.@rem See the WebLogic platform support page@rem (http://e-docs.bea.com/wls/platforms/index.html) for an ➥

up-to-date list of@rem supported JVMs on Windows NT.@rem PATH - Adds the JDK and WebLogic directories to the system path.@rem CLASSPATH - Adds the JDK and WebLogic jars to the classpath.@rem@rem Other variables that installSvc takes are:@rem@rem WLS_USER - admin username for server startup@rem WLS_PW - cleartext password for server startup@rem ADMIN_URL - if this variable is set, the server started will be a@rem managed server, and will look to the url specified (i.e.@rem http://localhost:7001) as the admin server.@rem PRODUCTION_MODE - set to true for production mode servers, false for@rem development mode@rem JAVA_OPTIONS - Java command-line options for running the server. (These@rem will be tagged on to the end of the JAVA_VM and MEM_ARGS)@rem JAVA_VM - The java arg specifying the VM to run. (i.e. -server,@rem -client, etc.)@rem MEM_ARGS - The variable to override the standard memory arguments@rem passed to java@rem@rem jDriver for Oracle users: This script assumes that native libraries@rem required for jDriver for Oracle have been installed in the proper@rem location and that your system PATH variable has been set appropriately.@rem@rem For additional information, refer to the WebLogic Server Administration@rem Guide (http://e-docs.bea.com/wls/docs90/adminguide/startstop.html).@rem *************************************************************************

@echo offSETLOCAL

rem set DOMAIN_NAME=ALSBrem set SERVER_NAME=ESB_PROD2rem set WLS_USER=weblogicrem set WLS_PW=weblogic

set WL_HOME=C:\bea\weblogic91call "%WL_HOME%\common\bin\commEnv.cmd"

CHAPTER 14 ■ HOW DO I . . . ? 339

7974CH14.qxd 3/29/07 2:46 PM Page 339

Page 365: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

@rem Check that the WebLogic classes are where we expect them to be:checkWLSif exist "%WL_HOME%\server\lib\weblogic.jar" goto checkJavaecho The WebLogic Server wasn't found in directory %WL_HOME%\server.echo Please edit your script so that the WL_HOME variable pointsecho to the WebLogic installation directory.goto finish

@rem Check that java is where we expect it to be:checkJavaif exist "%JAVA_HOME%\bin\java.exe" goto runWebLogicecho The JDK wasn't found in directory %JAVA_HOME%.echo Please edit your script so that the JAVA_HOME variableecho points to the location of your JDK.goto finish

:runWebLogic

if not "%JAVA_VM%" == "" goto noResetJavaVMif "%JAVA_VENDOR%" == "BEA" set JAVA_VM=-jrocketif "%JAVA_VENDOR%" == "HP" set JAVA_VM=-serverif "%JAVA_VENDOR%" == "Sun" set JAVA_VM=-server

:noResetJavaVMif not "%MEM_ARGS%" == "" goto noResetMemArgsset MEM_ARGS=-Xms32m -Xmx200m

:noResetMemArgs

@echo on

set CLASSPATH=%WEBLOGIC_CLASSPATH%;%CLASSPATH%

@echo ***************************************************@echo * To start WebLogic Server, use the password *@echo * assigned to the system user. The system *@echo * username and password must also be used to *@echo * access the WebLogic Server console from a web *@echo * browser. *@echo ***************************************************

rem *** Set Command Line for service to execute within created JVM

@echo off

if "%ADMIN_URL%" == "" goto runAdmin@echo onset CMDLINE="%JAVA_VM% %MEM_ARGS% %JAVA_OPTIONS% -classpath \"%CLASSPATH%\"

CHAPTER 14 ■ HOW DO I . . . ?340

7974CH14.qxd 3/29/07 2:46 PM Page 340

Page 366: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

-Dweblogic.Name=%SERVER_NAME% -Dweblogic.management.username=%WLS_USER% ➥

-Dweblogic.management.server=\"%ADMIN_URL%\" ➥

-Dweblogic.ProductionModeEnabled=%PRODUCTION_MODE% ➥

-Djava.security.policy=\"%WL_HOME%\server\lib\weblogic.policy\" ➥

weblogic.Server"goto finish

:runAdmin@echo onset CMDLINE="%JAVA_VM% %MEM_ARGS% %JAVA_OPTIONS% -classpath \"%CLASSPATH%\" -Dweblogic.Name=%SERVER_NAME% -Dweblogic.management.username=%WLS_USER% ➥

-Dweblogic.ProductionModeEnabled=%PRODUCTION_MODE% ➥

-Djava.security.policy=\"%WL_HOME%\server\lib\weblogic.policy\" ➥

weblogic.Server"

:finishrem *** Set up extrapath for win32 and win64 platform separatelyif not "%WL_USE_64BITDLL%" == "true" set EXTRAPATH=%WL_HOME%\server\native\win\32;➥

%WL_HOME%\server\bin;%JAVA_HOME%\jre\bin;%JAVA_HOME%\bin;➥

%WL_HOME%\server\native\win\32\oci920_8

if "%WL_USE_64BITDLL%" == "true" set ➥

EXTRAPATH=%WL_HOME%\server\native\win\64\;%WL_HOME%\server\bin;➥

%JAVA_HOME%\jre\bin;%JAVA_HOME%\bin;%WL_HOME%\server\native\win\64\oci920_8

rem *** Install the service"%WL_HOME%\server\bin\beasvc" -install -svcname:"BEA Products ➥

%DOMAIN_NAME%_%SERVER_NAME%" -javahome:"%JAVA_HOME%" ➥

-execdir:"%USERDOMAIN_HOME%" -extrapath:"%EXTRAPATH%" ➥

-password:"%WLS_PW%" -cmdline:%CMDLINE%

ENDLOCAL

Listing 14-3. Installing the ALSB Admin Server As a Windows Service

echo offSETLOCALset CLASSPATH=C:\bea\WEBLOG~1\servicebus\lib\sb-public.jar; ➥

C:\bea\WEBLOG~1\servicebus\lib\sb-internal.jar; ➥

C:\bea\WEBLOG~1\integration\common\lib\wlicommon.jar; ➥

C:\bea\WEBLOG~1\integration\common\lib\qs_p13n_system.jar; ➥

C:\bea\WEBLOG~1\servicebus\lib\xbus-core.jar; ➥

C:\bea\WEBLOG~1\server\lib\wlxbean.jar; ➥

C:\bea\WEBLOG~1\server\lib\xquery.jar; ➥

C:\bea\WEBLOG~1\server\lib\binxml.jar; ➥

C:\bea\WEBLOG~1\common\lib\log4j.jar; ➥

C:\bea\WEBLOG~1\servicebus\lib\uddi_library.jar; ➥

CHAPTER 14 ■ HOW DO I . . . ? 341

7974CH14.qxd 3/29/07 2:46 PM Page 341

Page 367: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

C:\bea\WEBLOG~1\servicebus\lib\uddi_client_v3.jar; ➥

C:\bea\patch_weblogic910\profiles\default\sys_manifest_classpath\➥

weblogic_patch.jar;C:\bea\JDK150~1\lib\tools.jar; ➥

C:\bea\WEBLOG~1\server\lib\weblogic_sp.jar; ➥

C:\bea\WEBLOG~1\server\lib\weblogic.jar; ➥

C:\bea\WEBLOG~1\server\lib\webservices.jar; ➥

C:\bea\WEBLOG~1\servicebus\lib\version.jar; ➥

C:\bea\WEBLOG~1\common\eval\pointbase\lib\pbclient51.jar; ➥

C:\bea\WEBLOG~1\server\lib\xqrl.jar; ➥

C:\bea\WEBLOG~1\integration\lib\util.jar;

set JAVA_HOME=C:\bea\jdk150_04set JAVA_VENDOR=Sunset DOMAIN_NAME=WM_ESB_DOMAIN_1set USERDOMAIN_HOME=D:\APPS\WM_ESB_DOMAIN_1set SERVER_NAME=WM_ESB_SRVR_ADMINset PRODUCTION_MODE=trueJAVA_OPTIONS=-Dweblogic.Stdout="D:\APPS\WM_ESB_DOMAIN_1\stdout.txt"➥

-Dweblogic.Stderr="D:\APPS\WM_ESB_DOMAIN_1\stderr.txt"set MEM_ARGS=-Xms40m -Xmx250m

call "C:\BEA\weblogic91\server\bin\installSvc.cmd"

ENDLOCAL

Listing 14-4. Installing a Managed Server As a Windows Service

echo offSETLOCALset CLASSPATH=C:\bea\WEBLOG~1\servicebus\lib\sb-public.jar; ➥

C:\bea\WEBLOG~1\servicebus\lib\sbinternal.jar; ➥

C:\bea\WEBLOG~1\integration\common\lib\wlicommon.jar;➥

C:\bea\WEBLOG~1\integration\common\lib\qs_p13n_system.jar; ➥

C:\bea\WEBLOG~1\servicebus\lib\xbus-core.jar; ➥

C:\bea\WEBLOG~1\server\lib\wlxbean.jar; ➥

C:\bea\WEBLOG~1\server\lib\xquery.jar;C:\bea\WEBLOG~1\server\lib\binxml.jar; ➥

C:\bea\WEBLOG~1\common\lib\log4j.jar; ➥

C:\bea\WEBLOG~1\servicebus\lib\uddi_library.jar; ➥

C:\bea\WEBLOG~1\servicebus\lib\uddi_client_v3.jar; ➥

C:\bea\patch_weblogic910\profiles\default\sys_manifest_classpath\➥

weblogic_patch.jar;C:\bea\JDK150~1\lib\tools.jar; ➥

C:\bea\WEBLOG~1\server\lib\weblogic_sp.jar; ➥

C:\bea\WEBLOG~1\server\lib\weblogic.jar; ➥

C:\bea\WEBLOG~1\server\lib\webservices.jar; ➥

C:\bea\WEBLOG~1\servicebus\lib\version.jar; ➥

C:\bea\WEBLOG~1\common\eval\pointbase\lib\pbclient51.jar; ➥

C:\bea\WEBLOG~1\server\lib\xqrl.jar; ➥

CHAPTER 14 ■ HOW DO I . . . ?342

7974CH14.qxd 3/29/07 2:46 PM Page 342

Page 368: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

C:\bea\WEBLOG~1\integration\lib\util.jar;set JAVA_HOME=C:\bea\jdk150_04set JAVA_VENDOR=SunREM Modify the DOMAIN_NAME, USERDOMAIN and SERVER_NAME as appropriateset DOMAIN_NAME=WM_ESB_DOMAIN_1set USERDOMAIN_HOME=D:\APPS\WM_ESB_DOMAIN_1set SERVER_NAME=WM_ESB_SRVR_1set PRODUCTION_MODE=trueJAVA_OPTIONS=-Dweblogic.Stdout="D:\APPS\WM_ESB_DOMAIN_1\stdout.txt"➥

-Dweblogic.Stderr="D:\APPS\WM_ESB_DOMAIN_1\stderr.txt"set ADMIN_URL=http://SYDBIZS02:7001set MEM_ARGS=-Xms40m -Xmx250mcall "C:\BEA\weblogic91\server\bin\installSvc.cmd"

ENDLOCAL

What happens to “in-flight” processes when I update aproxy service?The fact that ALSB is configuration driven instead of code driven leads to some interestingquestions. If you change a proxy service while it is running (that is, in the middle of receivingrequests and sending responses), what happens?

The answer is simple. If a proxy service is in the middle of a request or response whenit’s updated, it’s cached as a copy of the proxy service until the transaction is complete. Thenewer version is immediately activated and starts to handle all new requests. The cached copyhandles all current work until all current (also known as “in flight”) work is completed. Onceall the current work is complete, the cached version of the proxy service is removed frommemory.

Messaging and ProtocolsThis section is devoted to messaging topics and issues with transport protocols.

How do I retrieve a SOAP Header using XQuery?If you want to add an appinfo field to your SOAP header so you can use the data for reporting,use the following code:

<SOAP-ENV:Header xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:xsd="http://www.w3.org/2001/XMLSchema"xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><MyHeader xmlns:myns="http://foo.com/soaplatform/">

<myns:appinfo>TESTAPPLICATION</myns:appinfo></MyHeader></SOAP-ENV:Header>

CHAPTER 14 ■ HOW DO I . . . ? 343

7974CH14.qxd 3/29/07 2:46 PM Page 343

Page 369: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

How can I get the TESTAPPLICATION field out? I can onlymanage to get the entire SOAP header, which isn’t very useful.Perform the following steps:

1. Add a user-defined namespace for myns with the value of http://foo.com/soaplatform/.

2. Use the XQuery $header/MyHeader/myns:appinfo/text() to retrieve the text value of theheader.

Thanks to Deb Ayers for this answer.

How do I get the HTTP URL parameters?Use the $inbound/ctx:transport/ctx:request/http:query-string element to get all the argu-ments in the URL. For an example of how to do this, see the next question.

How do I accept HTTP/POST information from a web form?You can create a proxy service in ALSB that can be invoked by an HTML form. This mightsound odd, but it is a good example of using ALSB to integrate non-web service systems. List-ing 14-5 shows the HTML code that will HTTP/POST for form data to a proxy service in ALSB.

Listing 14-5. The HTML Form That Will POST Data to an ALSB Proxy Service

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>XML HTTP POST Example</title></head><body><h1>Use this form to post a message to the XMLWSDL service</h1><form name="GetGreeting" action="http://localhost:7001/HTTPPOSTProxy/"><textArea rows="20" cols="60" name="payload">Foo</textArea><button name="Submit" type="submit">Submit</button></form></body></html>

Create a proxy service called HTTPPOSTProxy based on the Any XML Service service type.Set the Endpoint URI to /HTTPPOSTProxy (so that it matches the action URI of the HTML form).In the message flow of the proxy service, add a Pipeline Pair with a single stage that containsthree actions.

The first action is an Assign action that assigns the value of the following expression to thevariable queryString:

$inbound/ctx:transport/ctx:request/http:query-string

CHAPTER 14 ■ HOW DO I . . . ?344

7974CH14.qxd 3/29/07 2:46 PM Page 344

Page 370: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

The second action is also an Assign action that assigns the value of the following expres-sion to the variable payload:

fn:substring-before(fn:substring-after($queryString, 'payload='), '&Submit')

As you can see, this expression simply extracts a substring from the queryString variablebetween the payload= and &Submit markers in the queryString variable.

The third and final action is a Log action so that you can see the value of the payload fieldthat is HTTP/POSTed to the proxy service. The Log action should have the following expression:

concat('queryString = ', $queryString, ' payload = [', $payload, ']')

This will clearly show you the entire contents of the queryString that was posted to theproxy service, and the fully parsed value of the payload field.

How do I calculate the content length of an inboundHTTP request?You can’t get this information directly, or even exactly. John Shafer of BEA offers the followingsolution:

There’s no easy way to calculate content length on your own, especially if attachments areinvolved. Note that $attachments uses an XML representation, whereas a transport-level mes-sage containing attachments will be represented as a multipart MIME package, so the lengthswill differ by quite a bit. Also, if you have any binary attachments (that is, non-XML or non-text), that content isn’t even part of $attachments, so any length calculation based simply onthe serialization of $attachments will be way off.

Even if attachments aren’t involved and you update your formula using the fn-bea:serialize() method, your following formula doesn’t take into account the <SOAP:Envelopexmlns:SOAP="..."> wrapper. Also, the formula will only calculate character length, and notbyte length. For example, although UTF-8 uses a single byte for encoding US-ASCII charac-ters, characters in other languages might require two or even three bytes when encoded inUTF-8 for transport. Of course, other nonuniversal encodings such as ISO-8859-1 are singlebyte by definition.

In any event, if you’re only looking for a rough estimate, aren’t using attachments, and arewilling to deal with a character-based length rather than byte based, then the followingtweaked formula might be a reasonable estimate:

fn:string-length(fn-bea:serialize($header)) +fn:string-length(fn-bea:serialize($body)) + 90

The 90 is an estimate of the character length of the start and end <SOAP:Envelope>elements, including the SOAP namespace declaration.

Of course, none of this applies if you aren’t dealing with SOAP.

How can I get the WSDL/Policy/MFL/Schema/Proxy via HTTP?You can retrieve many of the resource types directly from the ALSB server by using HTTPinstead of having to use the service bus console. The general pattern for the URL is as follows:

http://[hostname]:[port]/sbresource?[Resource Type]/[Project Name]/[Resource Name]

CHAPTER 14 ■ HOW DO I . . . ? 345

7974CH14.qxd 3/29/07 2:46 PM Page 345

Page 371: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

The [Resource Type] section of the URL may be any one of the following values:

• MFL

• POLICY

• PROXY

• SCHEMA

• WSDL

The URL must be UTF-8 encoded. If the resource is stored in a directory, then the direc-tory structure needs to be declared explicitly in the URL also.

For example, in the Hello World project in Chapter 4 of this book, we defined a WSDLresource in the WSDL folder of the project. The name of that WSDL resource is set toHelloWorld. To retrieve this WSDL, you would use the following URL:

http://localhost:7001/sbresource?WSDL/Hello+World/WSDL/HelloWorld

If you wanted to see the WSDL for the proxy service, you would use the following URL:

http://localhost:7001/sbresource?PROXY/Hello+World/ProxyServices/HelloWorld

Many thanks to Gregory Haardt for this tip!

How do I update the EJB client JAR resource of an EJBTransportbusiness service?When you update the client JAR of an EJB business service, you need to update ALSB with thenew client JAR. The process is simple, though it might not be obvious. To update the businessservice in ALSB, you simply click the link of the EJB client JAR resource.

How do I map a URL context root to a service?Sometimes you might want a proxy service to be identified by part of a URL, and have theremainder of the URL act as a command. This allows you to create simple web-based serviceswithout the need for WSDLs, XSDs, and the like. This is similar in nature to taking theRepresentational State Transfer (REST) approach to web services. In this example, you’llcreate a proxy service that looks for commands encoded into the URL and prints thosecommands to STDOUT. The format for the URL to invoke this service is as follows:

http://[host]:[port]/[Service context]/[Commands]

You’ll create a proxy service and bind it to the /CommandHandler context root. When theproxy is invoked, it will examine the remainder of the URL to discover the command and asso-ciated parameters. Figure 14-1 shows the start of a RESTful proxy service creation. Be sure toselect Messaging Service as the service type.

CHAPTER 14 ■ HOW DO I . . . ?346

7974CH14.qxd 3/29/07 2:46 PM Page 346

Page 372: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 14-1. Defining a RESTful proxy service

The key to creating a service such as this is to set the request message type to None(you’re only parsing the URL) and the return type to XML, as shown in Figure 14-2. By specify-ing XML as the return type, but not specifying a specific XML schema element, your service isfree to return any XML value.

Figure 14-2. Set the request and response types

Click the Next button and set the Endpoint URI to /CommandHandler for this sample.Your proxy service definition should match what’s described in Figure 14-3.

CHAPTER 14 ■ HOW DO I . . . ? 347

7974CH14.qxd 3/29/07 2:46 PM Page 347

Page 373: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 14-3. The proxy service definition

You’ll implement the proxy service’s message flow using a simple Pipeline Pair with asingle stage in the request and the response pipelines. The request stage simply gathers thecommand and params values from the relative URI, found in the $inbound/ctx:transport/ctx:request variable. The actions for the request processing are shown in Figure 14-4.

Figure 14-4. The action in the request stage

The first Assign action assigns the results of the following expression to the commandvariable:

fn:tokenize(data($inbound/ctx:transport/ctx:request/http:relative-URI), '/')[1]

CHAPTER 14 ■ HOW DO I . . . ?348

7974CH14.qxd 3/29/07 2:46 PM Page 348

Page 374: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

The second Assign action assigns the results of the following expression to the paramsvariable:

fn:tokenize(data($inbound/ctx:transport/ctx:request/http:relative-URI), '/')[2]

The response stage is equally simple. In this stage, you’ll construct an arbitrary XMLresponse that contains the command and the parameters that were extracted from the origi-nal URL. The step is to assign your XML structure, including the command and params variablesto the xmlResponse variable. You use the concat function to assemble a string version of yourXML, then you use the fn-bea:inlinedXML function to turn the string into an XML variable:

fn-bea:inlinedXML(concat('<Response><Command>', $command, '</Command><Params>',$params, '</Params></Response>'))

The next two actions are straightforward. You replace the node contents of the body vari-able with the $xmlResponse. Then you log the $xmlResponse so you can see what’s going onwhen you test this service. Figure 14-5 shows the details of this stage.

Figure 14-5. The create response stage

One thing to note: because this service has a request type of None, you cannot use theALSB test console to test this service. Instead, you’ll use a web browser where you can specifyany arbitrary URL. You can send commands with parameters in the URL; for example:

http://localhost:7001/CommandHandler/Foo/Bar=4;happy=1

The CommandHandler will identify Foo as the command and Bar=4;happy=1 as the parame-ters. You can find the code for this in the REST project if you download the ALSB sbconfig.jarfile from the Source Code/Download area of the Apress web site at http://www.apress.com.

Many thanks to Stuart Charlton for this tip!

CHAPTER 14 ■ HOW DO I . . . ? 349

7974CH14.qxd 3/29/07 2:46 PM Page 349

Page 375: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

XML, XQuery, and XSLTMany questions about using ALSB successfully are really questions about XML, XQuery, andXSLT technologies. ALSB is built on these technologies. Here are some of the most commonquestions we’ve encountered in the field.

How can I convert XML into a string using XQuery?ALSB provides an extension to XQuery to perform this function. fn-bea:serialize($arg-xml)converts an XML variable into an XML string.

How can I convert a String value into an XML variable usingXQuery?ALSB provides an extension to XQuery that performs this function. fn-bea:inlinedXML($arg-string) converts a string argument into an XML variable that you can then use inconjunction with other XQuery and XPath statements.

How do I get the namespace of an XML node?XQuery provides a function for this explicitly:

fn:namespace-uri($node-with-namespace-containing-version)

Closely related to this question is the following question.

How do I get the version number from the namespace?It’s common practice to include some version information embedded into the namespace. Forexample, the following namespace uses the release date of February 15, 2004 to indicate itsversion number:

http://www.openuri.org/acmeworld/schemas/2004/02/15/Financial

The XQuery statement to extract the version number simply splits the namespace stringusing two nested substring operations, as follows:

fn:substring-before(fn:substring-after(xs:string(fn:namespace-uri(➥

$node-with-namespace-containing-version)),"/schemas/"),"/Financial")

This returns the string 2004/02/15. Thanks to Mike Wooten for this tip.

How do I test for a null?Handling null values in XQuery is simple, but not intuitive to those who are new to the lan-guage. Beginners often try to use expressions such as Eq NULL or is null in their tests. Thecorrect way to test for null values in XML tags is to use one of the following expressions:

not exists(column)

CHAPTER 14 ■ HOW DO I . . . ?350

7974CH14.qxd 3/29/07 2:46 PM Page 350

Page 376: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

or

empty( column )

Thanks to Michael Reiche for this tip.

MiscellaneousHere are some general tips that just don’t fit into any other category,

How do I get rid of the WorkManager warnings whenstarting ALSB?When starting the service bus, you might see a series of errors on the console, such as thefollowing:

<Jan 5, 2007 11:20:51 AM PST> <Warning> <WorkManager> <BEA-002919> <Unable tofind a WorkManager with name weblogic.wsee.mdb.DispatchPolicy. Dispatch policyweblogic.wsee.mdb.DispatchPolicy will map to the default WorkManager forthe application bea_wls9_async_response>

If you’re like us, you hate to see extraneous errors. This error is caused by the fact thata default installation of ALSB doesn’t have any WorkManagers defined. The solution issimple: define a WorkManager using the WebLogic console. Log into the WebLogic console(not the service bus console), create a WorkManager with the name weblogic.wsee.mdb.DispatchPolicy, and these warning messages will cease. Be sure to target the WorkManagerto the machine(s) in the domain.

How do I read from a database?In ALSB version 2.5 and later, it’s possible to have ALSB read information from a database. It’seasy to overlook this feature, because it doesn’t use an action. It uses an XQuery function toaccess the database.

The following XQuery line demonstrates how to use ALSB to read from a data sourcedefined in the host WLS. The 'jdbc.mySQLDS' argument is the JNDI name of the data sourcedefined in WLS. The 'total' argument is the name of the tag used to encapsulate the result ofthe query. The last argument is the SQL statement that will execute.

fn-bea:execute-sql('jdbc.mySQLDS', 'total', 'select count(*) from company')

Executing the preceding SQL statement returns the following value (assuming you have atable named company in your MySQL database):

<total><COUNT_x0028__x00210__x0029_>122</COUNT_x0028__x00210__x0029_></total>

CHAPTER 14 ■ HOW DO I . . . ? 351

7974CH14.qxd 3/29/07 2:46 PM Page 351

Page 377: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

The <COUNT_x0028__x00210__x0029_> tag is the translation of the count(*) portion of theSQL expression, using XML safe encoding. This is fairly ugly, but using a modified SQL state-ment can fix it. For example, change the expression to the following:

fn-bea:execute-sql('jdbc.mySQLDS', 'total', 'select count(*) as count from company')

This yields the following result:

<total><COUNT_>122</COUNT></total>

This looks much cleaner.

How do I get a list of disabled services?When you’re dealing with numerous web services in your environment, it becomes impracti-cal to examine individual services manually to see if they are enabled or not. Fortunately, theSmart Search capability in the ALSB console makes finding disabled services a breeze (seeFigure 14-6).

Figure 14-6. The Smart Search feature

You can access the Smart Search feature from the Operations section of the Dashboard.Thanks to Gaston Ansaldo for this tip.

What is an EJB Converter JAR?The EJB transport (introduced in ALSB 2.5) supports the notion of converter classes. Theseclasses help map parameter and return value types to Java classes that can be mapped toXML. Prior to ALSB 2.6, these converter classes had to be packaged in the EJB client JAR, thesame JAR containing the client stubs.

We received feedback from users that they didn’t like having to package the converterclasses in with their EJB client JAR files. The EJB client JARs are typically produced by EJBtools. People don’t like having to unjar this JAR, add the converter classes, and rejar them.

CHAPTER 14 ■ HOW DO I . . . ?352

7974CH14.qxd 3/29/07 2:46 PM Page 352

Page 378: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

That’s cumbersome. By having a separate EJB converter JAR entry, they can package theirconverter classes separately. In addition, the EJB converter JAR can be used on several EJBbusiness services. So, this is a usability improvement.

SummaryWe hope that this chapter will save you a lot of time and trouble in your career using ALSB.When you come across a question in the field, look here first. With luck, you’ll find youranswers so quickly that your question will never exist long enough to become a problem.Obviously, we can’t answer every ALSB question in a single chapter, but these questions repre-sent the most common questions we encounter, especially with people who are new to ALSB.If you cannot find an answer to your question here, search the web, especially BEA’s Dev 2 Devwebsite at http://dev2dev.bea.com, for a more exhaustive list of questions and the most up-to-date answers.

CHAPTER 14 ■ HOW DO I . . . ? 353

7974CH14.qxd 3/29/07 2:46 PM Page 353

Page 379: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

7974CH14.qxd 3/29/07 2:46 PM Page 354

Page 380: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

AquaLogic Service Bus Actions

Actions are the real workhorses of ALSB. Actions contain the bulk of the logic and function-ality of any proxy service. ALSB 2.6 supports 22 different action types. Actions are divided intofour major categories: communication, flow control, message processing, and reporting.There is also a fifth category of actions that we call miscellaneous actions, for lack of a betterterm. These are actions that don’t show up on the primary action pop-up menus because oftheir specialized nature.

An action is similar in nature to a statement in a procedural programming language. Bycombining actions, you can customize the functionality of your proxy services. The importantdifference between actions in ALSB and statements in a procedural language is that actionsdon’t need to be compiled before they can take effect. You configure the actions by providingparameters and scripts.

Communication ActionsCommunication actions are focused on sending messages to other web services. Those otherweb services may be business services, or other proxy services within the service bus. Thiscollection of actions is shown in Figure 1.

Figure 1. The pop-up menu path to access the communication actions

355

A P P E N D I X

7974App.qxd 4/4/07 5:17 PM Page 355

Page 381: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Dynamic PublishYou use the Dynamic Publish (shown in Figure 2) action when you need to determine which ofseveral services to invoke at runtime. Like the Publish action, the Dynamic Publish action is anasynchronous invocation of a web service. You need to have several components in place tomake dynamic routing work. First, you need an XQuery resource that provides the list of pos-sible endpoints. Listing 1 provides a sample lookup table (in XML format). Note that the<service> tag needs to contain the fully qualified service name. A fully qualified service nametakes the following form, where the [Folder Name] is optional and may be repeated as manytimes as is necessary:

<Project Name>/[Folder Name...]/<Service Name>

Figure 2. The Dynamic Publish action

In Listing 1 we see that the project name is Dynamic Route and Publish and all three ofthe services are contained in a folder named Shared.

Listing 1. A Sample Lookup Table for Dynamically Publishing to a Service

<lookup-table><!-- Map supplier id to a service and optionally to an operation--><supplier id='ABC'>

<service>Dynamic Route and Publish/Shared/static response service 1</service></supplier><supplier id='XYZ'>

<service>Dynamic Route and Publish/Shared/static response service 2</service></supplier><supplier id='123'>

<service>Dynamic Route and Publish/Shared/soap echo service</service><operation>echo</operation>

</supplier></lookup-table>

You then use the lookup table XQuery resource in an XQuery expression defined in theDynamic Publish action, as shown in Listing 2.

APPENDIX ■ AQUALOGIC SERVICE BUS ACTIONS356

7974App.qxd 4/4/07 5:17 PM Page 356

Page 382: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Listing 2. A Sample Expression to Use in the Dynamic Publish Action

let $supplier := $lookupTable/supplier[@id=data($header/supplierID)]return<ctx:route>

<ctx:service isProxy='false'>{ data($supplier/service) }</ctx:service>{

if ($supplier/operation)then <ctx:operation>{data($supplier/operation)}</ctx:operation>else ()

}</ctx:route>

The message is in the predefined variables $body, $headers, and $attachments. Internally,a copy of these variables is created so modifications to these variables in request actions don’taffect actions accessing these variables after the dynamic publish is done.

PublishThe Publish action allows you to send a one-way message to a web service. There’s no abilityto receive a response from the web service.

As shown in Figure 3, the Publish action asynchronously invokes a service. Because of itsasynchronous nature, you can modify the request before it is sent to the service, but youcan’t modify the response. The message is in the predefined variables $body, $headers, and$attachments. Internally, a copy of these variables is created so modifications to these vari-ables in request actions don’t affect actions accessing these variables after the publish is done.

Figure 3. The Publish action

Publish TableThe Publish Table action is a set of routes, wrapped in a switch-style condition table. Figure 4shows the graphic interface of the Publish Table action. Set the <Expression> link to an XQueryvariable and then define one or more conditional tests, and the services that those tests repre-sent. The Request Actions field allows you to define the message format before it’s sent to theservice, thereby allowing you to perform any necessary message transforms for the specificoperation.

APPENDIX ■ AQUALOGIC SERVICE BUS ACTIONS 357

7974App.qxd 4/4/07 5:17 PM Page 357

Page 383: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 4. The Publish Table action

Like a switch statement in Java or C, you can also define a default case at the end of theswitch structure.

The message is in the predefined variables $body, $headers, and $attachments. Internally,a copy of these variables is created for each publish destination, so modifications to thesevariables in request actions don’t affect actions accessing these variables after the publish tothis destination is done.

Routing OptionsThe Routing Options action is not meant to be used in a standalone fashion. It needs to existwithin the Request Actions section of a Dynamic Publish action, Publish action, Route action,or a Dynamic Route action. In that context, you can use it to override many of the attributes ofa service invocation. As you can see from Figure 5, you can set the Quality of Service to eitherBest Effort or Exactly Once. You can set the Mode to either Request or Request-Response. Theother attributes should be self-explanatory.

Figure 5. The Routing Options action

APPENDIX ■ AQUALOGIC SERVICE BUS ACTIONS358

7974App.qxd 4/4/07 5:17 PM Page 358

Page 384: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Service CalloutYou use the Service Callout action to make a synchronous (blocking) call to another service.One-way calls are not supported. A typical use of this action is to invoke a service to make arouting decision or to retrieve data for message enrichment. As you can see in Figure 6, itsinterface is simple.

Figure 6. The Service Callout action

Transport HeadersYou use this action to define header values for both outbound requests and inboundresponses. You can select the header from a combo box of header types for HTTP/HTTPS,JMS, File, Email, and FTP transport types. You can also create custom headers. You can specifymultiple headers, as needed. For outbound requests, the Transport Headers action is typicallyused in the request actions of a dynamic or static Route or Publish action. Figure 7 shows thegraphic interface of this action.

Figure 7. The Transport Headers action

Flow Control ActionsFlow control actions are dedicated to managing conditional and looping logic within a proxyservice. Figure 8 shows the pop-up menus for accessing this family of actions.

APPENDIX ■ AQUALOGIC SERVICE BUS ACTIONS 359

7974App.qxd 4/4/07 5:17 PM Page 359

Page 385: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 8. The Flow Control actions pop-up menu

For Each For Each is a standard looping construct, found in most programming languages. It allows youto iterate over a group of values and execute a block of actions repeatedly. Unlike the “for”loops in traditional programming languages, this action also lets you see the total count of thenumber of objects in your loop, as shown in the graphic interface of this action in Figure 9.

Figure 9. The For Each action

For example, say you had a variable called $books that had the following structure:

<books><book>

<title>Moby-Dick</title><author>Herman Melville</author>

</book><book>

<title>A Christmas Carol</title><author>Charles Dickens</author>

</book></books>

Suppose you wanted to get the names of all the authors in the $books context variable andperform some actions on them. You would configure a For Each action as shown in Figure 10.

APPENDIX ■ AQUALOGIC SERVICE BUS ACTIONS360

7974App.qxd 4/4/07 5:17 PM Page 360

Page 386: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 10. Iterating over the collection of authors

This configuration would get the name of each <author> node and put it in the $authorvariable. The value of the index variable curAuthor would vary between 0 and 1 as the loop wasexecuted. The $numAuthors variable would have a fixed value of 2 while this loop ran.

■Note Currently, actions may only be nested to a depth of 4. After that, your actions won’t be visible in theALSB console.

If . . . ThenThe ability to make decisions is fundamental to any computer language. Simply click the<Condition> link to define your test condition. You can enter your condition directly as text,or you can use the Expression Builder to build more complex conditions if you prefer. Thegraphic interface of this action is shown in Figure 11.

Figure 11. The If . . . Then action

Raise ErrorThe Raise Error action allows you to raise an exception using a specific error code and adescription. The error code takes the form of a string argument. The variable $fault is set andthe next exception handler in scope is invoked. Its graphic interface is shown in Figure 12.

APPENDIX ■ AQUALOGIC SERVICE BUS ACTIONS 361

7974App.qxd 4/4/07 5:17 PM Page 361

Page 387: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 12. The Raise Error action

ReplyYou use the Reply action (see Figure 13) to send a success or failure reply back to the caller. ForSOAP messages, a failure response is returned as an HTTP 500 error. The Reply action messageis sent immediately and terminates all further processing of the action chain. Although thisaction has its place in the normal handling of messages, it’s also useful in debugging situationswhen you need to figure out how your message processing got to a specific point in the mes-sage flow.

Figure 13. The Reply action

The message that’s returned is constructed in the usual manner: by specifying the$header, $body, and $attachments message variables. If you don’t specify these variablesspecifically, then the current contents of those variables are returned.

ResumeThe Resume action is used exclusively in error pipelines. As you can see in Figure 14, its inter-face is the ultimate in simplicity. You use this action to resume the normal flow of actionprocessing from within an error handler. You might have to define compensating actionsand/or modify context variables, depending on the needs of your message handler. The pro-cessing will continue after the node or stage in which the error occurred.

Figure 14. The Resume action

APPENDIX ■ AQUALOGIC SERVICE BUS ACTIONS362

7974App.qxd 4/4/07 5:17 PM Page 362

Page 388: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

SkipThis is another simple action, as you can see in Figure 15. You can use the Skip action inrequest, response, or fault pipelines. It’s used to skip to the next stage in normal processing.

Figure 15. The Skip action

Message Processing ActionsThis family of actions is focused on manipulating data and data structures. You can accessthese actions using the pop-up menu system, as shown in Figure 16.

Figure 16. The Message Processing family of actions

AssignThe Assign action allows you to assign a value to a context variable. If the context variabledoesn’t exist, it will be created for you automatically. The value takes the form of an XQueryexpression.

Click the <Expression> link (shown in Figure 17) to define an XQuery expression (or selectan XQuery resource or an XSLT resource), then enter the variable name where you wish tostore the results of the expression.

Figure 17. The Assign action

APPENDIX ■ AQUALOGIC SERVICE BUS ACTIONS 363

7974App.qxd 4/4/07 5:17 PM Page 363

Page 389: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Delete You use the Delete action to delete a context variable, or all the nodes of an XPath expression.The graphic interface of this action is shown in Figure 18.

Figure 18. The Delete action

Using Delete on a context variable removes the variable from the memory space, whichmight be handy if you’re using a variable to store a large amount of scratch memory. Deletingan XPath expression from a context variable is often useful when transforming from one XMLSchema to another. Use this for removing optional data, especially if that optional data takesup a lot of memory in process or must be communicated over the wire.

InsertYou use the Insert action to insert the result of an XQuery expression into a document. Thisis frequently used in transforming between XML Schemas. As shown in Figure 19, you canselect where to insert the information by using the combo box. Use it to insert the result of anXQuery expression (or you can use an XQuery or XSLT resource) into a variable relative to thegiven XPath expression.

Figure 19. The Insert action

Java CalloutA Java Callout action (see Figure 20) is the mechanism that allows your message flows tomake calls to Java code defined as a resource within ALSB. You must compile the Java codeinto a JAR resource. Furthermore, you must define the Java method that is called as bothpublic and static. It’s possible to use a Java method to instantiate new Java objects, but thisis highly discouraged.

APPENDIX ■ AQUALOGIC SERVICE BUS ACTIONS364

7974App.qxd 4/4/07 5:17 PM Page 364

Page 390: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 20. The Java Callout action

MFL TransformThis action allows you to apply an MFL transformation on a given expression. You can choosefrom either an MFL resource within ALSB or an MFL resource identified dynamically at run-time by an XQuery expression. Its graphic interface is shown in Figure 21.

Figure 21. The MFL Transform action

RenameThe Rename action (see Figure 22) allows you to rename a node or set of nodes in an XPathexpression without modifying the contents or structure of the nodes. This is handy whenyou’re transforming between two schemas that have the same structure, but that use differentnames. The supplied radio buttons also allow you to rename the local name of the node, thenamespace of the node, or both.

Figure 22. The Rename action

APPENDIX ■ AQUALOGIC SERVICE BUS ACTIONS 365

7974App.qxd 4/4/07 5:17 PM Page 365

Page 391: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

ReplaceThe Replace action allows you to replace a node or the contents of a node defined by an XPathstatement with the value(s) defined in an expression. Like the Rename action, this action iscommonly used during message transformations. The graphic interface for this action isshown in Figure 23.

Figure 23. The Replace action

ValidateYou use the Validate action (see Figure 24) to validate elements selected by an XPath expres-sion against an XML Schema element or type, or a WSDL element or type. This is an amazinglyuseful action, especially if you are transforming complex XML documents. Use this action toensure that your XML documents comply with the expected format when you’re developingyour transformations. This action will save you countless hours of frustration.

Figure 24. The Validate action

Reporting ActionsThis family of actions is used to generate report information and alerts, and to write eventsout to the logging mechanism built into ALSB. Figure 25 shows the pop-up menu to selectthese actions.

APPENDIX ■ AQUALOGIC SERVICE BUS ACTIONS366

7974App.qxd 4/4/07 5:17 PM Page 366

Page 392: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Figure 25. The Reporting family of actions

AlertThe Alert action allows you to generate an alert within a message flow. As shown in Figure 26,you select the alert destination and severity level, and provide an expression that contains thepertinent information for the alert. The summary field can contain only text and is optional.

Figure 26. The Alert action

LogThe Log action allows you to send output to the ALSB system log. The graphic interface for thisaction is shown in Figure 27. The <Expression> is sent to the log, along with the straight textannotation. The annotation is optional and can contain text only (no expressions). XQuery isusually used to form the expression, though XSLT can be used in its place if needed.

Figure 27. The Log action

APPENDIX ■ AQUALOGIC SERVICE BUS ACTIONS 367

7974App.qxd 4/4/07 5:17 PM Page 367

Page 393: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Often you’ll find yourself using this action like a System.out.println() function in Java. Itcan be very useful for debugging. We find ourselves using the XQuery concat() function mostoften. For example:

concat('Submit order proxy: firstName = ', $firstName, ', ➥

lastName = ', $lastName)

The severity level is important. Although everything is written to the log, if you would liketo see your debugging text in the WebLogic text console window instead of searching throughthe system log file, be sure to set the severity to Error.

The annotation field can contain only text, no expressions.

ReportThe Report action (see Figure 28) allows for message reporting of a proxy service. To see thisaction in use, refer to Chapter 8.

Figure 28. The Report action

APPENDIX ■ AQUALOGIC SERVICE BUS ACTIONS368

7974App.qxd 4/4/07 5:17 PM Page 368

Page 394: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Special Characters$attachments structure, 170$attachments variable, 345, 357, 362$author variable, 361$body context variable, 319$body message variable, 362$body variable, 60, 108, 113, 127, 131, 143,

162, 357$body/text( ) expression, 166$books variable, 360$fault variable, 361$header context variable, 319$header message variable, 362$header variable, 60$headers variable, 357$inbound structure, 155$inbound variable, 300$inbound/ctx:transport/ctx:request/

http:query-string element, 344$numAuthors variable, 361$outbound variable, 300$xmlResponse variable, 349*.* default value, 138| (pipe character), 275<%BEA_HOME%>weblogic92\common\bin

directory, 259/ (forward slash character), 276

AAbstract Syntax Notation number One

(ASN.1), 283Access Control configuration, 257Access Control Lists (ACLs), 196, 257accounting, 211ACLs (Access Control Lists), 196, 257action attribute, @WebMethod annotation,

28actions, 55activationComplete( ) method, 310, 313Add a Key pop-up menu, 188Address data types, 70<Address> element, 71, 91ad-hoc security, 197administration, 337–343

effect on “in-flight” processes whenupdating proxy services, 343

importing WSDL from URL, 337–338running multiple instances of PointBase

database on single machine, 338setting up ALSB server as Microsoft

Windows service, 338–343AdminServer, 133

AdminSrvrSvc.cmd, 338aggregation interval, 179Alert action, 367Alert Destination, 177Alert Rules, 177, 182Alert Severity field, 180Alert Summary portlet, 173alerts, 177all target, 35, 185<all> tag, 75ALSB (AquaLogic Service Bus), 6

actions, 355–368communication actions, 355–359flow control actions, 359–363message processing actions, 363–366overview, 355reporting actions, 366–368

certification by security assessment, 335clusters

controlling managed servers, 273creating clusters, 270–271deploying to clusters, 274location transparency, 274–278Node Manager, 271–273overview, 267, 269

creating HelloWorld project in, 35–37creating project, 176–177overview, 7–9reading from databases, 351–352security, 198–203

digital signatures and encryption, 201identity propagation in ALSB, 200inbound security in ALSB, 198–199overview, 198SSL authentication, 200–201

setting up server as Microsoft Windowsservice, 338–343

WorkManager warnings, eliminatingwhen starting, 351

alsb_book domain, 259–261, 267–268alsb_cluster domain, 271, 275–276alsb_clusterbin directory, 272ALSB_Prod domain, 259–260alsb_prod server, 262, 267alsbConnectionFactory connection factory,

133alsbJMSResources module, 133alsbJMSResources Name field, 133<alsb:name> tags, 48alsb:return node, 62And conjunction, 184Ant, 11, 15–16, 26ant export command, 262

Index

369

797-4INDEX 4/3/07 6:26 PM Page 369

Page 395: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Ant/Runtime category, Preferences dialog, 15Any XML Service service type, 344APIs (Application Programming Interfaces),

207appinfo field, 343Application Programming Interfaces (APIs),

207Application Service Layer (ASL), 207, 214, 222Application Service Providers (ASPs), 251application services, 212AquaLogic Server, configuring WebLogic

Workshop for, 16, 18AquaLogic Service Bus. See ALSBAquaLogic Service Bus folder, 148AR/AP domain service, 215architectural transformation, 219, 224Archive Directory, 138, 153ASL (Application Service Layer), 207, 214, 222ASN.1 (Abstract Syntax Notation number

One), 283ASPs (Application Service Providers), 251asset service, 211Assign action, 57, 64, 107, 128, 131, 143, 344,

348, 363Assign statement, 170assign variables node, 105assign variables stage, 105asynchronous invocation

asynchronous business service, 120–124overview, 119setting up WebLogic server, 120

Asynchronous Request-Response services,119

AttachmentsSource Source interface, 318attributeFormDefault attribute, 92–93authentication, 198, 335–337authenticity, 196<author> node, 361authorization policies, 198Auth.xml policy, 201automation, 260–267Available Operations combo box, 47

BBar=4;happy=1 parameters, 350<bar> element, 188bare encoding, 67Basic Authentication, 9BASIC-to-C language converters, 67BEA_HOMEweblogic92common\

nodemanager directory, 273behaviors array, 174BEST_EFFORT rollback, 327bin directory, 260–261, 271, 273, 338binary messaging types

creating JMS assets, 132–135creating message-driven bean, 135–137creating proxy service, 137–139defining business service, 137end-to-end testing, 139–140

overview, 132routing proxy to business service, 139

BinaryBusinessService, 139<binary-content/> XML snippet, 319binaryFileTopic, JMS Destination Properties

page, 135BinaryService proxy, 137Bind Variables section, 156Binding section, <definitions> root element,

68<binding> tag, 77, 87BindingTypeInfo, 305BinXML representation, 319BinXMLSource class, 319Body element, 128, SOAPbody field, attachment metadata, 170body node, 156body section, 125body variable, 57, 105bottom node, 44bottom-up approach, 213branch node, 111–112Branch node, Message Flow, 51BrowserTextBox object, 304Build Project, 157BUILD SUCCESSFUL message, 287build task, 170build.properties file, 289build.xml Ant script, 185build.xml file, 260, 274built-in configuration-driven options, 198Business Service, 42business service, creating, 40–41Business Service folder, 169business services, 8Business Services folder, 159ByteArraySource Source interface, 318BytesMessage input message, 136

Ccached proxy service, 343calculateTax operation, 162, 166CarInfo data type, 243–244Cayenne, 206CCM (CustomerContactManager)

application, 2Certificate Lookup and Validation (CLV), 201certification

certificate-based authentication, 204by security assessment, 335

Change Center, 36, 154, 167, 170, 253–254Change Center, ALSB console, 9changeOil operation, 243–244CheckBox object, 304CheckingAccount service, 238<choice> tag, 75client code, 169Client Jar field, 160clientgen utility, 32ClientGenTask, Ant, 16

■INDEX370

797-4INDEX 4/3/07 6:26 PM Page 370

Page 396: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

close( ) method, 321–322cluster license, 173clusters, ALSB

controlling managed servers, 273creating, 270–271deploying, 274location transparency, 274–278Node Manager, 271–273overview, 267–269

CLV (Certificate Lookup and Validation), 201CN (common name) value, 200coding, 7, 9Collection argument, 127colocated call, 328CoLocatedMessageContext class, 328com.bea.wli.config.env package, 266com.bea.wli.sb.util.EnvValueTypes class, 266command value, 348command variable, 348/CommandHandler context root, 346Commercial, Off The Shelf (COTS)

application, 80Commercial Service Providers (CSPs), 251Common Criteria Certification, 335common name (CN) value, 200communication actions, 355–359

Dynamic Publish, 356–357overview, 355Publish, 357Publish Table, 357–358Routing Options, 358Service Callout, 359Transport Headers, 359

communication principles and patternscommunication pattern I, 225communication pattern II, 227communication pattern III, 228communication pattern IV, 229communication principle I, 225communication principle II, 225communication principle III, 225overview, 224

Compensating flag attribute, 311Complex Expression section, 183<complexType> type, 77components, 207com.proalsb.business package, 24concat( ) function, 349, 368<Condition> link, 361conditional subtype, of Branch nodes, 54config.cmd file, 259config.sh file, 259configuration, 7Configuration wizard, 14, 259, 270configuring software. See installing and

configuring softwareconflicts

management, 253–254resolution, 254–256

connection factory, 137Connection Factory radio button, 133Content-Description field, attachment

metadata, 170

Content-Disposition field, attachmentmetadata, 170

Content-ID field, attachment metadata, 170Content-Location field, attachment

metadata, 170Content-Transfer-Encoding field, attachment

metadata, 170Content-Type field, attachment metadata,

170Context Root field, 23context variable, 364contextPath attribute, 25, 27<context-root> declaration, 277ContractManagerAppService, 80ContractManagerAppTypes, 81converting XML into string using XQuery, 350Coordinate System, SOA

overview, 205Service Domain Scale, 210–211Software Abstraction Scale, 205–210

coordinates, 205CORBA protocol, 282COTS (Commercial, Off The Shelf)

application, 80count(*) portion, 352<COUNT_x0028__x00210__x0029_> tag, 352coupling

loose, 5–8tight, 3–4

Create button, Change Center, 37create greeting stage, 128create method, 312create operation, 311Create Resource combo box, 37, 103createEndpoint( ) method, 310, 313createRequestMetaData( ) method, 314createResponseMetaData( ) method, 314, 320CRM (Customer Relationship Management),

211CSPs (Commercial Service Providers), 251curAuthor variable, 361custom data types, 74–75custom security, 197custom transports, 281–333

building, 294–333deploying service endpoints using

custom transport, 313implementing transport provider

runtime classes, 313–332implementing transport provider user

interface classes, 301–309overview, 294overview of tasks, 296overview of transport SDK interfaces,

294–296registering the transport provider,

332–333transport provider configuration XML

file, 297–298transport provider schemas, 298–301

components of, 285how fits into ALSB, 283–285overview, 281–282

■INDEX 371

Find it faster at http://superindex.apress.com/

797-4INDEX 4/3/07 6:26 PM Page 371

Page 397: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

reasons for building, 282–283sample socket transport, 285–294

building and installing sampletransport, 286–290

capabilities of socket transport, 286overview, 285using sample socket transport, 290–294

customer class, 74Customer object, 74Customer Relationship Management (CRM),

211customer service, 211<CustomerAddress> root element, 71CustomerContactManager (CCM)

application, 2CustomerEmailFormat node, 154CustomerEmailFormat object, 148CustomerEmailFormat.mfl file, 147, 151CustomerEmailToFTP resource, 156customerftp Service Account, 154CustomerFTPFormat MFL resource, 153CustomerFTPFormat object, 149CustomerFTPFormat tag, 151CustomerFTPFormat.mfl file, 151CustomerService component, 80customizationFile variable, 261Customization.xsd file, 267customize.xml file, 260, 266–267

DData warehouses, 218DEBUG_PORT setting, 260DefaultRequestHeaders class, 315DefaultRequestMetaData class, 315defining services, 213<definitions> element, 68, 72delay( ) operation, 176Delete action, 364dependency trap, 80–83deployment, 258–267

advanced automation technique, 267ALSB clusters, 274deployment automation basics, 260–267overview, 258–260

Deployments link, 193Deprecated service, 249design-time code, 285destinationJNDIName attribute, 135development stage, 248–249D:\filedir directory, 139digital signatures, 201diminishing detail, 207disabled services, finding, 352discovering services, 213DNS (Domain Name Server), 5DNS router, 275Document Wrapped, 160document-centric vs. Remote Procedure Call

(RPC)document-centric style emerges, 84encoded vs. literal, 84overview, 83

Remote Procedure Call (RPC) history andissues, 83–84

wrapping, 85Domain Configuration wizard, 286Domain Name Server (DNS), 5Domain Service Layer (DSL), 214, 222Domain Structure portlet, 273DOMAIN_DIR variable, 286DOMSource Source interface, 318Download Directory, 153DSL (Domain Service Layer), 214, 222Dynamic Publish action, 356–357DynamicTable object, 304

EEAL (Evaluation Assurance Level) 4, 335EAR file, 7, 290, 298early ESBs, 5EchoService project, 274EchoService_Service object, 278Eclipse, 11–12, 15–16Eclipse Package Explorer pane, 157Eclipse workspace, 127Edit a Proxy Service, 42Edit Message Flow button, proxy service, 43“Edit Stage Configuration: Route Node” page,

56Edit Stage Configuration window, 45Edit the Branch Definitions window, 111EJBBusiness bean, 157–159EJBCallout project directory, 157EJBs (Enterprise Java Beans), 282

creating business service, 159–160creating EJBBusiness bean, 157–159creating JNDI provider, 161creating message flow, 162creating proxy service, 161EJB applications, 3overview, 157reasons for using, 163

EJBTransport business services, 346element attribute, 76<element> tag, 72, 74elementFormDefault attribute, 88–93elements, vs. types, 78–80e-mail server, 11Email transport, 281Email/SMTP Servers, 256Enable Monitoring, 179Enable Service, 179Enabled flag attribute, 311encoding character, 290encryption, 201Encrypt.xml policy, 201Endpoint URI, 128, 141EndPointConfiguration attribute, 311EndPointConfiguration class, 296, 307endpointInterface attribute, @WebService

annotation, 26EndPointOperations interface, 295end-to-end security, 202

■INDEX372

797-4INDEX 4/3/07 6:26 PM Page 372

Page 398: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Enter New Project Name field, 37Enterprise Java Beans. See EJBs (Enterprise

Java Beans)Enterprise Service Layer (ESL), 207Enterprise Service Mapping (ESM), 205,

213–214envelope, 125EnvValueQuery( ) command, 266EnvValueQuery class, 266Error Code, 189Error Directory, 138, 153error handler, 52, 362errors, 351ESB_Cluster, 273ESL (Enterprise Service Layer), 207ESM (Enterprise Service Mapping), 205,

213–214Evaluation Assurance Level (EAL) 4, 335EXACTLY_ONCE rollback, 327examine attachment stage, 170Execute button, 58ExpandableTable object, 304ExportImport directory, 262export.properties file, 260–261export.py file, 260, 263, 266export.py script, 266<Expression> element, 188<Expression> link, 154, 357eXtensible Stylesheet Language

Transformation (XSLT), 7external XQuery variable, 63

FFaçade pattern, 102, 206Fault section, 190<fault> element, 77Federal Information Process Standard 140-2,

335File Mask field, 138File Transfer Protocol (FTP), 6, 141File transport protocol, 137FileZilla FTP server, 11, 140Filter link, 189<FindAddress> element, 90FindAddressResponse document, 90FindAndReplaceCustomization( ) method,

266FindCustomer element, 87firstName node, 154fixed credentials, 199flow control actions, 359–363

For Each, 360–361If . . . Then, 361overview, 359Raise Error, 361Reply, 362Resume, 362Skip, 363

fn-bea:inlinedXML function, 349fn-bea:inlinedXML($arg-string) function, 350fn-bea:serialize( ) method, 345

fn-bea:serialize($arg-xml) function, 350fn:codepoints-to-string(10) function, 171Foo service, 241, 350For Each action, 171, 360–361for loop structure, 278Format Builder application, 146forward slash character (/), 276frameworks, 206FTP (File Transfer Protocol), 6, 141ftp command, 143FTP server, 11ftproot directory, 141fulfillment, 117

Ggenerate task, 170get Email Info stage, 154get method, 318get name stage, 128getCreditRating( ) operation, 95getCustomerInfo service, 250getEditPage( ) method, 305, 307getEndpoint( ) method, 320getGenericInfo( ) method, 303getGreeting( ) operation, 22, 25, 45, 60, 128,

240getGreetingResponse operation, 61getGreeting(String firstName, String

lastName) ; String operation, 244getGreeting(String name) operation, 244–246getInputStream( ) method, 317getMessage( ) method,

InboundTransportMessageContext,320

getMessageId( ) method,InboundTransportMessageContext,320

getNewProducts( ) operation, 243getProductCatalog( ) operation, 95getProducts( ) method, 242–243getProducts(TireSize); ProductList operation,

243getProviderSpecificConfiguration( ) method,

307getRequestMetaData( ) method, 320getRequestPayload( ) method, 321getResult( ) method, 4getTireProductList operation, 243getViewPage( ) method, 308global monitoring, 256Global Positioning System (GPS), 205Goodbye World, 55–58, 60–65, 292goodbyeGreeting variable, 57Governance groups, 228GPS (Global Positioning System), 205greeting local variable, 128

Hheader section, 125Hello proxy, 254Hello Secure Proxy, 257

■INDEX 373

Find it faster at http://superindex.apress.com/

797-4INDEX 4/3/07 6:26 PM Page 373

Page 399: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Hello World link, Project Explorer, 37Hello World service, 55

business services and proxy servicescreating business service, 40–41creating proxy service, 41–45overview, 39testing proxy service, 46–48View Configuration Changes page, 45

creating and deploying web service@SoapBinding, 26–27@WebMethod, 28–30@WebService, 26@WLHttpTransport, 27–28overview, 21–26

creating POJO test clientcreating HelloWorld project in ALSB,

35–37creating WSDL, 37–38overview, 31–35

overview, 21Hello2 WSDL, 254HelloWorldClient project, 31HelloWorld.java file, 24HelloWorldService field, 24–25HelloWorldService web service, 260HelloWorldSoapPort, 25, 40Hibernate, 206HR service, 211HTTP

inbound requests, calculating contentlength of, 345

retrievingWSDL/Policy/MFL/Schema/Proxyvia, 345–346

URL parameters, 344HTTP POST protocol, 127HTTP POST/GET protocol, 127HTTP Transport Configuration window, 41HttpClusterServlet class, 275HttpClusterServlet web application, 276HTTP/POST information, accepting from

web forms, 344–345HTTPS, 281, 335, 337Human resources, 211hype cycle, 220

IIBM WebSphere MQ API, 282ID field, 147IDE, 13identity management, 196identity propagation in ALSB, 200If . . . Then action, 361IIOP protocol, 282IMAP Folder, 153IMAP Move Folder, 153import Ant task, 274Import dialog, 18import javax.jws.SOAPBinding, 27Import Projects wizard, 18import statement, 71, 76

importingWSDL from URL, 337–338XML schemas, 76

import.properties file, 260–261import.py file, 260, 267inbound message processing, 320, 325inbound security in ALSB, 198–199InboundTransportMessageContext interface,

295, 314InboundTransportMessageContext object,

320–321“in-flight” processes, effect when updating

proxy services, 343<init-param> tags, 275InnerType complex type, 92input local variable, 131<input> element, 76, 167InputStream getInputStream interface

source, 317Insert action, 364installing and configuring software

configuring Ant in Eclipse, 15–16creating Service Bus domain, 14–15importing sample code, 18overview, 12WebLogic Workshop

configuring, 12configuring for AquaLogic Server, 16–18quick tour of, 13–14

integration, 229integrity, 196interfaces, 4inventory service, 211IP:Port combinations, 275isServiceTypeSupported( ) method, 302IT department, 251IT shops, 1

JJAR files, 9, 14, 159

EJB client, updating resources, 346EJB converter, 352–353

JARs directory, ALSB console, 165Java Callout action, 166, 281, 364Java Database Connectivity (JDBC) drivers,

258, 338Java Development Kit (JDK ), 11Java Mail Server, 11Java Message Service (JMS), 6, 132–135Java methods, 116Java Naming Directory Interface (JNDI), 122,

161, 256Javadoc API documentation, 296JDBC (Java Database Connectivity) drivers,

258, 338'jdbc.mySQLDS' argument, 351JDK (Java Development Kit), 11JMS (Java Message Service), 6, 132–135JMS Destination Properties page, 135JMS Module Resources, 133

■INDEX374

797-4INDEX 4/3/07 6:26 PM Page 374

Page 400: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

JMS Transport Configuration window, 137JNDI (Java Naming Directory Interface), 122,

161, 256JRockit JDK, 11JwscTask, Ant, 16Jython scripting language, 258

Kknowledge dependency, 207Kodo, 206

Llatitude scale, 205Lexus ES 300, 239Libraries tab, Properties dialog, 32line of business (LOB), 246literal encoding, 67load balancing, 6, 8LoadBalancer server, 277LOB (line of business), 246localhost:7101 value, 263, 266location transparency, 6, 8, 274, 278Lock & Edit button, 132, 193Log action, 58, 143, 167, 171, 190, 345,

367–368logical map, 212longitude scale, 205loose coupling, 3, 5–8low-level script file, 338

MMachine Format Language (MFL), 8MailClient.java program, 156makeWLSChangesOnCreate( ) method, 313managed servers, 267, 273Map of Message Flow portion, 111mapped credentials, 199mapping

SOA, 213–219bottom-up approach, 215overview, 213service maps at scale, 218–219service tooling, 219SOA mapping test 1, 216–217SOA mapping test 2, 217–218top-down approach, 213–215

URL context roots to services, 346–349maxOccurs attribute, 75MaxPermSize argument, 271mediation, 6, 8mental model, 239message flow, 44, 170, 193

actions, 55Branch nodes, 54Goodbye World, 55–58, 60–65overview, 51–52, 95Pipeline Pairs, 52–53Route nodes, 55

scenario 1: user requests product catalog,95–109

scenario 2: user orders product, 110–116Message Flow Business service, 108Message Flow Proxy WSDL folder, 104Message Flow web service, 102Message Format Language (MFL), 144, 146message handler, 362message level, authentication, 199message payload representation, 317–319message processing actions, 363–366

Assign, 363Delete, 364Insert, 364Java Callout, 364MFL transform, 365overview, 363Rename, 365Replace, 366Validate, 366

Message Reports link, 189message section, <definitions> root element,

68Message Type project, 141<message> element, 76MessageContextSource Source interface, 318message-count request header, 315message-file-location message, 290MessageFlow project, 96, 268message-level security, 197, 204messaging, advanced topics

asynchronous invocationasynchronous business service, 120–124overview, 119setting up WebLogic server, 120

overview, 117service types and transport protocols

EJB, 157–163messaging types, 131–157overview, 124–125Plain Old Java Objects (POJO), 164–167SOAP with attachments, 167–171SOAP with WSDL, 125–126SOAP without WSDL, 126–127XML with WSDL, 127–130XML without WSDL, 131

synchronous invocation, 117–119messaging and protocols, 343–349

accepting HTTP/POST information fromweb forms, 344–345

calculating content length of inboundHTTP requests, 345

HTTP URL parameters, 344mapping URL context roots to services,

346–349retrieving SOAP Headers using XQuery,

343retrieving TESTAPPLICATION fields, 344retrieving

WSDL/Policy/MFL/Schema/Proxyvia HTTP, 345–346

updating EJB client JAR resources ofEJBTransport business services, 346

■INDEX 375

Find it faster at http://superindex.apress.com/

797-4INDEX 4/3/07 6:26 PM Page 375

Page 401: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

Messaging Service, 137messaging types

binarycreating JMS assets, 132–135creating message-driven bean, 135–137creating proxy service, 137–139defining business service, 137end-to-end testing, 139–140overview, 132routing proxy to business service, 139

overview, 131text, 140–144XML, 144–157

metadata descriptions, 231methodology, 213MFL (Machine Format Language), 8MFL (Message Format Language), 144, 146MFL transform action, 365MFLBusiness service, 156MFLEmail2FTP proxy, 152MFLSource Source interface, 318Microsoft Windows, setting up ALSB server

as service of, 338–343MIME (Multipurpose Internet Mail

Extensions), 125MimeSource Source interface, 318minOccurs attribute, 75Mode property, 326monitoring, 7, 9, 173–187

overview, 173temperamental service, 174–187

coding proxy client, 185–187creating ALSB project, 176–177creating business services, 174–176defining Service Level Agreements

(SLAs), 177–185overview, 174

Monitoring Configuration window, 179, 183Monitoring icon, 178Monitoring portlet, 174mput *.txt command, FTP, 144MSG_GUID field, 192Multipurpose Internet Mail Extensions

(MIME), 125

NNagle’s Algorithm, 286name argument, 22, 56name attribute, 24, 26, 74, 122Name field, 147name property, 24name variable, 54namespace keyword, 70namespaces

retrieving version numbers from, 350WSDL

default namespace, 71–73overview, 70–71target namespace, 73

of XML nodes, retrieving, 350native data types, 74network routers, 7

New flag attribute, create operation, 311New Project wizard, 24New Server dialog, 16NewProduct document type, 242NewProductList document type, 242Node Manager, 271–273nodemanager.domain file, 273nodemanager.properties file, 273nodes, 51NoServiceTransportSender parameter, 326not found error, 87null values, 350–351numAttachments variable, 170

Oobject orientation, 239object-relational mapping tools, 206onError( ) method, 327one-way SSL authentication, 200onMessage method, 136onReceiveResponse( ) method, 327OpA operation performance, 183open namespace, 162open source software, 10<operation> element, 76operational subtype, of Branch nodes, 54operationName attribute, @WebMethod

annotation, 28OperationName property, 326Operations portion, ALSB console, 189Operations settings, 256–257Operations tab, 256Operation.variableCreditCheck.Response

Time checkbox, 182Or conjunction, 184or .sh (setDomainEnv.cmd) script, 338order database, 188Order domain, 215Order management, 211order processing, 117Order web service, 70Ordering Proxy Start node, 105outbound message processing, 326–332Outbound Service section, 190OutboundTransportMessageContext class,

328OutboundTransportMessageContext

interface, 295, 314, 327Outline window, 169<output> element, 76

PP2P (point-to-point) integrations, 2, 220Package Explorer tab, 22Package Explorer window, 18package keyword, 70parameterStyle attribute, @SoapBinding

annotation, 27params value, 348params variable, 349

■INDEX376

797-4INDEX 4/3/07 6:26 PM Page 376

Page 402: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

<part> element, 76, 87Partner relationship management, 211Pass By Reference checkbox, 138passphrase variable, 261pass-through credentials, 199password, 141Password object, 304payload variable, 345pipe character (|), 275Pipeline alert, 188pipeline error handler, 53Pipeline Pairs, 51, 52–53, 105, 111, 127, 142,

166, 344PKI (Public Key Infrastructure)

authentication, 199Plain Old Java Objects. See POJOs (Plain Old

Java Objects)planned service, 248PointBase, 338point-to-point (P2P) integrations, 2, 220POJOs (Plain Old Java Objects), 24, 164–167

test client, creatingcreating HelloWorld project in

AquaLogic Service Bus (ALSB), 35–37creating Web Services Description

Language (WSDL), 37–38overview, 31–35

Polling Interval, 138, 152<port> element, 68, 77–78portName attribute, @WLHttpTransport

annotation, 27<portType> element, 68, 76–77Post Read Action, 138, 153postStart( ) method,

ApplicationLifecycleListener, 333prefix field, 154privacy protection, 196Pro_ALSB domain, 16processOrder service, 95Product definition, 242Product domain, 218product service, 211Project Browser, 30Project Explorer link, navigation bar, 36Project Explorer window, 24Proxy Service, 6, 39, 51, 110, 127, 152, 196

Create Resource combo box, 42creating, 41–45security, 198steps in invoking, 203testing, 46–48

Proxy Service creation wizard, 126proxy service pipeline, 254Proxy Service Provider, 199Proxy Services directory, 165Proxy Services folder, 161, 169proxy services secure, [email protected] e-mail account, 156Public Key Infrastructure (PKI)

authentication, 199public method, 364

Publish action, 357, 359Publish Table action, 357–358

QQoS property, 321, 326quality assurance (QA), 275queryString variable, 344–345

R\r delimiter, 146radio buttons, 166, 365Raise Error action, 361rapidCreditCheck( ) operation, 176Raw sockets, 282RDBMS (Relational Database Management

System) services, 215RDBMS Service Layer (RSL), 215RDBMS-layer service, 218Read Limit, 153README.TXT file, 286Ref attribute, 310refactor application, 222referential integrity checker, 253registering transport provider, 332–333Registration code, 285Relational Database Management System

(RDBMS) services, 215Released stage, 249Remote Procedure Call (RPC). See document-

centric vs. Remote Procedure Call(RPC)

Rename action, 365replace( ) function, XQuery, 57Replace action, 57, 64, 108, 156, 162, 366Replace action icon, 58replace function, 57, 60, 63replace statement, 60Reply action, 362Report action, 188, 190, 193, 368Report Index expression, 189report provider, 188Report Proxy proxy service, 188reporting, 188–193

actions, 366–368Alert, 367Log, 367–368overview, 366Report, 368

overview, 188–189purging report information, 191–192reporting providers, 192–193viewing report information, 189–190

ReportProxy service, 188Representational State Transfer (REST), 346Request Actions field, 357Request Actions section, 156Request Document section, 47Request element, 73Request Pipeline start, 53RequestHeaders class, 295, 314RequestHeadersXML base schema, 300

■INDEX 377

Find it faster at http://superindex.apress.com/

797-4INDEX 4/3/07 6:26 PM Page 377

Page 403: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

RequestHeadersXML class, 296RequestMetaData class, 295, 314RequestMetaDataXML class, 296, 300Response element, 73Response Pipeline start, 53ResponseHeaders class, 295, 314ResponseHeadersXML class, 296ResponseMetaData class, 295, 314, 320ResponseMetaDataXML class, 296REST (Representational State Transfer), 346RESTful proxy service, 346Resume action, 362retrieving

namespaces of XML nodes, 350SOAP Headers using XQuery, 343TESTAPPLICATION fields, 344version numbers from namespaces, 350WSDL/Policy/MFL/Schema/Proxy via

HTTP, 345–346retryCount attribute, 122retryDelay attribute, 122Route action, 108, 359Route node, 104, 112–113, 139, 162Route nodes, 51, 55, 58, 176routing node, 44Routing Options action, 358routing policy, 254RPC (Remote Procedure Call). See document-

centric vs. Remote Procedure Call(RPC)

RSL (RDBMS Service Layer), 215Rule Enabled field, 180run task, 170runMonitoringTest( ) method, 187runtime code, 285run.wsclient target, 185

SSAAJSource Source interface, 318SAF (Store And Forward) agent, 120SAML (Security Assertion Markup

Language), 9, 199SAMPLE_DIR variable, 286Scan SubDirectories checkbox, 139SCC (source code control systems), 4, 238scenario description, 216–217schema transformation, 6, 8schema_compile step, 300<schema> element, 72–73, 88schemas

attributeFormDefault attribute, 92–93elementFormDefault attribute, 88–92overview, 88troubleshooting, 85–88

ScratchPad attribute, 311Secure FTP (SFTP), 282Secure Sockets Layer (SSL), 9, 281secure-shell-based (SSH-based) FTP

protocol, 196

securityALSB certification by security assessment,

335enforcing, 7, 9sample test clients, 335–337

Security Assertion Markup Language(SAML), 9, 199

Security Configuration section, 141, 257security enforcement, 196security interoperability, 196security models and service bus, 195–204

ALSB security model, 198–201digital signatures and encryption, 201identity propagation in ALSB, 200inbound security in ALSB, 198–199overview, 198SSL authentication, 200–201

overview, 195recommendations, 203–204security paradigms with SOA challenges,

195–197ad-hoc, custom, token-based security,

197message-level security, 197overview, 195–196transport-level security, 196–197

using ALSB security, 201–203Select object, 304Select Project Facets page, New Project

wizard, 22Select Wizard dialog, 31self-described attribute, 297send( ) method, 329sendMessageAsync( ) method, 326, 328<sequence> tag, 75Service Account, 141–142, 152, 199service aggregation, 6, 8Service Authorization Policy, 257Service Browser window, 42service bus. See security models and service

busService Bus domain, 14–15Service Callout action, 105, 107, 164, 359Service Domain Scale, 210–211service domains, 221service interface, 131Service Level Agreements (SLAs), 39, 173,

177–185service management tools, 219service mapping, 214service mediation, 102service orchestration, 6Service Oriented Architecture (SOA), 5service portfolio, 248service providers, 39service repositories, 62, 219service section, <definitions> root element, 68Service Summary, 173service types and transport protocols

EJBcreating business service, 159–160creating EJBBusiness bean, 157–159creating JNDI provider, 161

■INDEX378

797-4INDEX 4/3/07 6:26 PM Page 378

Page 404: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

creating message flow, 162creating proxy service, 161overview, 157reasons for using, 163

messaging typesbinary, 132–140overview, 131text, 140–144XML, 144–157

overview, 124–125Plain Old Java Objects (POJO), 164–167SOAP

with attachments, 167–171without WSDL, 126–127with WSDL, 125–126

XMLwithout WSDL, 131with WSDL, 127–130

<service> tag, 77, 356<service>_Impl class, 35service-enable service endpoints, 203ServiceInfo class, 294serviceName attribute, @WebService

annotation, 26services, versioning

service orientation, 237–238whether to version services or operations,

239–244Services domain, 211ServiceTransportSender interface, 295ServiceTransportSender parameter, 326ServiceTypes project, 141, 151ServiceTypes/MFL directory, 148serviceURI attribute, @WLHttpTransport

annotation, 27<servlet> declaration, 275session controller, 253setDelay( ) operation, 176setDomainEnv command, 261setDomainEnv script, 262, 271–273setDomainEnv.cmd (or .sh) script, 338setDomainEnv.cmd file, 260setResponse( ) method, 321setResponseMetaData( ) method,

InboundTransportMessageContext,320

setResponsePayload( ) method,InboundTransportMessageContext,320

SFTP (Secure FTP), 282<ShippingAddress> root element, 71show text info stage, 143Siebel, 212Sign.xml policy, 201sim prefix, 90Simple Network Management Protocol

(SNMP), 9Simple Object Access Protocol. See SOAP

(Simple Object Access Protocol)SimpleTable object, 304SingleUseSource interface, 317Skip action, 363SLA alert, 188

SLAs (Service Level Agreements), 39, 173,177–185

Smart Search capability, 352SNMP (Simple Network Management

Protocol), 9SOA, 203

Coordinate Systemoverview, 205Service Domain Scale, 210–211Software Abstraction Scale, 205, 210

mapping, 213–219bottom-up approach, 215overview, 213service maps at scale, 218–219service tooling, 219SOA mapping test 1, 216–217SOA mapping test 2, 217–218top-down approach, 213–215

security paradigms with SOA challenges,195–197

ad-hoc, custom, token-based security,197

message-level security, 197overview, 195–196transport-level security, 196–197

SOA (Service Oriented Architecture), 5SOAP (Simple Object Access Protocol), 125

with attachments, 167–171without WSDL, 126–127with WSDL, 125–126

SOAP Binding Configuration page, 41SOAP Headers, 197, 343SOAPBinding property, 25<soap:body> element, 60, 319soapBodyRequest variable, 106<SOAP:Envelope xmlns:SOAP=.“.”> wrapper,

345<SOAP:Envelope> element, 345<SOAP:Header> element, 319soapMsg variable, 127SOAPwithAttachment project, in Workshop,

167Socket Transport Configuration screen, 284SocketBS test console, 293SocketCoLocatedMessageContext class, 328SocketInboundMessageContext object, 321,

324SocketOutboundMessageContext class, 329SocketRequestHeaders class, 315SocketRequestMetaData class, 315SocketResponseMetaData class, 315SocketTransportProvider class, 297, 301SocketTransportReceiver class, 324software. See installing and configuring

softwareSoftware Abstraction Scale, 205–206, 210Sort By Arrival checkbox, 138source code control systems (SCC), 4, 238Source Code/Download, 18, 145Source interface, 295, 317SSH-based (secure-shell-based) FTP

protocol, 196

■INDEX 379

Find it faster at http://superindex.apress.com/

797-4INDEX 4/3/07 6:26 PM Page 379

Page 405: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

SSL (Secure Sockets Layer), 9, 281SSL authentication, 200–201Stage Directory, 138start node, 44Start node, Message Flow, 51startNodeManager command, 272startWebLogic.cmd script, 260static credential, 199static method, 364STDOUT command, 346Stop Processing More Rules, 180Store And Forward (SAF) agent, 120StreamSource interface, 317StreamSource Source interface, 318String argument, 240String field, 147String file, 167String greeting, 240String response, 241string type, 74, 87string values, 54, 350StringSource Source interface, 318style attribute, @SoapBinding annotation, 27submitAsyncOrder( ) function, 121, 124submitNewOrder( ) operation, 243submitOrder( ) operation, 242submitOrder service, 95submitTireOrder operation, 243Summary of Message Reports window, 189Supply chain management, 211Supply domain, 216switch statement, 358switches, 7Synchronize icon, 256synchronous invocation, 117–119system administration, 256System.out messages, 58System.out.println( ) function, 368

T\t delimiter, 146tab-delimited message format, 146targetNamespace attribute, 26, 73, 88tasks, 296taxableAmount argument, 159taxableAmount local variable, 166TaxProxy.wsdl file, 161TCP/IP sockets, 286team development, 253–256

Change Center, 253–254conflict management, 253–254conflict resolution, 254–256overview, 253

telephones, 234temperamental service, 174–187

coding proxy client, 185–187creating ALSB project, 176–177creating business services, 174–176defining Service Level Agreements (SLAs),

177–185overview, 174

TemperamentalCustomerService webservice, 176

TemperamentalProxy service, 177test clients, 335–337Test Console button, 46test console window, 115TESTAPPLICATION fields, retrieving, 344TestCluster project, 277testing

for null values, 350–351proxy service, 46–48

/text( ) command, 105text annotation, 367text messaging type, 140–144Text service, 140TextArea object, 304TextBox object, 304textContents local variable, 143tight coupling, 3–4TireSize argument, 243t-models, 256tns prefix, 87to XMLnoWSDLService proxy service, 131token-based security, 197top-down approach, 213'total' argument, 351toXML( ) method, 314tracing, 256Transformation, 150Transformer interface, 295Transport Authorization Policy, 257Transport Configuration screen, 304transport header, 197Transport Headers action, 299, 314, 359transport level, authentication, 198transport protocol, 235Transport SDK, 283TransportCommon.xsd XML schema file,

296, 300TransportEditField class, 303TransportEditFields, 305TransportEndPoint interface, 295transportException method, 327transport-level security, 196–197TransportManager interface, 294TransportManager.getTransformer( ) master

transformer, 319TransportManagerHelper class, 294, 313, 319,

320–321, 327, 329, 333TransportOptions class, 321TransportOptions parameter, 326TransportProvider interface, 294, 301, 310,

326TransportProviderConfiguration class, 296TransportProvider.sendMessageAsync( )

method, 327transports. See custom transportsTransportSender parameter,

sendMessageAsync( ) method, 326TransportSendListener interface, 295TransportSendListener method, 329

■INDEX380

797-4INDEX 4/3/07 6:27 PM Page 380

Page 406: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

TransportSendListener parameter,sendMessageAsync( ) method, 326

TransportUIBinding interface, 295, 302TransportUIError array, 307TransportUIFactory class, 295TransportUIFactory.TransportUIObject type,

304TransportUIGenericInfo value object, 303TransportUIObject attribute, 306TransportViewField objects, 308TransportWLSArtifactDeployer interface,

295, 310, 313troubleshooting WSDLs and schemas, 85–88Tuxedo transport, 282two-way SSL authentication, 200type attribute, 87, 310types, vs. elements, 78–80types section, <definitions> root element, 68<types> element, 72

custom data types, 74–75importing XML schemas, 76minOccurs and maxOccurs, 75native data types, 74overview, 74

UUDDI (Universal Discovery, Description, and

Integration), 225, 256UDDI element, 297UDDI tModel definition, 297UI elements, 284Universal Discovery, Description, and

Integration (UDDI), 225, 256UpdateEditPage( ) method, 306updating

JAR resources of EJBTransport businessservices, 346

proxy services, effect on “in-flight”processes, 343

URI property, 326URL, importing WSDL from, 337–338URL context roots, mapping, to services,

346–349use attribute, @SoapBinding annotation, 27user account, creating in FileZilla, 140User Authentication, 142UtilityTypes schema, 80

VValidate action, 366validateMainForm( ) method, 303–304validateProviderSpecificForm( ) method, 307variableCreditCheck( ) method, 179version numbers, retrieving from

namespaces, 350versioning services, 233–251

constrained by reality, 245and future of IT, 250–251overview, 233–236service orientation, 237–238

whether to version services or operations,239–244

overview, 239–240versioning operations, 240–243versioning services, 243–244

versions, 238View Configuration Changes page, 45View Message Detail window, 190VIP (virtual IP address), 275Virtual Private Network (VPN), 103void data type, 120void writeTo interface source, 317VPN (Virtual Private Network), 103

WWAR file, 7web forms, accepting HTTP/POST

information from, 344–345Web Service Project, Web Services folder, 22Web Service Security headers, 257Web Service Security policy, 257Web Service Security profiles, ALSB for, 197Web Service Security specifications, 197Web Service Security username token

authentication policy, 202Web Service Security Username Token

profile, 197web service stacks, 84web services, 234Web Services Description Language. See

WSDL (Web Services DescriptionLanguage)

Web Services Reliable Messaging (WS-RM),282

Web Services Security authentication, 199web-inf/weblogic.xml file, 275web-inf/web.xml file, 275WebLogic 9, 12WebLogic console, 132, 193WebLogic Diagnostic Framework, 173WebLogic domain, 268WebLogic Scripting Tool (WLST), 258WebLogic Server (WLS), 10, 21, 120WebLogic text console window, 368WebLogic Workshop, 11, 185

configuring, 12configuring for AquaLogic Server, 16, 18quick tour of, 13–14

WebLogicCluster parameter, 275weblogic.home property, 35weblogic.jar file, 275weblogic.xml file, 276web.xml file, 275Windows, setting up ALSB server as service

of, 338–343wire protocol, 235WLDeploy, Ant, 16WLHttpTransport property, 25WLI_QS_REPORT_ATTRIBUTE table, 192WLI_QS_REPORT_DATA table, 192WLS (WebLogic Server), 10, 21, 120

■INDEX 381

Find it faster at http://superindex.apress.com/

797-4INDEX 4/3/07 6:27 PM Page 381

Page 407: Davies j.   the definitive guide to soa. bea aqua logic service bus(2007)(408)

WLS console, 120wlsbjmsrpDataStore data store, 192wlsbJMSServer server, 192WLST (WebLogic Scripting Tool), 258WorkManagers, 351Workshop, for WebLogic Platform, 22workspace, 12wrapping, 85writeTo method, Source interface, 317WSDL (Web Services Description Language),

5, 37–38, 54, 253best practices

dependency trap, 80–83document-centric vs. Remote

Procedure Call (RPC), 83–85elements vs. types, 78–80overview, 78

<binding>, 77creating, 37–38importing from URL, 337–338<message>, 76namespaces

default namespace, 71–73overview, 70–71target namespace, 73

overview, 67–69<port>, 78<portType>, 76–77<service>, 77Simple Object Access Protocol (SOAP)

with, 125–126Simple Object Access Protocol (SOAP)

without, 126–127troubleshooting WSDLs and schemas,

85–88<types>

custom data types, 74–75importing XML schemas, 76minOccurs and maxOccurs, 75native data types, 74overview, 74

visualizing documents from schemasattributeFormDefault attribute, 92–93elementFormDefault attribute, 88–92overview, 88

XML with, 127–130XML without, 131

WSDL property, 25WSDL service type, 125WsdlcTask, Ant, 16<wsdl:definitions> tag, 87

wsdlLocation attribute, @WebServiceannotation, 26

WSDL/Policy/MFL/Schema/Proxy, retrievingvia HTTP, 345–346

<wsdlsoap:binding> section, 26WS-RM (Web Services Reliable Messaging),

282

Xxf:helloToGoodbye function, 64XML, 60

converting into string using XQuery, 350as messaging type, 144–157nodes, retrieving namespaces of, 350variables, converting String values into,

using XQuery, 350without WSDL, 131with WSDL, 127–130

XML Schema Document (XSD), 5, 253XML Schema objects, 157XML schemas, 8, 76XML snippet, 293XMLBean classes, 285, 296XMLBean schemas, 285XmlObject class, 314XmlObject interface, 300XMLObject representation, 319XmlObject Source interface, 318XmlObjectSource Source interface, 318XmlObject.type attribute, 301xmlResponse variable, 349XMLWSDLService proxy service, 128XPath link, 57, 108XQuery, 60

converting String values into XMLvariables using, 350

converting XML into string using, 350retrieving SOAP Headers using, 343retrieving version numbers from

namespaces, 350testing for null values, 350–351

XQuery Resources link, 156XQuery Transformation wizard, 148, 151XSD (XML Schema Document), 5, 253xsd: prefix, 72XSLT (eXtensible Stylesheet Language

Transformation), 7xs:string argument, 63

■INDEX382

797-4INDEX 4/3/07 6:27 PM Page 382