Spring Boot and WordPress CMS Integration

There are a lot of excellent open source content management systems available today,  WordPress being one of them, which is widely used. WordPress is a PHP based CMS so not a lot of cohesion is available with other technologies like Java, and is simply ignored as a viable content management option just for being non-Java.

In this post I will demonstrate how WordPress can be integrated with Spring Boot applications, all made possible with WordPress REST plugin and a Spring client. Both of these are open source and available for free. Below is a simple design diagram that explains how this integration works. This post assumes that the reader has prior knowledge of WordPress and Spring Boot.

First install and activate WP-API v2 plugin on the WordPress site. After activation, you could verify that the plugin is working by accessing http://yoursite/wp-json/wp/v2/posts, which should display all the posts in JSON format.

In the spring boot application add the following dependency in order to include the Spring WP-API client.

Below is a sample configuration we need in the application.properties file, so that we can connect our Spring Boot application to our WordPress site.

The Spring WP-API client needs the RestTemplate so lets create a bean in our Application and autowire the Spring client. We also need to add component scan annotation so that Spring finds and autowires all the required dependencies.

Now our spring boot application is all setup to connect to out WordPress site in order to retrieve and create content. So lets try and lookup all the posts having the keyword “Spring”, below is how we can do this.

The complete test application is available with the Spring WP-API client on Github.

This is just a small example of how we can integrate Spring Boot and WordPress. We can take this further by properly integrating WordPress in the Spring web applications platform, e.g. by enabling Single Sign On using the CAS plugin.

And we can evolve this design even further by having a second-level content storage, like a database or an in-memory caching solution etc. This storage can serve as a cache and can also be used for additional configuration, so that we display relevant content faster in our Spring applications.

For more information please see the documentation of the WordPress REST plugin and Spring WP-API client.

Using Standalone ActiveMQ Broker with Wildfly

Wildfly is an open source J2EE container, which comes with an embedded HornetQ JMS broker enabled by default in it’s full configuration. The embedded HornetQ works great out of the box, but sometimes it can be handy to use an existing JMS broker, like ActiveMQ. ActiveMQ includes a JCA resource adaptor that can be used to integrate it with J2EE containers. Below we will see how to integrate standalone ActiveMQ 5.13.2 with Wildfly 9.0.2 server.

The first step is to download, tweak and deploy the ActiveMQ Resource Adaptor (RA) on Wildfly. ActiveMQ RA binaries are available on Apache’s site for download. So lets download and unpack the adaptor.

Now, because we don’t need to run ActiveMQ embedded in Wildfly, we’ll comment out the necessary configuration. This can be done by editing the activemq-rar/META-INF/ra.xml, and removing the config-property with the following comment:

After this we’ll pack the adaptor and deploy it on Wildfly.

We can now configure this Resource Adaptor on Wildfly in order to create and bind an ActiveMQ connection factory in JNDI. Below is a sample configuration that we need in Wildfly’s standalone.xml configuration file (or the server’s current domain configuration file depending on the setup). The resource adaptor configuration reference is available on Apache’s site

After this, in our applications deployed on Wildfly, we can simply lookup the ActiveMQConnectionFactory from JNDI (java:/ConnectionFactory) and start sending and receiving messages.

XMPP web chat with ejabberd, Converse.js and Spring MVC

Converse.js is a fine little XMPP web chat client that can easily be used in web applications. It can integrate with various online XMPP services, like Google Talk, MSN etc. In this post I will demonstrate how to use converse.js with ejabberd in a Spring based application. I used Ubuntu linux box to for this demo.

ejabberd is available in main Ubuntu repositories so can be installed by using the following command.

The first thing to do is to add an admin user, by adding the following to the /etc/ejabberd/ejabberd.cfg configuration file.

Then restart ejabberd

Now register the admin user by entering the following command on the shell prompt.

For more details on ejabberd setup and additional options, follow this tutorial.

[turbo_widget widget-prefix=text&obj-class=WP_Widget_Text&widget-text–title=&widget-text–text=%3C!–+Post+Ad+–%3E%0A%3Cins+class%3D%22adsbygoogle%22%0A+++++style%3D%22display%3Ablock%22%0A+++++data-ad-client%3D%22ca-pub-4433761869744390%22%0A+++++data-ad-slot%3D%229020480262%22%0A+++++data-ad-format%3D%22auto%22%3E%3C%2Fins%3E%0A%3Cscript%3E%0A(adsbygoogle+%3D+window.adsbygoogle+%7C%7C+%5B%5D).push(%7B%7D)%3B%0A%3C%2Fscript%3E&widget-text–filter=false]

Next we enable http binding, which is required because converse.js will communicate with ejabberd using the BOSH protocol. In order to do this look for the 5280 (ejabberd_http) port setup in the configuration file and update it to look like below:

Then add the http_bind module under the modules section, then restart ejabberd.

Now the XMPP server is setup for this demo. The http binding can be verified by opening the following link in the web browser.

Optionally we can also setup Apache/Nginx web server to proxy the http bind requests to ejabberd. If required add something like the following to the web server configuration. This is useful, if ejabberd port 5280 is blocked by the firewall.

Converse.js can now talk to the ejabberd server. The javascript snippet below shows how to use it in the web application.

This requires login, and also allows registration of new users from the frontend.

[turbo_widget widget-prefix=text&obj-class=WP_Widget_Text&widget-text–title=&widget-text–text=%3C!–+Post+Ad+–%3E%0A%3Cins+class%3D%22adsbygoogle%22%0A+++++style%3D%22display%3Ablock%22%0A+++++data-ad-client%3D%22ca-pub-4433761869744390%22%0A+++++data-ad-slot%3D%229020480262%22%0A+++++data-ad-format%3D%22auto%22%3E%3C%2Fins%3E%0A%3Cscript%3E%0A(adsbygoogle+%3D+window.adsbygoogle+%7C%7C+%5B%5D).push(%7B%7D)%3B%0A%3C%2Fscript%3E&widget-text–filter=false]

ejabberd HTTP Pre-binding

Sometimes it is desirable not to ask the users to login again, if they are already logged on to the parent application. Which means that the parent application should login to ejabberd from the backend, and then attach the ejabberd session to converse.js. This is achieved by something known as “http pre-binding”, which is supported by converse.js. In order to use an existing ejabberd session, created by the parent application, converse.js needs three pieces of information:

  1. JID (ejabberd user id)
  2. SID (ejabberd session id)
  3. RID (request id)

These IDs are obtained by the parent application, after initiating the session, from the backend, by logging on to ejabberd. In the demo, it is done from a custom spring security AuthenticationProvider.

The converse.js javascript snippet below shows how pre-binding is configured on the frontend.

The prebind URL must return the three IDs, mentioned above, in JSON format. More information on prebind_url is available on converse.js homepage.

The complete Spring boot application is available on Github, which covers ejabber authentication and pre-binding.

Clustering and Load balancing Tomcat servers

Tomcat is by far the most popular open source Java servlet container that can easily be scaled to ensure high availability. In this post I will show how easy it is to distribute and scale java web applications using tomcat clusters. In this example we will also use Apache web server to load balance the cluster.

Below is a simple setup of a cluster with two Tomcat 7 nodes with Apache web server 2.2 as a load balancer.



Load balanced clustering on tomcat is done in four simple steps:

1- Uniquely naming each node
2- Configure clustering in server.xml
3- Configure the session persistence in context.xml (Optional)
4- Enable distribution in the Java web application

The following configuration is done on each tomcat instance either running on the same machine or on separate virtual or physical servers. If multiple instances are running on the same machine then it should be ensured that each instance is listening on different ports.

Naming the tomcat nodes

The server node can be named by adding the jvmRoute element to the tomcat Engine as shown below. This node name is appended to the session id.

Configuring the cluster

Clustering can easily be enabled in tomcat by adding the following to the server.xml file

[turbo_widget widget-prefix=text&obj-class=WP_Widget_Text&widget-text–title=&widget-text–text=%3C!–+Post+Ad+–%3E%0A%3Cins+class%3D%22adsbygoogle%22%0A+++++style%3D%22display%3Ablock%22%0A+++++data-ad-client%3D%22ca-pub-4433761869744390%22%0A+++++data-ad-slot%3D%229020480262%22%0A+++++data-ad-format%3D%22auto%22%3E%3C%2Fins%3E%0A%3Cscript%3E%0A(adsbygoogle+%3D+window.adsbygoogle+%7C%7C+%5B%5D).push(%7B%7D)%3B%0A%3C%2Fscript%3E&widget-text–filter=false]

This will also enable session replication on all tomcat nodes. Below is a detailed example that shows more options, including multicast and deployer configuration. See the tomcat documentation for more info.

Configuring session persistence (Optional)

Session persistence in configured in the context.xml file by defining a persistence manager. By default the session is persisted in-memory but optionally a disk or database storage can be also be configured. The example below shows how the session is persisted on the local disk using a session store.

Making the application distributable

The java web applications can be configured to run in a cluster by adding the following to application’s web.xml file.

Once all this configuration is done on each node, the servers will be running in a cluster with session replication enabled.

[turbo_widget widget-prefix=text&obj-class=WP_Widget_Text&widget-text–title=&widget-text–text=%3C!–+Post+Ad+–%3E%0A%3Cins+class%3D%22adsbygoogle%22%0A+++++style%3D%22display%3Ablock%22%0A+++++data-ad-client%3D%22ca-pub-4433761869744390%22%0A+++++data-ad-slot%3D%229020480262%22%0A+++++data-ad-format%3D%22auto%22%3E%3C%2Fins%3E%0A%3Cscript%3E%0A(adsbygoogle+%3D+window.adsbygoogle+%7C%7C+%5B%5D).push(%7B%7D)%3B%0A%3C%2Fscript%3E&widget-text–filter=false]

Load balancing the cluster

Now the next step is to configure load balancing to effectively use the scalable tomcat cluster and to ensure high availability. Meaning if one of the nodes, in the cluster, goes down, the application will still be available on the other node. And with session replication enabled the service and user experience will not be impacted.

In this example I am using Apache’s mod_proxy_ajp to load balance the two tomcat instances. The configuration is fairly simple and is added to the httpd.conf file. The example also shows how session sticky-ness is enabled. The loadfactor defines the weighted load that is applied on each node. The lbmethod configures the load balancing strategy, which can either be byrequests or bytraffic.

Note: mod_proxy_ajp is not the only way apache is used to load balance tomcat instances, the other commonly used methods are mod_jk and mod_proxy.

Demise of J2ME

Since the arrival of iOS and Android smartphones, J2ME has really faded into the background. And it is not because iOS and Android are better platforms, it is because J2ME didn’t evolve with the rapid technological growth of mobile devices. J2ME was originally intended for low-end devices, as a lightweight Java runtime and was very successful. But we haven’t seen any new enhancements to the platform for the commonly available new high-end mobile devices nowadays. There has been some maintenance releases here and there but no substantial improvements were seen in the platform. Some proposed enhancements are lying dormant in the neo-political and ever bureaucratic JCP. And since Oracle acquired Sun Microsystems, and started pushing their ADF platform for corporate mobile solutions, the future of J2ME is looking very bleak.

Noone has anything interesting to say about J2ME anymore and their market-share is gradually decreasing. It is hard to understand why J2ME has been orphaned, which once used to be the only real mobile platform supported by majority of phone vendors. The market did show some positive vital signs for J2ME, when the sales of iOS and Android went down last year, which had some people excited; it also showed that the platform might still have potential. But Oracle, for some strange reason, failed to capitalize on it.

Oracle may brag about millions of devices running Java, but the truth is Oracle doesn’t have a proper platform for modern mobile devices. Realistically speaking, today, J2ME cannot compete with the likes of iOS, and it’s cousin Android, which provides, although non-standard and controversial, but a full featured Java 5 runtime for mobile along with many open source goodies from Apache. From the end-user perspective, J2ME does not give you the same feature-rich user experience as Android, iOS or even Blackberry. The J2ME developers also never saw a standard app-store, available on all mobile devices, where they could sell their apps, which is one of the major success attributes of iOS and Android. And with the success of cross-platform HTML5/AJAX based technologies, it will be pretty hard for J2ME to compete unless it brings something new to table, which doesn’t seem likely with all these years of EDS.

It would have been nice to see a standards-based Java Mobile platform backed by the JCP. Android did come close to becoming the next J2ME, which was also a good news for Java being Open, but the success was marred by the Oracle law-suits. In the end, as a developer it is sad to witness the gradual but imminent demise of J2ME. So R.I.P J2ME, you had your day and it was nice knowing you.

Crawl, index and search

Sometimes you need to search for files or pages on content-rich websites or browser-based information software/encyclopedias that don’t really have a search functionality. And it could be a pain to find what you are looking for. I wrote a little crawler once in python that works well to search for stuff, on websites, on the fly. But sometimes a real “index” is needed for searching. There are a few libraries available and among them is the open source Apache Lucene, an excellent high-performance text search engine library that one can use for free. Lucene coupled with a multi-threaded web crawler and you have a pretty good index and search functionality; though not as good as google, but close.

Below is an example of how you can use Lucene to build searchable indexes for websites.

Now once the index is created we can start searching it for content. Lucene provides IndexSearcher class that is used to search the index using a Query. Below is an example that searches for results in the above created index, and prints the website URL where the required content is found.

The full source of this example, including the web crawler, can be found here and is available under GPL.

Oracle-IBM pact and Android

IBM-Oracle pact is a good news for Java developers and for the open source community in general. OpenJDK is a more natural open alternative to Oracle J2SE and is well backed by the Java community, so IBM’s move to shift “its development effort from the Apache project Harmony to OpenJDK” makes sense. And remember IBM also wanted to acquire Sun mainly because of Java. Apache Harmony on the other hand never gained enough popularity because of the TCK-issuance tussle between Sun and Apache. But Harmony remains as another open-source implementation of Java, free from legal infringements.

Now a lot of people see this pact as a threat to Google’s Android platform, and associate it with Oracle’s lawsuit against Google, but I don’t think this is the case (although Oracle may think otherwise). First of all OpenJDK is not built for mobile platforms, it could be a threat to Oracle’s own J2SE but not to Android. Secondly Google uses Apache Harmony, which has been rewritten and is Open. Google also uses a Dalvik VM, which is a special virtual machine written from scratch for mobile devices, and is also backed by the Open Handset Alliance. Dalvik VM is also open-source and uses it’s own form of bytecode, which is “distinct and different from Java bytecode“. So Google is not using any Java component in their Android platform, which would obligate them to require a license from Oracle.

As a developer, I think IBM’s move is good for Java being Open. To Google it is kind of an opportunity to start owning Harmony and to control development on it; and Google should seriously start investing in Harmony and capitalize on this opportunity. And for the lawsuit, I think Google can win it, if it is not thrown out of the court, may be fined for “some incompatibilities” in their version of Java. But it is the time this suit is going to take, “may” cause some hardware vendors to slowdown their production of android phones, but the demand will drive it and I don’t see it happening because Android phones are much cheaper; a lot of android phones are lined up for 2011 with Android-3-based tablets.

Oracle, a patent troll, just wants money and will try to prolong the lawsuit as much as they can to get some leverage from “time” and “doubts” about future of android. But in the end it is not going to matter much because Oracle is not Android’s competitor and doesn’t have a “real” mobile platform except for the dying-j2me, which they inherited from Sun.

Log4J: Emailing specific errors only

Log4J’s SMTPAppender provides enough basic functionality to send out error messages as emails. Although emailing error messages is not always a good idea, unless something really goes wrong in system. Sometimes it is required to send out only specific errors in specific areas of the system. It is possible to do that with the SMTPAppender, even if these specific errors lie in the same category(WARN, ERROR etc.) as other errors. This is achieved with TriggeringEventEvaluator. Here is a sample config for the SMTPAppender.

The parameter EvaluatorClass is where we specify the implementation of TriggeringEventEvaluator, which acts like a filter to allow emailing only specific errors:

Now only ERRORs from “SomeSeriousErrorLogger” will be emailed.

Merging arrays in Java

I was playing around with java arrays and ran into a problem where I wanted to merge smaller arrays into a single big array. So the first thing I thought was to make a new array of size equal to the total length of all smaller arrays and then populating the values using loops. Then I went on to make a generic method to merge Generic arrays of same type but I realized that I cannot create a Generic array. So I thought of another way to merge Generic arrays using List.

This code here will merge any number of generic arrays into one single array. The last line gives an unchecked cast warning, but can be ignored because we already assumed that the arrays are of same type.

Resolving log4j.dtd error on JBoss

I recently faced an issue where the application was not able to find the log4j.dtd, when deployed on jboss. We were using our own repository selector for logging and an isolated classloader. But could see a “FileNotFoundException” for log4j.dtd in the JBoss log when the application was deployed, although the dtd was part of the log4j jar contained within the application. The reason for that was the xml parser was not looking in the classpath resources for the dtd, but was just looking in a path relative to the application’s root directory.

Now in order to load the dtd from the classpath I updated the repository selector and set an EntityResolver to the DocumentBuilder so that when the parser encounters the dtd reference the resolver looks it up from the classpath. Here is the code to that.

Assuming that the doctype reference in log4j.xml is:

The code to override the default behavior of the parser to look for the dtd in the classpath:

Now our EntityResolver will return the dtd from classpath whenever the parser encounters it. Although I wish the parser could support the “classpath” protocol in the doctype uri.