This document provides an overview of several technologies for asynchronous communication between client and server: Server Sent Events (SSE), WebSockets, JSON-P, JAXRS 2.0, and AsyncServlet. It describes how SSE allows a server to push data to clients via an event stream, discusses the WebSocket protocol for full-duplex communication, and explains how JSON-P and JAXRS 2.0 support processing JSON on the Java platform. Code samples are provided for using these technologies. The document concludes by describing a demo application that integrates several of these techniques to asynchronously retrieve and display Twitter data.
What do you mean, Backwards Compatibility?Trisha Gee
Lessons learnt developing the new Java driver for MongoDB. This is a totally different version of my backwards compatibility talk, delivered at JFokus.
Webinar: Building Your First App with MongoDB and JavaMongoDB
This webinar will walk you through building a simple Java-based application in MongoDB. We’ll cover the basics of MongoDB’s document model, query language, aggregation framework, and deployment architecture.
In this webinar, you will discover:
- How easy it is to start building Java applications with MongoDB
- Key features for manipulating and accessing data
- High availability and scale-out architecture
- WriteConcerns and ReadPreference
Application Continuity with Oracle DB 12c Léopold Gault
Application Continuity is a feature of Oracle database 12c, when used through the JDBC replay driver (by java applications). You can benefit from this features when using a RAC or Data Guard.Those are my personal notes on the subject. Views expressed here are my own, and do not necessarily reflect the views of Oracle.
MongoDB Days Silicon Valley: Winning the Dreamforce Hackathon with MongoDBMongoDB
Presented by Greg Deeds, CEO, Technology Exploration Group
Experience level: Introductory
A two person team using MongoDB and Salesforce.com created a geospatial machine learning tool from various datasets, parsing, indexing, and mapreduce in 24 hours. The amazing hack that beat 350 teams from around the world designer Greg Deeds will speak on getting to the winners circle with MongoDB power. It was MongoDB that proved to be the teams secret weapon to level the playing field for the win!
Speaker: Charlie Swanson, Software Engineer, MongoDB
Level: 200 (Intermediate)
Track: How We Build MongoDB
Learn how MongoDB answers your queries from a query system engineer. If you've ever had a performance problem with a query but didn't know how to find the cause, or if you've ever needed to confirm that your shiny new index is being put to work, the explain command is an excellent place to start. MongoDB's explain system is a powerful tool for solving this type of problem, but can be intimidating and unwieldy to use. In this talk, we will discuss how the explain command works and break down its output into digestible pieces.
What You Will Learn:
- Exactly how indexes are used during your queries and aggregations
- How to diagnose your poorly performing operations
- How to tune your most important operations to ensure that they scale seamlessly
What do you mean, Backwards Compatibility?Trisha Gee
Lessons learnt developing the new Java driver for MongoDB. This is a totally different version of my backwards compatibility talk, delivered at JFokus.
Webinar: Building Your First App with MongoDB and JavaMongoDB
This webinar will walk you through building a simple Java-based application in MongoDB. We’ll cover the basics of MongoDB’s document model, query language, aggregation framework, and deployment architecture.
In this webinar, you will discover:
- How easy it is to start building Java applications with MongoDB
- Key features for manipulating and accessing data
- High availability and scale-out architecture
- WriteConcerns and ReadPreference
Application Continuity with Oracle DB 12c Léopold Gault
Application Continuity is a feature of Oracle database 12c, when used through the JDBC replay driver (by java applications). You can benefit from this features when using a RAC or Data Guard.Those are my personal notes on the subject. Views expressed here are my own, and do not necessarily reflect the views of Oracle.
MongoDB Days Silicon Valley: Winning the Dreamforce Hackathon with MongoDBMongoDB
Presented by Greg Deeds, CEO, Technology Exploration Group
Experience level: Introductory
A two person team using MongoDB and Salesforce.com created a geospatial machine learning tool from various datasets, parsing, indexing, and mapreduce in 24 hours. The amazing hack that beat 350 teams from around the world designer Greg Deeds will speak on getting to the winners circle with MongoDB power. It was MongoDB that proved to be the teams secret weapon to level the playing field for the win!
Speaker: Charlie Swanson, Software Engineer, MongoDB
Level: 200 (Intermediate)
Track: How We Build MongoDB
Learn how MongoDB answers your queries from a query system engineer. If you've ever had a performance problem with a query but didn't know how to find the cause, or if you've ever needed to confirm that your shiny new index is being put to work, the explain command is an excellent place to start. MongoDB's explain system is a powerful tool for solving this type of problem, but can be intimidating and unwieldy to use. In this talk, we will discuss how the explain command works and break down its output into digestible pieces.
What You Will Learn:
- Exactly how indexes are used during your queries and aggregations
- How to diagnose your poorly performing operations
- How to tune your most important operations to ensure that they scale seamlessly
JSON stands for JavaScript Object Notation. JSON objects are used for transferring data between server and client.
JSON is a subset of JavaScript. ( ECMA-262 ).
Language Independent, means it can work well with most of the modern programming language
Text-based, human readable data exchange format
Light-weight. Easier to get and load the requested data quickly.
Easy to parse.
JSON has no version and No revisions to the JSON grammar.
JSON is very stable
Character Encoding is Strictly UNICODE. Default: UTF-8. Also UTF-16 and UTF-32 are allowed.
official Internet media type for JSON is application/json.
JSON Is Not XML.
JSON is a simple, common representation of data.
AJAX:
AJAX, or Asynchronous JavaScript and XML.
Describes a Web development technique for creating interactive Web applications using a combination of HTML (or XHTML) and Cascading Style Sheets for presenting information; Document Object Model (DOM).
JavaScript, to dynamically display and interact with the information presented; and the XMLHttpRequest object to interchange and manipulate data asynchronously with the Web server.
It allows for asynchronous communication, Instead of freezing up until the completeness, the browser can communicate with server and continue as normal.
Database Trends for Modern Applications: Why the Database You Choose Matters MongoDB
Matt Kalan, Senior Solutions Architect, MongoDB
Matt will explain how modern technology requirements have changed the requirements of the database. In order to handle agile development, big data, cloud, APIs, continuous availability, and unlimited scale while lowering costs, new capabilities are required. Do you need to tolerate the impedance mismatch between an object model and the relational model, or is there another way? We will walk through the application development process, to the code level, to compare using an RDBMS with MongoDB.
MongoDB + Java - Everything you need to know Norberto Leite
Learn everything you need to know to get started building a MongoDB-based app in Java. We'll explore the relationship between MongoDB and various languages on the Java Virtual Machine such as Java, Scala, and Clojure. From there, we'll examine the popular frameworks and integration points between MongoDB and the JVM including Spring Data and object-document mappers like Morphia.
Back to Basics: My First MongoDB ApplicationMongoDB
This Back to Basics webinar series will introduce you to NoSQL and the MongoDB database. You will find out what MongoDB is, why you would use it, and what you would use it for.
MongoDB .local Chicago 2019: Practical Data Modeling for MongoDB: TutorialMongoDB
For 30 years, developers have been taught that relational data modeling was THE way to model, but as more companies adopt MongoDB as their data platform, the approaches that work well in relational design actually work against you in a document model design. In this talk, we will discuss how to conceptually approach modeling data with MongoDB, focusing on practical foundational techniques, paired with tips and tricks, and wrapping with discussing design patterns to solve common real world problems.
High Performance Python Microservice CommunicationJoe Cabrera
Python Microservices are becoming increasingly popular for large scale web applications. We’ll start by talking about some of the trade-offs of different microservice communication designs. Afterwards we’ll dive into code regarding specific configurations including RPC and traditional REST.
Development time is wasted as the bulk of the work shifts from adding business features to struggling with the RDBMS. MongoDB, the leading NoSQL database, offers a flexible and scalable solution.
Let if flow: Java 8 Streams puzzles and moreBhakti Mehta
This talk covers Java 8 Streams in details and using programming puzzles will discuss about various techniques with Streams: how to do complex data processing , queries with Streams API, how to use all the goodies like map, flatMap,filter, how to group, and partition data, how to use infinite streams, parallel streams, creating lazy lists.
If you are a beginner or a pro with Java 8 wanting to challenge your knowledge there is something for all!
JSON stands for JavaScript Object Notation. JSON objects are used for transferring data between server and client.
JSON is a subset of JavaScript. ( ECMA-262 ).
Language Independent, means it can work well with most of the modern programming language
Text-based, human readable data exchange format
Light-weight. Easier to get and load the requested data quickly.
Easy to parse.
JSON has no version and No revisions to the JSON grammar.
JSON is very stable
Character Encoding is Strictly UNICODE. Default: UTF-8. Also UTF-16 and UTF-32 are allowed.
official Internet media type for JSON is application/json.
JSON Is Not XML.
JSON is a simple, common representation of data.
AJAX:
AJAX, or Asynchronous JavaScript and XML.
Describes a Web development technique for creating interactive Web applications using a combination of HTML (or XHTML) and Cascading Style Sheets for presenting information; Document Object Model (DOM).
JavaScript, to dynamically display and interact with the information presented; and the XMLHttpRequest object to interchange and manipulate data asynchronously with the Web server.
It allows for asynchronous communication, Instead of freezing up until the completeness, the browser can communicate with server and continue as normal.
Database Trends for Modern Applications: Why the Database You Choose Matters MongoDB
Matt Kalan, Senior Solutions Architect, MongoDB
Matt will explain how modern technology requirements have changed the requirements of the database. In order to handle agile development, big data, cloud, APIs, continuous availability, and unlimited scale while lowering costs, new capabilities are required. Do you need to tolerate the impedance mismatch between an object model and the relational model, or is there another way? We will walk through the application development process, to the code level, to compare using an RDBMS with MongoDB.
MongoDB + Java - Everything you need to know Norberto Leite
Learn everything you need to know to get started building a MongoDB-based app in Java. We'll explore the relationship between MongoDB and various languages on the Java Virtual Machine such as Java, Scala, and Clojure. From there, we'll examine the popular frameworks and integration points between MongoDB and the JVM including Spring Data and object-document mappers like Morphia.
Back to Basics: My First MongoDB ApplicationMongoDB
This Back to Basics webinar series will introduce you to NoSQL and the MongoDB database. You will find out what MongoDB is, why you would use it, and what you would use it for.
MongoDB .local Chicago 2019: Practical Data Modeling for MongoDB: TutorialMongoDB
For 30 years, developers have been taught that relational data modeling was THE way to model, but as more companies adopt MongoDB as their data platform, the approaches that work well in relational design actually work against you in a document model design. In this talk, we will discuss how to conceptually approach modeling data with MongoDB, focusing on practical foundational techniques, paired with tips and tricks, and wrapping with discussing design patterns to solve common real world problems.
High Performance Python Microservice CommunicationJoe Cabrera
Python Microservices are becoming increasingly popular for large scale web applications. We’ll start by talking about some of the trade-offs of different microservice communication designs. Afterwards we’ll dive into code regarding specific configurations including RPC and traditional REST.
Development time is wasted as the bulk of the work shifts from adding business features to struggling with the RDBMS. MongoDB, the leading NoSQL database, offers a flexible and scalable solution.
Let if flow: Java 8 Streams puzzles and moreBhakti Mehta
This talk covers Java 8 Streams in details and using programming puzzles will discuss about various techniques with Streams: how to do complex data processing , queries with Streams API, how to use all the goodies like map, flatMap,filter, how to group, and partition data, how to use infinite streams, parallel streams, creating lazy lists.
If you are a beginner or a pro with Java 8 wanting to challenge your knowledge there is something for all!
Resilience planning and how the empire strikes backBhakti Mehta
t is well said that "The more you sweat on the field, the less you bleed in war". Failures are an inevitable part of complex systems. Accepting that failures happen, will help you design the system's reactions to specific failures.
This talks on best practices for building resilient, stable and predictable services: preventing cascading failures, timeouts pattern, retry pattern,circuit breakers and other techniques which have been pervasively used at Blue Jeans Network. Join me in this talk which ensures that the show must go on in spite of random load, stress or other failures!
Expect the unexpected: Anticipate and prepare for failures in microservices b...Bhakti Mehta
This session covers best practices for building resilient, stable RESTful services that can survive failures in distributed environments, such as transient impulses, random load, stress, or failures from some dependent components. It focuses on various techniques such as circuit breakers, bulkheads, and fail fast to ensure that services stay up and keep running despite failures.
Real world RESTful service development problems and solutionsBhakti Mehta
Learn all you ever wanted to learn about RESTful services development challenges in large scale applications
This session is a deep dive as well as an interactive discussion on design principles, considerations, lessons learned from mistakes that can be taken into account when developing RESTful services. It will cover a variety of topics from Designing of RESTful resources, Versioning, Exception Handling, Caching, Validation, Security, Rate limiting, HATEOAS, Testing and Documentation. This talk will walk through and compare the different REST API provided by companies like Twitter, Paypal, Google, Stripe and more we can learn the good, the bad and ugly. So join me in this talk to build high quality applications that can be highly scalable, available and reliable.
Expect the unexpected: Prepare for failures in microservicesBhakti Mehta
My talk at Confoo 2016 Montreal
It is well said that "The more you sweat on the field, the less you bleed in war". Failures are an inevitable part of complex systems. Accepting that failures happen, will help you design the system's reactions to specific failures.
This talks on best practices for building resilient, stable and predictable services:
preventing Cascading failures, Timeouts pattern, Retry pattern,Circuit breakers
and many more techniques in microservices
With the growing challenges we face with shortage of resources there is a constant need to improve scalability and performance. Fortunately Java EE 7 and Java SE 7 has provided a rich set of APIs which can be used to avoid the conventional request-response paradigm. The session will span across JSRs cover how JAX-RS, Servlets, WebSockets, EJB provide support to submit asynchronous requests and cover topics like callbacks, timeouts, client side asynchrony, API like non blocking IO and lots of good stuff from Java EE 7 and Java SE 7 . Prerequisite: An open mind and be ready to “Think async”
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!Masoud Kalali
This session focuses on how Java EE 7 provides extensive set of new and enhanced features to support standards like HTML5, WebSockets, and Server Sent Events among others.In this session we will show how these new features are designed and matched to work together for developing lightweight solutions matching end users high expectation from a web application’s responsiveness. The session will cover best practices and design patterns governing application development using JAX-RS 2.0, Async Servlet, and JSON-P (among others) as well as iterating over the pitfalls that should be avoided. During the session we will show code snippets and block diagrams that clarify use of APIs coming from the demo application we will show at the end.
Node.js is an extremely light weight framework for rapidly developing and deploying next generation web and mobile apps. It enables developers to have full stack development. Not only does it save lines of code, but also saves a lot of time in writing those critical code.
Node.js is built on open source Chrome V8 engine. Its built on top of C++ layer. JS code is compiles into machine code for blazing execution on your machine or server.
This slide gives a jump start and a sneak peak for node.js.
About Parth:
Parth Joshi is a Tech - Entrepreneur and a Corporate Trainer. He has been part of two internet startups and has been lead technical architect and project manager. He has zeal for exploring new technology and how innovation solves problems of people at large. He currently acts as consultant for various startups. He also trains tech teams to make them startup ready. For more information about how Parth can train your team visit: www.parthjoshi.in/Training
Follow him on
Twitter: twitter.com/joshiparthin
Connect with him on LinkedIN : linkedin.com/in/joshiparthin
Based on the Star Wars theme, this session focuses on how Java EE 7 provides an extensive set of new and enhanced features to support standards such as HTML5, WebSocket, and Server-sent events, among others. The session shows how these new features are designed and matched to work together for developing lightweight solutions matching end users’ high expectations for Web application responsiveness. It covers best practices and design patterns associating the technologies with analogies from Star Wars. So join me in this fun filled talk where technology meets science and innovation..
May the force be with you!
Asynchronous Web Programming with HTML5 WebSockets and JavaJames Falkner
(Talk originally given @ KCDC - http://kcdc.info ).
Over the last decade, advances in web computing have removed many of the barriers to entry for developers. New languages, frameworks, and development methodologies have kickstarted new ideas and new ways to develop web applications to make modern life easier and more efficient. WebSockets (introduced as part of HTML5) is one such technology that enables a new class of scalable, super-responsive, collaborative, and real-time web applications with a wide range of uses.
In this talk, we will first cover the basics of asynchronous web programming using WebSockets, including predecessors such as polling and long-polling, applications of WebSockets, its limitations and potential bottlenecks, and potential future improvements.
Next, we will demo and dissect a real-world use case for realtime social data analytics, using the Apache Tomcat implementation of WebSockets and the Java-based Liferay Portal Server. This will include a discussion about development of WebSocket endpoints, its lifecycle within the application container and browser, debugging WebSockets, and scalability topics.
JAVA EE DEVELOPMENT (JSP and Servlets)Talha Ocakçı
Java and J2EE is the most used technologies in enterprise web development. Telecom operators, service providers are using these technlogies; banking and insurance companies are moving to Java from old generation technologies.
https://www.udemy.com/java-web-developmen-with-real-world-development-flow
If you want to earn much in web development business, you also need to learn Java web technologies.
Java has de facto standart frameworks such as EJB 3.0, Spring and others that can be bound to them.
But at heart, they all use the similar JSP/Servlet technology and add some layers above them to speed up the development.
You will use them in your daily business but before using them, you must learn the basics and what is going on while using them. Otherwise, you will not be able to find a proper solution to common problems.
This course will make you understand the basics of JSP / servlet technlogies, designing a relational database, DB operations, design patterns, working with other developers,
and let you know the must-do operations in professional projects such as performance increasing, logging errors.
If you want to develop a web-site in a couple of hours without understanding what you are doing, you may go ahead and find other resources. But if you really want to understand what you are doing and learn the theory at the same time, this course will be a great oppurtunity for you. You will develop a real working project. Yow will first write quick and dirty code then you will apply professional patterns one by one while investigating the problems.
You will walk through a real development flow:
1- Write a quick and dirty code for doing the job.
2- You will design database tables and high performance queries
3 - You will apply design patterns to make the code reusable and high performance.
4 - You will beautify the user interface with Javascript and CSS tweaks
5- You will add exception handling, logging mechanism for production environment
6- AT THIS STEP, YOU WILL BE HIRED FOR MUCH MUCH HIGHER SALARIES. BECAUSE YOU ARE A REAL PROFESSIONAL.
Similar to Con fess 2013-sse-websockets-json-bhakti (20)
3. Introduction
§All new or improved in Java EE 7
§GlassFish trunk build is in-progress implementation of EE 7
§All sample codes work on latest GlassFish 4
:http://dlc.sun.com.edgesuite.net/glassfish/4.0/promoted/
4. Polling
§Used by vast number of AJAX applications
§Poll the server for data
§Client --->request--> Server
§If no data empty response is returned
5. Polling Drawbacks
§Http overhead
§Long intervals result in delay in getting the latest data
§Short intervals consume more resources
§Not scalable for many many users in smaller farms
6. Long Polling
§Uses persistent or long-lasting HTTP connection between the server
and the client
§If server does not have data holds request open
§COMET
7. Long Polling Drawbacks
§Missing error handling
§Involves hacks by adding script tags to an infinite iframe
§Hard to check the request state
8. Server Sent Events
§Client subscribe to event source
§Events can be streamed from server to client when happens
§Connection stays open
§Unidirectional channel between server and client
9. Server Sent Events and EventSource
§Subscribing to event stream (JavaScript way)
• create an EventSource object:
eventSource = new EventSource(url);
source.onmessage = function (event) {
// a message arrived
};
§Event Source is a URL of course.
§Can setup handlers for source.onopen and source.onerror
10. Server Sent Events and Message format
§Plain text format
§Response Content-Type is text/event-stream
§The content follows the SSE format
§The response should contain a "data:" line, followed by the message,
followed by two "n" characters to end the stream:
§Sample message format
data: My messagenn
11. Server Sent Events and JSON
§Possible to send multiline texts
§E.g. Sending JSON
data: {n
data: "name": "John Doe",n
data: "id": 12345n
data: }nn
§On client side
source.addEventListener('message', function(e) {
var data = JSON.parse(e.data);
//process the data
}, false);
12. Server Sent Events and Reconnection
§If the connection drops, the EventSource fires an error event and
automatically tries to reconnect.
§The server can also control the timeout before the client tries to
reconnect.
13. Server Sent Events and Jersey 2.0 apis
§Client apis in Jersey 2.0
Client client = ClientBuilder.newClient();
WebTarget webTarget= client.target(new URI(TARGET_URI)) ;
§ EventSource apis in Jersey 2.0
EventSource eventSource = new EventSource(webTarget) {
@Override
public void onEvent(InboundEvent inboundEvent) {
//Get the data from the InboundEvent
//Process it as needed.
}
14. Best practices for ServerSentEvents
§Check that the data in question is of the expected format.
§Limit the arriving messages per minute
§Check if eventSource's origin attribute is the expected
domain to get the messages from
if (e.origin != 'http://foo.com') {
alert('Origin was not http://foo.com');
return;
15. Best practices for ServerSentEvents
§Associating an ID with an event
●
Each event has an unique ID as event.id
●
EventSource uses the event.id when reconnecting
●
Server knows how many pushed events the client has missed
●
Good to resume a failed connection
16. Polling vs Long Polling vs Server Sent Events
§Polling: GET. If data, process data. GET...
1 GET = 1 HTTP response header and maybe a chunk of data.
§Long-polling: GET. Wait. Process data. GET...
1 GET = 1 HTTP response header and chunks of data.
§SSE: Subscribe to event stream. Wait. Process data. Wait. Process
data. Wait..
1 GET = 1 HTTP response header, many chunks of data
17. WebSockets
§Full duplex communication in either direction
§A component of HTML5
§API under w3c, protocol under IETF(RFC 6455)
§Good support by different browsers
§Use existing infrastructure
18. WebSockets Client Server Handshake
§Client and Server upgrade from Http protocol to WebSocket protocol
during initial handshake
GET /text HTTP/1.1rn
Upgrade: WebSocketrn
Connection: Upgradern
Host: www.websocket.orgrn …rn
§Handshake from server looks like
HTTP/1.1 101 WebSocket Protocol Handshakern
Upgrade: WebSocketrn
Connection: Upgradern …rn
19. WebSockets Code Snippet
§After the upgrade HTTP is completely out of the picture.
§Messages are send bidirectional using WebSockets wire protocl
§In JavaScript:
var socket = new WebSocket("ws://localhost:8000/ws/wsst");
socket.onopen: When a socket has opened
socket.onmessage: When a message has been received
socket.onclose: When a socket has been closed
§For example
socket.onmessage = function(msg){
alert(msg);
}
20. WebSockets API JSR 356
§@ServerEndpoint
signifies that the Java class it decorates is to be deployed as
a WebSocket endpoint.
§The following components can be annotated with @ServerEndpoint
●
a stateless session EJB
●
a singleton EJB
●
a CDI managed bean
21. WebSockets Annotations
§Decorate methods on @ServerEndpoint annotated Java class with
●
@OnMessage To specify the method processing the message
●
@OnOpen to specify a handler when a connection is opened.
●
@OnClose to specify the handler when connection is closed.
●
@OnError To specify the handler when error happened
23. Java API for Processing JSON (JSON-P)
JSR 353
§Part of Java EE 7
§Streaming API to produce/consume JSON Similar to StAX API in XML
world
§Object model API to represent JSON Similar to DOM API in XML
world
24. Json Stream parsing API Main classes
§JsonParser: Pull parser
§JsonGenerator: Stream writer
§JsonObject/JsonArray – JSON object and array structure
§JsonString and JsonNumber for string and number value
25. JsonParser class
§JsonParser: Parses JSON in a streaming way from input sources
§Similar to StAX’s XMLStreamReader, a pull parser
§Parser state events :
START_ARRAY, START_OBJECT, KEY_NAME, VALUE_STRING,
VALUE_NUMBER, VALUE_TRUE, VALUE_FALSE, VALUE_NULL, END_OBJECT,
END_ARRAY
§Created using :
javax.json.Json.createParser(…),
Json.createParserFactory(...).createParser(…)
28. JsonGenerator
§JsonGenerator: Generates JSON in a streaming way to output
sources
§Similar to StAX’s XMLStreamWriter
§Created using :
Json.createGenerator(…),
Json.createGeneratorFactory(...).createGenerator(…)
30. Object Model API Main Classes
§JsonBuilder – Builds JsonObject and JsonArray Programmatically
§JsonReader – Reads JsonObject and JsonArray from input source
§JsonWriter – Writes JsonObject and JsonArray to output source
§JsonObject/JsonArray – JSON object and array structure
§JsonString and JsonNumber for string and number value
31. JsonReader
§Reads JsonObject and JsonArray from input source
§Uses pluggable JsonParser
§Read a json object:
JsonReader reader = new JsonReader(io)
JsonObject obj = reader.readObject();
32. JsonWriter
§Writes JsonObject and JsonArray to output source
§Uses pluggable JsonGenerator
§Write a json object:
JsonWriter writer = new JsonWriter(io)
writer.writeObject(obj);
33. JAX-RS 2.0
§New in JAX-RS 2.0
§Client API
§Filters and Interceptors
§Client-side and Server-side Asynchronous
§Improved Connection Negotiation
§Validation Alignment with JSR 330
39. Demo class diagram
Gets data from
twitter search
apis
Writes the message
on the EventChannel
Create EventSource
ParseJson data
Display in servlet
40. AsyncServlet code sample
protected void service(final HttpServletRequest request, final HttpServletResponse response)
throws ServletException, IOException {
final AsyncContext asyncContext = request.startAsync();
asyncContext.setTimeout(TIMEOUT);
asyncContext.addListener(new AsyncListener() {
// Override the methods for onComplete, onError, onAsyncStartup
}
Thread t = new Thread(new AsyncRequestProcessor(asyncContext));
t.start();
}
41. AsyncServlet code sample
class AsyncRequestProcessor implements Runnable {
@Override
public void run() {
Client client = ClienttBuildernewClient();
webTarget = client.target(new URI(TARGET_URI));
EventSource eventSource = new EventSource(webTarget, executorService) {
public void onEvent(InboundEvent inboundEvent) {
try {
//get the JSON data and parse it
}
42. Trying the sample
Clone the sample from the following repo:
https://github.com/kalali/jersey-sse-twitter-sample/
Follow the readme which involves:
●
Do a mvn clean install
●
Get latest GlassFish build
●
Deploy the application
●
Hit the http://localhost:8080/jersey-sse-twitter-sample/TestClient