c12 JSE XML JAXB JDK11 9 ReactiveStreams

Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

Lecture 12

Java XML & JSON, Reactive


Streams Programming

presentation
Java Programming – Software App Development
Cristian Toma

D.I.C.E/D.E.I.C – Department of Economic Informatics & Cybernetics


www.dice.ase.ro
Cristian Toma – Business Card
Agenda for Lecture 12

1 2 3
XML + XSD +
XPath / XSLT
Java XML &
JSON
Programming
Exchange
Ideas
1
XML, XSD, X-Path / XSLT

XML & JSON Concepts


1. XML Concepts
XML Concepts:

http://www.w3schools.com | http://www.w3schools.com/xml/default.ASP
1. XML Concepts
XML Concepts:

http://www.w3schools.com | http://www.w3schools.com/xml/default.ASP
1. XML Concepts
XML Concepts:

http://www.w3schools.com | http://www.w3schools.com/xml/default.ASP
1. XML Concepts
XML Concepts – What about JSON?:

http://www.w3schools.com | http://www.w3schools.com/xml/default.ASP
1. XML Concepts
XML Concepts:

http://www.w3schools.com | http://www.w3schools.com/xml/default.ASP
1. XML Concepts
XML Concepts:

The root element in the example is <bookstore>. All


<book> elements in the document are contained
within <bookstore>.

The <book> element has 4 children: <title>,<


author>, <year>, <price>.
http://www.w3schools.com | http://www.w3schools.com/xml/default.ASP
1. XML Concepts
XML Concepts – Synthax:

All XML Elements Must Have a Closing Tag

In XML, it is illegal to omit the closing tag. All elements must have a closing tag:

<p>This is a paragraph.</p>
<br />

XML Tags are Case Sensitive

XML tags are case sensitive. The tag <Letter> is different from the tag <letter>.
Opening and closing tags must be written with the same case:

<Message>This is incorrect</message>
<message>This is correct</message>

Note: "Opening and closing tags" are often referred to as "Start and end tags"

http://www.w3schools.com | http://www.w3schools.com/xml/default.ASP
1. XML Concepts
XML Concepts – Synthax:
XML Elements Must be Properly Nested
In XML, all elements must be properly nested within each other:

<b><i>This text is bold and italic</i></b>

In the example above, "Properly nested" simply means that since the <i> element is
opened inside the <b> element, it must be closed inside the <b> element.

XML Documents Must Have a Root Element


XML documents must contain one element that is the parent of all other elements. This
element is called the root element.

<root>
<child>
<subchild>.....</subchild>
</child>
</root>

http://www.w3schools.com | http://www.w3schools.com/xml/default.ASP
1. XML Concepts
XML Concepts – Synthax:

XML Attribute Values Must be Quoted


XML elements can have attributes in name/value pairs just like in HTML.
In XML, the attribute values must always be quoted.
Study the two XML documents below. The first one is incorrect, the second is correct:

<note date=12/11/2007>
<to>Tove</to>
<from>Jani</from>
</note>

<note date="12/11/2007">
<to>Tove</to>
<from>Jani</from>
</note>

The error in the first document is that the date attribute in the note element is not quoted.

http://www.w3schools.com | http://www.w3schools.com/xml/default.ASP
1. XML Concepts
XML Concepts – Synthax:
Entity References
Some characters have a special meaning in XML.
If you place a character like "<" inside an XML element, it will generate an error because the parser
interprets it as the start of a new element.

This will generate an XML error:


<message>if salary < 1000 then</message>

To avoid this error, replace the "<" character with an entity reference:
<message>if salary &lt; 1000 then</message>

There are 5 predefined entity references in XML:

Comments in XML
The syntax for writing comments in XML is similar to that of
HTML.
<!-- This is a comment -->

XML Stores New Line as LF


* Windows applications store a new line as: carriage return
and line feed (CR+LF).
* Linux/Unix and Mac OSX uses LF.
http://www.w3schools.com | http://www.w3schools.com/xml/default.ASP
1. XML Concepts
What is an XML Element?
An XML element is everything from (including) the element's start tag to (including) the
element's end tag. An element can contain: * other elements, * text, * attributes, * or a
mix of all of the previous...
<bookstore>
<book category="CHILDREN">
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title>Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>

In the example above, <bookstore> and <book> have element contents, because they
contain other elements. <book> also has an attribute (category="CHILDREN"). <title>,
<author>, <year>, and <price> have text content because they contain text.
http://www.w3schools.com | http://www.w3schools.com/xml/default.ASP
1. XML Concepts
XML Concepts - Namespace:
Name Conflicts
In XML, element names are defined by the developer. This often results in a conflict when
trying to mix XML documents from different XML applications.
This XML carries HTML table information:
<table>
<tr>
<td>Apples</td>
<td>Bananas</td>
</tr>
</table>

This XML carries information about a table (a piece of furniture):


<table>
<name>African Coffee Table</name>
<width>80</width>
<length>120</length>
</table>
If these XML fragments were added together, there would be a name conflict. Both
contain a <table> element, but the elements have different content and meaning.
A user or an XML application will not know how to handle these differences.
http://www.w3schools.com | http://www.w3schools.com/xml/default.ASP
1. XML Concepts
XML Concepts - Namespaces:
XML Namespaces - The xmlns Attribute <root
When using prefixes in XML, a so-called namespace xmlns:h="http://www.w3.org/TR/html4/"
for the prefix must be defined. The namespace is xmlns:f="http://www.w3schools.com/fur
defined by the xmlns attribute in the start tag of an niture">
element. The namespace declaration has the
following syntax. xmlns:prefix="URI". In the example
<h:table>
above, the xmlns attribute in the <table> tag give the
h: and f: prefixes a qualified namespace. <h:tr>
When a namespace is defined for an element, all <h:td>Apples</h:td>
child elements with the same prefix are associated <h:td>Bananas</h:td>
with the same namespace. Namespaces can be </h:tr>
declared in the elements where they are used or in </h:table>
the XML root element.
<f:table>
Note: The namespace URI is not used by the parser
<f:name>African Coffee Table</f:name>
to look up information.
The purpose is to give the namespace a unique <f:width>80</f:width>
name. However, often companies use the <f:length>120</f:length>
namespace as a pointer to a web page containing </f:table>
namespace information.
Try to go to http://www.w3.org/TR/html4/ </root>
http://www.w3schools.com | http://www.w3schools.com/xml/default.ASP
1. XML Concepts
Validating XML – XSD – XML Schema:
An XML Schema describes the structure of The XML Schema is interpreted like this:
an XML document, just like a DTD. § <xs:element name="note"> defines the
An XML document with correct syntax is element called "note“
called "Well Formed". § <xs:complexType> the "note" element is a
An XML document validated against an XML complex type
Schema is both "Well Formed" and "Valid". § <xs:sequence> the complex type is a
sequence of elements
XML Schema § <xs:element name="to" type="xs:string">
the element "to" is of type string (text)
<xs:element name="note">
§ <xs:element
<xs:complexType> name="from" type="xs:string"> the
<xs:sequence> element "from" is of type string
<xs:element name="to" type="xs:string"/> § <xs:element
<xs:element name="from" type="xs:string"/> name="heading" type="xs:string"> the
<xs:element name="heading" type="xs:string"/> element "heading" is of type string
<xs:element name="body" type="xs:string"/> § <xs:element
</xs:sequence> name="body" type="xs:string"> the
</xs:complexType>
element "body" is of type string
</xs:element> Everything is wrapped in "Well Formed" XML.
http://www.w3schools.com | http://www.w3schools.com/xml/default.ASP
1. XML Concepts
XML Schema:
Why Use an XML Schema?
With XML Schema, your XML files can carry a description of its own format.
With XML Schema, independent groups of people can agree on a standard for interchanging
data.
With XML Schema, you can verify data

XML Schemas Support Data Types


One of the greatest strength of XML Schemas
XML Schemas are More Powerful than DTD
is the support for data types:
XML Schemas are written in XML
It is easier to describe document content
XML Schemas are extensible to additions
It is easier to define restrictions on data
XML Schemas support data types
It is easier to validate the correctness of data
XML Schemas support namespaces
It is easier to convert data between different
data types

http://www.w3schools.com | http://www.w3schools.com/xml/default.ASP
1. XML Concepts
XML Path: is a language for finding information in an XML document.

§ XPath is a syntax for defining parts of an XML document


§ XPath uses path expressions to navigate in XML documents
§ XPath contains a library of standard functions
§ XPath is a major element in XSLT
§ XPath is also used in XQuery, XPointer and XLink
§ XPath is a W3C recommendation

XPath Path Expressions


XPath uses path expressions to select nodes or node-sets in an XML document. These
path expressions look very much like the expressions you see when you work with a
traditional computer file system.
Today XPath expressions can also be used in JavaScript, Java, XML Schema, PHP, Python,
C and C++, and lots of other languages

XPath is Used in XSLT


XPath is a major element in the XSLT standard. Without XPath knowledge you will not be
able to create XSLT documents.
Xpath + XSLT Transformations + JSON should be detailed
http://www.w3schools.com | http://www.w3schools.com/xml/default.ASP
Section Conclusion
Java is working with
Fact:

various data structures


encoding
In few samples it is simple to understand: XML and
JSON.
2
Java XML – SAX, DOM, XSLT, XPath, JAXB 2, org.json

Java XML & JSON Programming


2. Java XML Programming – see XML Samples
2. Java JSON Programming – see JSON samples
Section Conclusions
Please review Java XML and JSON samples.

Java XML-JSON Programming


for easy sharing
3
Java Programming & XML | JSON

Communicate & Exchange Ideas


?
Questions & Answers!

But wait…
There’s More!
3. Java 9+ and 11 Reactive Streams
Java 9 Reactive Streams
Reactive Streams is about asynchronous processing of stream, so there should be
a Publisher and a Subscriber. The Publisher publishes the stream of data and the Subscriber
consumes the data.

Sometimes it is necessary to transform the data between Publisher and Subscriber. Processor is the
entity sitting between the end publisher and subscriber to transform the data received from publisher
so that subscriber can understand it. It is possible to have a chain of processors. Processor works both
as Subscriber and a Publisher.

Copyright: https://www.journaldev.com/20723/java-9-reactive-streams
3. Java 9+ and 11 Reactive Streams
The new Flow API in Java 9 follows
the Reactive Streams
Specification and is aligned with the
paradigms of the Reactive Manifesto:
Responsive, Resilient, Elastic,
Message Driven.

The reactive streams can be used


with:
• Java 9 and the Flow API,
• RxJava2,
• Akka,
• Reactor

Copyright:
https://www.hascode.com/2018/01/reactive-
streams-java-9-flow-api-rxjava-and-reactor-
examples/
3. Java 9+ and 11 Reactive Streams
Java 9 Flow API Classes and Interfaces
public final class Flow {
private Flow() {} // uninstantiable
@FunctionalInterface
public static interface Publisher<T> {
public void subscribe(Subscriber<? super T> subscriber);
}
public static interface Subscriber<T> {
public void onSubscribe(Subscription subscription);
public void onNext(T item);
public void onError(Throwable throwable);
public void onComplete();
}
public static interface Subscription {
public void request(long n);
public void cancel();
}
public static interface Processor<T,R> extends Subscriber<T>,
Publisher<R> {}
}
Copyright: https://dzone.com/articles/reactive-streams-in-java-9
3. Java 9+ and 11 Reactive Streams
Java 9 Flow API Classes and Interfaces

Java 9 Flow API implements the Reactive Streams Specification. Flow API is a combination
of Iterator and Observer pattern. Iterator works on pull model where application pulls items from the
source, whereas Observer works on push model and reacts when item is pushed from source to application.
Flow API classes and interfaces:

java.util.concurrent.Flow: This is the main class of Flow API. This class encapsulates all the important
interfaces of the Flow API. This is a final class and it can’t be extend.

java.util.concurrent.Flow.Publisher: This is a functional interface and every publisher has to implement it’s
subscribe method to add the given subscriber to receive messages.

java.util.concurrent.Flow.Subscriber: Every subscriber has to implement this interface. The methods in the
subscriber are invoked in strict sequential order. There are four methods in this interface:
onSubscribe: This is the first method to get invoked when subscriber is subscribed to receive messages
by publisher. Usually we invoke subscription.request to start receiving items from processor.
onNext: This method gets invoked when an item is received from publisher, this is where we
implement our business logic to process the stream and then request for more data from publisher.
onError: This method is invoked when an irrecoverable error occurs, we can do cleanup taks in this
method, such as closing database connection.
onComplete: This is like finally method and gets invoked when no other items are being produced by
publisher and publisher is closed. We can use it to send notification of successful processing of stream.
Copyright: https://www.journaldev.com/20723/java-9-reactive-streams
3. Java 9+ and 11 Reactive Streams
Java 9 Flow API Classes and Interfaces

Flow API classes and interfaces (cont.).

java.util.concurrent.Flow.Subscription: This is used to create asynchronous non-blocking


link between publisher and subscriber. Subscriber invokes its request method to demand
items from publisher. It also has cancel method to cancel the subscription i.e. closing the
link between publisher and subscriber.

java.util.concurrent.Flow.Processor: This interface extends both Publisher and Subscriber,


this is used to transform the message between publisher and subscriber.

java.util.concurrent.SubmissionPublisher: A Publisher implementation that asynchronously


issues submitted items to current subscribers until it is closed. It uses Executor framework
We will use this class in reactive stream examples to add subscriber and then submit items
to them.

Copyright: https://www.journaldev.com/20723/java-9-reactive-streams
3. Java 9+ and 11 Reactive Streams
Reactive Streams - Publishers, Subscribers, and Subscriptions
Instead of having a client and server style of data handling, where a client requests data from a server and
the server responds, possibly asynchronously, to the client with the requested data, we instead use a
publish-subscribe mechanism: A subscriber informs a publisher that it is willing to accept a given number
of items (requests a given number of items), and if items are available, the publisher pushes the maximum
receivable number of items to the subscriber. It is important to note that this is a two-way communication,
where the subscriber informs the publisher how many items it is willing to handle and the publisher
pushes that number of items to the subscriber.

The process of restricting the number of items that a subscriber is willing to accept (as judged by the
subscriber itself) is called backpressure and is essential in prohibiting the overloading of the subscriber
(pushing more items that the subscriber can handle). This scheme is illustrated in the figure below.
When publisher is producing messages in much faster rate than it’s being consumed by subscriber, back
pressure gets built. Java 9 Flow API doesn’t provide for the moment any mechanism to signal about back
pressure or to deal with it. But we can devise our own strategy to deal with it, such as fine tuning the
subscriber or reducing the message producing rate.

Copyright: https://dzone.com/articles/reactive-streams-in-java-9
3. Java 9+ and 11 Reactive Streams
Reactive Streams - Publishers,
Subscribers, and Subscriptions

This two-way connection between a publisher and a


subscriber is called a subscription. This subscription binds a
single publisher to a single subscriber (one-to-one
relationship) and may be unicast or multicast. Likewise, a
single publisher may have multiple subscribers subscribed
to it, but a single subscriber may only be subscribed to a
single producer (a publisher may have many subscribers,
but a subscriber may subscribe to at most one publisher).
When a subscriber subscribes to a publisher, the publisher
notifies the subscriber of the subscription that was created,
allowing the subscriber to store a reference to the
subscription (if desired). Once this notification process is
completed, the subscriber can inform the publisher that it is
ready to receive some n number of items.
When the publisher has items available, it then sends at
most n number of items to the subscriber. If an error occurs
in the publisher, it signals the subscriber of the error. If the
publisher is permanently finished sending data, it signals
the subscriber that it is complete. If the subscriber is
notified that either an error occurred or the publisher is
complete, the subscription is considered canceled and no
more interactions between the publisher and subscriber (or
the subscription) will take place. This subscription workflow
is illustrated in the figure below.

Copyright: https://dzone.com/articles/reactive-streams-in-java-9
3. Java 9+ and 11 Reactive Streams
Reactive Streams - Publishers, Subscribers, and Subscriptions
It is important to note that there are two theoretical approaches to streaming data to a subscriber:
(1) the subscription holds the items or
(2) the publisher holds the items.
In the first case, the publisher pushes items to the subscription when they become available; when, at a later time, the subscriber
requests n items, the subscription provides n or fewer items it has previously been given by the publisher. This may be used when the
publisher manages queued items, such as incoming HTTP requests.
In the second case, the subscriber forwards requests to the publisher, which pushes n or fewer items to the subscription, which in turn
pushes those same items to the subscriber. This scenario may be more suitable for instances were items are generated as needed, such as
with a prime number generator.

For example, suppose a subscriber requests 5 items and 7 are currently available in the publisher. The outstanding demand for the subscriber
is 5 so 5 of the 7 items are pushed to the subscriber. The remaining 2 items are maintained by the publisher, awaiting the subscriber to
request more items. If the subscriber then requests 10 more items, the 2 remaining items are pushed to the subscriber, resulting in an
outstanding demand of 8. If 5 more items become available in the publisher, these 5 items are pushed to the subscriber, leaving an
outstanding demand of 3. The outstanding demand will remain at 3 unless the subscriber requests n more items, in which case the
outstanding demand will increase to 3 + n, or more i items are pushed to the subscriber, in which case the outstanding demand will decrease
to 3 - i (to a minimum of 0).

If an entity is both a publisher and a subscriber, it is called a processor. A processor commonly acts as an intermediary between another
publisher and subscriber (either of which may be another processor), performing some transformation on the stream of data. For example, a
processor can be created that filters out items that match some criteria before passing them onto its subscriber. A visual representation of a
processor is illustrated in the figure below.

Copyright: https://dzone.com/articles/reactive-streams-in-java-9
What’s
Thanks!Your Message?

Java SE
End of Lecture 12 – XML | JSON Programming

You might also like