Sunteți pe pagina 1din 132

JMP 105 XML and Web Services Jumpstart

Paul T. Calhoun | Chief Technology Officer

Obligatory Introduction Slide


Paul T. Calhoun Chief Technology Officer NetNotes Solutions Unlimited pcalhoun@nnsu.com www.nnsu.com I'm a Speaker, Trainer and Consultant who provides customer-focused knowledge transfer and consulting to businesses worldwide. I currently develop solutions using Domino, Xpages, W eb Services, Java, and XML for customers using Domino, Portlet Factory, W ebSphere and Eclipse. I am administration and developer certified on all releases since 3.0. I coauthored the IBM Redbook XML Powered by Domino, and have developed several online courses for both Application Development as well as System Administration. I have spoke at technical conferences world wide and published over a dozen articles in leading publications. I contribute frequently to the XPages Blog.

Evaluations

Please make sure you fill out your evaluations from the pages at the back of you notepad. THANKS !!!!!!!!

Please Put you Phone/PDA On Silent Mode

Agenda

XML Overview XML Development in IBM Lotus Domino W eb Services Overview Developing W eb Service Providers Developing W eb Service Consumers Q&A

XML Overview

Current State of XML XML Technologies YOU need to know


XML Syntax XSD Schema XSL XSLT XPATH XSL-FO

XML is 13 Years Old (That's like 91 technology years) XML = eXensible Markup Language Developed by W 3 committee headed by Sun's Jon Bosak

Current State of XML


Still @ version 1.0 (Fifth revision) http://www.w3.org/tr/xml

Standard is still maintained by the W 3 today http://www.w3.org

A newer, different, better, cooler HTML

XHTML (XHTML is DEFINED using XML)

XML is NOT...

Any specifically defined markup language or tag definition like W ML, DXL XHMLT, MathML

All about the DATA !! All about the DATA !! All about the DATA !!

All about the DATA !!

All about the DATA !! All about the DATA !!

XML is...
All about the DATA !! All about the DATA !!

All about the DATA !!

All about the DATA !! All about the DATA !! All about the DATA !!

With XML you can ...

Create/Define your own Markup Language


Using Syntax Rules defined in the XML standard (defined at www.w3.org) Set of tags that describe specific DATA structures

Books Documents Cars Business Processes Messages Pizza <insert YOUR markup language here>

With XML you can ...

Exchange DATA with ANYONE

Ubiquitous data transfer from system A to system B regardless of


Platform Operating System Programming Language Protocol Connectivity

Best Practice

Define

Software/Hardware configuration Tool set properties Industry Standard Markup Languages Web Services Transactions

SOAP WSDL UDDI REST

At the end of the day XML is what YOU make it to be !

Starts with a correct XML declaration <?xml version = 1.0 ?> Each opening tag must have a corresponding closing tag

All tags are enclosed with angle brackets "< >" A root tag encompasses all other tags
<books> ..xml content... </books>

XML Syntax Rules

Tag names are case sensitive All attribute values must be enclosed in quotes
(single quotes OR double quotes but be contestant)

Tags can be nested but cannot overlap

Comments start with <!-- and end with -->

XML Declaration

First line of an XML document All the following are valid XML declarations

<?xml version="1.0" ?> <?xml version="1.0" encoding="UTF-8" ?> <?xml version="1.0" encoding="UTF-8" standalone="yes" ?>

XML Tags

All tags are enclosed with angle brackets "< >" A root tag encompasses all other tags Each opening tag must have a corresponding closing tag Tags can be nested but cannot overlap

<?xml version="1.0" encoding="UTF-8" ?> <Pizza> <Type>Supreme</Type> </Pizza>

Tag Names are Case Sensitive

Valid Tag Combinations <Pizza></Pizza> <pizza></pizza> <PIZZA></PIZZA>

Invalid Tag combinations <Pizza></PIZZA> <pizza></Pizza> <Pizza><pizza>

Attributes must be enclosed in quotes


Single ( ' ' ) Double ( ) Be consistent

<?xml version="1.0" encoding="UTF-8" ?> <Pizza attrib1=value1> <Type attrib2=value2>supreme</Type> </Pizza>

Processing Instructions and Comments

Processing instructions start with <? and end with ?>


Processing Instructions are used to provide additional information to the parser Schema Definitions Stylesheet locations

Comments start with <!-- and end with -->

Comments are ignored by the parser

<?xml version="1.0" encoding="UTF-8" ?> <?xml-stylesheet type="text/xsl" href="style.xsl"?> <!-- This is an XML Comment --> <Pizza attrib1=value1> <Type attrib2=value2>supreme</Type> </Pizza>

W ell Formed: XML followed all Syntax Rules

Not W ell-Formed: XML did not follow all Syntax Rules

XML Documents must be WELL FORMED


An XML document can be a ...
Physical file on disk Stream of data on same system Stream of data from remote system In memory resource

Checking for well-formedness


XML documents are processed by parsers Parsers are software built into many

Applications Application Servers Web Browsers Development Software

Trivia:There has been an XML parser in Domino since Release 5

The Parser determines if the XML document is well-formed


If the XML document is NOT well-formed then processing stops and the parser throws an error If the XML document is well-formed the processing continues

Parsers can optionally determine if an XML document is Valid according to an existing schema

More on this later

XML Parser API's

DOM - Document Object Model

SAX - Simple API for XML

XML documents are parsed into an in-memory Node Tree Good for smaller XML documents Most common http://www.w3.org/DOM/

XML document is processed from beginning to end Each element of the XML document is processed in real time Not as common http://www.saxproject.org/

Both DOM and SAX parsers are available in all the common programming languages

Java .NET C C++ C sharp Javascript Lotuscript Fortran

Demo - Testing XML for Well-Formedness

Valid:
After parser verifies the document is well-formed will optionally validate against a referenced schema

Schema API's:
Document Type Definition (DTD) XML Schema (XSD)

XML Documents can optionally be VALID


Schemas are generally a 1 to many relationship

Validating API's

Document Type Definition DTD


XML Schema - XSD


Original XML validation mechanism Issues

Replacement for DTD's Addresses all of the DTD issues More complex More verbose Not easily created

Does not allow for data typing

(Everything is a string)

Does not Support Namespaces Not written in XML syntax

Validation Best Practices


DTD's were XML's original validation mechanism Primary con is lack of data typing Although DTD's are still supported (primarily for backwards compatibility) developers should standardize and implement XML validation via XSD as a best practice

What to develop first?

W hat do you develop first? The XML data or the XSD that defines the data ?

Either approach is valid Tools available to generate XML sample from XSD as well as tool to generate XSD from sample XML For Domino development most XML is going to be generated via an agent from document data

During development this is generally a dynamic ongoing process with many changes

Best practice is to finalize the XML stream and then use tools to generate the XSD schema

Generating XSD Schemas

XSD schema documents can be written manually with any XML editor

But you don't want to (remember the verbose part?)

The problem is tools to generate XSD files from XML are

Not Free Rational application Developer Altova XML Spy Style Studio Not easily available/configurable

So I wrote you one and put it in the download !


Based upon Apache XMLBeans Creates XSD Schema Documents from generated or static XML Allows developers to set schema format

XSD Schema Formats

There are three generally used XSD schema formats

Russian Doll Follows a cascading tree structure Salami Slice (Seriously. This is not a typo)

Based upon layers Venetian Blind


Combination of the first two

Using our well formed Pizza XML document as the XML source <?xml version="1.0" encoding="UTF-8" ?> <!-- This is an XML Comment --> <pizza attrib1="value1"> <pizzaStyle attrib2="value2">supreme</pizzaStyle> </pizza>

XSD Russian Doll


<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="pizza"> <xs:annotation> <xs:documentation>This is an XML Comment</xs:documentation> </xs:annotation> <xs:complexType> <xs:sequence> <xs:element name="pizzaStyle"> <xs:complexType> <xs:simpleContent> <xs:extension base="xs:string"> <xs:attribute type="xs:string" name="attrib2" /> </xs:extension> </xs:simpleContent> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute type="xs:string" name="attrib1" /> </xs:complexType> </xs:element> </xs:schema>

XSD Salami Slice


<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="pizza"> <xs:annotation> <xs:documentation>This is an XML Comment</xs:documentation> </xs:annotation> <xs:complexType> <xs:sequence> <xs:element ref="pizzaStyle" /> </xs:sequence> <xs:attribute type="xs:string" name="attrib1" /> </xs:complexType> </xs:element> <xs:element name="pizzaStyle"> <xs:complexType> <xs:simpleContent> <xs:extension base="xs:string"> <xs:attribute type="xs:string" name="attrib2" /> </xs:extension> </xs:simpleContent> </xs:complexType> </xs:element> </xs:schema>

XSD Venetian Blind


<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="pizza" type="pizzaType"> <xs:annotation> <xs:documentation>This is an XML Comment</xs:documentation> </xs:annotation> </xs:element> <xs:complexType name="pizzaType"> <xs:sequence> <xs:element type="pizzaStyleType" name="pizzaStyle" /> </xs:sequence> <xs:attribute type="xs:string" name="attrib1" /> </xs:complexType> <xs:complexType name="pizzaStyleType"> <xs:simpleContent> <xs:extension base="xs:string"> <xs:attribute type="xs:string" name="attrib2" /> </xs:extension> </xs:simpleContent> </xs:complexType> </xs:schema>

NameSpaces

Did you notice something different about the Schema XML? XML tags in an XML document can be combined from more than one vocabulary or Markup Language Namespaces prefixes are typically defined in the root tag of an XML document

Tags defined in that markup language or vocabulary are then prefixed with that Namespace

This is what allows tags from multiple markup languages to exist in the same XML document
<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="pizza" type="pizzaType"> <xs:annotation> <xs:documentation>This is an XML Comment</xs:documentation> </xs:annotation> </xs:element>

Demo Validating XML

XML Stylesheet Language - XSL

W hat if I need an XML document in a different format than the one it is currently in ? XSL XML Stylesheet Language

XSLT XSL Transformations XPATH Expressions used to traverse an XML document XSL-FO XSL Formatted Objects

Transforming XML

XML Document

Text Document

XML Document

XSLT Processing Engine

HTML Document

XSL Stylesheet ????? Document W ML Document

XSLT Stylesheets

XSLT Stylesheets are


Well-formed XML documents A list of instructions (templates) that use XPATH notations that read the xml and output the results

Most systems that include an XML Parser also include XSL processing capabilities Transformation requires

XML Source Document XSL Source Document Output Document

Example Stylesheet

Transforms Pizza XML into alternate XML

<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output indent="yes" /> <xsl:template match="/"> <xsl:apply-templates select="pizza" /> </xsl:template> <xsl:template match="pizza"> <xsl:element name="pizzaPie"> <xsl:apply-templates select="pizzaStyle" /> <xsl:apply-templates select="toppings" /> </xsl:element> </xsl:template> <xsl:template match="pizzaStyle"> <xsl:element name="typeOfPizza"> <xsl:value-of select="."></xsl:value-of> </xsl:element> </xsl:template> <xsl:template match="toppings"> <xsl:element name="ingredients"> <xsl:apply-templates select="topping" /> </xsl:element> </xsl:template> <xsl:template match="topping"> <xsl:element name="ingredient"> <xsl:value-of select="." /> </xsl:element> </xsl:template> </xsl:stylesheet>

Transformations In Domino

There is a bug in 8.5.0 that throws a security error whenever any XSLT transformation is done This Bug is Fixed in 8.5.1 !!!!!

Demo Transforming XML

Agenda

XML Overview XML Development in IBM Lotus Domino W eb Services Overview Developing W eb Service Providers Developing W eb Service Consumers Q&A

39

XML and Domino

XML capabilities of Notes/Domino ?


Notes/Domino contains an XML Parser (Since Release 5.0.3) Notes/Domino contains an XSLT processing engine

Design Elements that can produce XML


Forms Views Pages Agents LotusScript and Java Servlets


Java only

Design Elements that can consume XML


Agents Servlets

XML and Domino

XPages

XPages source code is formatted as a well-formed XML document This source code is then used to compile the XPage that is then served to the browser and Notes clients

DXL The Domino Markup Language

Domino design elements and data represented as XML


Documents Database Forms Views Items Agents

DXL can be exported


From the Designer Client By using code

LotusScript and Java

DXL can be imported

Only by using code

LotusScript and Java

LotusScript XML Classes

NotesXMLProcessor

A base class that contains properties and methods common to all XML classes.

NotesDOMParser

A class that parses XML into a standard DOM (Document Object Model) tree. Additional NotesDOM classes allow you to work with DOM trees.

NotesSAXParser

A class that processes XML as events using a SAX (Simple API for XML) parser.

NotesXSLTransformer

A class that transforms XML through XSLT.

NotesStream

A class for streaming XML to or from a memory buffer or file.

LotusScript XML Classes (cont)

NotesDXLImporter

A class that enables the import of domino data and design elements as DXL (Domino XML Language).

NotesDXLExporter

A class that enables the export of domino data and design elements as DXL (Domino XML Language).

NotesNoteCollection

A class that builds subsets of Domino design and data elements for DXL exporting

Java XML Classes

There are not corresponding XML processing classes in the Domino Java implementation There are XML parsers and XSLT transformation capabilities included in the SUN J2SE implementation that is part of the Core Notes/Domino Java API

javax.xml.parsers javax.xml.transform javax.xml.transform.dom javax.xml.transform.sax javax.xml.transform.stream

Java XML Classes (cont)

There are two native Domino Classes


DxlExporter DxlImporter

XML processing capabilities exist in some of the Domino core classes as properties and methods

Document EmbeddedObject Item MIMEEntity RichTextItem

Demo Producing XML from Domino

Demo Consuming XML from Domino

Agenda

XML Overview XML Development in IBM Lotus Domino W eb Services Overview Developing W eb Service Providers Developing W eb Service Consumers Q&A

49

Web Services Overview

W hat are W eb Services ?


Request Response architecture for communicating between two Systems Should be Loosely Coupled

Client and Server (Requestor / Responder) should not rely on one another

Standards based

Any client on any platform should be able to access a Web service on any server

Linux Windows Java .NET English Russian

No operating system or language dependencies No need for proprietary drivers

Web Services components

XML

Lingua Franca of Web Services Web Service Requests and Responses all formatted using XML

SOAP Simple Object Access Protocol

Specific Format of Web Service Requests and Responses

W SDL W eb Services Description Language

XML documents that describe a web services functionality

UDDI Universal Description, Discovery and Integration

SOAP

Simple Object Access Protocol


An XML based protocol for information exchange in decentralized and distributed environments Co-developed by

IBM and Microsoft (now thats collaboration!)

Send XML data formatted as a SOAP message TO the W eb service

Message is parsed to read the request

Data for one of the defined service methods

Receive XML data formatted as a SOAP message FROM the W eb service

Message is parsed to read the response


Data that provides the information that fulfills the service request Or an error message

SOAP Versions

You need to send and receive messages based upon a common SOAP version

Version 1.1 Version 1.2

Specification maintained at the W 3C

http://www.w3.org/TR/soap

SOAP Version 1.1 Request


<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> <SOAP-ENV:Body> <m:GetLastTradePriceDetailed xmlns:m="Some-URI"> <Symbol>DEF</Symbol> <Company>DEF Corp</Company> <Price>34.1</Price> </m:GetLastTradePriceDetailed> </SOAP-ENV:Body> </SOAP-ENV:Envelope>

SOAP Version 1.1 Response


<SOAP-ENV:Envelope same ns as request> <SOAP-ENV:Body> <m:GetLastTradePriceResponse xmlns:m="Some-URI"> <PriceAndVolume> <LastTradePrice>34.5 </LastTradePrice> <DayVolume>10000 </DayVolume> </PriceAndVolume> </m:GetLastTradePriceResponse> </SOAP-ENV:Body> </SOAP-ENV:Envelope>

SOAP Version 1.2 Request


<?xml version='1.0' ?> <env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope"> <env:Header> <test:echoOk xmlns:test=http://example.org/ts-tests env:role="http://www.w3.org/2003/05/soap-envelope/role/next"> foo </test:echoOk> </env:Header> <env:Body> </env:Body> </env:Envelope>

SOAP Version 1.2 Response


<?xml version='1.0' ?> <env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope"> <env:Header> <test:responseOk xmlns:test="http://example.org/ts-tests"> foo </test:responseOk> </env:Header> <env:Body> </env:Body> </env:Envelope>

Is it necessary to know all that syntax?

Yes !

If you dont know the syntax (or at least how to read the reference) then you cant

Troubleshoot ill-formed SOAP envelopes Parse the SOAP packet to get to the data easily

And no

Most Web services development platforms / toolkits produce the SOAP envelopes for you The SOAP request envelopes are produced dynamically by your code SOAP responses can be parsed with any XML parser

Web Services Description / Definition language

An XML-formatted language used to

Describe a Web service's capabilities as collections of communication endpoints capable of exchanging messages WSDL describes the public interface to the Web service

These are the methods that get invoked

This is an XML-based service description on how to communicate using the Web service A description of the services provided by a Web service Method names, Return data types Written in XML syntax as an XML document

Seems to be some confusion about what the D stands for


Description/Definition Dont worry about it, it's all the same thing

Example WSDL Document


<?xml version="1.0"?> <definitions name="StockQuote" targetNamespace="http://example.com/stockquote/definitions" xmlns:tns="http://example.com/stockquote/definitions" xmlns:xsd1="http://example.com/stockquote/schemas" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns="http://schemas.xmlsoap.org/wsdl/"> <import namespace="http://example.com/stockquote/schemas" location="http://example.com/stockquote/stockquote.xsd"/> <message name="GetLastTradePriceInput"> <part name="body" element="xsd1:TradePriceRequest"/> </message> <message name="GetLastTradePriceOutput"> <part name="body" element="xsd1:TradePrice"/> </message> <portType name="StockQuotePortType"> <operation name="GetLastTradePrice"> <input message="tns:GetLastTradePriceInput"/> <output message="tns:GetLastTradePriceOutput"/> </operation> </portType> </definitions>

UDDI

Universal description, discovery, and integration

A platform-independent, XML-based registry for businesses worldwide to list themselves on the Internet UDDI is an open industry initiative (sponsored by OASIS) enabling businesses to discover each other and define how they interact over the Internet

The UDDI authors had a vision of a world in which consumers of W eb Services would be linked up with providers through a dynamic brokerage system

Anyone needing a service would go to a broker and select one This vision has not come to pass Instead, services write custom service endpoints with custom WSDL descriptions Consumers then hard-code the URLs to their SOAP endpoints, working only with specific systems The most common place that a UDDI system can be found is inside a company where it is used to dynamically bind client systems to implementations

Web Service Architecture

Agenda

XML Overview XML Development in IBM Lotus Domino W eb Services Overview Developing W eb Service Providers Developing W eb Service Consumers Q&A

63

Web Service Provider Support

Server based W eb Services were introduced in Domino 7

Enhanced in Domino 8

W SDL

Version 1.1

SOAP

Version 1.1

The Apache Axis engine is used for web service processing

AXIS 1 (Version 1.4)

The W eb service design element is similar to an agent Can be coded in


Java LotusScript

Compatibility

W eb Services created on a Domino 7 server can be ported AS-IS to a Domino 8.x Server

In other words, copy the database from Server A (Dom Version 7.x) to Server B(Dom Version 8.x) and don't open it in the designer client

These services will continue to execute on the Domino 7.x AND 8.x environments

For example during a conversion from 7.x to 8.x and you are replicating between 7 and 8 servers

As soon as the W eb Service is opened AND saved in a version 8 designer client


The Web Service will no longer execute on a Domino 7.x server only Domino 8.x A HUGE warning will be displayed and you will have to accept it

Don't say we didn't tell you !!

Creating Web Service Providers

In the Domino Designer Client


Expand Code | Web Service Providers Click the New Web Service Provider Action in the Action bar Provide a Name / Alias / Comment and choose the Programming Language Type

This can not be changed to a different type after the Web Service is Created

The editor that loads is based upon the language type selected

LotusScript

The editor that loads is based upon the language type selected (cont)

Java

Web Service Properties - Basics

Name

Required

Alias and Comment W arn if the W SDL interface is modified

Will not let you save a Web service if you add code that changes the WSDL

Port Type class

Class in Declarations that contains the publicly exposed methods

Any other classes will not be available (unless they are complex types)

Web Service Properties - Security


These are identical to the agent security properties W eb service security respects normal Notes ACL security including: Basic or session-based authentication Run-time privileges Allow public access use HTTP error 401 is returned requestor is not authorized to use the W eb Service

Web Service Properties - Advanced

Programming model

Almost always RPC Message is XML document based

SOAP Message format

More information in the next slide

Include operation name in SOAP action


Usually optional Checked by default

Port type and service names

Generated automatically on Web Service Save

SOAP message format

Affects W SDL format, which affects SOAP message format


Doesnt affect your how you write your code in either language Some clients (Like .NET) are pickier about the format RPC - Document/literal is emerging as the defacto standard

Notes 8.x default is

RPC Document/Literal

Notes 7 default is

RPC Encoded

See the following URL for a detailed discussion

http://www.ibm.com/developerworks/webservices/library/ws-whichwsdl/

Coding a LotusScript WS Provider


STOP !!!!!!! This is an excellent time to consider adding Java to your programming toolbox Unless you are calling existing libraries that contain LotusScript Code then start your W eb Services adventure using Java

Coding LotusScript Web Service Provider

For those I didn't convince to try Java, here are the LotusScript procedures LotusScript W eb Service Provider Editor is still old LotusScript Editor All code should go in the Declarations Event

All code should be in a single class definition Declare variables to be used Create a SUB to instantiate the variables Create 1 to N public functions

Functions can optionally take an input Majority return a value

Skeleton LotusScript Web Service code


Class W SClassName REM Declare Variables here Sub New REM Instantiate Variables here REM At least the Session object End Sub Public Function functionName(varName As String) As String REM Code logic goes here End Function End Class

Simple LotusScript Web Service


Class WSDemo6WebService session As NotesSession db As Notesdatabase view As NotesView Sub New Set session = New NotesSession Set db = session.GetDatabase("","Names.nsf") Dim doc As NotesDocument If db.IsOpen Then Set view = db.GetView("($NamesFieldLookup)") End If End Sub Public Function getEmailAddress(UserName As String) As String Dim EmailAddress As String Set doc = view.getDocumentByKey(UserName) If doc Is Nothing Then EmailAddress = "No Name Found" Else EmailAddress = doc.InternetAddress(0) End If getEmailAddress = EmailAddress End Function End Class

More Complex Web Services

W eb Service input parameters can be


Nothing Strings Arrays Classes

W eb Services can return


Nothing (Although you should at least check the return code) Strings Arrays Classes

Demo LotusScript WS Providers

Coding Java Web Service Providers


Code Editor uses new Eclipse Java Editor Interface All code should be in a single class definition

Declare variables to be used Use the class constructor to instantiate the variables

Create 1 to N public methods


Methods can optionally take input Majority return a value

Skeleton Code Java WS Provider


import lotus.domino.*; public class WSClassName { //Declare Variables here public WSClassName() throws NotesException { //Instantiate Variables here } public String methodName(String varName) { try { //Method Logic Here } catch (NotesException e) { e.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } return DataTypeValue; } }

Simple Java Web Service


public class mywcjavaws { private Session session; private Database db; private View vw; private Document doc; public mywcjavaws() throws NotesException { session = WebServiceBase.getCurrentSession(); // ac = session.getAgentContext(); db = session.getDatabase("", "Names.nsf"); vw = db.getView("($NamesFieldLookup)"); } public String getEmailAddress(String UserName) { String EmailAddress = ""; try { doc = vw.getDocumentByKey(UserName); if (doc == null) { EmailAddress = "No Name Found"; } else { EmailAddress = doc.getItemValueString("InternetAddress"); if(EmailAddress.equalsIgnoreCase("")){ EmailAddress = "Email Address Field is Blank"; } } } catch (NotesException e) { e.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } return EmailAddress; } }

More Complex Web Services

W eb Service input parameters can be


Nothing Strings Arrays Classes

W eb Services can return


Nothing (Although you should at least check the return code) Strings Arrays Classes

Demo Java WS Providers

Testing Web Services


W eb Services can be tested without manually creating client code W hy test the W eb Service before creating the client consumer?

Ensures the Web Service is working properly Allows for providing input to the Web Service without writing any test code Allows you to see the results returned by the Web Service Allows you to focus on your client code

If coding your own W eb Service client (for example, if you are still using Domino 6.x or 7.x) testing allows you to

Examine the exact SOAP that needs to be sent to the service Examine the exact SOAP that will be returned from the service

Web Service Testing Tools

There are several tools available that will test W eb Services without creating any client code Free tools

Eclipse Any 3.x version with the Web Tools Plug-in (WTP) loaded Latest version is part of the Galileo project (ver 3.5) soapUI

Not as feature rich as Eclipse

Not so free tools


Rational Application Developer Visual Studio .NET

You can also Google W eb Service Test Client to search for available test clients

Eclipse Web Service Explorer

Includes a W eb Service Test client

Built on the fly from the referenced WSDL

You can test any accessible W eb Service, not just Domino W eb Services

Via URL or local project file

It does not require you to create any project code Includes wizards to generate Java based W eb Service Client code

In non 8.5.1 environments this is an excellent time saver for generating and testing web service clients prior to incorporating them into Domino

Using the Eclipse Web Service Explorer


W ell use the Eclipse W eb Services Explorer test client From either the W eb or JavaEE perspective From the Run menu

Launch the Web Services Explorer

Using the Eclipse Web Service Explorer

The W eb Services Explorer simply needs the URI of a W eb Service Definition Language (W SDL) document The W SDL will be parsed and a test client created on-the-fly

Using the Eclipse Web Service Explorer

Once the W SDL file is parsed, the Public methods of the W eb Service are available as links

Click a link in the Navigator view The Actions view will open where inputs can be provided if required Click the GO button to invoke the Web Service Results will be displayed in the Status View at the bottom of the WS Explorer

Using the Eclipse Web Service Explorer

In the Status View source you can review the SOAP Request/ Response envelopes Click the Source link in the Status View to display the Soap Envelops Click the Form link to return to the previous view

Demo Testing Domino Web Services

Agenda

XML Overview XML Development in IBM Lotus Domino W eb Services Overview Developing W eb Service Providers Developing W eb Service Consumers Q&A

92

Consuming Web Services


The ability to consume W eb Services in Domino is new to release 8.0 In 8.0.x

Web Service clients are implemented as script libraries


Can be coded in either LotusScript or Java Script libraries can then be called from agents or events

In 8.5

Web Service clients are implemented via the Web Service Consumer interface

Can be coded in either LotusScript or Java Can be called from agents or events

Only resource required to create web service client code is the W eb Services W SDL

In File format Via URI

There is no out of the box solution for consuming W eb Services in any prior release

Consuming Web Services in ND 6.x and 7.x


The W eb Service must be created using regular agents There is no Native or out-of-the-box solution for creating LotusScript W eb Service clients

Although there are third-party COM objects available

The core Java packages contain all the needed classes to implement a W eb Services client

Client code is most easily created using a Java IDE (like Eclipse) In the Web Service Explorer there is a built-in wizard for creating Web Service client code See resources at end for example locations

Consuming Web Services in ND 8.0.x

In ND 8.0.x W eb Service clients are created as script libraries


LotusScript Java

Create a new Script Library

Click the WSDL button at the bottom of the designer

Consuming Web Services in ND 8.5.x

In Domino Designer

Expand Code

Select Web Service Consumers Click New Web Service Consumer

Consuming Web Services in ND 8.5.x

Name

Provide a descriptive name for what this web service consumes/returns

Comment

More descriptive info on what is being consumed

Get W eb service description from

Local WSDL File File stored on file system URL that points to WSDL file

Best Practice

A valid URL that returns the WSDL

In 8.5.0 reading a W SDL from URL does not work

Consuming Web Services

If the W SDL file is imported from a file that has been exported from a Domino W eb Service

The Service End Point will need to be edited to the actual URI BEFORE referencing it from the Web Service Consumer Domino Defaults the Service End Point to LocalHost

<wsdl:service name="W SDemo1Service"> <wsdl:port binding="intf:DominoSoapBinding" name="Domino"> <wsdlsoap:address location="http://localhost"/> </wsdl:port> </wsdl:service> <wsdl:service name="W SDemo1Service"> <wsdl:port binding="intf:DominoSoapBinding" name="Domino"> <wsdlsoap:address location="http://host/path/wsdlurl"/> </wsdl:port> </wsdl:service>

Consuming Web Services

If the W SDL file was imported from a URI


Either Domino or Non-Domino Then no changes should need to be made to the imported code as the correct Service End Point is already included

LotusScript Imported Code Structure

If importing into a LotusScript W S consumer, a class will be created in the Declarations Event The class will have:

A SUB that implements Web Service using the Service End Point One to N defined functions that will be called in your agent code

Java Imported Code Structure


If importing into a Java W S Consumer, several classes will be created The Service End Point is located in the W SNAMEServiceLocator.java source file

Sample code on how to implement the W eb Service is located in the W SNAMEService class

Web Service Consumers

Once the W eb Service is saved, it will be listed in the W eb Service Consumers designer view Actions

The Sign Action can be used to sign the Web Service without opening it and saving it. Export WSDL Export the WSDL to the local file structure Show WSDL Display WSDL in browser

Consuming Domino Web Services

If consuming external W eb Services


Web Services not being hosted on the same Domino server as the Web Service client No changes will need to be made to the Notes/Domino configuration

If consuming local Domino W eb Service (W eb Service is hosted on the same Domino Server as the W eb Service Consumer and client)

Changes will need to be made to the Domino Configuration Server Document Internet Protocols > Domino Web Engine Web Agents and Web Services Enable to run concurrently In Version 7.x and 8.0.x, If this is not done then the HTTP task will lock up in a race condition that will never terminate causing the server to have to be shut down by killing the Server process at the O/S level

Creating Web Service Consumers


The process for creating W eb Service Consumers is always the same Create the W eb Service Consumer

LotusScript Java

Use that W eb Service Consumer in an Agent or supported event


Agents LotusScript Java Supported Events

LotusScript

Demo Creating Web Service Consumers

Including Web Service Consumers in LotusScript Agents and Events

Once the W eb Service Consumer code has been created, Agents or supported events can be created that use that code The steps to implement the W eb Service are:

USE the Web Service Library Name in the Options event Use WebServiceLibraryName In the action event, initialize an instance of the class defined in the Web Service Library

Dim WSVar As New WSLibraryName

Call the methods of the Web Service WSVar.FunctionName(OptionalParameter) Use the returned value in your code

LotusScript Agent calling WS Consumer


Option Public Option Declare Use "LSReturnEmailAddress" Sub Initialize() Dim ws As New Slsws Dim emailaddress As String, username As String, msgtext As String username = "Mary" emailaddress = ws.Getemailaddress(username) msgtext = msgtext +username +"'s Mail address is - " + emailaddress MsgBox msgtext,0,"Email Address" Exit Sub End Sub

Calling Multiple Methods with Error Handling


Option Public Option Declare Use "LSImplementTwoMethods" Sub Initialize()

On Error 4746 GoTo errhandle Dim ws As New Slswstwomethods Dim emailaddress As String, mailserver As String, username As String Dim msgtext As String, CRLF As String username = "Mary" CRLF = Chr(10) & Chr(13) emailaddress = ws.getEmailAddress(username) mailserver = ws.getMailServer(username) msgtext = msgtext +username +"'s Mail address is - " + emailaddress + CRL msgtext = msgtext +username +"'s Mail Server is - " + mailserver + CRLF MsgBox msgtext,0,"Directory Information" Exit Sub errhandle: MsgBox "The Web Services host can not be found." Exit Sub End Sub

Consuming Complex Web Services


W eb Services are not limited to returning single text or numeric values W eb Services can return complex data types, such as:

Classes Arrays Vectors XML data

Consuming Complex Web Services

The following is the generated W eb Service Consumer code generated when consuming a web service that uses a class
Public Public Public Public INTERNETADDRESS As String MAILSERVER As String MAILFILE As String MAILDOMAIN As String

Class DIRINFO As XSD_ANYTYPE

Sub NEW End Sub End Class Class Clswsusingclass As PortTypeBase Sub NEW Call Service.Initialize ("UrnDefaultNamespaceclswsusingclassService", _ "clswsusingclassService.Domino", "http://nnsuportal:80/JMP105.nsf/clswsusingclass?OpenWebService", _ "Clswsusingclass") End Sub Function GETDIRINFO(USERNAME As String) As DIRINFO Set GETDIRINFO = Service.Invoke("GETDIRINFO", USERNAME) End Function End Class

Consuming Complex Web Services

The following W eb Service client implements the W eb Service and a corresponding class object DirInfo

Option Public Option Declare Use "LSDirInfoViaClass" Sub Initialize() On Error 4746 GoTo errhandle Dim ws As New Clswsusingclass Dim DirectoryInfo As DirInfo Dim username As String, msgtext As String, CRLF As String username = "Mary" Set DirectoryInfo = ws.getDirInfo(username) CRLF = Chr (10 ) & Chr (13) msgtext = msgtext +username +"'s Mail address is - " + DirectoryInfo.INTERNETADDRESS + CRLF msgtext = msgtext +username +"'s Mail Server is - " + DirectoryInfo.MAILSERVER + CRLF msgtext = msgtext +username +"'s Mail File is - " + DirectoryInfo.MAILFILE + CRLF msgtext = msgtext +username +"'s Mail Domain is - " + DirectoryInfo.MAILDOMAIN + CRLF MsgBox msgtext,0,"Directory Information" Exit Sub errhandle: MsgBox "The Web Services host can not be found." Exit Sub End Sub

Web Query Save using Web Services

The Agent code that implements the W eb Service client can be incorporated into a forms W ebQuerySave event to provide W eb Service parameters and process the W eb Service results

Option Public Use "LSReturnEmailAddress" Sub Initialize On Error 4746 Goto errhandle Dim s As New NotesSession Dim ws As New Slsws Dim emailaddress As String , username As String Dim doc As NotesDocument Set doc=s.DocumentContext username = doc.UserName( 0) emailaddress = ws.getEmailAddress(username) Print Print Print Print Print Print | | | | | | <!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>Web Query Save Example</title></head><body> | <h1>Web Query Save Example</h1> | <br /><br /> | <h2>The users email address is : | emailaddress | </h2> |

Exit Sub errhandle: Msgbox "The Web Services host can not be found." Exit Sub End Sub

Error Handling in LotusScript

There are specific errors defined in the LSXBEERR.LSS file that are specific to W eb Services

Public Const lsERR_NOTES_WSENGINE_UNINIT_METHOD_ARG = 4743 Public Const lsERR_NOTES_WSENGINE_NOTINIT = 4744 Public Const lsERR_NOTES_WSENGINE_ERROR = 4745 Public Const lsERR_NOTES_WSENGINE_METHOD_ERROR = 4746 Public Const lsERR_NOTES_WSENGINE_METHOD_FAULT = 4747

By using a class defined in the LSXSD.LSS, these errors can be trapped Use the wsfault class to trap for errors
errhandle: Set wsfault = ws.getlastfault() If wsfault.getfault() Then Msgbox "There was a fault in the web service, error message is: " & Chr(13) & wsfault.getFaultString() Else Msgbox Error$ Msgbox Err End If Exit Sub

Passing Credentials to Web Services in LotusScript


Call the setcredentials method of the W eb Service class Pass User ID and Password Values as parameters
Option Public Option Declare Use "LSReturnEmailAddress" Sub Initialize() Dim ws As New Slsws Call ws.setcredentials("Paul Calhoun", "password") Dim emailaddress As String, username As String, msgtext As String username = "Mary" emailaddress = ws.Getemailaddress(username) msgtext = msgtext +username +"'s Mail address is - " + emailaddress MsgBox msgtext,0,"Email Address" Exit Sub End Sub

Demo LotusScript Web Service Clients

Including Web Service Consumers in Java Agents

The steps to implement the W eb Service Consumer in a Java Agent are:

Click the Import button in the Java Agent Project Manager and choose Web Service Consumer In the opened Dialog Box choose Web Service to include in Agent and click Import

Java Agent Calling Web Service Consumer

In the Code editor:

Instantiate an Instance of the Service Locator class using the code sample from the Web Service Script Library Call the public methods of the class that returns the Web Service content

import lotus.domino.*; public class JavaAgent extends AgentBase { public void NotesMain() { try { SimpleJavaWebService stub = new SimpleJavaWebServiceServiceLocator().getDomino(); System. out.println( stub.getEmailAddress( "Mary")); } catch (Exception e) { e.printStackTrace(); } } }

Consuming Web Services

Java Agents can consume the same complex W eb Services that LotusScript can Java Agents that consume web services can also be called from a forms web query save agent

Error Handling in Java WS Agents

In Java W eb Service clients, the Error handling is taken care of by the default behavior of using the Try-Catch-Finally block structure
import lotus.domino.*; public class JavaAgent extends AgentBase { public void NotesMain() { try { SimpleJavaWebService stub = new SimpleJavaWebServiceServiceLocator().getDomino(); System.out .println(stub.getEmailAddress("Mary")); } catch(Exception e) { e.printStackTrace(); } } }

Passing Credentials to Web Services in Java

In the generated DominoSoapBindingStub class in the W eb Service Consumer


Add two lines to the public method that implements _call Pass in the User ID and Password Works in 8.0.x and 8.5.x

public class DominoSoapBindingStub extends lotus.domino.websvc.client.Stub implements SimpleJavaWebService { public DominoSoapBindingStub(java.net.URL endpointURL, javax.xml.rpc.Service service) super (endpointURL, service); } throws lotus.domino.types.Fault {

public java.lang.String getEmailAddress(java.lang.String in0) throws java.rmi.RemoteException { lotus.domino.websvc.client.Call _call = createCall( "getEmailAddress" ); //The following two lines were added to implement authentication _call.setUsername( "Paul"); _call.setPassword( "password"); //End of additional code java.lang.Object _resp = _call.invoke( new java.lang.Object[] {in0}); return (java.lang.String) _call.convert(_resp, java.lang.String. class ); } }

Passing Credentials to Web Services in Java

In the Agent that consumes the W eb Service


Call the setCredentials method of the stub class Pass in the User ID and Password Works in Version 8.5.1

SimpleJavaWebServiceRPC stub = new SimpleJavaWebServiceRPCServiceLocator().getDomino(); stub.setCredentials( "Mary Smith","password");

Capturing SOAP Request and Response

In the generated DominoSoapBindingStub class in the W eb Service Consumer


Add the following code to the public method that implements _call Write the output to the console or capture in a Log file Use this procedure during DEVELOPMENT only. Disable once Web Service goes in production
import java.io.ByteArrayOutputStream; import java.io.IOException; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage;

Best Practice

try { SOAPMessage soapReq = SOAPMessage soapRes = ByteArrayOutputStream ByteArrayOutputStream _call.getMessageContext().getRequestMessage(); _call.getMessageContext().getResponseMessage(); reqOut = new ByteArrayOutputStream(); resOut = new ByteArrayOutputStream();

soapReq.writeTo(reqOut); soapRes.writeTo(resOut); System.out.println("****SOAP Request Envelope*****"); System.out.println(reqOut.toString()); System.out.println(); System.out.println("****SOAP Response Envelope*****"); System.out.println(resOut.toString()); } catch (SOAPException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace();}}}

Demo Java Web Service Clients

Calling Web Services from an XPage

W eb Services can be called from an XPage by adding code that implements an Apache Axis client The following code in the value property of a computed control will invoke the Simple Java W eb Service This code does NOT work when calling Document/Literal based web services
var nameval = getComponent("PerName").getValue(); var wsc = new org.apache.axis.client.Service; var call = wsc.createCall(); call.setTargetEndpointAddress("http://localhost/jmp207.nsf/sjws?WSDL"); call.setOperationName("getEmailAddress"); var xmlType = new javax.xml.rpc.encoding.XMLType(); call.addParameter("INPUT1", xmlType.XSD_STRING, javax.xml.rpc.ParameterMode.IN); call.setReturnType(xmlType.XSD_STRING); var a = new java.lang.Object[1]; a[0] = nameval; var retname = call.invoke(a); return retname;

What you learned !!!


XML is ALL ABOUT THE DATA !!!!!! Remember to stay well-formed and optionally valid If you don't like the format your XML is in TRANSFORM it Serving up Domino content via W eb Services increases the visibility of Domino in your world and others Domino can consume any W eb Service accessible on the wire

As a Web Service Consumer As an Agent

Resources

Learn XML and W eb Services in your Notes Client


http://www.tlcc.com Go by their booth number 626 in the exhibit hall and get a demo Courses available for versions 7 and 8 The 8.5.1 course will be available in the 1 st Quarter

For information on creating W eb Service Clients in all pre 8 releases go to my web site

http://www.nnsu.com In the downloads area, download the slides from Lotusphere 2007 and 2008

SOAP message format technical reference on IBM developerW orks


Russel Butek, Which style of WSDL should I use? www.ibm.com/developerworks/webservices/library/ws-whichwsdl/=

Testing tools

Eclipse www.eclipse.org SoapUI www.soapui.org

Resources

All of the following can be downloaded at my website


Slides JMP105.nsf (XML Test harness and XSD Schema Generator) XSLT to transform Domino Forms to Xpages

Click on the downloads link All items will be available the Monday AFTER Lotusphere

http://www.nnsu.com

Resources

W 3 Schools Tutorials on XML and W eb Services

http://www.w3schools.com/

W 3 Organization All specification Documents

http://www.w3.org

Developer W orks XML and W eb Services Zones


http://www.ibm.com/developerworks/webservices/ http://www.ibm.com/developerworks/xml/

ZVON Organization XSLT and XPath Testing tools

http://www.zvon.org/

Eclipse Organization W eb Service Explorer

http://www.eclipse.org

XMethods Organization Sample W eb Services for Testing

http://www.xmethods.org/

Agenda

XML Overview XML Development in IBM Lotus Domino W eb Services Overview Developing W eb Service Providers Developing W eb Service Consumers Q&A

129

Friendly Reminder

Please remember to fill out you evaluations and drop at the back of the room THANKS !!!!!!

130

Questions and Answers

Contact me at: Email: pcalhoun@nnsu.com I am available for Consulting and Mentoring on Domino, Java, Web Services and XPages !!!!!
131

Legal Disclaimer
IBM Corporation 2009. All Rights Reserv ed. The inf ormation contained in this publication is prov ided f or inf ormational purposes only . While ef f orts were made to v erif y the completeness and accuracy of the inf ormation contained in this publication, it is prov ided AS IS without warranty of any kind, express or implied. In addition, this inf ormation is based on IBMs current product plans and strategy , which are subject to change by IBM without notice. IBM shall not be responsible f or any damages arising out of the use of , or otherwise related to, this publication or any other materials. Nothing contained in this publication is intended to, nor shall hav e the ef f ect of , creating any warranties or representations f rom IBM or its suppliers or licensors, or altering the terms and conditions of the applicable license agreement gov erning the use of IBM sof tware. Ref erences in this presentation to IBM products, programs, or serv ices do not imply that they will be av ailable in all countries in which IBM operates. Product release dates and/or capabilities ref erenced in this presentation may change at any time at IBMs sole discretion based on market opportunities or other f actors, and are not intended to be a commitment to f uture product or f eature av ailability in any way . Nothing contained in these materials is intended to, nor shall hav e the ef f ect of , stating or imply ing that any activ ities undertaken by y ou will result in any specif ic sales, rev enue growth or other results.

If the text contains perf ormance statistics or ref erences to benchmarks, insert the f ollowing language; otherwise delete: Perf ormance is based on measurements and projections using standard IBM benchmarks in a controlled env ironment. The actual throughput or perf ormance that any user will experience will v ary depending upon many f actors, including considerations such as the amount of multiprogramming in the user's job stream, the I/O conf iguration, the storage conf iguration, and the workload processed. Theref ore, no assurance can be giv en that an indiv idual user will achiev e results similar to those stated here.

If the text includes any customer examples, please conf irm we hav e prior written approv al f rom such customer and insert the f ollowing language; otherwise delete: All customer examples described are presented as illustrations of how those customers hav e used IBM products and the results they may hav e achiev ed. Actual env ironmental costs and perf ormance characteristics may v ary by customer.

Please rev iew text f or proper trademark attribution of IBM products. At f irst use, each product name must be the f ull name and include appropriate trademark sy mbols (e.g., IBM Lotus Sametime Uny te). Subsequent ref erences can drop IBM but should include the proper branding (e.g., Lotus Sametime Gateway , or WebSphere Application Serv er). Please ref er to http://www.ibm.com/legal/copy trade.shtml f or guidance on which trademarks require the or sy mbol. Do not use abbrev iations f or IBM product names in y our presentation. All product names must be used as adjectiv es rather than nouns. Please list all of the trademarks that y ou use in y our presentation as f ollows; delete any not included in y our presentation. IBM, the IBM logo, Lotus, Lotus Notes, Notes, Domino, Quickr, Sametime, WebSphere, UC2, PartnerWorld and Lotusphere are trademarks of International Business Machines Corporation in the United States, other countries, or both. Uny te is a trademark of WebDialogs, Inc., in the United States, other countries, or both. If y ou ref erence Adobe in the text, please mark the f irst use and include the f ollowing; otherwise delete: Adobe, the Adobe logo, PostScript, and the PostScript logo are either registered trademarks or trademarks of Adobe Sy stems Incorporated in the United States, and/or other countries. If y ou ref erence Jav a in the text, please mark the f irst use and include the f ollowing; otherwise delete: Jav a and all Jav a-based trademarks are trademarks of Sun Microsy stems, Inc. in the United States, other countries, or both. If y ou ref erence Microsof t and/or Windows in the text, please mark the f irst use and include the f ollowing, as applicable; otherwise delete: Microsof t and Windows are trademarks of Microsof t Corporation in the United States, other countries, or both. If y ou ref erence Intel and/or any of the f ollowing Intel products in the text, please mark the f irst use and include those that y ou use as f ollows; otherwise delete: Intel, Intel Centrino, Celeron, Intel Xeon, Intel SpeedStep, Itanium, and Pentium are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States and other countries. If y ou ref erence UNIX in the text, please mark the f irst use and include the f ollowing; otherwise delete: UNIX is a registered trademark of The Open Group in the United States and other countries. If y ou ref erence Linux in y our presentation, please mark the f irst use and include the f ollowing; otherwise delete: Linux is a registered trademark of Linus Torv alds in the United States, other countries, or both. Other company , product, or serv ice names may be trademarks or serv ice marks of others. If the text/graphics include screenshots, no actual IBM employ ee names may be used (ev en y our own), if y our screenshots include f ictitious company names (e.g., Renov ations, Zeta Bank, Acme) please update 132 and insert the f ollowing; otherwise delete:

S-ar putea să vă placă și