scdjws 6. rest jax-p

Download SCDJWS 6. REST  JAX-P

If you can't read please download the document

Upload: francesco-ierna

Post on 16-Apr-2017

1.072 views

Category:

Technology


0 download

TRANSCRIPT

PRESENTATION NAME

REST, JSON, SOAP and XML Processing

Francesco Ierna

Rest

Rest: REST defines a set of architectural principles by which you can design Web services that focus on a system's resources, including how resource states are addressed and transferred over HTTP by a wide range of clients written in different languages. A REST web service provides a way to retrieve a representation of such a resource and to manipulate resources using a limited set of verbs. Main interest are the URI and the HTTP methodThe information that selects which resource to operate on is kept in an URI.

Every request to a REST web service happens in complete isolation

Resources are manipulated by exchanging representations of the resources

REST web services typically allow for the resource representation to be in a format selected by the client at the time of the request

Using:

explicits use of HTTP methods in a way that follows the protocol as defined by RFC 2616. with HTTP, these operations are the HTTP operations GET, POST, PUT, DELETE

Problems:Using GET is not very sure.to move the parameter names and values on the request URI into XML tags and to use POST in which we put the xml as body

Rest

Rest: REST defines a set of architectural principles by which you can design Web services that focus on a system's resources, including how resource states areaddressed and transferred over HTTP by a wide range of clients written in different languagesmapping between create, read, update, and delete (CRUD) operations and HTTP methods.To create a resource on the server, use POST.

To retrieve a resource, use GET.

To change the state of a resource or to update it, use PUT.

To remove or delete a resource, use DELETE.

Stateless: are less complicated to design, write, and distribute across load-balanced serversServer: Generates responses that include links to other resources to allow applications to navigate between related ressources

Client application: Uses the Cache-Control response header to determine whether to cache the resource (make a local copy of it) or not. A 304 HTTP response code means the client can safely use a cached

Expose directory structure-like URIs: should be intuitive to the point where they are easy to guessThis type of URI is hierarchical, rooted at a single path, and branching from it are subpaths that expose the service's main areas: http://www.myservice.org/discussion/2008/12/10/{topic}

Hide the server-side scripting technology file extensions, Substitute spaces with hyphens or underscores, Avoid query strings as much as you can, Instead of using the 404 code always provide a default page or resource as a response

Rest Overview

JSON

JSON support is implemented as a custom binding. So just like there are SOAP/HTTP binding or Plain Old XML binding, you can specify JSON binding to expose a

Such web services can be JAX-WS web services or REST web services

JSON text can be dynamically executed as JavaScript

JSON is not as verbose as XML while retaining some of the flexibility and extensibility

JSON

JSON Types

Pro REST/SOAP

REST OK when:

Are completely stateless

A caching infrastructure can be leveraged for performance

The service producer and service consumer have a mutual understanding of the context and content being passed along

Bandwidth is particularly important and needs to be limited. PDAs and mobile phones

Web service delivery or aggregation into existing web sites can be enabled easily with a RESTful style. Asynchronous JavaScript with XML (Ajax) and toolkits such as Direct Web Remoting (DWR) to consume the services in their web applications

SOAP OK when:

A formal contract must be established to describe the interface that the web service offers

The architecture must address complex nonfunctional requirements

The architecture needs to handle asynchronous processing and invocation

Pro REST/SOAP

Why REST/SOAP

REST OK when:

Serializing simpler data structures, as opposed to documents like web pages

Clients are AJAX clients.

Bandwidth usage needs to be minimized

Validation of the format and contents of the data is not required.

SOAP OK when:You want to ensure that the data returned by the web service can not be evaluated

Format, and to some extent the contents, of the data sent to and received from the web service needs to be validated.

Better tooling is required

Reuse of existing data structure definitions is desired

JAXP

JAXP: The Java API for XML Processing (JAXP) is for processing XML data using applications written in the Java programming languageSAX, DOM, XML, StAX, XSLT, Xpath, XInclude

supports the Extensible Stylesheet Language Transformations (XSLT) standard

JAXP also provides namespace support, allowing you to work with DTDs that might otherwise have naming conflicts

SAX

SAX: provides an event-driven, serial access mechanism that processes XML data one element at a time. SAX is a push API, which means that the client implements callbacks that are invoked as certain data, such as elements, are encountered in the document being parsedObjects

SAXParserFactory: creates an instance of the parser determined by the system property

SAXParser: The SAXParser interface defines several kinds of parse() methods

SAXReaderIt is the SAXReader that carries on the conversation with the SAX event handlers you define

Events:DefaultHandler: you can override only the ones you're interested in

ContentHandler: are invoked when an XML tag is recognized

ErrorHandler: are invoked in response to various parsing errors

DTDHandler: Defines methods you will generally never be called upon to use

EntityResolver: The resolveEntity method is invoked when the parser must identify data identified by a URI. In most cases

When we should use SAX:fast and efficient, but its event model makes it most useful for such state-independent filtering

With a pull parser, you get the next node, whatever it happens to be, at any point in the code that you ask for it

SAX requires much less memory than DOM, because SAX does not construct an internal representation

SAX Overview

SAX Example

public static void main(String argv[]) {// Use an instance of ourselves as the SAX event handlerDefaultHandler handler = new Echo();// Use the default (non-validating) parserSAXParserFactory factory = SAXParserFactory.newInstance();try {// Set up output streamout = new OutputStreamWriter(System.out, "UTF8");// Parse the inputSAXParser saxParser = factory.newSAXParser();saxParser.parse(new File(argv[0]), handler);} catch (Throwable t) {t.printStackTrace();}}

DOM

SAX: Objects

javax.xml.parsers.DocumentBuilderFactory: selects the factory implementation that is used to produce the builder

DocumentBuilder.newDocument(): method to create an empty Document that implements the org.w3c.dom.Document interface

Parse: to create a Document from existing XML data

When we should use DOM:is platform-neutral and language-neutral API that enables programs to dynamically update the contents of XML documents

allows extreme flexibility in parsing, navigating, and updating the contents of a document

high memory requirements and the need for more powerful processing capabilities

DOM Overview

DOM Example

public static void buildDom() {DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();try {DocumentBuilder builder = factory.newDocumentBuilder();document = builder.newDocument();Element root = (Element) document.createElement("rootElement");document.appendChild(root);root.appendChild(document.createTextNode("Some"));root.appendChild(document.createTextNode(" "));root.appendChild(document.createTextNode("text") );} catch (ParserConfigurationException pce) {// Parser with specified options can't be builtpce.printStackTrace();}}

XSLT

SAX: Objects:

TransformerFactory: used to create a Transformer

javax.xml.transform: This package defines the factory class you use to get a Transformer object

Input/ouput

transform() method to make the transformation happen

javax.xml.transform.dom: DOMSource and DOMResult classes, which let you use a DOM as an input to or output from a transformation

javax.xml.transform.sax: Defines the SAXSource and SAXResult classes, which let you use a SAX event generator as input to a transformation, or deliver SAX events as output to a SAX event processor

javax.xml.transform.stream: Defines the StreamSource and StreamResult classes, which let you use an I/O stream as an input to or output from a transformation

CURSOR API: cursor API represents a cursor with which you can walk an XML document from beginning to endXMLStreamReader; XML Information model, including document encoding, element names, attributes, namespaces, text nodes, start tags, comments, processing instructions, document boundaries

ITERATOR API: iterator API represents an XML document stream as a set of discrete event objects. These events are pulled by the application and provided by the parser in the order in which they are read in the source XML document

XSLT Overview

XSLT Example

Example: javax.xml.transform.domDocument document;try {File f = new File(argv[0]);DocumentBuilder builder = factory.newDocumentBuilder();document = builder.parse(f);// Use a Transformer for outputTransformerFactory tFactory = TransformerFactory.newInstance();Transformer transformer = tFactory.newTransformer();DOMSource source = new DOMSource(document);StreamResult result = new StreamResult(System.out);transformer.transform(source, result);}

StAX API

SAX: exposes methods for iterative, event-based processing of XML documents. XML documents are treated as a filtered series of events, and infoset states can be stored in a procedural fashion. API is bidirectional, meaning that it can both read and write XML documents

CURSOR API: cursor API represents a cursor with which you can walk an XML document from beginning to endXMLStreamReader; XML Information model, including document encoding, element names, attributes, namespaces, text nodes, start tags, comments, processing instructions, document boundaries

ITERATOR API: iterator API represents an XML document stream as a set of discrete event objects. These events are pulled by the application and provided by the parser in the order in which they are read in the source XML document

CURSOR vs ITERATOR:you can make smaller, more efficient code with the cursor API

the cursor API is more efficient.

XML processing pipelines, use the iterator API

modify the event stream, use the iterator API

to be able to handle pluggable processing of the event stream, use the iterator API

When we should use StAX:bidirectional features, small memory footprint, and low processor requirements

is that StAX is difficult to use if you return XMLdocuments that follow complex schema