Random JCache stuff: multiple Providers and JMX beans

JCache (JSR 107) is the Java standard for Caching… enough said. No more introductory stuff.

This is a quick fire post which talks about

  • Multiple JCache provider configurations, and
  • Feature: JCache stats via JMX Mbeans

Managing multiple JCache providers

In case you are dealing with a single JCache provider, javax.jcache.Caching.getCachingProvider() returns an instance of the one and only CachingProvider on your classpath.
If you have multiple JCache implementations on your application class path, an attempt at using the above snippet to bootstrap your JCache provider will greet you with the following exception (which is surprisingly friendly !)

javax.cache.CacheException: Multiple CachingProviders have been configured when only a single CachingProvider is expected

Overloading to the rescue!

There are overloaded versions of the getCachingProvider method, one of which allows you to specify the fully qualified class name of a specific JCache provider implementation. The exact class name would be provided as a part of your JCache vendor documentation e.g. com.tangosol.coherence.jcache.CoherenceBasedCachingProvider and com.hazelcast.cache.HazelcastCachingProvider are the provider classes for Oracle Coherence and Hazelcast respectively.

This would work just fine:

CachingProvider coherenceJCacheProvider = Caching.getCachingProvider(“com.tangosol.coherence.jcache.CoherenceBasedCachingProvider”).getCacheManager()

You can also grab the same from the META-INF/services/javax.cache.spi.CachingProvider of the JCache provider JAR file

JCache Provider SPI Configuration

JCache Provider SPI Configuration

JMX statistics

JCache offers configuration and run time performance statistic for free! This is driven by provider specific implementations.

  • javax.cache.management.CacheMXBean – make sure you enable this by calling setManagementEnabled(true) on the JCache MutableConfiguration object
  • javax.cache.management.CacheStatisticsMXBean – – make sure you enable this by calling setStatisticsEnabled(true) on the JCache MutableConfiguration object

Example snippet

MutableConfiguration config = new MutableConfiguration().setManagementEnabled(true).setStatisticsEnabled(true);

Introspect the Mbeans from JConsole or any equivalent client

JCache Configuration stats

JCache Configuration stats

JCache runtime performance stats

JCache runtime performance stats

Nice ha ?

Cheers! :-)

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

WebSocket Client API in Java EE 7

In this post, let’s explore the less talked about Web Socket Client API and how to leverage it within a Java EE 7 container itself

Web Socket Server API rules

The server side API of JSR 356 (Web Socket API for Java) is most commonly used for building Web Socket endpoint implementations. More often than not, from a client perspective, the standard JavaScript Web Socket API is leveraged by the HTML5 (browser) based clients which attach themselves to web socket server end points and enjoy bi-directional and full-duplex communication. You would have seen common examples such applications such as live maps, stock tickers, games, screen sharing etc – all these use cases are perfect for Web Sockets and Java EE 7 is the ideal platform for building scalable Web Socket driven back end.

What about the Web Socket client side API ?

The Web Socket specification includes a client side API as well and its mandatory for all JSR 356 (e.g. Tyrus, Undertow etc) implementations to provide one. There are quite a few use cases wherein a browser based / end user facing web socket client might not be required.

Example

Consider a scenario where you want to connect to a third party Web Socket end point, consume it’s information and persist it for later use ? Maybe for further analysis ? In such cases, its useful to leverage the client API within the Java EE container itself.

Let’s explore this with a simple example.

(annotated) Web Socket Client

Note: the logic for @OnMessage was excluded on purpose and has been implemented in a different way (clarified later)

A Stock Ticker (info) JPA entity

A Stateless bean

  • Handles persistence of Stock Ticker info
  • Executes its operations against the default JDBC data source provided by the Java EE 7 container (convention over configuration in action!)

Singleton EJB

  • Leverages the Web Socket ContainerProvider API
  • Initiates the connection to a web socket server
  • Injects the StockInfoPersistenceService bean and uses it within the addMessageHandler implementation

As per previous note, the (persistence) logic which could have been embedded in a @OnMessage annotated method within the StockTickerClient class has been included here. This is because the injection of the StockInfoPersistenceService (stateless) bean was failing and the instance itself was being resolved to null.

That’s pretty much it. Although this was a relatively simple example, its not too hard to imagine that one can apply any sort of complex business logic on the information received by the web socket server endpoint. You might also want to think about sending messages to connected clients in an asynchronous fashion using the session.getAsyncRemote#sendAsync method

Cheers!

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

RESTful timers in Java EE

In this post….

  • Whirlwind tour of EJB timers
  • Working with EJB timers on the fly via simple REST interface with a sample implementation

——————————- Update (14 July 2015) ————————-

The front end for the application is now available on OpenShift. Since I am a front end novice, I assembled this HTML5 + AngularJS app with help from other sources ;-) So it might feel a little clunky. Please bear with me while I try and improve upon this!

From the UI, you can

  • look at all the active timers
  • create a timer
  • cancel a timer

——————————- Update (14 July 2015) ————————-

The EJB @Schedule annotation comes in handy in case you need to create timers automatically. One can use cron-like expression to configure the appropriate schedule. If you need more flexibility, the good old TimerService works like a charm.

Quick background

  • The TimerService interface was Introduced in EJB 2.1 [yeah .. J2EE days ! ;-) ]
  • Used to create Timer objects programmatically
  • Used to work in conjunction with an implementation of the TimedObject interface [pre EJB 3.0] to serve as a call back for timer triggers
  • Since EJB 3.0, the @Timeout annotation was used to mark a method in a (stateless/singleton/message driven) bean to act as the receiver of timer call backs from the EBJ container
  • Things were further improved in EJB 3.1 with the introduction of ScheduleExpression which allowed fine grained timer scheduling – this was the programmatic equivalent of @Schedule

EJB Timer related components (for quick reference)

RESTful Timers

One can easily expose a simple RESTful interface to work with EJB Timers. Actions such as creating timers, fetching timer details as well cancelling timers can be executed on the fly.

A simple implementation is available via this Github project. It’s a simple Java EE 7 Maven project built on Netbeans. You should be able to set it up easily.

Here is a gist

  • POST a request to schedule a timer (JSON/XML payload representing the schedule configuration)

  • GET all active timers and their respective details (JSON/XML representation)

  • GET information for a specific timer (JSON/XML representation)

  • DELETE (cancel) an existing timer

The WADL should tell the story

RESTful-EJB-Timers-wadl

Cheers!

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

JAX-RS and HTTP ‘OPTIONS’

The JAX-RS specification defines sensible defaults for the HTTP OPTIONS command. I actually stumbled upon this by chance! Not sure of this is very obvious (if it is, be kind and don’t laugh at me !)

The discovery

For the JAX-RS resource represented in the code snippet below, if you execute a HTTP OPTIONS command against the http://host:port/context-root/user URI, you will be surprised to not get a HTTP Status 404 – Not Found error message [ at least I was surprised, until I looked in the JAX-RS specification document of course ;-) ]

It gave me back the WADL as a response. Sweet ! :-)

WADL returned by the JAX-RS runtime

WADL returned by the JAX-RS runtime

To be noted

  • If there is an explicit resource method which is annotated with @OPTIONS, then the corresponding logic will be executed and the default behavior would get suppressed (now that’s obvious!)
  • This does not mean that you can execute the OPTIONS command at any random URI within your RESTful app. This kicks in after the request matching process and will be applicable only for a valid URI as defined by @Path annotations in your resource classes.
  • I tested with Jersey 2.10 on Glass Fish 4.1. This is standard feature mandated by the specification, hence it is applicable to ANY JAX-RS compliant implementation out there (e.g. RESTEasy)

Cheers!

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

‘Micro’ Java EE on the cloud with ‘dockerized’ Payara

Thankfully I don’t have to write much because I have a screen cast.. Yay ! My second one [ trying to get better at this ;-) ]

The idea is to show you how easy it is to get up and running with Java EE on the cloud. I decided to use Payara and its docker images because I particularly like its micro version. This should be applicable to any other dockerized Java EE server though e.g. Weblogic 12c.

Here is list of the commands for your reference

General Docker setup

  • sudo yum update
  • sudo yum install -y docker
  • sudo service docker start
  • sudo usermod -a -G docker ec2-user
  • docker info

‘Dockerized’ Payara setup

  • docker search payara
  • docker pull payaradocker/payara-micro:4.1.152.1.micro.oraclejdk8
  • docker run –name pmc -d -p 8080:8080 -i -t payaradocker/payara-micro:4.1.152.1.micro.oraclejdk8 /bin/bash
  • docker ps
  • docker attach –sig-proxy=false pmc
  • java -jar payara-micro-4.1.152.1.jar –port 8080 –deploy showcase-5.2.war

Useful links

Cheers amigos !

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

Quick tip: Exception handling in Message Driven Beans

Let’s do a quick review of exceptional handling with regards to Message Driven Beans.

The entry point into a MDB is the overridden onMessage method. It does not provide any scope for throwing checked exceptions and as a result, you will need to propagate unchecked exceptions (subclass of java.lang.RuntimeException) from your code if you want to handle error scenarios.

Types of exceptions

There are two categories of exceptions defined by the EJB specification and the container differentiates one from the other based on well stated semantics (again, in the EJB specification).

Application Exception

If you throw a checked exception (not possible for MDB but other EJBs can use this) which is not a java.rmi.RemoteException or it’s subclass, OR a RuntimeException (unchecked) which is annotated with @javax.ejb.ApplicationException, the container treats this as an Application Exception. As a result, it rolls back transaction if specified by the @javax.ejb.ApplicationException rollback attribute and retains the MDB instance for reuse – this is extremely important to note.

System Exception

If you throw a java.rmi.RemoteException (a checked exception) or it’s subclass, OR a RuntimeException (unchecked) which is not annotated with @javax.ejb.ApplicationException, the container treats it as a System Exception. As a result, it executes certain operations like transaction rollback and discards the MDB instance (this is critical).

What about the critical part ??

It is important to take into account, the discarding of the MDB instance. In case of System Exceptions, the container always discards the instance – so make sure that you are using these exceptions for their intended reason. In case you are using Application Exceptions and they are unchecked ones (they have to be in case of MDBs), make sure you annotate them with @javax.ejb.ApplicationException – this will ensure that the MDB instance itself is not discarded.

Under heavy loads, you would want to have as many MDBs in the pool as possible and you would want to avoid MDB instances being moved out of service. Sensible exception handling can help you realize this goal. It’as simple as annotating your exception class with @javax.ejb.ApplicationException and leaving the rest to the container :-)

References

The EJB (3.2) specification is a 465 page PDF which might look intimidating at the outset, but it’s a great resource nonetheless and not that hard to grasp. In case you want to understand Exception Handling semantics in further detail, please do check out Chapter 9 which is dedicated to this topic

Cheers!

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

Types of JMSContext in JMS 2.0

If you follow Java EE, the simplified API components in JMS 2.0 (Java EE 7) will not be unknown to you. One of the important interfaces which forms a part of the simplified API is the javax.jms.JMSContext interface.

JMSContext can be categorized in to two types depending on how it’s instance is obtained and managed (life cycle) – Container managed and Application managed

Application Managed

Let’s look at a code snippet

In this case, an instance of JMSContext was obtained using ConnectionFactory and hence needs to be closed by the application code. The container will not manage it’s lifecycle

Container Managed

If you use @Inject to allow the container to inject the JMSContext instance, the container assumes full responsibility for it’s lifecycle.

If you call close() on a container managed JMSContext, you will end up with this exception – javax.jms.IllegalStateRuntimeException: This method is not permitted on a container-managed (injected) JMSContext.

And….

In the previous example, the container automatically uses the default Connection Factory (as per Java EE 7). You can also leverage @JMSConnectionFactory annotation (another useful addition to JMS 2.0) to specify a Connection Factory of your choice.

That’s it for now.. Cheers !

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

Java EE 7 in production . . . so far. . .

This is a quick post for folks who are searching for examples/instances of real world a.k.a production use of Java EE 7 . Please note that this list is courtesy two major sources –  JavaOne Conference (2014) talk delivered by Arun Gupta (check out the entire talk here) and Adam Bien’s blogs

  Let’s check them out……..

UNHCR ( UN Refugee Agency ) using  Java EE 7 on GlassFish 4

unhcr

tipi.camp using Java EE 7 on Wildfly 8.1

tipi

more information here and here

ZEEF powering search with Java EE 7 on Wildfly 8.2

zeef

read more on Adam’s blog

Hubeo leveraging Java EE 7 on Wildfly 8.2

hubeo

details on Adam’s blog

SAFSMS is a School management software using Java EE 7 on GlassFish

safsms

learn more here

DreamIT ( probably upgraded to Java EE 7 on GlassFish 4.1 already )

dreamIT

continue reading on Adam’s blog

IMO start up dynamics are quite different and more challenging in terms of many respects as compared to bigger organizations. Hence its rather heartening to witness the amount of faith being put into Java EE 7 by these companies and the way they are leveraging the stack.

Cheers !

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

Oracle IDM 11g R2 PS3: What’s new ??

Self Service and End User empowerment

Simplified Self Service UI

Better look and feel. More intuitive. Modern skin/widgets

simplified-UI

 

 

simplified-UI-1

 

Guided Access Catalog

Easier for end users. Displays steps to be performed much like e-commerce web sites

 

guided-catalog

 

Front end

New skin
Changes to how UI customizations are to be made
Few Design console operations have been deprecated

design-console

 

design-console-2

 

Core

Concept of a Home Organization

A user will be automatically added to an organization based on Home Organization Policy, which is nothing but a set of rules based on user attributes. OIM has default rules (OOTB) and one can build custom rules as well

 

home-org-1

 

home-org-2

 

Introduction of custom Admin Roles (in a simplified avatar)

More dynamic in nature as opposed to static Admin Roles in previous versions. Admin Roles are still there for backward compatibility but NOT recommended

 

admin-roles-1

 

admin-roles-2

 

No dependency on APM and OES

Need not deploy OES component for tweaking fine grained authorization

Temporal Grants for New and Existing Access

Users can specify start and end date while requesting access. This can be overridden by authoritative users and helps manage access more seamlessly

Self Service Capability Policy

Rules within this policy would help determine what operations can a user perform on his own profile. This is also driven by user attributes

 

self-service-cap-policy-1

 

self-service-cap-policy-2

Role Life cycle Management

When working with roles (adding members etc), a user will be able to see related statistics in a graphical fashion which can help him/her make a more informed decision w.r.t the action being executed on the Role

 

role-lcm

 

OIM Role categories are NOT recommended going forwards and usage of Catalog category attribute is advised.
Enhanced Password Policy Management

Enables common password policies for OIM and OAM. More flexibility in terms of defining Challenge Qs (system/user defined)

 

password-[policy

SoD replaced by Identity Audit capability

Needs to be explicitly enabled

identity-audit-1

 

identity-audit-2

Process forms are not required and hence not supported
Form Upgrade and FVC Utility have been dropped
Attestation is no more supported

Reporting and Auditing

Lightweight Audit Engine

A brand new audit engine has been introduced in PS3. This is synchronous in nature (unlike current engine which depends on JMS), pushes data into a single AUDIT_EVENT table. The new auditing engine also supports new entities

BI Publisher exposed via OIM

You can run Identity Audit (some of the reports) from OIM console itself

bi-reports

Approval layer

Introduction of Workflow Policies

Workflow Policies have replaced Approval Policies in PS3. However, in upgraded scenarios, Approval policies will continue to work

 

workflow-policies-1

 

workflow-policies-2

 

workflow-policies-3

 

Running OIM without workflows (disabled state)

A system property can be toggled to disable SOA all together. Although the capability can be re-enabled, but the caveat is that it is NOT recommended/supported

 

workflow-enabled

 

Request Catalog

  • The out of the box search form in Catalog can be replaced by a custom form (taskflow) and configured with the help of a system property called Catalog Advanced Search Taskflow

Catalog Advanced Search Taskflow

  • Its possible to add more attributes to the catalog search form (via UI customization of course)

Displaying additional information for catalog entities

Displaying additional information for App Instance, Role and Entitlement (post checkout) can be driven with help of customized taskflows which can be configured by using system properties Catalog Additional Application Details Task Flow, Catalog Additional Role Details Task Flow and Catalog Additional Entitlement Details Task Flow respectively.

request-catalog

 

Integration layer

REST services based in SCIM (Simple Cross Domain Identity Management) protocol

Finally! A standards based REST interface on top of OIM. Supports limited operations as of now, but its a good start

 

scim-1

 

scim-2

 

Remote Manager usage is NOT recommended any more and has been removed from a documentation standpoint (might be deprecated from future releases)

SPML support dropped
Callback Service support dropped
Simplified SSO Integration (without OAM)

Use basic HTTP (web) servers and integrate SSO with OIM on basis of HTTP headers

Diagnostics

Orchestration Engine MBean

This is a nice addition which helps probe the Orchestration kernel (engine) related information (its actually is a standard JMX bean implementation). Its accessible via Enterprise Manager and exposes operations like pushing orchestration info to a file, finding event handlers, finding events per process etc. Also aids in debugging orchestration process failures

orch-mbean

 

Enjoy !!!

Posted in Oracle Identity Governance, Oracle Identity Manager | Tagged , , , , | 2 Comments

Taking Ozark for a test drive…

Hey… my first screencast.. aka video blog ;-) Although it’s 20 minutes long, but I am pretty sure that actually writing a blog would have taken longer. Feels good… pretty efficient ha !

So what’s this about ?

Trying to experiment with Ozark, the Reference Implementation for MVC 1.0 which is a candidate for inclusion in the upcoming Java EE 8 Platform release..

The code is available on my github account (just in case!)

Enjoy!

Posted in Java, Java EE | Tagged , , , | 1 Comment