Příprava studijního programu Informatika je podporována projektem financovaným z Evropského sociálního fondu a rozpočtu hlavního města Prahy. Praha & EU: Investujeme do vaší budoucnosti Enterprise Java (BI-EJA) Technologie programování v jazyku Java (X36TJV) Katedra softwarového inženýrství Fakulta informačních technologií ČVUT v Praze Letní semestr 2010/2011, přednáška č. 7 Zdeněk Troníček, 2011
Agenda Java API for XML Binding (JAXB) Webové služby Java API for XML Web Services (JAX-WS) Java API for RESTful Web Services (JAX-RS) 2
XML (opak.) značkovací jazyk stejně jako HTML všechny tagy musí být uzavřeny a nesmí se křížit hodnoty atributů musí být uzavřeny v uvozovkách nebo apostrofech rozlišují se velká a malá písmena přípustné značky definuje např. DTD nebo XML schéma Znakové entity: & ' " < > Komentáře: <!-- This is a comment --> 3
Terminologie <message> start tag attribute element <priority type="urgent"/> <to>you@fit.cvut.cz</to> <from>me@fit.cvut.cz</from> empty element subelements <subject>car lights on</subject> </message> end tag 4
Well-formed & Valid XML Well-formed splňuje pravidla XML syntaxe Valid well-formed a podle připojeného DTD nebo XML schématu Parser validating non-validating Document Type Definition (DTD) <!DOCTYPE articles [ <!ELEMENT articles (article*)> <!ELEMENT article (articledata+)> <!ELEMENT articledata (title, author)> <!ELEMENT title (#PCDATA)> <!ELEMENT author (#PCDATA)> ]> 5
XML schéma umožňuje přesnější definici struktury než DTD obsahuje podporu typů, např. string, date, time, decimal telefonní číslo ve tvaru XX-XXXX <xsd:simpletype name="phone"> <xsd:restriction base="xsd:string"> <xsd:pattern value="\d{2}-\d{4}"/> </xsd:restriction> </xsd:simpletype> omezení rozsahu na interval <1,100) <xsd:simpletype name="age"> <xsd:restriction base="xsd:integer"> <xsd:mininclusive value="1"/> <xsd:maxexclusive value="100"/> </xsd:restriction> </xsd:simpletype> 6
Java API for XML Binding (JAXB) XML schema bind JAXB classes follows instances of document unmarshal marshal objects 7
Binding Compiler XML schema binding compiler schema-derived classes and interfaces <complextype name="itemtype"> <xsd:sequence> <xsd:element name="name" type="xsd:string"/>... public class ItemType { public String getname() public void setname(string n)... } </complextype> 8
Mapping @XmlRootElement @XmlType( proporder = {"name", "email", "phones"} ) public class Customer { @XmlElement public String getname() { return name; } } @XmlList public List<String> getphones() { return phones; } 9
Unmarshalling Content Objects XML document JAXB API JAXBContext ctx = JAXBContext.newInstance( "my.package" ); Unmarshaller u = ctx.createunmarshaller(); AddressBookType addrbook = (AddressBookType) u.unmarshal( new File( "addressbook.xml" )); 10
Mashalling Content Objects JAXB API XML document Marshaller m = ctx.createmarshaller(); m.setproperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE ); m.marshal( addrelement, System.out ); 11
Webová služba "A Web Service is a software component that is described via WSDL and is capable of being accessed via standard network protocols such as but not limited to SOAP over HTTP." distributed, loosely coupled, self-contained unit self-describing published, located, and accessed over the Internet language and platform neutral relies on standard Internet and XML-based protocols 12
Srovnání s RMI Remote Method Invocation within enterprise tied to a set of languages tightly-coupled firewall-unfriendly (to some extent) efficient processing Web services between enterprises language independent loosely-coupled firewall-friendly inefficient processing 13
Web Service Elements Client XML-based messages (SOAP) HTTP, HTTPS Service Service registry 14
Životní cyklus Web Service Provider 1 create, assemble, and deploy Service Description 2 publish Web Service Registry Service Registry Entry 6 access service 3 search Client Provider 5 create client 4 retrieve service information Web Service Client 15
UDDI who businessentity tmodel 1..1 0..* what businessservice Service registry public private hybrid 1..1 0..* 0..* bindingtemplate where/how 16
Web Service Description Language <definitions targetnamespace="http://ws/" name="stockservice"> <types>... </types> <message>... </message> <porttype>... </porttype> <binding>... </binding> <port>... </port> <service>... </service> adresa datové typy zprávy operace protokol a formát dat kolekce portů abstract concrete 17 </definitions>
WSDL příklad(1) <xs:complextype name="getquote"> <xs:sequence> <xs:element name="stock" type="xs:string" minoccurs="0"/> </xs:sequence> </xs:complextype> <xs:complextype name="getquoteresponse"> <xs:sequence> <xs:element name="return" type="xs:int"/> </xs:sequence> </xs:complextype> 18
WSDL příklad(2) <message name="getquote"> <part name="parameters" element="tns:getquote"/> </message> <message name="getquoteresponse"> <part name="parameters" element="tns:getquoteresponse"/> </message> <porttype name="stockexchange"> <operation name="getquote"> <input message="tns:getquote"/> <output message="tns:getquoteresponse"/> </operation> </porttype> 19
WSDL příklad(3) <binding name="stockexchangeportbinding" type="tns:stockexchange"> <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/> <operation name="getquote"> <soap:operation soapaction=""/> <input><soap:body use="literal"/></input> <output><soap:body use="literal"/></output> </operation> </binding> <service name="stockexchangeservice"> <port name="stockexchangeport" binding="tns:stockexchangeportbinding"> <soap:address location="http://localhost:1234/stockws/stockexchangeservice"/> </port> </service> 20
SOAP Java objects and primitive values marshalling SOAP message SOAP message Internet unmarshalling Utility wsgen wsimport 21
Java API for XML Web Services (JAX-WS) Client Service @WebService public class StockExchange { @WebMethod Stub Tie public BigDecimal getquote( @WebParam( name = "stock" ) String stock ) { Web Service Runtime Internet and XML-based protocols Web Service Runtime } }... 22
SOAP over HTTP HTTP request HTTP header HTTP body SOAP message SOAP Message SOAP envelope SOAP header header entry header entry XML namespace definitions Data encoding rules Attributes User authentication SOAP body body entry body entry Serialized data 23
Representational State Transfer (REST) architecture style alternativa k SOAPu založeno na pojmu resource každý resource je identifikován jednoznačným URI HTTP slouží jako aplikační protokol HTTP method POST GET PUT DELETE action CREATE RETRIEVE UPDATE DELETE 24
REST: postup 1. identifikujeme zdroje (resources) 2. každému zdroji přiřadíme jednoznačné URI 3. pro každý zdroj zvolíme příkazy (GET, POST, ) 4. vytvoříme XML reprezentaci zdrojů (zdroje propojujeme odkazy) Příklad: knihovna Zdroje: knihy, kategorie, 25
Příklad: knihovna (1) resource URI method representation kniha book/[id] GET PUT DELETE kategorie category/ GET PUT popis knihy popis knihy seznam kategorií seznam kategorií knihy v dané kategorii category/ [kategorie] GET PUT seznam knih seznam knih POST seznam knih 26
Příklad: knihovna (2) Category <category uri=" "> <name>travel</name> <book uri=" "/> <book uri=" "/> </category> Book <book uri=" "> <id>1</id> <title>cesta na sever</title> <author>karel Čapek</author> <pages>292</pages> </book> 27
Java API for RESTful Services (JAX-RS) resource path @Path( "book/{id}" ) public class BookResource { } @GET HTTP method path parameter output @Produces( "application/xml" ) @GET @POST @PUT @DELETE public BookConverter read( @PathParam( "id" ) Long id ) { } 28
Parameters @CookieParam @FormParam @HeaderParam @MatrixParam @PathParam @QueryParam Matrix parameters @PUT input @Consumes( "application/xml" ) public void update( BookConverter data ) { } JAXB class resources/map;lat=50;long=20;scale=32000 29
Otázky & odpovědi tronicek@fit.cvut.cz