This document discusses using WebSockets for bidirectional communication between a GWT client and server. It provides an overview of setting up WebSocket connections on both the client and server sides in GWT, including writing a JSNI wrapper to initialize the WebSocket on the client. It also discusses using GWT's existing RPC serialization mechanism to serialize and deserialize Java objects sent over the WebSocket connection, avoiding the need for additional serialization libraries. Code examples are provided for initializing the WebSocket and handling messages on both the client and server sides, as well as using GWT's serialization streams to serialize and deserialize objects between the client and server.
Ce tutoriel a pour but de développer une application web CRUD à trois couches (présentation, métier, accès aux données) avec la plateforme JEE (Java Enterprise Edition) que nous construisons avec les technologies suivantes :
- JavaServer Faces(JSF) et RichFaces : pour les interfaces web,
- JAva Beans: pour la couche métier
- Hibernate,Spring : pour la couches d'accès aux données
L'application sera développé avec l'éditeur netbeans 6.5.1 et sera déployé sur le serveur apache tomcat 6.0.18.le document contient beaucoup de code rendant possible le copier / coller.
This presentation walks the reader through implementing a simple web application and its tests using Python, Flask, and the Pytest testing framework. Emphasis is placed on following the process of test-driven development (TDD) in creating the application.
Slides from the NestJS MasterClass.
We learned how to build JavaScript server-side applications with NestJS - A progressive NodeJS framework built with TypeScript.
You can find the code on GitHub:
https://github.com/nirkaufman/task-manager
Ce tutoriel a pour but de développer une application web CRUD à trois couches (présentation, métier, accès aux données) avec la plateforme JEE (Java Enterprise Edition) que nous construisons avec les technologies suivantes :
- JavaServer Faces(JSF) et RichFaces : pour les interfaces web,
- JAva Beans: pour la couche métier
- Hibernate,Spring : pour la couches d'accès aux données
L'application sera développé avec l'éditeur netbeans 6.5.1 et sera déployé sur le serveur apache tomcat 6.0.18.le document contient beaucoup de code rendant possible le copier / coller.
This presentation walks the reader through implementing a simple web application and its tests using Python, Flask, and the Pytest testing framework. Emphasis is placed on following the process of test-driven development (TDD) in creating the application.
Slides from the NestJS MasterClass.
We learned how to build JavaScript server-side applications with NestJS - A progressive NodeJS framework built with TypeScript.
You can find the code on GitHub:
https://github.com/nirkaufman/task-manager
Support Dot Net avec C#. Ce cours traite les points suivants :
- Architecture .Net
- Les bases de C#
- Objet et Classe
- Héritage
- Encapsulation
- Polymorphisme
- Les exceptions
- Les entrées sorties
- Les interfaces graphiques
- Le multi Threading
- Programmation réseaux (Sockets et DataGram)
- Accès aux bases de données
Au commencement, était l’apprentissage en présentiel. Le numérique vint, révolutionna les pratiques et approches pédagogiques. On assista à l’émergence du e-learning dont la fièvre se répand encore avec le phénomène des MOOCs, webinaires, classes virtuelles… La fièvre ne s’est point encore estompée que nous apprenons l’apparition et l’expansion fulgurante d’un nouveau virus dénommé « blended-learning ». Mais qu’est ce qui se cache au juste derrière cette nouvelle méthode pédagogique combinant le présentiel et le distanciel ?Quel proportion ou ajustement doit être réalisé entre ces deux modes? Comment cela fonctionne-t-il ? Qui en sont les principaux acteurs sur le marché de formation 2.0 ? Quels principes et pratiques gouvernent ce « nouveau » modèle hybride de formation ? Quel en est l’impact sur la formation professionnelle et académique ainsi que les perspectives ?
How to build a chat application with react js, nodejs, and socket.ioKaty Slemon
In the tutorial, we will learn about how to build a chat app using ReactJs, NodeJS, and Socket.IO. Clone the Github repository and play around with the code.
Final tagless. The topic strikes fear into the hearts of Scala developers everywhere—and not without reason. Final tagless allows developers to build composable Domain Specific Languages (DSLs) that model interaction with the outside world. Programs written using the final tagless style can be tested deterministically and reasoned about at compile-time. Yet the technique requires confusing, compiler-choking higher-kinded types, like `F[_]`, and pervasive, non-inferable context bounds like `F[_]: Concurrent: Console: Logging`. Many have looked at final tagless and wondered if all the layers of complexity and ceremony are really worth the benefits.
In this presentation, John A. De Goes provides a gentle and accessible introduction to final tagless, explaining what it is and the problem it intends to solve. John shows that while final tagless is easier to use than free monads, the technique suffers from a litany of drawbacks that push developers away from functional programming in Scala. John then introduces a novel approach that shares some of the benefits of final tagless, but which is idiomatic Scala, easy to explain, doesn’t need any complex type machinery, provides flawless type inference, and works beautifully across Scala 2.x and Scala 3.
Come join John for an evening of fun as you learn how to write functional code in Scala that's easy to test and easy to reason about—all without the complexity of free monads or final tagless.
Ce Support de cours Spring contient :
- Architecture JEE (Over view)
- Spring Overview
- Spring IOC
- Spring MVC
- Spring Integration (RMI, JaxWS, JaxRS, JMS, JMX,...)
- Spring Security
Bon apprentissage à tous
Have ever heard that JavaScript is event-oriented? And that Node.js has a mainloop? Have you ever had issues with setTimeout, setInterval, setImmediate, nextTick order? This talk should help you with understanding deeply Node.js and Web event loop phases!
Have you ever thought, “I wish it was easier to change JavaScript code programmatically?” Maybe you wanted to write or edit a configuration block in source code. Perhaps you wanted to generate customized algorithmic code. For many, this kind of thing seems inaccessible.
The tools exist, though. In this talk, Stephen Vance will look at how he has used recast and esprima to edit and rewrite JavaScript code, leaving the untouched code completely intact, including whitespace and comments. At the end, you should have enough knowledge to be dangerous and start to write the next automatic programming, AI, take-over-the-world, self-improving software.
How to add a yellow circle around mouse cursor? - ThiyaguThiyagu K
This presentation explains the procedure of how to get or add a yellow circle around our mouse cursor or pointer. PenAttention is a free Windows program that displays a highlight, pencil, or pointer at the location of the pen. It's intended for use in presentations on a pen-enabled laptop or PC so our audience can see what we are pointing at on the screen. It is a self explanatory tutorial..
Para usufruir de uma mente tranquila, você e sua família precisam estar protegidas. As fechaduras digitais Yale cuidam de tudo isso para que você possa desfrutar da sua vida sem preocupações.
Support Dot Net avec C#. Ce cours traite les points suivants :
- Architecture .Net
- Les bases de C#
- Objet et Classe
- Héritage
- Encapsulation
- Polymorphisme
- Les exceptions
- Les entrées sorties
- Les interfaces graphiques
- Le multi Threading
- Programmation réseaux (Sockets et DataGram)
- Accès aux bases de données
Au commencement, était l’apprentissage en présentiel. Le numérique vint, révolutionna les pratiques et approches pédagogiques. On assista à l’émergence du e-learning dont la fièvre se répand encore avec le phénomène des MOOCs, webinaires, classes virtuelles… La fièvre ne s’est point encore estompée que nous apprenons l’apparition et l’expansion fulgurante d’un nouveau virus dénommé « blended-learning ». Mais qu’est ce qui se cache au juste derrière cette nouvelle méthode pédagogique combinant le présentiel et le distanciel ?Quel proportion ou ajustement doit être réalisé entre ces deux modes? Comment cela fonctionne-t-il ? Qui en sont les principaux acteurs sur le marché de formation 2.0 ? Quels principes et pratiques gouvernent ce « nouveau » modèle hybride de formation ? Quel en est l’impact sur la formation professionnelle et académique ainsi que les perspectives ?
How to build a chat application with react js, nodejs, and socket.ioKaty Slemon
In the tutorial, we will learn about how to build a chat app using ReactJs, NodeJS, and Socket.IO. Clone the Github repository and play around with the code.
Final tagless. The topic strikes fear into the hearts of Scala developers everywhere—and not without reason. Final tagless allows developers to build composable Domain Specific Languages (DSLs) that model interaction with the outside world. Programs written using the final tagless style can be tested deterministically and reasoned about at compile-time. Yet the technique requires confusing, compiler-choking higher-kinded types, like `F[_]`, and pervasive, non-inferable context bounds like `F[_]: Concurrent: Console: Logging`. Many have looked at final tagless and wondered if all the layers of complexity and ceremony are really worth the benefits.
In this presentation, John A. De Goes provides a gentle and accessible introduction to final tagless, explaining what it is and the problem it intends to solve. John shows that while final tagless is easier to use than free monads, the technique suffers from a litany of drawbacks that push developers away from functional programming in Scala. John then introduces a novel approach that shares some of the benefits of final tagless, but which is idiomatic Scala, easy to explain, doesn’t need any complex type machinery, provides flawless type inference, and works beautifully across Scala 2.x and Scala 3.
Come join John for an evening of fun as you learn how to write functional code in Scala that's easy to test and easy to reason about—all without the complexity of free monads or final tagless.
Ce Support de cours Spring contient :
- Architecture JEE (Over view)
- Spring Overview
- Spring IOC
- Spring MVC
- Spring Integration (RMI, JaxWS, JaxRS, JMS, JMX,...)
- Spring Security
Bon apprentissage à tous
Have ever heard that JavaScript is event-oriented? And that Node.js has a mainloop? Have you ever had issues with setTimeout, setInterval, setImmediate, nextTick order? This talk should help you with understanding deeply Node.js and Web event loop phases!
Have you ever thought, “I wish it was easier to change JavaScript code programmatically?” Maybe you wanted to write or edit a configuration block in source code. Perhaps you wanted to generate customized algorithmic code. For many, this kind of thing seems inaccessible.
The tools exist, though. In this talk, Stephen Vance will look at how he has used recast and esprima to edit and rewrite JavaScript code, leaving the untouched code completely intact, including whitespace and comments. At the end, you should have enough knowledge to be dangerous and start to write the next automatic programming, AI, take-over-the-world, self-improving software.
How to add a yellow circle around mouse cursor? - ThiyaguThiyagu K
This presentation explains the procedure of how to get or add a yellow circle around our mouse cursor or pointer. PenAttention is a free Windows program that displays a highlight, pencil, or pointer at the location of the pen. It's intended for use in presentations on a pen-enabled laptop or PC so our audience can see what we are pointing at on the screen. It is a self explanatory tutorial..
Para usufruir de uma mente tranquila, você e sua família precisam estar protegidas. As fechaduras digitais Yale cuidam de tudo isso para que você possa desfrutar da sua vida sem preocupações.
Getting started with Websocket and Server-sent Events using Java - Arun Gupta jaxconf
Server-Sent Events defines a standard technology for server-push notifications. WebSocket attempts to solve the issues and limitations of HTTP for real-time communication by providing a full-duplex communication over a single TCP channel. Together, they bring new opportunities for efficient server-push and peer-to-peer communication, providing the basis for a new generation of interactive and “live” Web applications. This session provides a primer on WebSocket and Server-Sent Events and their supported use cases.
Getting Started with WebSocket and Server-Sent Events using Java by Arun GuptaCodemotion
Server-Sent Events and WebSocket allow to write more interactive applications on web. It examines the efforts under way to support WebSocket in the Java programming model using JSR 356. The session also explains how Server-Sent Events can be easily written using Jersey, the Reference Implementation for JAX-RS 2. Simple “Hello World” to more elaborate Collaborative Whiteboard applications will show different features of both the technologies. A complete development using NetBeans, deployment on GlassFish, and debugging using Chrome will be shown.
This is a presentation given on October 24 by Michael Uzquiano of Cloud CMS (http://www.cloudcms.com) at the MongoDB Boston conference.
In this presentation, we cover Hazelcast - an in-memory data grid that provides distributed object persistence across multiple nodes in a cluster. When backed by MongoDB, objects are naturally written to Mongo by Hazelcast. The integration points are clean and easy to implement.
We cover a few simple cases along with code samples to provide the MongoDB community with some ideas of how to integrate Hazelcast into their own MongoDB Java applications.
7.1 Identify which attribute scopes are thread-safe:
Local variables
Instance variables
Class variables
Request attributes
Session attributes
Context attributes
7.2 Identify correct statements about differences between the multithreaded and single-threaded servlet models.
7.3 Identify the interface used to declare that a servlet must use the single thread model.
"Jclays, A global solution for application design and automatic GWT code gene...GWTcon
"Jclays, A global solution for application design and automatic GWT code generator" By Y. Nakoula and T. Houimel
#GWTcon2017 Florence September 28-29th 2017
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
In this presentation, we examine the challenges and limitations of relying too heavily on PHP frameworks in web development. We discuss the history of PHP and its frameworks to understand how this dependence has evolved. The focus will be on providing concrete tips and strategies to reduce reliance on these frameworks, based on real-world examples and practical considerations. The goal is to equip developers with the skills and knowledge to create more flexible and future-proof web applications. We'll explore the importance of maintaining autonomy in a rapidly changing tech landscape and how to make informed decisions in PHP development.
This talk is aimed at encouraging a more independent approach to using PHP frameworks, moving towards a more flexible and future-proof approach to PHP development.
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
Sidekick Solutions uses Bonterra Impact Management (fka Social Solutions Apricot) and automation solutions to integrate data for business workflows.
We believe integration and automation are essential to user experience and the promise of efficient work through technology. Automation is the critical ingredient to realizing that full vision. We develop integration products and services for Bonterra Case Management software to support the deployment of automations for a variety of use cases.
This video focuses on the notifications, alerts, and approval requests using Slack for Bonterra Impact Management. The solutions covered in this webinar can also be deployed for Microsoft Teams.
Interested in deploying notification automations for Bonterra Impact Management? Contact us at sales@sidekicksolutionsllc.com to discuss next steps.
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
1. GWT Web Socket and
data serialization
Michele Ficarra
Software Engineer at Thales Italy S.p.A
2. Case study
With GWT this!
is easy
Let's focus on the Browser <-> Server communication
3. “GWT provides an RPC mechanism based on
Java Servlets to provide access to server-side
resources. This mechanism includes generation
of efficient client-side and server-side code to
serialize objects across the network using
deferred binding.”
From gwtproject.org
5. GWT RPC
• Easy to write, hide all AJAX and serialization
complexity. !
• You can use the same POJO in client and server,
you need only to implement the serializable
interface.!
• But …
7. Possible solutions
• Polling!
• HTTP Long Polling (COMET)!
• Web Socket
Two RFC can help us to choose
8. “On today's Internet, the Hypertext Transfer
Protocol (HTTP) is often used (some would say
abused) to enable asynchronous, "server-initiated"
communication from a server to a
client as well as communication from a client to
a server.”
From RFC 6202 - Bidirectional HTTP - April 2011
9. “The WebSocket protocol consists of an
opening handshake followed by basic message
framing, layered over TCP. The goal of this
technology is to provide a mechanism for
browser-based applications that need two-way
communication with servers”
From RFC 6455 - The WebSocket Protocol - December 2011
10. • WebSocket seems to be the right choice, but GWT
doesn’t provide natively a way to use it!
• On Internet we can find a lots of library that can
help:!
• Errai - http://erraiframework.org/!
• Gwt-ws - https://code.google.com/p/gwt-ws/!
• …!
• But this time we want to make our hands “dirty” and
try to do it by ourself!
12. Web Socket - Client Side
For use the previous code with GWT we need to write a JSNI wrapper
package ws;
import com.google.gwt.core.client.JavaScriptObject;
!
public abstract class WebSocket {
!
private JavaScriptObject ws;
!
public WebSocket(String url) {
ws = init(url);
}
!
abstract void onClose();
abstract void onError();
abstract void onMessage(String msg);
abstract void onOpen();
!
private native JavaScriptObject init(String url) /*-{
. . .
}-*/;
!
native void send(String message) /*-{
this.@ws.WebSocket::ws.send(message);
}-*/;
}
JAVA
13. Web Socket - Client Side
private native JavaScriptObject init(String url) /*-{
var websocket = new WebSocket(url);
var wrapper = this;
websocket.onopen = function(evt) {
wrapper.@ws.WebSocket::onOpen()();
};
websocket.onclose = function(evt) {
wrapper.@ws.WebSocket::onClose()();
};
websocket.onmessage = function(evt) {
wrapper.@ws.WebSocket::onMessage(Ljava/lang/String;)(evt.data);
};
websocket.onerror = function(evt) {
wrapper.@ws.WebSocket::onError()();
};
return websocket;
}-*/;
JAVA
14. Web Socket - Server Side
• For develop the server side we can use the Java
API for WebSocket (JSR 356), that is part of the
Java EE 7 standard!
• If we want use the JSR 356 without a full JEE 7
container it’s possibile to embed a WS server like
Tyrus - https://tyrus.java.net/
<dependency>
<groupId>org.glassfish.tyrus</groupId>
<artifactId>tyrus-server</artifactId>
<version>1.8.3</version>
</dependency>
<dependency>
<groupId>org.glassfish.tyrus</groupId>
<artifactId>tyrus-container-grizzly-server</artifactId>
<version>1.8.3</version>
</dependency>
MAVEN
15. Web Socket - Server Side
Example of an Echo Web Socket service with JSR 356
package ws;
!
import javax.websocket.OnMessage;
import javax.websocket.server.ServerEndpoint;
!
@ServerEndpoint("/echo")
public class EchoEndpoint {
!
@OnMessage
public String echo(String message) {
return message + " (from your server)";
}
!
}
JAVA
16. Web Socket - Server Side
Start Tyrus Server in Jetty 6 (DevMode)
package ws;
!
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.websocket.DeploymentException;
!
import org.glassfish.tyrus.server.Server;
!
public class InitListener implements ServletContextListener {
!
private Server server = null;
!
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
server.stop();
}
!
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
try {
server = new Server("localhost", 8025, "/", null, EchoEndpoint.class);
server.start();
} catch (final DeploymentException e1) {
e1.printStackTrace();
}
}
}
JAVA
WEB.XML
<listener>
<listener-class>ws.InitListener</listener-class>
</listener>
17. Data Serialization
• Now we are capable of send string back and
forward from the browser to the server and
viceversa!
• But if we want use this technology in a complex
environment this result is a little poor. We want
send Object not String!!
• The first idea to fix the problem can be to use JSON
serialization…
18. • … and after a little search we found a lots of way to
do that:!
• http://www.gwtproject.org/doc/latest/tutorial/JSON.html!
• https://github.com/nmorel/gwt-jackson!
• …!
• But every solution require a lot of boilerplate code
or adding annotation to the data model!
• We would like something more similar to the GWT
RPC, that require only the Serializable interface.
May be it can be reused?
19. • After searching in the web and in the GWT source
code the solution come out!
• We need to define the interface of an RPC and reuse
the serialization engine already present in GWT
20. Data Serialization
public class Message implements Serializable {
!
private String data;
private String username;
private Date time;
!
/* ... */
}
JAVA
JAVA
@RemoteServiceRelativePath("MessageService")
public interface MessageService extends RemoteService {
Message getMessage(Message message);
!
}
The RPC Serialization is designed for function call. The
client serialize the function argument and the server the
return value. So, if we want exchange the same object, it’s
important that in the service definition the args and the
return value are the same class
21. public String serializeMessae(Message message) {
try {
SerializationStreamFactory factory =
(SerializationStreamFactory) GWT.create(MessageService.class);
SerializationStreamWriter writer = factory.createStreamWriter();
writer.writeObject(message);
final String data = writer.toString();
return data;
} catch (final SerializationException e) {
e.printStackTrace();
}
return null;
}
JAVA
Data Serialization - Client Side
Here there is the trick, the Async Service that is usual
return by the deferred binding is also an instance of a
SerializationStreamFactory. That can be used for serialize
and deserialize objects
22. public Message deserializeMessae(String data) {
try {
SerializationStreamFactory factory =
(SerializationStreamFactory) GWT.create(MessageService.class);
final SerializationStreamReader streamReader = factory
.createStreamReader(data);
final Message message = (Message) streamReader.readObject();
return message;
} catch (final SerializationException e) {
e.printStackTrace();
}
return null;
}
JAVA
Data Serialization - Client Side
23. Data Serialization - Server Side
private Message deserializeMessage(String data)
throws SerializationException {
ServerSerializationStreamReader streamReader =
new ServerSerializationStreamReader(
Thread.currentThread().getContextClassLoader(),
new CustomSerializationPolicyProvider());
// Filling stream reader with data
streamReader.prepareToRead(data);
// Reading deserialized object from the stream
final Message message = (Message) streamReader.readObject();
return message;
}
JAVA
On server side is more or less the same of the client. We
need an instance of a ServerSerializationStreamReader for
read the object.
The only hack is how create a
CustomSerializationPolicyProvider
24. Data Serialization - Serialization Policy
public class CustomSerializationPolicyProvider
implements SerializationPolicyProvider {
!
@Override
public SerializationPolicy getSerializationPolicy(String moduleBaseURL, String serializationPolicyStrongName) {
return new SimpleSerializationPolicy();
}
!
}
JAVA
public class SimpleSerializationPolicy extends SerializationPolicy {
!
@Override
public boolean shouldDeserializeFields(Class<?> clazz) {
return isSerializable(clazz);
}
!
@Override
public boolean shouldSerializeFields(Class<?> clazz) {
return isSerializable(clazz);
}
!
/* ... */
!
private boolean isSerializable(Class<?> clazz) {
if (clazz != null) {
if (clazz.isPrimitive()
|| Serializable.class.isAssignableFrom(clazz)
|| IsSerializable.class.isAssignableFrom(clazz)) {
return true;
}
}
return false;
}
}
JAVA
RPC generates a serialization
policy file during GWT
compilation. The serialization
policy file contains a whitelist
of allowed types which may be
serialized.!
In this simple implementation
there is only the check of the
Serializable interface.!
Watch out of what are you
serializing or you can perform
problem on client side.
25. Data Serialization - Server Side
private String serializeMessage(final Message messageDto)
throws SerializationException {
!
ServerSerializationStreamWriter serverSerializationStreamWriter =
new ServerSerializationStreamWriter(new SimpleSerializationPolicy());
!
serverSerializationStreamWriter.writeObject(messageDto);
String result = serverSerializationStreamWriter.toString();
return result;
}
JAVA
26. Data Serialization - OnMessage
Now we have all pieces for finish the OnMessage method
@OnMessage
public void onMessage(String message, Session session) {
try {
!
Message messageDto = deserializeMessage(message);
!
String result = serializeMessage(messageDto);
!
for (Session s : session.getOpenSessions()) {
if (s.isOpen()) {
s.getBasicRemote().sendText(result);
}
}
} catch (final SerializationException | IOException e) {
logger.log(Level.WARNING, "Error", e);
}
}
JAVA
Deserialization of an
incoming message
from a client
Serialization for the
clients. The clients can
deserialize only object
encoded by the sever due
the request - response
nature of the RPC
Web Socket
broadcast
27. That’s all, happy hacking and thanks for the attention.
Full working example available on: !
https://github.com/michelefi/gwtcon-websocket
Questions?