Skip to content

Feed aggregator

Integrating iTunes into Oracle JET

Here's a search string for iTunes:

Let's integrate that into an Oracle JET application, with this result:

After a bit of fiddling with the parsing of the JSON, this is how I built up the table above.

Here's the view:

<table data-bind="ojComponent: {component: 'ojTable',
    data: dataSource,
    columns: [
        {headerText: 'Name', field: 'name'},
        {headerText: 'Price', field: 'price'}

Here's the viewModel: 

define(['ojs/ojcore', 'knockout', 'ojs/ojtable'
], function (oj, ko) {
    function homeContentViewModel() {
        var self = this; = ko.observableArray();
                then(function (json) {
                    var entry = json.feed.entry;
                    $.each(entry, function () {
                            name: this['im:name'].label,
                            price: this['im:price'].label
        self.dataSource = new oj.ArrayTableDataSource(
                {idAttribute: 'name'}
    return homeContentViewModel;

Next steps would be to replace the hardcoded search string with some UI elements so that the user can specify the search string at runtime.

A reference that helped me with the above:

Categories: Open Source

Detecting Java Race Conditions With Tests Part 2: Non-Atomic Updates

If you update a field from different threads, you must make sure that between the read and the write from one thread the field is not updated by another thread. You can achieve this by using a synchronized block or the atomic compareAndSet method. But how can you test it?

Example of a Test

Let us look at an example of an incorrect synchronized class:

Categories: Communities

My Favourite Spring Data JPA Feature

I like Spring Data JPA. It helps simplify my codebase, and most of the time frees me up from writing JPAQL or SQL. I’m also impressed by the complexity of query you can write using Spring Data. My favourite feature is returning the first or top records from a table.

Let's say I have a table tracking document versions -

Categories: Communities

The Developer's Midlife Crisis: What's Next?

This week I resigned from my comfortable, well-paid job.

I guess I reached that moment where one looks back on what he/she has achieved so far, and wonders what's the plan for the next thirty years.

Categories: Communities

Java vs. .NET vs. Python vs. Ruby vs. Node.js: Who Reigns the Job Market?

Every now and then a new article/blog post/opinion piece/twitter rant is published wondering about the future of Java. However, the cold facts state that it’s still the most popular language in the programming world, but what does it actually mean?

In the following post we’ll dig into the buzz around Java through analysing the current job market, focusing on server side languages. Who knows, it might even help you find your next position.

Categories: Communities

Java Web Weekly, Issue 131

baeldung - Coding and Testing Stuff - Thu, 06/30/2016 - 21:00
I just released the Starter Class of "Learn Spring Security":


At the very beginning of last year, I decided to track my reading habits and share the best stuff here, on Baeldung. Haven’t missed a review since.

Here we go…

1. Spring and Java >> Java 9 Additions To Optional []

Some interesting stuff is definitely coming to Optional in the JDK.

>> 5 Common Hibernate Exceptions and How to Fix Them []

I like to go through these exception focused articles – they usually have new insights I can glean for when I do get the exception.

>> Managing Secrets with Vault []

Storing secret configuration data is almost always an important thing to get right in the overall architecture of a system.

It’s also one of the most common question I get from readers when it comes to project configuration. So this writeup is an interesting solution to that question. Not the only solution, but certainly an interesting one.

>> Turn Around. Don’t Use JPA’s loadgraph and fetchgraph Hints. Use SQL Instead. []

A different perspective on picking the persistence solution of your next greenfield project, talking about preferring plain SQL over something higher level such as JPA.

>> 14 High-Performance Java Persistence Tips []

Some low-hanging fruit (and not so low-hanging) to improve the performance of a Hibernate implementation.

>> ‚ÄúMicro Profile in Enterprise Java‚ÄĚ Announced ! [] and >> The Enterprise Java Future Is Bright: Java EE 8 MicroProfile Launched []

Big announcements in the Java EE world (seems like every week now).

>> Close Encounters of The Java Memory Model Kind []

A fantastic deep-dive into the JMM (still reading through it now). Definitely one to bookmark.

Also worth reading:

Webinars and presentations:

Time to upgrade:

2. Technical and Musings >> Code Review and How Enterprises Can Miss The Point []

An insightful analysis of the motivations of different players in a large organization when it comes to code reviews and to getting something useful out of the practice. Well worth reading.

>> How I prepared for the NDC keynote (and other speaker tips) []

Some solid, to the point advice on speaking well.

I feel that speaking is a life-long journey and there’s always a lot to learn. And delivering a good presentation is such an important skill that it really makes sense to spend time and learn how to do it well, as much as possible.

>> Learning a Healthy Fear of Legacy Code []

Here be dragons.

>> Expanding the Cloud: Introducing the AWS Asia Pacific (Mumbai) Region []

Yeah, one more region to play with, after Frankfurt.

>> Special Skills []

There’s a time to study the foundations and there’s a time to specialize. And while foundations are important, specialization and niching down are more and more critical today.

>> Jepsen: Crate 0.54.9 version divergence []

Who knew that the Elasticsearch data consistency problems (which are quite real) would go beyond the core product and spread to other solutions as well. It’s not that surprising though.

>> Amazon Elastic File System ‚Äď Production-Ready in Three Regions [] and Elastic Network Adapter ‚Äď High Performance Network Interface for Amazon EC2 []

Two important announcements of new AWS goodness in a single week.

Also worth reading:

3. Comics

And my favorite Dilberts of the week:

>> Nothing about you is normal [] >> Two good ways to avoid listening to others [] >> Did someone tell you Twitter was a video game? [] 4. Pick of the Week >> This I Believe ‚Äď 25 Thoughts for Life [] Get the early-bird price (20% Off) of my upcoming "Learn Spring Security" Course:


Categories: Blogs

Force Text to UpperCase in RichInputText as the user is typing (make sure the cursor stays in one place)

AMIS Technology blog - Thu, 06/30/2016 - 10:33

The challenge is simple: users of an ADF Faces web application are only allowed to enter uppercase characters into a field. We want to help them by turning any lowercase character they type into its uppercase equivalent – as they are typing. And we of course need to make sure that this works, whether they are adding characters to the string in the input field or typing somewhere in the middle.

Our tools: clientListener for the keyUp event, JavaScript functions to determine the current caret position (position of cursor in text field) and to set the caret position in a specific field. And of course the toUpperCase() function on the JavaScript String object.

Edit: using Luc’s suggestion (see first comment) about the CSS Style property text-transform I have extended this blog post a little. This property can be used to define a style for an element that instructs the browser to show the value of that element in uppercase – even if the value is not uppercase. The user apparently is typing uppercase characters (whereas in fact she is typing whatever she is typing, for example lower case). When the user navigates out of the field, the value can be updated to be really uppercase; the user will not notice this as the field showed uppercase contents all along. The source below contains a second inputText element with this CSS style property set and a simple JavaScript function to perform the final capitalization of the contents.


Below the very simple ADF Faces page with those three JavaScript functions that will make it happen.

    <?xml version='1.0' encoding='UTF-8'?>
    <!DOCTYPE html>
    <f:view xmlns:f="" xmlns:af="">
        <af:document title="Form.jsf" id="d1">
        <af:resource type="javascript">
        /* source: */
        function getCaretPosition (oField) {
      // Initialize
      var iCaretPos = 0;
      // IE Support
      if (document.selection) {
        // Set focus on the element
        // To get cursor position, get empty selection range
        var oSel = document.selection.createRange();
        // Move selection start to 0 position
        oSel.moveStart('character', -oField.value.length);
        // The caret position is selection length
        iCaretPos = oSel.text.length;
      // Firefox support
      else if (oField.selectionStart || oField.selectionStart == '0')
        iCaretPos = oField.selectionStart;
      // Return results
      return iCaretPos;
    /* source: */
    function setCaretPosition(elem, caretPos) {
        if(elem != null) {
            if(elem.createTextRange) {
                var range = elem.createTextRange();
                range.move('character', caretPos);
            else {
                if(elem.selectionStart) {
                    elem.setSelectionRange(caretPos, caretPos);
        function forceUppercase(evt) {
          //TODO filter on evt.getKeyCode() represents a lower case character and otherwise do nothing
          // extract the ADF Faces Rich Client Component - presumably a RichInputText
          var comp = evt.getSource();
          // get the rich client component id - because from it we can derive the identitier for the DOM input element
          var adfComponentClientId = comp.getClientId();
          // get hold of the DOM element into which the user is typing text
          var elem = document.getElementById(adfComponentClientId + '::content');
          // find the current position of the cursor in the input element
          var currentCaret = getCaretPosition (elem);
          // turn the value in the RichInputText to Uppercase; NOTE: this will place the cursor after the last character in the field 
          // return the cursor to the position it was at
          setCaretPosition(elem, currentCaret);

       function toUppercase(evt) {
          var comp = evt.getSource();

            <af:form id="f1">
                <!-- Content -->
                <af:inputText label="Name" id="it21" shortDesc="Enter a value in uppercase" >
                    <af:clientListener type="keyUp" method="forceUppercase"/>
                <!-- and here the even simpler solution with the CSS Style property text-transform: uppercase -->
                <af:inputText label="Name" id="it2" shortDesc="Enter a value in uppercase"  contentStyle="text-transform: uppercase;">
                    <af:clientListener type="blur" method="toUppercase"/>

The post Force Text to UpperCase in RichInputText as the user is typing (make sure the cursor stays in one place) appeared first on AMIS Oracle and Java Blog.

Categories: Companies

This Week in Spring: Cloud Data Flow, RxJava, and Executable JARs

Welcome to another installment of This Week in Spring! This week I’m in Munich and Wolfsburg, Germany, visiting with customers, then it’s off to Seoul, South Korea, for customers and some user group talks.

This week we’ve got a lot of exciting Spring Cloud Data Flow news, coincident with the new Spring Cloud Data Flow RC1.

Categories: Communities

Lesson Learned From Gilded Rose Kata

I’d like to share some of my thoughts about my approach to solve the Gilded Rose Refactoring Kata by Emily Bache. If you don’t know this kata, read the description for a better understanding. I have published my whole solution on GitHub . I tried to make a commit after every step, so you can keep track of my steps in the log of Git. The chosen programming language is Java.

Solving Gilded Rose Step-By-Step

Let’s have a look at what I have done step-by-step.

Categories: Communities

Gradle 3.0 Preview by Hans Dockter

During our last Bay Area Gradle Users Meetup on May 26th, 2016 @ App Dynamics, Hans Dockter gave a demo of all the new features you will find in Gradle 3.0:

‚Äď Daemon enabled by default
‚Äď Composite Builds
‚Äď Performance Improvements

Categories: Communities

Java Quiz: Passing Objects to Methods

Before we get on with this week's quiz, we'd like to let you know that Sar's Java quizzes will be every other week starting with this one. Let's get started!

Passing Objects to Methods
public class MyClass{

    int x;

    MyClass(int y){
        this.x = y ++ ;
    int method(MyClass mc){
        if(mc.x == 5){
            mc.x += 6;
        if(mc.x == 6){
            mc.x += 9;
        return ++ mc.x;
    public static void main(String[] args){
        MyClass mc = new MyClass(5);

Categories: Communities

Microservices for Java Developers: Book Release [Announcement]

I‚Äôve just written a book that is now publicly available! The name of the book is ‚ÄúMicroservices for Java Developers‚ÄĚ (O‚ÄôReilly) and is a hands-on, step-by-step guide for building microservices with some popular Java frameworks like Spring Boot, Dropwizard, and WildFly Swarm! We also explore some of the non-functional requirements like safe deployments, exposing metrics, service interaction, service discovery, load balancing et. al. and how technology like Netflix OSS, Docker, and especially Kubernetes can help simplify the deployment and management of your microservices. Many many thanks to all of the reviewers who took the time to give feedback and for Red Hat for sponsoring my time especially Burr Sutter and the talented folks at O‚ÄôReilly who helped coordinate the effort and make it come to fruition.

I’ll have printed copies at DevNation/Summit (including a signing session Tuesday, June 28th at 3:30 at the Moscone Ctr.) and you can get a digital copy at the Red Hat Developers website. Stay tuned (@christianposta) as I may be working on part II :)

Categories: Communities

Howto create a private 10 Gb network on an ODA X5-2

AMIS Technology blog - Wed, 06/29/2016 - 20:15

In my previous post Network considerations on an ODA X5-2 I described a solution where I created a private network to optimize network performance between the components running on an Oracle Database Appliance. I am talking about a Virtualized setup in this article, and rebuilding the second pair of public interfaces to become a private network bond, in order to get a faster connection between the virtual machines.

In this article I will describe the steps how to create a private network on an ODA X5-2 and configure an additional SCAN-listener for this private network.

Connect the nodes

Let’s start by connecting the two nodes of the ODA directly to each other using Cat. 6 Ethernet cables. Make sure that the cables are long enough to route them through the Cable Management Arm. This way you don’t have to disconnect the cables when you have to do maintenance on the nodes.
We will use the second pair of interfaces for the configuration of the private network. Connect interfaces net2 and net3 on node0 to net2 and net3 on node1. This will create a 10 Gb network between the two nodes.

Pict. 1 – Oracle Database Appliance X5-2 Back Panel with net2 and net3 connected to each other

Now actually, you have a private network configured that you can assign to the VM’s.

Configure the interface on the ODA_BASE

In Dom0 the pair of interfaces is known as net2 and is assigned to the ODA_BASE.
Within the ODA_BASE the interface is known as eth1.

In this example we will use subnet for the private network.

Node0 :
Node1 :

There are several ways to assign an IP addresses to eth1 on the ODA_BASE on both nodes.

Using the Oracle Appliance Manager Configurator

If you are preparing for Oracle Database Appliance Installation and Deployment you configure the interface and ip-address during the deployment. The Oracle Appliance Manager Configurator will guide you through the process.

Using oakcli

If eth1 is unconfigured, you can use oakcli on the ODA_BASE of both nodes to configure it.

oakcli configure additionalnet

Provide Interface Name, DHCP, IP and Netmask

Manually change the IP address

Note. Don’t change the primary public IP addresses this way!!!
If you need to change the IP Address of the primary public interface, you need to follow the procedure described in
ODA: How to Change Oracle Database Appliance IP Addresses Post Deployment (Doc ID 1504734.1) on Oracle support.

If eth1 is already configured and you want to give it another IP address we can edit the ifcfg-eth1 file on the ODA_BASE of both nodes.

On Node0

cd /etc/sysconfig/network-scripts

vi ifcfg-eth1

#auto generated by OAK

Enable eth1 interface once.

ifup eth1

The next time the ODA_BASE is restarted, the interface will start automatically with the new address.

On Node1

cd /etc/sysconfig/network-scripts

vi ifcfg-eth1

#auto generated by OAK

Enable eth1 interface once.

ifup eth1

The next time the ODA_BASE is restarted, the interface will start automatically with the new address.

Note that the eth1 interface on the ODA_BASE is also known as net2 on the Dom0 and in the GRID infrastructure. Continuing this article I will use the term net2 for the private network.

Configure an additional SCAN Listener

When an ODA is installed and deployed, the Oracle Appliance Manager Configurator configures the SCAN listener on the interface defined as firstnet. Usually this will be net1.
Now that we have a private network, we wat to be able to use it for connections to the database. So we are going to add a SCAN listener to net2.
As a guide to creating another SCAN listener I am using ODA (Oracle Database Appliance): HowTo Configure Multiple Public Network on GI (Grid Infrastructure) 12c (Doc ID 2101109.1)

Configure hosts file and DNS

Before you configure the SCAN listeners we are going to add some entries to the /etc/hosts file of the ODA_BASE on both nodes
After initial deployment, the /etc/hosts file is filled with default values. For example.

# Following added by OneCommand    localhost.localdomain localhost

# PRIVATE HOSTNAMES oda11-priv0 oda12-priv0

# VIP HOSTNAMES oda11-vip oda12-vip

# NET(0-3) HOSTNAMES oda11 oda12

# Below are SCAN IP addresses for reference.
# ASR entry

Where is the subnet for net1 in this example.

Add the VIP hostnames of the newly created private network on net2.
To make things easy, used the same hostname as the public hostname and added -int to it.


# INTERNAL VIP HOSTNAMES, ADDED MANUALLY oda11-int-vip oda12-int-vip

Also add the vip addess of the SCAN listener to DNS before you create the new SCAN listener. On an ODA by default there are two ip addresses registered for the SCAN listener, so for the new SCAN listener we will also register two addresses on the private interface.    oda1-int-scan    oda1-int-scan

Configure Listener in GI Infrastructure

Logon to the ODA_BASE of node0 as user grid

Set environment to GI

[grid@oda11 ~]$ . oraenv
ORACLE_SID = [grid]? +ASM1
The Oracle base has been set to /u01/app/grid

Set interface type to pubic for eth1

[grid@oda11 ~]$ oifcfg setif -global eth1/
[grid@odadbsandta01 ~]$ oifcfg getif
eth0  global  public
ibbond0  global  cluster_interconnect,asm
eth1  global  public

Logon to the ODA_BASE of node0 as user root

Set environment to GI

[root@odadbsandta01 ~]# . oraenv
ORACLE_SID = [root]? +ASM1
The Oracle base has been set to /u01/app/grid

Add a network and vip addresses to GI

[root@oda11 grid]# srvctl add network -netnum 2 -S -w static
[root@oda11 grid]# srvctl add vip -n oda11 -A / -netnum 2
[root@oda11 grid]# srvctl add vip -n oda12 -A -netnum 2

Logon to the ODA_BASE of node0 as user grid

Set environment to GI

[grid@oda11 ~]$ . oraenv
ORACLE_SID = [grid]? +ASM1
The Oracle base has been set to /u01/app/grid

Start the newly created vip’s

[grid@oda11 ~]$ srvctl start vip -i
[grid@oda11 ~]$ srvctl start vip -i

Check if vip’s are enabled and running on both nodes

[grid@oda11 ~]# srvctl status vip -n oda11
VIP is enabled
VIP is running on node: oda11
VIP is enabled
VIP is running on node: oda11

[grid@oda11 ~]# srvctl status vip -n oda12
VIP is enabled
VIP is running on node: oda12
VIP is enabled
VIP is running on node: oda12

Add a listener on the net2 interface and start it

[grid@oda11 ~]$ srvctl add listener -l INT_LISTENER -p 1521 -netnum 2 -s
[grid@oda11 ~]$ srvctl start listener -l INT_LISTENER
[grid@oda11 ~]$ srvctl status listener
Listener INT_LISTENER is enabled
Listener INT_LISTENER is running on node(s): oda12,oda11
Listener LISTENER is enabled
Listener LISTENER is running on node(s): oda12,oda11

Logon to the ODA_BASE of node0 as user root

Set environment to GI

[root@odadbsandta01 ~]# . oraenv
ORACLE_SID = [root]? +ASM1
The Oracle base has been set to /u01/app/grid

Add SCAN and SCAN listener

[root@oda11 grid]# srvctl add scan -scanname oda1-int-scan -netnum 2
[root@oda11 grid]# srvctl start scan -netnum 2
[root@oda11 grid]# srvctl add scan_listener -netnum 2 -listener int -endpoints TCP:1521
[root@oda11 grid]# srvctl start scan_listener -netnum 2

[grid@oda11 ~]$ srvctl status scan
SCAN VIP scan1 is enabled
SCAN VIP scan1 is running on node oda12
SCAN VIP scan2 is enabled
SCAN VIP scan2 is running on node oda12

[grid@oda11 ~]$ srvctl status scan_listener
SCAN Listener LISTENER_SCAN1 is enabled
SCAN listener LISTENER_SCAN1 is running on node oda12
SCAN Listener LISTENER_SCAN2 is enabled
SCAN listener LISTENER_SCAN2 is running on node oda12

Register databases

In normal circumstances the databases should register themselves to the new listener. I have seen this working on an ODA X5-2 running version
So normally you are done with the database part.

Unfortunately version introduced a bug which prevents the registration of the database with the new listener.
Unfortunately the fix for this bug didn’t make it to the next release, nor the patchset of version
DO NOT try to install the normal server patchset Patch 19884033!! I have tried this and almost ruined our ODA installation.
Please wait for a patch specifically for the ODA.

Waiting for the bugfix, Oracle support supplied the following workaround.

ALTER SYSTEM SET listener_networks='((NAME=net2)(LOCAL_LISTENER=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=<net2_node1_vip>)(PORT=1521)))))','((NAME=net2)(REMOTE_LISTENER=net2_scan:1521))' SCOPE=BOTH SID='<instance1>'; 
ALTER SYSTEM SET listener_networks='((NAME=net2)(LOCAL_LISTENER=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=<net2_node2_vip>)(PORT=1521)))))','((NAME=net2)(REMOTE_LISTENER=net2_scan:1521))' SCOPE=BOTH SID='<instance2>';

Login to both the DB instances and run:

SQL> alter system register;

I am still working with Oracle support to get a one-off patch for this issue.

Using the private network

To use the private network, just add another network adapter to the vm or vmtemplate.

oakcli configure vm <vm name> -network "['type=netfront,bridge=net1','type=netfront,bridge=net2']"
oakcli configure vmtemplate <vm template name> -network "['type=netfront,bridge=net1','type=netfront,bridge=net2']"

In the VM the interfaces will be present as eth0 and eth1

Let’s take a look at the pictures I used in the previous blog, which are part of the design as an example.

In this design I configured the Oracle Traffic Director (OTD) and Fusion Middleware (in this case SOA Suite and MFT) VM’s with two interfaces.

The OTD is configured to listen on the public interface and routes traffic to the FMW components on the private interface.

The FMW components are configured to listen only on the private network. That way all traffic to the FMW components have to come from the OTD.
Also all cluster communication between the FMW components is routed through the private interface.

The FMW components route database traffic to and from the ODA_BASE through the private interface.

Note. The public interface on the FMW VM’s is only used for SSH.


By creating a private network on an ODA, you are not only able to improve performance. You are also capable of separating traffic from public to private. This creates a real one-box solution and, if implemented correctly, increases security. You are able to hide the back-end systems from the clients.
At customer sites where I have implemented the private network, they are very pleased with the solution.

Related Documents

Oracle Database Appliance Documentation
ODA: How to Change Oracle Database Appliance IP Addresses Post Deployment (Doc ID 1504734.1)
ODA (Oracle Database Appliance): HowTo Configure Multiple Public Network on GI (Grid Infrastructure) 12c (Doc ID 2101109.1)
Oracle White Paper on Oracle Single Client Access Name (SCAN)
Network considerations on an ODA X5-2

The post Howto create a private 10 Gb network on an ODA X5-2 appeared first on AMIS Oracle and Java Blog.

Categories: Companies

Keep Track of Logged In Users with Spring Security

baeldung - Coding and Testing Stuff - Wed, 06/29/2016 - 19:32
I just released the Starter Class of "Learn Spring Security":


1. Overview

In this quick tutorial, we’re going to show an example of how we can track the currently logged in users in an application using Spring Security.

For this purpose, we’re going to keep track of a list of logged in users by adding the user when they log in and removing them when they log out.

We’ll leverage the HttpSessionBindingListener to update the list of logged in users whenever user information is added to the session or removed from the session based on user logs into the system or logs out from the system.

2. Active User Store

For simplicity, we will define a class that acts as an in memory store for the logged in users:

public class ActiveUserStore {

    public List<String> users;

    public ActiveUserStore() {
        users = new ArrayList<String>();

    // standard getter and setter

We’ll define this as a standard bean in the Spring context:

public ActiveUserStore activeUserStore(){
    return new ActiveUserStore();
3. The HTTPSessionBindingListener

Now, we’re going to make use of the HTTPSessionBindingListener interface and create a wrapper class to represent a user that is currently logged in.

This will basically listen to events of type HttpSessionBindingEvent, which are triggered whenever a value is set or removed, or, in other words, bound or unbound, to the HTTP session:

public class LoggedUser implements HttpSessionBindingListener {

    private String username; 
    private ActiveUserStore activeUserStore;
    public LoggedUser(String username, ActiveUserStore activeUserStore) {
        this.username = username;
        this.activeUserStore = activeUserStore;
    public LoggedUser() {}

    public void valueBound(HttpSessionBindingEvent event) {
        List<String> users = activeUserStore.getUsers();
        LoggedUser user = (LoggedUser) event.getValue();
        if (!users.contains(user.getUsername())) {

    public void valueUnbound(HttpSessionBindingEvent event) {
        List<String> users = activeUserStore.getUsers();
        LoggedUser user = (LoggedUser) event.getValue();
        if (users.contains(user.getUsername())) {

    // standard getter and setter

The listener has two methods that need to be implemented, valueBound() and valueUnbound() for the two types of actions that trigger the event it is listening for. Whenever a value of the type that implements the listener is set or removed from the session, or the session is invalidated, these two methods will be invoked.

In our case, the valueBound() method will be called when the user logs in and the valueUnbound() method will be called when the user logs out or when the session expires.

In each of the methods we retrieve the value associated with the event, then add or remove the username from our list of logged in users, depending on whether the value was bound or unbound from the session.

4. Tracking Login and Logout

Now we need to keep track of when the user is successfully logged in or logged out so that we can add or remove active user from the session. In a Spring Security application, this can be achieved by implementing the AuthenticationSuccessHandler and LogoutSuccessHandler interfaces.

4.1. Implementing AuthenticationSuccessHandler

For the login action, we will set the username of the user logging in as an attribute on the session by overriding the onAuthenticationSuccess() method which provides us access to the session and authentication objects:

public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    ActiveUserStore activeUserStore;
    public void onAuthenticationSuccess(HttpServletRequest request, 
      HttpServletResponse response, Authentication authentication) 
      throws IOException {
        HttpSession session = request.getSession(false);
        if (session != null) {
            LoggedUser user = new LoggedUser(authentication.getName(), activeUserStore);
            session.setAttribute("user", user);
4.2. Implementing LogoutSuccessHandler

For the logout action, we will remove the user attribute by override the onLogoutSuccess() method of the LogoutSuccessHandler interface:

public class MyLogoutSuccessHandler implements LogoutSuccessHandler{
    public void onLogoutSuccess(HttpServletRequest request, 
      HttpServletResponse response, Authentication authentication)
      throws IOException, ServletException {
        HttpSession session = request.getSession();
        if (session != null){
5. Controller and View

In order to see all the above in action, we will create a controller mapping for the url “/users” that will retrieve the list of users, add it as a model attribute and return the users.html view:

5.1. Controller
public class UserController {
    ActiveUserStore activeUserStore;

    @RequestMapping(value = "/loggedUsers", method = RequestMethod.GET)
    public String getLoggedUsers(Locale locale, Model model) {
        model.addAttribute("users", activeUserStore.getUsers());
        return "users";
5.2. Users.html
    <h2>Currently logged in users</h2>
    <div th:each="user : ${users}">
        <p th:text="${user}">user</p>
6. Conclusion

In this article, we have demonstrated how we can determine who the currently logged in users are in a Spring Security application.

The implementation of this tutorial can be found in the github project ‚Äď this is an Maven based project, so it should be easy to import and run as it is.

Get the early-bird price (20% Off) of my upcoming "Learn Spring Security" Course:


Categories: Blogs

Convert a List to a Comma-Separated String in Java 8

Converting a List<String> to a String with all the values of the List comma separated in Java 8 is really straightforward. Let’s have a look how to do that.

In Java 8

We can simply write String.join(..), pass a delimiter and an Iterable and the new StringJoiner will do the rest:

Categories: Communities

Integrating Brazil into Oracle JET

Using the info from yesterday, it's easy to integrate Brazil into Oracle JET:

To get started, get the brazil-states.geojson file and put it in your project as described yesterday. Below, the file has been renamed to "brazil.json".

Then here's your viewModel:

        function (geo, oj, ko) {
            function mainContentViewModel() {
                var self = this;
                self.mapProvider = {
                    geo: JSON.parse(geo),
                    propertiesKeys: {
                        id: 'name',
                        shortLabel: 'name',
                        longLabel: 'sigla'
            return new mainContentViewModel();

And the view: 

<h1>Brazil Map</h1>
<div id='thematicmap1'
    component: 'ojThematicMap',
        basemap: 'Foo',
        mapProvider: mapProvider,
            layer: 'Bar',
            areaDataLayer: {
                id: 'adl1',
                areas: [
                    {id: 'a1', 'location': 'Tocantins', color: 'rgb(255, 181, 77)'},
                    {id: 'a2', 'location': 'Amazonas', color: 'rgb(255, 120, 90)'},
                    {id: 'a3', 'location': 'Mato Grosso', color: 'rgb(120, 30, 87)'},
                    {id: 'a4', 'location': 'Bahia', color: 'rgb(20, 80, 120)'}
     style="width:100%; height:600px;"/>

Take note of "Foo" and "Bar" above, i.e., these labels can be anything you like, they're just there as identifiers. The same is true for the "id" in the "areaDataLayer". The colors above are just an example of what you can do, i.e., they don't signify anything in this example. 

All this is pretty cool, isn't it?

Categories: Open Source

Announcing Java EE Microprofile

The Java community has likely been the greatest factor in Java‚Äôs success and influence over the past 20+ years. This community has rallied and collaborated to improve the language and its capabilities through JSRs, libraries, APIs, frameworks, and more. Now Java EE has become ‚Äúthe dominant standard for companies building business-critical multi-tier enterprise applications.‚ÄĚ

With that in mind, and with microservices architectures becoming ever more popular as monolithic applications hinder the advances of continuous delivery and integration, minimize performance, and lead to downtimes that are unacceptable for today’s technologies, there’s a new hurdle for the Java community to jump. Yesterday, the MicroProfile initiative was announced to inspire the community to overcome that hurdle together.

Categories: Communities

Singletons Must Die

I think it's too obvious to say that a singleton is an anti-pattern as there are tons of articles about that (singleton being an anti-pattern). However, more often than not, the question is how to define global things without a singleton; and the answer to that is not obvious for many of us. There are several examples: a database connection pool, a repository, a configuration map, etc. They all naturally seem to be "global"; but what do we do with them?

Perdita Durango (1997) by √Ālex de la IglesiaPerdita Durango (1997) by √Ālex de la Iglesia

I assume you already know what a singleton is and why it's an anti-pattern. If not, I recommend you read this StackOverflow thread: What is so bad about singletons?

Categories: Communities

XML Libraries Support in Java

baeldung - Coding and Testing Stuff - Wed, 06/29/2016 - 08:18
1. Introduction

In this article we will be comparing Java XML libraries and APIs.

This is the second article from the series about Java support for XML, if you want to go deeper into the XPath support in Java have a look at the previous article.

2. Overview

Now we’re going to dig deeper into the XML world support and for that we’re going to start by explaining as simple as possible all the subject-related initials.

In Java XML support we can find few API definitions, each one has its pros and cons.

‚ÄĘ SAX: It is an event based parsing API, it provides a low level access, is memory efficient and faster than DOM since it doesn‚Äôt load the whole document tree in memory but it doesn‚Äôt provide support for navigation like the one provided by XPath, although it is more efficient it is harder to use too.

‚ÄĘ DOM: It as model based parser that loads a tree structure document in memory, so we have the original elements order, we can navigate our document both directions, it provides an API for reading and writing, it offers XML manipulation and it is very easy to use although the price is high strain on memory resources.

‚ÄĘ StAX: It offers the ease of DOM and the efficiency of SAX but it lacks of some functionality provided by DOM like XML¬†manipulation and it only allows us to navigate the document forward.

‚ÄĘ JAXB: It allows us to navigate the document both directions, it is more efficient than DOM, it allows conversion from XML to java types and it supports XML manipulation but it can only parse a valid XML document.

You could still find some references to JAXP but last release of this project is from March 2013 and it is practically dead.

XML Apis Table

XML APIs Table

3. The XML

In this section we are going to see the most popular implementations, so that we can test real working samples and check differences between them.

In the following examples we will be working with a simple XML file with a structure like this:

    <tutorial tutId="01" type="java">
        <description>Introduction to Guava</description>
4. DOM4J

We’re going to¬†start by taking a look at what we can do with DOM4J¬†and for this example we need to add¬†the last version of this dependency.

This is one of the most popular libraries to work with XML files, since it allows us to perform bi-directional reading, create new documents and update existing ones.

DOM4J can work with DOM, SAX, XPath and XLST. SAX is supported via JAXP.

Let’s take a look here for example, how can we select an element filtering by a given id.

SAXReader reader = new SAXReader();
Document document =;
List<Node> elements = document.selectNodes("//*[@tutId='" + id + "']");
return elements.get(0);

The SAXReader class is responsible for creating a DOM4J tree from SAX parsing events. Once we have a org.dom4j.Document we just need to call the necessary method and pass to it the XPath expression as a String.

We can load an existing document, make changes to its content and then update the original file.

for (Node node : nodes) {
    Element element = (Element)node;
    Iterator<Element> iterator = element.elementIterator("title");
    while (iterator.hasNext()) {
        Element title =(Element);
        title.setText(title.getText() + " updated");
XMLWriter writer = new XMLWriter(
  new FileWriter(new File("src/test/resources/example_updated.xml")));

In the example above, we are changing¬†every title’s content and create a new file.

Notice here how simple it is to get every title’s¬†node in a list by calling elementIterator and passing the name of the node.

Once we have our content modified, we will use the XMLWriter that takes a DOM4J tree and formats it to a stream as XML.

Creating a new document from the scratch is as simple as we see below.

Document document = DocumentHelper.createDocument();
Element root = document.addElement("XMLTutorials");
Element tutorialElement = root.addElement("tutorial").addAttribute("tutId", "01");
tutorialElement.addAttribute("type", "xml");
tutorialElement.addElement("title").addText("XML with Dom4J");
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter(
  new FileWriter(new File("src/test/resources/example_new.xml")), format);

DocumentHelper gives us a collection of methods to use by DOM4J, such as createDocument that creates an empty document to start working with it.

We can create as many attributes or elements as we need with the methods provided by DOM4J, and once we have our document completed we just write it to a file as we did with the update case before.


In order to work with with JDOM, we have to add this dependency to our pom.

JDOM’s working style is pretty similar to DOM4J’s, so we are going to take a look at¬†just a couple of examples:

SAXBuilder builder = new SAXBuilder();
Document doc =;
Element tutorials = doc.getRootElement();
List<Element> titles = tutorials.getChildren("tutorial");

In the example above, we are retrieving all elements from the root element in a very simple way as we can do with DOM4J:

SAXBuilder builder = new SAXBuilder();
Document document = (Document);
String filter = "//*[@tutId='" + id + "']";
XPathFactory xFactory = XPathFactory.instance();
XPathExpression<Element> expr = xFactory.compile(filter, Filters.element());
List<Element> node = expr.evaluate(document);

Again, here in the code above, we have a SAXBuilder creating a Document instance from a given file. We are retrieving an element by its tutId attribute by passing an XPath expression to the XPathFactory provided by JDOM2.

6. StAX

Now, we are going to see how we could retrieve all elements from our root element using the Stax API. Stax is included in the JDK since Java 6 so you don’t need to add any dependencies.

Firstly, we need to create a Tutorial class:

public class Tutorial {
    private String tutId;
    private String type;
    private String title;
    private String description;
    private String date;
    private String author;
    // standard getters and setters

and then we are ready to follow with:

List<Tutorial> tutorials = new ArrayList<>();
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLEventReader eventReader = factory.createXMLEventReader(new FileReader(this.getFile()));
Tutorial current;
while (eventReader.hasNext()) {
    XMLEvent event = eventReader.nextEvent();
    switch (event.getEventType()) {
        case XMLStreamConstants.START_ELEMENT:
            StartElement startElement = event.asStartElement();
            String qName = startElement.getName().getLocalPart();
        case XMLStreamConstants.CHARACTERS:
            Characters characters = event.asCharacters();
        case XMLStreamConstants.END_ELEMENT:
            EndElement endElement = event.asEndElement();
            // check if we found the closing element
            // close resources that need to be explicitly closed

In the example above, in order to help us retrieve the information, we needed to create a class to store the retrieved data in.

To read the document, we declared what is called event handlers and we used them to navigate our document ahead. Remember that the SAX¬†implementations don’t provide bi-directional navigation. As you can see here, a lot of work needs to be done¬†just to retrieve a simple list of elements.


JAXB¬†is included with the JDK, so initially we could think that we don’t need to add any dependency to our project, but this is not completely true, since JAXB needs XercesImpl to work correctly, so we should add this dependency to make it work.

It’s very simple to load, create and manipulate information from an XML file using JAXB.

We just need to create the correct java entities to bind the XML and that’s it.

JAXBContext jaxbContext = JAXBContext.newInstance(Tutorials.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Tutorials tutorials = (Tutorials) jaxbUnmarshaller.unmarshal(this.getFile());

In the example above, we load our XML file into our object and from there we can handle everything as a normal Java structure;

To create a new document, it is as simple as reading it but doing the reverse way, like done in the below code.

Firstly, we are going to modify our Tutorial class to add JAXB annotations to getters and setters:

public class Tutorial {
    public String getTutId() {
        return tutId;
    public void setTutId(String tutId) {
        this.tutId = tutId;
    public void setTitle(String title) {
        this.title = title;

public class Tutorials {
    private List<Tutorial> tutorial;

    // standard getters and setters with @XmlElement annotation

With @XmlRootElement we define what object is going to represent the root node of our document and then we use @XmlAttribute or @XmlElement to define whether that attribute represents an attribute of a node or an element of the document.

Then we can follow with:

Tutorials tutorials = new Tutorials();
tutorials.setTutorial(new ArrayList<>());
Tutorial tut = new Tutorial();
JAXBContext jaxbContext = JAXBContext.newInstance(Tutorials.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(tutorials, file);

As you can see, binding XML file to Java objects is the easiest way to work this kind of files.

8. XPath Expression Support

To create complex XPath expressions, we can use Jaxen. This is an open source XPath library adaptable to many different object models, including DOM, XOM, DOM4J, and JDOM.

We can create XPath expressions and compile them against many supported documents.

String expression = "/tutorials/tutorial";
XPath path = new DOMXPath(expression);
List result = path.selectNodes(xmlDocument);

To make it work we’ll need to add this dependency to our project.

9. Conclusion

As you can see there are many options for working with XML, depending on the requirements of your application, you could work with any of them or you may have to choose between efficiency and simplicity.

You can find the full working samples for this article in our git repository here.

Categories: Blogs

Design Patterns in the Real World: Strategy

Quite some software engineers think that design patterns are some overly complicated, mythical, abstract things that bring no practical value to software development. This is unfortunate. In order to prove they are indeed something real, in this (and some upcoming) post(s) we are going to take a look at a few examples on how real software products implement some of the GoF design patterns. Today, we are going to visit Strategy, from HotSpot’s point of view. (See the previous post about Flyweight here).

Strategy Defined

Wikipedia defines Strategy as follows:

Categories: Communities