JAX-RS 2.1 Server Sent Events

If you find this post better-worded (and grammatically correct) compared to the usual standard on this blog, its because the text below is part of the proposed JAX-RS 2.1 specification, which was authored by Santiago :)

If you want to provide feedback to this chapter, please send us a note to users@jax-rs-spec.java.net.

Server Sent Events

Server-sent events (SSE) is a specification originally introduced as part of HTML5 by the W3C, but is currently maintained by the WHATWG. It provides a way to establish a one-way channel from a server to a client. The connection is long running: it is re-used for multiple events sent from the server, yet it is still based on the HTTP protocol. Clients request the opening of an SSE connection by using the special media type text/event-stream in the Accept header.

Events are structured and contain several fields, namely, event, data, id, retry and comment. SSE is a messaging protocol where the event field corresponds to a topic, and where the id field can be used to validate event order and guarantee continuity. If a connection is interrupted for any reason, the id can be sent in a request header for a server to re-play past events —although this is an optional behavior that may not be supported by all implementations. Event payloads are conveyed in the data field and must be in text format; retry is used to control re-connects and finally comment is a general purpose field that can also be used to keep connections alive.

Client API

The JAX-RS client API for SSE was inspired by the corresponding JavaScript API in HTML5, but with changes that originate from the use of a different language as well as the desire to support the Flow API from Java 9 – but without introducing a dependency with that version of Java.

The entry point to the client API is the type SseEventSource, which provides a fluent builder similarly to other classes in the JAX-RS API. An SseEventSource is constructed from a WebTarget that is already configured with a resource location; SseEventSource does not duplicate any functionality in WebTarget and only adds the necessary logic for SSE.

The following example shows how to open an SSE connection and read some messages for a little while:

try (final SseEventSource eventSource =
.build()) {
Thread.sleep(500); // consume events for 500 ms.
} catch (InterruptedException e) {
    // ...

As seen in this example, an SseEventSource implements AutoCloseable. Before opening the source, the client subscribes to the event stream and registers an event consumer that simply prints each event. Additional handlers for other life-cycle events such as onSubscribe, onComplete and onError are also supported, but for simplicity only onEvent is shown in the example above.

Server API

The JAX-RS SSE server API is used to accept connections and send events to one or more clients (also known as subscribers). A resource method that injects an SseEventSink and produces the media type text/event-stream is an SSE resource method.

The following example accepts SSE connections and uses an executor thread to send 3 events before closing the connection:

public void eventStream(@Context SseEventSink eventSink,
                        @Context Sse sse) {
    executor.execute(() -> {
try(SseEventSink sink = eventSink) {
} catch (IOException e) {
// handle exception

SSE resource methods follow a similar pattern to those for asynchronous processing in that the object representing the incoming connection, in this case SseEventSink, is injected into the resource method.

The example above also injects the Sse type which provides factory methods for events and broadcasters. Note that, just like SseEventSource, the interface SseEventSink is also auto-closeable, hence the use of the try-with-resources statement above.


Applications may need to send events to multiple clients simultaneously. This action is called broadcasting in JAX-RS. Multiple SseEventSink’s can be registered (or subscribed) on a single SseBroadcaster. Thus, all SseBroadcaster’s are also publishers in the sense defined by the Java 9 Flow API, supporting the same methods as Flow.Publisher<T> but not directly extending that interface to avoid dependencies on Java 9. More precisely, an SseBroadcaster implements Flow.Publisher<OutboundSseEvent>.

A broadcaster can only be created by calling method newBroadcaster on the injected Sse instance. The life-cycle and scope of an SseBroadcaster is fully controlled by applications and not the JAX-RS runtime. The following example shows the use of broadcasters, note the @Singleton annotation on the resource class:

public class SseResource {
private final Sse sse;
    private final SseBroadcaster sseBroadcaster;

public SseResource(@Context Sse sse) {
this.sse = sse;
this.sseBroadcaster = sse.newBroadcaster();

public void subscribe(@Context SseEventSink eventSink) {

public void broadcast(@FormParam("event") String event) {


The SseEventSource class uses the existing JAX-RS mechanism based on RuntimeDelegate to find an implementation using the service name javax.ws.rs.sse.SseEventSource.Builder. The majority of types in the javax.ws.rs.sse are thread safe; the reader is referred to the Javadoc for more information on thread safety.

Posted in java | Tagged , , , , | Leave a comment

JAX-RS 2.1 Reactive Client API

I’m happy to announce that I was selected to replace Marek as JAX-RS co-spec lead. Meaning that I’ll have something to blog about during next moths, most likely until JavaOne 2017.

If you are following discussions within various specifications, you might have noticed that JAX-RS was very quiet during last year. That is going to change. Or already did actually. The Expert Group (EG) is now working with updated schedule, which is mainly about following three items:

  • Reactive Client API
  • Server Sent Events
  • Non-blocking I/O

First two items were already proposed in some way, but were never blessed from the EG, so we need to update them (if necessary), get them reviewed and incorporate review comments. That is what happened to Reactive Client API and this post will try to summarise that change.

JAX-RS Reactive Client API

Firstly, the goal of this feature is include support for reactive style programming on the client side. Not anything else. Also, we don’t want to create another client. Existing one already has support for synchronous and asynchronous request execution and we want to extend this with reactive style.

Let’s see the simples example:

CompletionStage<Response> csResponse =

You can notice couple new things, namely the returned type is not the javax.ws.rs.Response or Future<Response> (which would be the case when rx() is replaced with async()) and there is new method in Client fluent API invocation chain – rx().

CompletionStage is a new interface, introduced in Java 8, which is also the only reactive standard which made it into the platform. (More about that later).

rx() method has been added to be able to switch from sync/async invoker to something new – RxInvoker in this case. It defines the same methods as the others, but it doesn’t have the return type specified in the same way – you can create subclass and redefine it, for example to the CompletionStage, as it is done in CompletionStageRxInvoker, which is also part of the proposed API.

There are several variants of the rx() method. One is related to providing an ExecutorService, the other one is about providing RxInvoker class. The former is simple to explain – reactive invocations are async by nature and we want to be able to specify the thread pool / executor service, which will be used to invoke that (which might be revisited later, for example removed by allowing client-wide async executor service configuration), the latter is about extensibility. That deserves another section, so..:

Reactive Extensions

If you are implementing reactive application on Java, you most likely know other datatypes, provided by various frameworks. Namely Guava, RxJava and others. They do provide similar functionalities to CompletionStage, but with different APIs. Those can be beneficial to use, especially if you have an application already written using other, non-standard, frameworks and JAX-RS wants to make itself usable as easily as possible. Let’s start with code example:

Client client = ClientBuilder.newClient();

Flowable<Response> csResponse =

Here, we do see how RxJava2 Flowable could be used when getting a JAX-RS Response.

Both FlowableProvider and FlowableInvoker are provided by the 3rd party – for example, if RxJava2 developer community things JAX-RS in important enough, they might release extension module, which will contain these classes. Also, as always, any JAX-RS implementation can choose the features and might provide similar provider as part of their implementation.

I don’t want to get into more detail, since this might be changed, but for now it seems like we have reached a conclusion, that this is the best possible way how the extensibility can be provided. If you are interested in knowing the decision process, feel free to read JAX-RS spec EG mailing list.

I hope you like newly proposed API. If you have any comments, please share them at the users mailing list on JAX-RS project!

Links, mailing lists, etc.

Posted in java | Tagged , , , , | Leave a comment

WebSocket Client API – Java 8

Since Java 8 was released, lots of new or reworked APIs emerged, simply because Java 8 is really evolutionary step in Java language specification and it is definitely worth to update the APIs to enable newly added features.

Unfortunately, Java EE APIs have different release cycle and we’d need to wait a little bit for next version, but I was able to add at least something to Tyrus, which is reference implementation of JSR 356 – WebSocket API for Java. There are some other changes which could be made, but most of them require changes in the API itself, which we cannot do at the moment, so I focused on other features which do enhance the experience. You can view this as the “first” attempt to bring some Java 8 API features into the existing programming model.

The area covered in this post is Client API – mainly because this change can be used easily with any WebSocket API implementation; it is built on top of existing API. If I would be thorough, I’d apply this to deployment of the programmatic endpoints on the server side as well, but that would be far more work and since the server side usually uses annotated endpoints instead of programmatic ones, I believe this should be sufficient to evaluate the proposal and provide any feedback you might have.

The client API was originally crafted as something, which should be similar to the JavaScript counterpart, but the language differences at that time diminished that effort to basically just naming and few other details (and the alignment with server side API had higher priority). Anyway, I believe it is the time, when we should reconsider Client API (and programmatic model in general).

If you look at javascript API, it’s basically just one object, to which you can set handlers for some events:

window.websocket = new WebSocket(window.wsUrl("/sample-btc-xchange/market"));
 var websocket = window.websocket;
 websocket.onopen = function () { /* ... */ };
 websocket.onmessage = function (evt) {/* ... */ };
 websocket.onclose = function () { /* ... */ };
 websocket.onerror = function () { * ... */ };

The current Java version of this would be:

client.connectToServer(new Endpoint() {
  public void onOpen(Session session, EndpointConfig EndpointConfig) {

    try {
      session.addMessageHandler(new MessageHandler.Whole() {
        public void onMessage(String message) {

  public void onClose(Session session, CloseReason closeReason) {

 }, ClientEndpointConfig.Builder.create().build(), getURI(EchoEndpoint.class));

which does not seem nice to me, additionally, since Lambdas and Method References were added to the language, we could do much better than that. The main idea behind these changes is that programmatic endpoint (class javax.websocket.Endpoint) is no longer necessary, since it can be replaced by three method references, especially when you usually don’t need all of them. And Java 8 offers nice predefined Functional Interfaces, which work just fine, so we don’t even need to introduce declaration of those, we only need to define consumed types.

With these in mind, the previous code could look like:

Session session = new SessionBuilder().uri(getURI(SessionBuilderTestEndpoint.class))
 .messageHandler(String.class, message -> { })
 .onClose((session, closeReason) -> { })

The main advantage I see here (other than readability) is that the configuration is no longer in two places – programmatic connectToServer method requires Endpoint, ClientEndpointConfig and other parameters, but it does not allow to register MessageHandler right away – user needs to implement that logic in @OnOpen method. On the other hand, proposed approach does that for you, so @OnOpen implementation in this case will be only what it is supposed to be. And I believe it could be omitted in lots of cases, which also contributes to readability and ease of use. Also, last but not least, less code written, less bugs introduced..

Previous code sample included lambdas, but sometimes, you might want to have more complicated code there, which does not look good implemented as lambda. In that case, you can declare standard methods with appropriate parameters and provide Method Reference instead. Slightly more complex sample would then look like:

Session s = new SessionBuilder().uri(getURI(SessionBuilderTestEndpoint.class))
 .messageHandler(String.class, this::onMessage)

More code examples can be seen in SessionBuilderTest class.

You are welcomed to try and give us your feedback. The SessionBuilder is in module “org.glassfish.tyrus.ext:tyrus-client-java8″, which is currently released only as snapshot (should be part of next Tyrus release), so you’ll need to add reference to maven.java.net snapshot repository: https://maven.java.net/content/repositories/snapshots/

Complete dependencies and repo declaration in pom.xml might look like:





Any feedback appreciated!


Posted in java | Tagged , , , , | Leave a comment

WebSocket vs REST

As controversial or potentially “flame starting” topic this might seem to be, don’t worry. I will approach this purely from pro-WebSocket view and the comparison with REST will be done on the sample, which heavily favours WebSocket ;)

Not that long ago, I had to explain one of my colleague where he should consider using WebSocket protocol and I realised, that lots of people don’t really know about it much. I even heard question whether WebSocket is successor of REST, like REST was/is to SOAP web services.. well, I’ll try to make this little bit clearer in this post.

For starters, WebSocket is NOT REST replacement. These are two technologies, which can coexist very nicely even in single application or webpage. Both are doing similar things and for some applications are even interchangeable. Bold statement, but it’s true. Both approaches have it’s own pros and cons, as with everything else..

Let’s go little back to the history of web services and remember why was WebSocket protocol even created – to allow bi-directional communication with clients, mainly represented by web pages. It was (and still is) possible to achieve the same with plain REST, but there are some issues with it. Let’s name two of them:

  • REST is always Request/Response “stateless” communication,
  • by the nature of the HTTP protocol, lots of information must be sent in each Request and response.

The first one implies simple fact – web server cannot send anything to the webpage without a Request. There are various workarounds (yes, workarounds. First real standard solution is WebSocket protocol) like long polling or JSONP, but they are solving only the communication from server to client, which implies that there needs to be the other channel from client to server. And we are getting to the second item in short list above – efficiency. When the application needs to communicate frequently with the server, the volume of HTTP traffic can be really big. Now try to compute the entropy (how much information is acquired due to observation of the Request/Response) and see how much redundant and unimportant bytes is sent with each HTTP communication. This is already addressed in HTTP/2, but anyway, the overhead still exists. I intentionally skip the HTTP/2 server push implementation – I plan to address that in another blogpost.

Enough with history lesson and plain “code-less” chatter. You might remember Shared collection sample introduced couple of moths ago in Tyrus workspace – the last modification of it was inspired by the discussion with that colleague – I wanted to compare REST and WebSocket implementation of the same thing.

Quick recapitulation – the sample exposes a map-like object in JavaScript and Java and synchronises their changes using WebSocket. Additionally you can register listeners on both sides, so you always know when anyone changes anything.. basically very simple and fragile implementation of coherence/hazelcast/yourFavouriteDistributedFramework.

As you most likely already expect, I implemented the same thing (or extended that implementation) to support REST based transport instead of WebSocket. I must admit I cheated a little – I used Server-Sent Events (SSE), which is not really RESTful, but this feature is implemented as part of Jersey, which is Reference Implementation of JAX-RS: The JavaTM API for RESTful Web Services and also my favourite REST framework (I used to be a contributor, so consider this as another very-impartial fact). SSE also has simple JavaScript API implemented in all modern browsers, so it was an easy decision for me – I have the channel from server to client covered and the other way will be just standard request using XMLHttpRequest (or an ActiveXObject when in M$ Internet Explorer).

Below is the simple scheme with mentioned protocols.

Screen Shot 2015-03-11 at 16.10.45

When you compile and deploy the sample, the standard behaviour is actually quite comparable (I’m on localhost, so that is not that much surprising), both maps receive and send updates and the experience is almost the same. So let’s look under the hood…

When you create or modify a map entry, browsers sends and event. In case of WebSocket, it is short (text) message containing Json “object” + few bytes (let’s say 8) of overhead – WebSocket message “header”. On the other hand, when you do the same action on REST version of the page, HTTP Request is sent (and Response received – it does not contain anything, just status, headers and no entity):

Screen Shot 2015-03-11 at 16.44.18

I don’t even want to know what is the overhead in this case…

You might say that it does not matter, since we are not connected using 33.6 kbps modems.. well, that’s true, but every byte introduces some delay, additional handling in the network and even app servers – they have to read/write that byte, even when it won’t be used. And that’s not everything related to the resources utilisation – imagine, that every such Request created new TCP connection to the server (which does not need to be true when HTTP keep-alive is used). Since I’m still on localhost, I wanted to push the bar little higher and wrote simple performance test: method, which will create 10k updates of single map entry (you can execute it by clicking on [PerfTest] button on the sample page – both Rest and WebSocket version have it). Starting with WebSocket – it does what is expected and I can measure how long it takes to have some comparison with REST.. but.. the problem is that the REST version does not even finish. I did not dig into that that much, but seems like every browser has some kind of limit for JavaScript requests. I was usually able to achieve something around 3-5k Requests, but after that, browser “run out of resources”, most likely to protect itself or the target site from potentially DDoS-y case.

Conclusion? If you need truly bi-directional communication, with high frequency of shorter messages (it is far easier to handle those in JavaScript than big ones), you should consider using WebSocket. On the other side, if you have some application, which already works well and uses REST efficiently, you don’t need to change that! REST is still the best solution for lots of use cases, you should look at these two technologies/protocols as complements, not as competitors.

And please don’t forget, that this was not by any means an attempt for unbiased comparison :-) Any comments/feedback is appreciated!


Posted in java | Tagged , , , , , , | Leave a comment

Simplest picture gallery (bash, convert)

This is more for me than for others, I just thought someone else could also use it ;)

mkdir orig ; mkdir small ; mkdir thumb
# upload all pics into "orig" directory
ls ./orig | while read X ; do convert -resize 40% ./orig/"$X" ./small/"$X" ; done
ls ./orig | while read X ; do convert -resize 5% ./orig/"$X" ./thumb/"$X" ; done
ls ./small/ | while read X ; do echo "<a href='$X.html'><img src='thumb/$X' /></a>" >> index.html ; done
ls ./small/ | while read X ; do echo "<a href='./orig/$X'><img src='small/$X' /></a>" > "$X".html ; done

The result is just a basic gallery, but surprisingly, it works and it does not screw pictures like facebook and others sharing services. Of course, you will need to have some webserver somewehere to share it with others.

What I also usually do is something like:

 zip -j ./orig/all.zip ./orig/*
 zip -j ./small/all.zip ./small/*

to allow easy download of all pics.

Enjoy! :)

Posted in other | Leave a comment

Why Checkstyle matters…

I’ve read something about ZeroMQ and its java clone recently and decided I should give it a try. JeroMQ is quite small project (same as ZeroMQ I guess), so I decided to checkout the sources directly, since that usually gives me last version of everything, including samples etc. When I opened the project in my IDE, I noticed some minor issues in the code, starting with some unnecessary properties, ending with missing null checks and invalid String comparisons. (You can find these in any project, so that was not so surprising).

Interesting part started when I fixed the issues locally and ran “mvn clean install” to verify my changes, build failed. No surprises there ;) but it failed on check style issues. That was something I did not expect. It turned out, that the project enforces defined set of rules. Not saying that I like the style chosen for that particular project (common guys, its Java, not C), I really liked the idea behind that decision.

Generally, it is far better when single project uses single code style – developer might need to adapt to that and it can take time, but for me, when I got past this period, code is much easier to read and understand, because I don’t need to think about that particular formatting, looking for potentially mistyped code blocks or parenthesis etc. Even when switching among projects with different code style, it is still better than having to adapt to various styles in single module or even class. (Yes, that happens. In any older project, which accepted contributions from lot of people).

After this reflection, I thought about applying this to one project, where I can do almost anything I want – Tyrus. Short version: I did it!

Slightly longer version: It was a pain. Really. And I don’t have by any chance that rich check style rule set as mentioned JeroMQ. To be honest, I thought that we should be fine, since we do often detailed code reviews, but you can always miss something which is not really well formatted.. Nice fact about Checkstyle is, that there are no compromises. You can exclude some rules for some class or even some lines of that class, but .. why? It would add unnecessary housekeeping when modifying the code and it could be accidentally disabled by just refactoring the class name. So I went for “zero tolerance” for defined rules.

The problem is, that there is no simple tool which would fix all check style issues. It kind of makes sense, since lots of them are not easily fixable automatically. Anyway, I found some recipe which involved Eclipse plugin and generating Eclipse formatter from checkstyle.xml. That worked somehow and the formatter can be exported and included to other IDEs (I personally use IntelliJ). There are some issues. One of caveats was max line length. The formatter was able to “clean” these warnings from the build, but sometimes produced code like:

if (wseMaxSessionsAnnotation != null) {
   TyrusServerEndpointConfig.Builder builder = TyrusServerEndpointConfig.Builder.create(annotatedClass,

Which is far from acceptable :). Long story short, I ended up with defining own formatting rules, setting them in IntelliJ code style, reformatted and then manually checked and fixed issues in all changed source files. It was originally ~500 files, it shrunk a little after my review, since I removed all non-java files from that change. You can see the commit at github (don’t worry if it takes some time to load, it is a bigger one).

Anyway, I’m still glad I did that. Now I know that once the build or pull request passes, it has the code already formatted in a way, that I don’t need to check it (that much). If you are interested, there is checkstyle-build.xml used for build time validation, and the configuration in pom.xml.

What can be better? IntelliJ and I guess even other IDEs could be more accessible for checkstyle configuration. Meaning that formatter/code style/… should have better support for importing checkstyle config file + it should be able to actually use it well. The latter statement is almost true (for some edgecases, which cannot be easily solved I guess), so the first one is more important. Since I know that the settings are already there and its only about correct values of some properties, I cannot see it is not already there.

That’s it for now ;) Hopefully you’ll feel inspired and try to at least run the checkstyle configured to your code style and see whether you can incorporate it easily in your build. If you have any suggestions or comments about this topic, please share them with me, especially if I left out something usable for Tyrus or other projects. Thanks!

Posted in java | Tagged , , , , | Leave a comment

Tyrus 1.10

Tyrus 1.10 is a maintenance relase, so unfortunately no cool new features to highlight, but we were able to add some new examples – Shared collection and BTC Xchange.

Complete list of fixed issues is below. I would like to thank to java.net users “toto2″ and “gray” for their help with GLASSFISH-21213. There is one other issue worth mentioning and that is TYRUS-329. In 1.10 release, Tyrus (after added tests for Per-Message compression) becomes fully compliant with Autobahn Test Suite.

Let me shortly introduce the new samples which were added in this version, just to make this blog post justifiable :).

Shared Collection Sample

In this example I tried to explore one possibility of data sharing between JavaScript client and Java code. The sample name could be misleading, the only implemented collection is a Map, which is backed up by WebSocket connection going back to the server. Both sides do implement “standard” Map, with some added flavour of distributed structures – update listener.

If you want to try it, you can follow the instructions in README.html; the application should present itself with a simple JavaScript based interface to modifying the content of the map. Don’t modify the content right away, open it in another window and observe how fast are changes propagated to other window(s).

BTC Xchange Sample

Another sample which demonstrates simple-to-implement communication with JavaScript code. On the title page you can see the graph, which in this case represents current exchange rate BTC/USD and there are some buy and sell proposals which can be executed. The sample currently allow you to go to “red numbers”, but you can create few simple modifications and make a “game” from that – the sample can be also opened from multiple windows and you can try to compete with someone else; for example, you can make a goal of getting some amount of USD or BTC :)

Complete list of changes

  • [TYRUS-394]  – Proxy bypassed on Linux but not on Windows.
  • [TYRUS-391]  – Tyrus reconnect handler not reached on Android.
  • [TYRUS-393] – Incorrect handling of sending whole message during (unfinished) partial message.
  • [TYRUS-329] – Deflate extension fixes – autobahn test suite.
  • [GLASSFISH-21213] – Deadlock (HttpSession vs TyrusWebSocket).
Posted in java | Tagged , , | Leave a comment

Is WebSocket Session really thread safe?

Todays article would be about one simple use-case of JSR-356: Java API for WebSocket. This was brought to my attention by Mark Thomas, who started relatively long thread on the jsr356-experts mailing list. The described problem can be simplified to following code:


You might be wondering what is the problem here.. first message is sent asynchronously and the second one synchronously. Session object itself is meant to be thread safe (last paragraph on class level javadoc), but there is a problem with container itself, more precisely with RemoteEndpoint.Basic interface, see following quote of its documentation:

If the websocket connection underlying this RemoteEndpoint is busy sending a message when a call is made to send another one, for example if two threads attempt to call a send method concurrently, or if a developer attempts to send a new message while in the middle of sending an existing one, the send method called while the connection is already busy may throw an IllegalStateException.

What I get from this paragraph is that the second line (from the sample above) can throw an IllegalStateException, when previous message is not sent. To be honest, reference implementation did not throw that exception (ever) and I don’t believe that any sample application or any WebSocket application I wrote checks for that state. Anyway, the javadoc does not mention that it MUST throw an exception, so for the mentioned sample, it is ok to block the second send until both messages are sent.

Unfortunately, that’s not all :). WebSocket API also allows sending partial messages and when you mix partial messages and whole messages in this context, you might start getting small headache… let’s consider following:

session.getBasicRemote().sendText(message, false); // partial msg
session.getBasicRemote().sendText(message, true); // partial msg

In this sample, the second message should not be sent before the message from third line. Problem arises when this sequence is executed from a single thread – if second line blocks until text message is completed, we would have a problem. Implementation cannot really assume what will or won’t happen and generally it does not want to block the thread for a long time, so throwing IllegalStateException seem to be relatively OK.

(Sidenote: reference implementation, Tyrus, did not handle this scenario correctly.  The issue related to this functionality was filed as TYRUS-393 and the fix will be present in next released version – 1.10)

Since this seem to be grey area in the specification (it says what “may” be done, not what MUST or MUST NOT be done), the implementation can choose whatever it want – actually I believe that blocking the thread and waiting until it can send a message is valid, specification compliant approach. For Tyrus, I implemented little more defensive solution: the implementation waits (blocks the thread) for short period of time and if the conditions still don’t allow sending the message, IllegalStateException will be thrown.

Conclusion is not as clear as it should be – WebSocket Session object is thread safe for sure, but there are some conditions and states, which might be surprising and confusing for common users of this API. All of them can be prevented by following some rules when using WebSocket Sessions – for example if you are sending only whole messages synchronously, you don’t need to care about anything. If you are sending messages only asynchronously, it should be similar, but you might encounter some discrepancies among the implementations. When you want or need to send partial message, the issue might be harder to deal with – since WebSocket Session does not offer any way how to check the current state, it will need to be stored somewhere else and checked before invoking send* methods. My current advice is that the applications you write should add handling of  IllegalStateException from RemoteEndpoint.Basic.send* methods, especially if you expect that it can be run on different JSR 356 implementation.

Posted in java | Tagged , , | Leave a comment

Reducing WebSocket client jar size with ProGuard

We already know there is a demand for standalone web socket client runnable even on different platforms than just Java EE or Java SE – Tyrus publishes client runtime all-in-one bundles for Java 6 (works on Android!) and Java 7+ (takes advantage of NIO API introduced in Java 7). In following article, we will try to create optimised version of these bundles to see whether they do contain some redundant classes. (spoiler: they do).

Tool of the choice for todays exercise would be ProGuard. Maybe not that easy to use, but it is low-level tool capable of various optimisations. We won’t cover any obfuscation, our goal is to create smaller jar with the same functionality.

Starting point is:

551K tyrus-standalone-client-jdk-1.10-SNAPSHOT.jar
1.9M tyrus-standalone-client-1.10-SNAPSHOT.jar

These jar files are representing two distribution which were already mentioned – client-jdk is Java 7 based client, client jar is Grizzly based (JDK 6+). For those who don’t know, Grizzly is Java NIO container, so it basically does the same thing as Java 7 NIO API, but in a little different manner. Also, Grizzly is the NIO framework of choice for Glassfish, Java EE reference implementation.

Downloading and executing ProGuard is not complicated, there is even GUI if you are more used to this kind of applications. After initial study and few trial runs, it seems I can produce optimised jar files with following configuration:

-keepattributes Signature,InnerClasses,*Annotation*
-keepclassmembers,allowoptimization enum * {
public static **[] values();
public static ** valueOf(java.lang.String);

-keep public class org.glassfish.tyrus.** { public protected private *; }

-keep public class javax.websocket.** { public protected *; }


 The command line for running this configuration against Tyrus client distributions would look somehow like following:

proguard.sh -injars ./client-jdk/target/tyrus-standalone-client-jdk-1.10-SNAPSHOT.jar -outjars tyrus-client-jdk.jar -libraryjars $JAVA_HOME/jre/lib/rt.jar @tyrus-client.pro

(previous line is for client-idk distribution, but it is very similar to the other one; just for the completeness of presented data, I’m using JDK 8; if you are using different version, your “-libraryjars” parameter might need to be adjusted).


533K tyrus-client-jdk.jar
1.2M tyrus-client.jar

For the Java 7+ client distribution, the difference is actually quite small, so we can make an assumption that the distribution is already quite optimal. The other is different story – but there is a good reason for it. Java 6+ distribution is based on Grizzly and Grizzly is mainly written as a server, not as a client. We are reusing some stuff from there, but the problem seem to be in not optimal modularization for client usecases. Anyway, just to sum that up, ProGuard was able to find and remove approximately 700 kB of “not used code”.

The conclusion is that you should consider using tool similar to ProGuard, especially when you are redistributing any java application. Special note for Android developers: you are already doing this, maybe even without knowing – DexGuard seem to be standard part of Android application development lifecycle.

Posted in java | Tagged , , , | Leave a comment

New Tyrus sample – Shared Collection

Sometime in JavaOne 2014 timeframe colleague came to me and showed me Meteor.js library, which seems to be really nice javascript framework, client and server side (kudos to the authors!). I started looking at the docs and examples and discovered leaderboard sample. In short, it is about having javascript collection backed up by some (persistent) storage on the server side, which is also shared (or replicated, if you wish) to all other clients. Meteor.js does this in Javascript “class” called Mongo.Collection (used to be Meteor.Collection, but it was renamed before 1.0 release). I really liked the idea and dug little bit more into the implementation and saw that they are using Socket.IO for the communication with the server, which is basically websocket (+fallback and other handy features).

Long story short – I wanted to do something similar and ideally publish it as Tyrus sample :-) and it wasn’t that hard! Obviously, this task is more about client javascript implementation than about what is going to happen on the server side, but it was refreshing experience – next step is Tyrus version of  Socket.IO (nah, I’m kidding…).

I don’t really want to go into details in javascript implementation, since I don’t feel very confident about that (and you can check it out in the Tyrus sources), but the goal was to create a java map-like API to store data and have it synchronized using WebSocket with all other client.

 * Create new Tyrus map.
 * @param {string} url
 * @param {function} updateListener
 * @constructor
Tyrus.Collection.Map = function (url, updateListener) {
  // …

I created Tyrus.Collection namespace and “class” Map in it. The constructor have two arguments – URL of websocket endpoint and update listener. Update listener is invoked whenever the map is changed (this is not optimal, so currently it might be called even when you are putting the key value pair which is already there). Map has following public methods, which should feel familiar for java developers:

     * Get size of the map.
     * @returns {Number} number of records in the map.
    self.size = function () { };
     * Return {@code true} when the map is empty.
     * @returns {boolean} {@code true} when the map is empty, {@code false} otherwise.
    self.isEmpty = function () { };

     * Get value corresponding to provided key from a map.
     * @param {string} key key.
     * @returns {*} value for corresponding key or {@code null} when there is no such key.
    self.get = function (key) { };

     * Put an item into the map.
     * @param {string} key key.
     * @param {*} value value.
    self.put = function (key, value) { };

     * Remove key (and corresponding value) from the map.
     * @param {string} key key to be removed.
    self.remove = function (key) { };

     * Clear the map.
    self.clear = function () { };

     * Get the key set.
     * @returns {Array} array containing all keys from the map (as indexes AND values - TODO).
    self.keySet = function () { };

Server side implementation was quite simple and it currently stores the info only in static map. You can easily extend this by persisting the map to file/database/anywhere else. The communication is driven by very simple protocol, which broadcasts mutating messages to other clients. All get operations are handled by client-side javascript, the map on the server side is kept in sync only because it is a source for clients connected later – this is why this is just “shared” map, not “distributed” (which would be more complicated to implement). The source of the sever endpoint can be found on github, in samples directory: SharedCollectionEndpoint.

Instruction how to run this sample are included in README.html in sample root dir.

When you access the front page, you should see something like:

Tyrus Shared Collection Sample

You can add/modify existing items in the map by using the form on the bottom side (it will automatically load an item when you click on it) and you can remove any item by clicking on the red cross on the right side. All changes should be automatically propagated to all other clients (just open the page in another browser window).

Hope you’ll enjoy the new sample and if you have any comments or suggestions, please send us a note to users@tyrus.java.net.


Posted in java | Tagged , , , , , | Leave a comment