WebSocket endpoint as Singleton EJB

By default …

… a WebSocket implementation creates a new (server) endpoint instance per client. In case you need a single instance, you can implement this using a custom ServerEndpointConfig.Configurator (by overriding the getEndpointInstance method)

The catch: you might have to sacrifice some of the (Java EE) platform related services like dependency injection and interceptors

More details here

Alternate solution ?

A similar behavior can be achieved by decorating the WebSocket endpoint with @Singleton

This approach has the caveat of not being a standard feature outlined by the spec (although injection of EJBs as well as interceptors support is clearly mentioned in the Java WebSocket spec Sec 7.1)

Concurrency semantics ?

In case of a @Singleton, all the clients will interact with the one-and-only server endpoint instance. Here is a quick summary of how the EJB as well as WebSocket threading semantics are applied

  • The Singleton bean default approach WRITE lock ensures single threaded access across all connected clients
  • If thread-safety is not a concern (e.g. in case where you do not deal with client specific data/state in your logic) and in case the single-threaded access model proves to be a bottleneck, override the default behavior by switching to a READ lock which allows concurrent threads to access the methods (unless of course a WRITE lock is not already in effect)

Note: The above mentioned semantics are with respect to ALL the WebSocket clients. From the point of view of a single client, the default strategy of one thread at a time, per endpoint instance per client continues to apply (more details here)

Further reading..

Cheers!

Posted in Java, Java EE | Tagged , , , , | Leave a comment

New release: Java WebSocket API handbook

Happy to announce the initial release of the Java WebSocket API handbook. This is still a work in progress but moving at a strady pace. You can read this on Gitbook or grab your PDF/ePub/Mobi version from Leanpub

 

cover

Here is a quickie about the book

The book is what it says it is – a handbook, a quick reference, a fast track guide. It covers the nitty gritty of the Java WebSocket API which is a standard (specification) for building WebSocket applications. It is targeted (primarily) towards Java/Java EE developers and can be used in various capacities

  • As a getting started with the Java WebSocket API guide
  • You are already well versed with this API and its constructs, but need a quick peek/reference to a specific API, it’s usage, nuances etc.
  • Maybe you’re just curious about what Java has to offer in terms of WebSocket support – feel free to check it out

Current status

The majority of the big ticket chapters are complete

toc.jpg

Enjoy!

 

 

Posted in Java, Java EE | Tagged , , , , , | Leave a comment

Microservices messaging on Oracle Cloud using Apache Kafka

Here is a blog I posted on the Oracle Cloud Developer Solutions portal. This is the first of a two-part series which shows asynchronous messaging b/w microservices with the help of a simple example (application)

high-level-arch.jpg

 

Technical components

Oracle Cloud

Open source

  • Apache Kafka: scalable pub-sub message hub
  • Jersey: Used to implement REST and SSE services. Uses Grizzly as a (pluggable) runtime/container

Cheers!

 

Posted in Cloud, Java, Oracle Application Container Cloud, Oracle Cloud, Oracle PaaS | Tagged , , , , , , , , | Leave a comment

(eBook) ‘REST assured with JAX-RS’ now available on Gitbook

title_page.jpg

 

 

You can now read REST assured with JAX-RS online on Gitbook, or grab the PDF from Leanpub.. Happy reading!

Posted in Java, Java EE | Tagged , , , , | Leave a comment

Using Asynchronous timeouts in the Java WebSocket API

Sending messages in an asynchronous manner avoid blocking the sending thread. This is a great where your solution needs to scale in order to support a large number of clients.

But there is a limit on how long can we wait for the asynchronous process to complete

The Java WebSocket API gives you a few options in this regard

Async Timeout support

  • first and foremost, there is a notion of a timeout and this can be configured using the setSendTimeout method in the RemoteEndpoint.Async interface
  • secondly, the failure result manifests itself using the Future object or java.websocket.SendResult

How do timeouts manifest ?

It depends on which strategy you’re using in order to send your messages

  • Callback based
  • Future (java.util.concurrent) based

In case you are using the java.websocket.SendHandler i.e. the callback handler route, the timeout exception details will be available via SendResult.getException()

If you chose to use the Future to track the completion, calling it get method will result in a java.util.concurrent.ExecutionException

Further reading

Cheers!

Posted in Java, Java EE | Tagged , , , , , | Leave a comment

Started a new blog: Simply Distributed

Hello readers!

Happy to announce that I have recently initiated another blog – Simply Distributed. Some things to note about the blog

  • it will revolve around topics in the Distributed Systems domain
  • focus on real world distributed computing products & solutions (e.g. Kafka, Zookeeper etc.)

Some more info here… and also check out the first blog post on Apache Kafka

Cheers and happy reading!

Posted in Java EE | Tagged , | Leave a comment

Dynamic provider registration in JAX-RS

The DynamicFeature class in JAX-RS (2.0) allows you to register providers

  • Dynamically i.e. without any pre-defined binding strategy (e.g. annotations)
  • Based on criteria i.e. to help decide which provider to bind to which JAX-RS resource(s)

The JAX-RS implementation detects and executes the DynamicFeature implementations at deployment time

Here is an example where we instruct the JAX-RS run time to dynamically bind the AuthenticationFilter (a JAX-RS post construct filter) to be applied when a PUT is invoked on UserResource (which is a JAX-RS resource class)

Criteria based

Criteria is provided by ResourceInfo and it’s based on 2 attributes

  • the resource class, and
  • the resource method

Dynamic

The dynamic registration is achieved using FeatureContext whose register method can be used to bind the provider

Note

  • @Provider usage is needed for automatic discovery by the JAX-RS run time
  • Applicable for – filters, interceptors and  any Feature
  • In case of filters, the following applicability criteria apply
    • Post matching (@PreMatching filters excluded)
    • Server side filters i.e. ClientRequestFilter and ClientResponseFilter cannot be registered using this method
  • Once used, it overrides other bindings (static or using @NameBinding)

Further reading

Posted in Java, Java EE | Tagged , , , , | Leave a comment

WebSocket and CDI integration.. again..

In one of my older blog posts, I had written about what does not work as far as WebSocket and CDI integration within the Java EE Platform 😉 This one talks about what’s possible with CDI in terms of

  • Dependency Injection
  • Interceptors

Before you dig in, here is a summary

Feature Supported in EJB Annotated WebSocket endpoint ? Supported in Plain WebSocket endpoint ?
Inject CDI managed beans yes yes
Use CDI interceptors yes yes

DI support

It is possible to inject CDI managed beans in WebSocket endpoints. All injection targets are supported i.e. field, constructor, method

 

Interceptor support

You can use interceptors to implement cross-cutting concerns in for the business methods in your WebSocket endpoints

Good to know

Now that you have an idea about how WebSockets work with CDI in terms of Dependency injection and Interceptors, here are some other points

  • DI and interceptors are supported for both server and client endpoints running within a JavaEE container
  • DI and interceptors are supported for both annotated and programatic endpoints running within a JavaEE container
  • container managed injection features are not available to WebSocket endpoints which override the container implemented initialization (using the ServerEndpointConfig.Configurator)

Additional reading

 

Cheers!

Posted in Java, Java EE | Tagged , , , , , , , | 3 Comments

Integrating Oracle Application Container & Database Cloud using ‘Service Bindings’

blog-logo.jpg

Don’t forget to check out my new blog post on the Oracle Cloud Developer solutions community portal ! It demonstrates usage of Oracle Application Container Cloud and Database Cloud service. To be precise, it covers the following

  • An introduction to Service bindings (in Application Container Cloud) including setup + configuration and leveraging them to integrate with Oracle Database Cloud service
  • Developing a sample (Java SE based) application using JPA (Eclipselink implementation) for persistence and JAX-RS (Jersey framework) to expose a REST API
  • Build, package and deploy the solution to the Application Container cloud using its REST APIs

Cheers!

Posted in Java, Java EE, Oracle Application Container Cloud, Oracle Cloud, Oracle PaaS | Tagged , , , , , , , | Leave a comment

Configuring WebSocket server endpoints

WebSocket Server endpoint configuration

Before we dive into the details, here is a quick snapshot of the related interfaces

Class/Interface Description
ServerEndpointConfig A derivative of EndpointConfig interface which is specific for configuration related to server side WebSocket endpoints
ServerEndpointConfig.Configurator An interface whose custom implementation allows sharing of global (for all endpoints) available logic/state as well opportunity to intercept the WebSocket handshake process (via method override)
ServerEndpointConfig.Builder Used only for programmatic server endpoints to build a ServerEndpointConfig instance

From here on, we’ll explore the configuration strategies for annotated and programmatic server endpoints

Configuring annotated server endpoints

Annotated server endpoints are configured implicitly via the elements of the @ServerEndpoint annotation. The WebSocket container picks up the value from the annotation elements and creates an instance of EndpointConfig behind the scenes. This instance is automatically injected (at run time by the WebSocket container) as a parameter of the @OnOpen method

Configuring programmatic server endpoints

Programmatic endpoints need (explicit) coding as far as configuration is concerned. This is because of the fact that programmatic endpoints are deployed differently and need an instance of ServerEndpointConfig

Please look at this blog post for details of the deployment aspects for programmatic WebSocket endpoints

Here is where the fluent builder ServerEndpointConfig.Builder comes into picture. Let’s look at an example which deomnstrates it’s usage

The big picture

Annotated and programmatic endpoint configuration are handled differently, but the end result is the same. Below is a table which shows the mapping b/w corresponding element of the @ServerEndpoint annotation, the corresponding method in ServerEndpointConfig as well as appropriate the method in the ServerEndpointConfig.Builder

@ServerEndpoint annotation element ServerEndpointConfig method ServerEndpointConfig.Builder method
value getPath() create(Class<?> endpointClass, String path)
configurator getConfigurator() configurator(ServerEndpointConfig.Configurator serverEndpointConfigurator)
decoders getDecoders() decoders(List<Class<? extends Decoder>> decoders)
encoders getEncoders() encoders(List<Class<? extends Encoder>> encoders)
subprotocols getSubprotocols() subprotocols(List subprotocols)

Also check out…

.. the new eBook – Java WebSocket API Handbook

Cheers!

Posted in Java, Java EE | Tagged , , , , | Leave a comment